How to get a BareJid in smack 4.2.0 - smack

I used Roster to create Roster Entry by Roster's method createEntry(BareJid user, String name, String[] groups),but I don't know how to get a BareJid. Anybody could help me?Here are my code,my userJid is a String:
Roster roster = XmppConnectionManager.getInstance().getRoster();
if (roster != null) {
try {
// String[] jids = userJid.split("#");
roster.createEntry(userJid, nickname, null);
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Log.w(TAG,"roster is null");
}

I just found it by Google, there is a JID helper class JidCreate:
JidCreate.bareFrom(userJid)

Related

when use mina-sshd to execute command ,timeout occurred,how can i deal with it

Here follows is my code,how can i deal with it
public ConnectResponse runCommand(UserInfo userInfo, String command, long timeout) {
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.start();
ChannelExec execChannel = null;
try (ClientSession session = sshClient
.connect(userInfo.getUsername(), userInfo.getTargetIp(), 22)
.verify(CLIENT_VERIFY_TIMEOUT)
.getClientSession();) {
session.addPasswordIdentity(userInfo.getAuthentication());
session.auth().verify(SESSION_VERIFY_TIMEOUT);
execChannel = session.createExecChannel(command);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
execChannel.setOut(out);
execChannel.setErr(err);
execChannel.open();
Set<ClientChannelEvent> events = execChannel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new BusinessException(500, String.format("执行命令 {%s} 超时了!", command));
}
return new ConnectResponse(out.toString(), err.toString(), execChannel.getExitStatus());
} catch (Exception e) {
throw new BusinessException(e.getCause(), 500, String.format("执行命令 {%s} 出现了一行了!", command));
} finally {
if (!Objects.isNull(execChannel)) {
try {
execChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Blackberry - send sms timeout

I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}

How To Change the field on focus in blackberry

Hello Sir I m making an app in which i got stuck in a problem please help me out ...
in one page i m getting the data from server and displaying that data on the page now i m use Focusable for highlighting them ...now my requirement is that when focus come on any data the it should change the field taking that name on which focus is present ..
following is the code which is showing the data on the page now it is working on field change where i need to click the label field ....
static LabelField[] CrDrLabels;
public LowerCreditors() throws Exception {
super(VerticalFieldManager.VERTICAL_SCROLL);
CrDrLabels = new LabelField[CrDrList.VendorNameArr.length];
for (int i = 0; i < CrDrLabels.length; i++) {
final int t = i;
VerticalFieldManager hfm = new VerticalFieldManager(USE_ALL_WIDTH) {
protected void sublayout(int Width, int Height) {
// TODO Auto-generated method stub
super.sublayout(Width, Height);
setPositionChild(getField(0), 15, 0);
setPositionChild(getField(1), Display.getWidth()
- getFont().getAdvance(CrDrList.VendorValArr[t])
- 10, 0);
}
};
CrDrLabels[i] = new LabelField(CrDrList.VendorNameArr[i],
LabelField.FOCUSABLE | Field.USE_ALL_WIDTH) {
protected boolean navigationClick(int status, int time) {
fieldChanged(this, 0);
return true;
};
};
LabelField Value = new LabelField(CrDrList.VendorValArr[i]);
CrDrLabels[i].setPadding(0, 170, 0, 0);
hfm.add(CrDrLabels[i]);
hfm.add(Value);
add(hfm);
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
for (int i = 0; i < CrDrList.VendorNameArr.length; i++) {
getFieldWithFocus();
if (field == CrDrLabels[i]) {
String LN = CrDrLabels[i].getText();
CrDrList.cname1 = LN;
LabelField cname1 = CrDrLabels[i];
CrDrList.selLad = CrDrLabels[i];
}
}
}
and the the other code is
menu.add(new MenuItem("View last 5 days transaction", 20, 10) {
public void run() {
if(property.Status.equals("online"))
{
Viewlast5daystransaction();
}
else
{
Dialog.alert("Please login Online to access the data..");
}
}
String LedgerName = CrDrList.cname1;
private void Viewlast5daystransaction() {
//Dialog.alert("Last 5 Days Transaction");
int resCode = 0;
HttpConnection connection = null;
try {
connection = getConn(property.LedgerDetailsURL);
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
e1.printStackTrace();
}
try {
resCode = connection.getResponseCode();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(resCode==0)
{
Dialog.alert("Internet Connectivity not available.. Please try again later..");
TallyA TA;
try {
TA = new TallyA();
UiApplication.getUiApplication().popScreen();
UiApplication.getUiApplication().pushScreen(TA);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sPostdata = "{\"tok\":\""
+ CompanyList.tok;
System.out.println("Postedddddd Dataaaaaaaaa" + sPostdata);
try {
String response = LedgerSearchReport();
System.out.println("response" + response);
ParseBankdetails.parsebankdetails(response);
System.out.println("response : " + response);
if(response != null)
{
LastFiveDaysCr LF;
try {
LF = new LastFiveDaysCr();
UiApplication.getUiApplication().pushScreen(LF);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Dialog.alert("No Data..");
Creditiors LF;
try {
LF = new Creditiors();
UiApplication.getUiApplication().pushScreen(LF);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
in this field only i want that instead of field change there should be focus change ...
please help me on that ...
I think you should implement the logic in "onFoucus()" method ,instead of using "onfieldChanged()" for CrDrLabels[i];

Primefaces filedownload error handling

How to handle error with primefaces filedownload
<p:fileDownload value="#{testBean.file}" />
TestBean.java
public StreamedContent getFile() {
if(selectedReport ==null){
FacesContext.getCurrentInstance().addMessage(.."Please select a file");
return null;//What to do here
}
InputStream inps = ReportGenerator.getPDF(selectedReport);
return new DefaultStreamedContent(inps, "application/pdf", "report.pdf");
}
This helped http://forum.primefaces.org/viewtopic.php?f=3&t=8263
<p:commandButton ajax="false"
value="Download Detailed Report"
actionListener="#{reportBean.generateDetailedReport}">
<p:fileDownload value="#{reportBean.detailedReport}"/>
</p:commandButton>
public void generateDetailedReport(ActionEvent ae) {
......
reportStream = ExcelReport.generate(reportList);
if (reportStream == null) {
FacesUtil.addError("Error generating report");
throw new AbortProcessingException();
}
}
public StreamedContent getDetailedReport() {
return new DefaultStreamedContent(reportStream, "application/xls", "report.xls");
}
If you mean handle error by show an html message to the user, then you should put the code that can throw an exception inside a try...catch block, and the catch block changes the content type back to text/html and display the error in the way you want.
But since the content type is added in the DefaultStreamedContent, maybe only a redirection can solve this.
Better to use obtain all exception in one like ;
} catch (Exception e) {
handleError(e);
}
handleError method ;
private void handleError (Throwable t) {
try {
throw t;
} catch (AccessException ae) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (SQLException sqle) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (ConnectException ce) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (RemoteException re) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (NotBoundException nbe) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (IOException ioe) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (IllegalArgumentException iae) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (Throwable tt) {
FacesUtil.setErrorMessage("CCCCCCC");
}
FacesUtil.completeResponse();
}

Error while using RSA encryption on BlackBerry

I'm trying to use RSA encryption on Blackberry with their native API's. I made a public/private key pair in Java and saved the Modulus and Exponents of the keys as strings so i can generate the keys from this for encryption and decryption. The following code is from the client side and i'm getting a InvalidKeyException and the backtrace is null so I don't know what's happening:
public byte[] Encrypt(byte[] data)
{
try {
RSACryptoSystem cryptoSystem = new RSACryptoSystem(1024);
RSAPublicKey publicKey = new RSAPublicKey(cryptoSystem, _publicKeyExponent.getBytes(), _publicKeyModulus.getBytes());
RSAEncryptorEngine encryptorEngine = new RSAEncryptorEngine(publicKey);
PKCS5FormatterEngine formatterEngine = new PKCS5FormatterEngine( encryptorEngine );
ByteArrayOutputStream output = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor( formatterEngine, output );
encryptor.write(data);
encryptor.close();
output.close();
return output.toByteArray();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
System.out.println();
e.printStackTrace();
} catch (CryptoTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoUnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
And this is what i did server side to generate my keys:
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyFactory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
try {
publicKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
privateKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
privateKeyModulus = privateKeySpec.getModulus().toString();
privateKeyExponent = privateKeySpec.getPrivateExponent().toString();
publicKeyModulus = publicKeySpec.getModulus().toString();
publicKeyExponent = publicKeySpec.getPublicExponent().toString();
Any ideas?
EDIT: i tried doing a simple test on the server by encrypting and decrypting there and when when I try to decrypt I get a IllegalBlockSizeException these are my encrytion and decryption methods (server side):
public byte[] Decrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public byte[] Encrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
And this is the simple test i'm trying:
userName = Base64.encode(encryptorDecryptor.Encrypt(userName.getBytes()));
password = Base64.encode(encryptorDecryptor.Encrypt(password.getBytes()));
userName = new String(encryptorDecryptor.Decrypt(Base64.decode(userName)));
password = new String(encryptorDecryptor.Decrypt(Base64.decode(password)));
It is a bug to use String as a container for arbitrary random bytes, e.g. userName = new String(encryptorDecryptor.Encrypt(userName.getBytes()));
is wrong.
I'm not familiar with Blackberry's Java API but in usually you cannot encrypt more than one block with RSA
the toString() methods on arrays (e.g. publicKeySpec.getModulus().toString()) don't return anything useful. You should be able to figure this out just by looking at the data. This is really a beginner java mistake more than a cryptography issue.
Don't using the default character set for the String constructor and String.getBytes() methods. Always specify a character set, usually "UTF-8" is perfect.
That's all I had the patience for.

Resources