Smack 4.1 connection to gtalk - smack

I updated to smack 4.1, but now cannot connect to gtalk. This is my code I am using:
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setHost("talk.google.com");
configBuilder.setPort(5222);
configBuilder.setServiceName("gmail.com");
configBuilder.setSecurityMode(SecurityMode.required);
configBuilder.setDebuggerEnabled(true);
configBuilder.setSendPresence(true);
configBuilder.setUsernameAndPassword(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));
SASLAuthentication.blacklistSASLMechanism(SASLMechanism.PLAIN);
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
try
{
connection.connect();
connection.login();//.login(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
This is the error i get:
D/SMACK(12807): SENT (3): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-OAUTH2'>REMOVED_THIS=</auth>
D/SMACK(12807): RECV (3): <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><incorrect-encoding/></failure>

The problem is the line in SASLXOauth2Mechanism:
Base64.encode(toBytes('\u0000' + authenticationId + '\u0000' + password));
As a quick test replace in your code
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
with this
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build())
{
#Override
public void send(PlainStreamElement auth) throws NotConnectedException
{
if(auth instanceof AuthMechanism)
{
final XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement(AuthMechanism.ELEMENT)
.xmlnsAttribute(SaslStreamElements.NAMESPACE)
.attribute("mechanism", "X-OAUTH2")
.attribute("auth:service", "oauth2")
.attribute("xmlns:auth", "http://www.google.com/talk/protocol/auth")
.rightAngleBracket()
.optAppend(Base64.encodeToString(StringUtils.toBytes("\0" + authenticationId + "\0" + password)))
.closeElement(AuthMechanism.ELEMENT);
super.send(new PlainStreamElement()
{
#Override
public String toXML()
{
return xml.toString();
}
});
}
else super.send(auth);
}
};
I didn't test it, but I hope it works. authenticationId and token are your credentials.

Related

401:Authentication credentials were invalid - Invalid or expired token. code - 89

This is the code and I am recieving the error 401: Authentication Error
public class Server {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public void tweet() throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDaemonEnabled(true).setOAuthConsumerKey("......")
.setOAuthConsumerSecret("......")
.setOAuthAccessToken("......")
.setOAuthAccessTokenSecret(".....");
TwitterFactory tf = new TwitterFactory();
twitter4j.Twitter twitter = tf.getInstance();
List status = twitter.getHomeTimeline();
for (Status st : status) {
System.out.println(st.getUser().getName() + "---- Tweets----" + st.getText());
}
}
// constructor with port
public Server(int port) throws TwitterException {
// starts server and waits for a connection
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
if (line.equalsIgnoreCase("Data")) {
tweet();
}
} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) throws TwitterException {
Server server = new Server(5000);
}
}
Please make sure that the tokens are valid.
Then, you could try enabling system proxies like so:
System.setProperty("java.net.useSystemProxies", "true");

org.apache.commons.net.ftp hangs timeout

I am in trouble with org.apache.commons.net.ftp.
My client need to detect timeout when uploading (Timeout for downloads works like a charm)
if i unplugged the network cable or switch off the adsl, upload hangs and timeouts are not working. I have made several test but nothing works, it's going to make me crazy
this is my code :
public boolean uploadFile2(String localFile, String serverFile) {
try {
InputStream stO = new FileInputStream(localFile);
OutputStream stD = storeFileStream(serverFile);
setDataTimeout(dataTimeOut);
Util.copyStream(stO, stD, getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamAdapter() {
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
System.out.println("On transfert " + "/" + totalBytesTransferred + "/" + bytesTransferred + "/" + streamSize);
}
});
completePendingCommand();
} catch (Exception e) {
}
return false;
}
public boolean connectAndLogin(String host, String userName, String password) throws IOException, UnknownHostException,
FTPConnectionClosedException {
boolean success = false;
setDefaultTimeout(this.defaultTimeOut);
setConnectTimeout(this.connectionTimeOut);
addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
setPassiveMode(true);
connect(host);
int reply = getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
success = login(userName, password);
setKeepAlive(true);
setControlKeepAliveTimeout(keepAliveTimeout);
setControlKeepAliveReplyTimeout(keepAliveResponseTimeout);
setSoTimeout(soTimeOut);
setDataTimeout(dataTimeOut);
setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
setFileType(FTP.BINARY_FILE_TYPE);
}
if (!success) {
disconnect();
}
return success;
}
Any help would be appreciated, thanks
and this does not work either:
FileInputStream in = new FileInputStream(localFile);
boolean result = storeFile(serverFile, in);
in.close();
return result;

Display HTTP Request Information - BlackBerry

How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}

Critical Tunnel failure exception. How to solve this

I wrote the below code to send location coordinates to server:
setTitle("version 5.0");
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
// bc.setFailoverMode(GPSInfo.GPS_MODE_ssCDMA_MS_ASSIST, 2, 100);
try {
LocationProvider lp=LocationProvider.getInstance(criteria);
if(lp !=null)
{
Location loc=null;
// while(loc==null)
// {
loc=lp.getLocation(-1);
// }
if(loc!=null){
add(new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
}
else
add(new EditField("unable to find the location provider", ""));
}
else
{
add(new EditField("unable to find the location provider", ""));
}
} catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ButtonField b = new ButtonField("Send");
add(b);
b.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
try{
String url="http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true";
Dialog.alert(url);
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection
ConnectionDescriptor conDescriptor = factory.getConnection(url, TransportInfo.TRANSPORT_TCP_CELLULAR,null);
if ( conDescriptor != null ) {
HttpConnection conn = (HttpConnection) conDescriptor.getConnection();
Dialog.alert("http");
//conn.setRequestMethod(HttpConnection.GET);
Dialog.alert("conn.setre");
int responseCode = conn.getResponseCode();
Dialog.alert(Integer.toString(responseCode));
if(responseCode == HttpConnection.HTTP_OK)
{
Dialog.alert("OK");
InputStream data = conn.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while(nRead > 0)
{
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
}
}
}catch(Exception e){
Dialog.alert(e.getMessage());
}
}
});
I am getting an exception Critical tunnel failure. But i am able to retrieve the location coordinates correctly. I am using blackberry 8520 with airtel sim which is enabled with data services. Actually this app worked well in the mobile with version 5.0. But it's not working in the mobile which i've upgraded from 4.6.1.3 to 5.0.0 what might be the problem? Please provide me a solution. thank you
I also tried the below url's:
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=null
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=airtelgprs.com
I also enabled apn settings in my mobile
It is because you haven't set up the apn correctly. As you are using direct tcp, the apn has to be set in order to connect to the network.
Also , network connections should be done on a separate thread.

Retriving url from webservice and how to connect to that url

i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if simulator is running
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}

Resources