I am trying to register a new user using my XMPP client using asmack library in Android on ejabberd server. The problem is that I am getting following error & the user is not being created on the server:
bad-request(400)
at org.jivesoftware.smack.AccountManager.createAccount(AccountManager.java:243)
at in.ui.MainActivity$1$1$1.run(MainActivity.java:316)
at java.lang.Thread.run(Thread.java:841)
Following is the code:
_xmppUsername = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_ID);
_xmppPassword = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_PASSWORD);
_xmppHost = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_HOST);
try {
_xmppPortNo = Integer.parseInt (XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_PORT));
} catch (Exception e) {
e.printStackTrace ();
Log.e (TAG, e.getMessage ());
}
_xmppServiceName = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_SERVICE_NAME);
ConnectionConfiguration conConfig = new ConnectionConfiguration (_xmppHost, _xmppPortNo, _xmppServiceName);
_xmppConnection = new XMPPConnection (conConfig);
if (!_xmppConnection.isAuthenticated ()) {
login ();
}
/*
* If connection has not been established or had been established &
* broken again then login
*/
#Override
public void onShow (final DialogInterface dialog) {
Button positiveButton = _dlgRegistration.getButton (DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
// Creating registration thread
new Thread (new Runnable () {
#Override
public void run () {
String clientID = null;
String password = null;
clientID = "user" + XMPP_SERVICE_NAME;
try {
// Getting hash password from UUID
password = "password";
Log.i (TAG, clientID + password);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace ();
}
}
AccountManager manager = _xmppConnection.getAccountManager ();
try {
// Creating account on the server
manager.createAccount (clientID, password, attr);
}
} catch (XMPPException e) {
e.printStackTrace ();
}
}
}).start ();
}
});
The problem was this line clientID = "user" + XMPP_SERVICE_NAME; where I shouldn't have been appending Domain or Service Name after "user".
Related
I want to wait for the completion of a sub-thread to determine the login status. But I'm not familiar with how to write internal classes, so I'd like to ask how to write code to wait for a child thread to finish execution in the login function.
public class LoginDataSource {
static LoggedInUser loggedUser = new LoggedInUser();
public Result<LoggedInUser> login(String username, String password) {
try {
// TODO: handle loggedInUser authentication
loginMyBlog(username, password, loggedUser);
if (loggedUser.isLogStatue()) {
return new Result.Success<>(loggedUser);
} else {
return new Result.Failed("pass incorrect");
}
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
public void logout() {
// TODO: revoke authentication
}
private void loginMyBlog(String usernames, String passwords, LoggedInUser userAuth) {
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
// Code for sending network requests
//...
//Code to determine if the login is successful
try {
Response response = client.newCall(request).execute();
final String responseData = response.body().string();
JSONObject jsonObject = JSONObject
.parseObject(responseData);
String code = jsonObject.getString("code");
if (code.equals("20000")){
// login success
JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
userAuth.setId(dataObject.getInteger("id"));
userAuth.setIntro(dataObject.getString("intro"));
userAuth.setLogStatue(true);
Log.d("test", "登录成功"+userAuth);
}else if (code.equals("51000")){
// login failed
userAuth.setLogStatue(false);
}
} catch (IOException e) {
e.printStackTrace();
// network err
}
}
}).start();
}
}
Thanks.
private void setOauthParameter() {
GoogleOAuthParameters oauthParam = new GoogleOAuthParameters();
oauthParam.setOAuthConsumerKey(ClientId);
oauthParam.setOAuthConsumerSecret(ClientSecrate);
oauthParam.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
// Init the service and set the auth
service = new ContactsService("chat.com.contactssharing");
try {
service.setOAuthCredentials(oauthParam, new OAuthHmacSha1Signer());
service.getRequestFactory().setHeader("User-Agent", "chat.com.contactssharing");
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void queryEntries() throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
myQuery.setStringCustomParameter("sortorder", "ascending");
try {
// Execution of this line i'm getting an exception
ContactFeed resultFeed = (ContactFeed) this.service.query(myQuery, ContactFeed.class);
Log.d(TAG, resultFeed.toString());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
} catch (Exception ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
My objective to get the friends contacts list from gmail and i have check no's of post for this Exception but no one is commented by correct solution.It's become blocker for me so please help me to out this problem and guide what is doing wrong at above code.
I have the following TestHub class in my server.
public class TestHub:Hub {
public override Task OnConnected() {
//do some work here
return base.OnConnected();
}
}
and my android client uses the following code to start negotiating with server.
//set serverUrl, device_id, logger, serverHub
Platform.loadPlatformComponent(new AndroidPlatformComponent());
HubConnection connection = new HubConnection(serverUrl, "device_id="+device_id, false, logger);
HubProxy proxy = connection.createHubProxy(serverHub);
proxy.subscribe(this);
proxy.on("test", new SubscriptionHandler1<String>() {
#Override
public void run(String x) {
System.out.println(x);
}
}, String.class);
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I'm trying to do some work in server OnConnected() method but it won't hit. i have signalr connection successfully but i want to do some stuff in OnConnected() method. what should i do?
Ok, I give up. Anyone have experience using Google's IssueAuthToken and MergeSession to authenticate with certain Google services that do not have official API access? In this case I'm trying to get Google bookmarks (from google.com/bookmarks).
I get the SID and LSID using getAuthToken and that works fine. I then call
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://accounts.google.com/IssueAuthToken?service=bookmarks&Session=false");
String url = ISSUE_AUTH_TOKEN_URL.buildUpon()
.appendQueryParameter("SID", sid)
.appendQueryParameter("LSID", lsid)
.build().toString();
I receive the "ubertoken".
I then do a GET to MergeSession and that's where it all goes wrong:
String url2 = "https://accounts.google.com/MergeSession?source=chrome&uberauth="+uberToken+"&service=bookmarks&continue=https%3A%2F%2Fwww.google.com%2Fbookmarks%2F";
HttpGet getCookies = new HttpGet(url2);
Looking through the headers of getCookies I am not seeing the extra cookies I should see, and I also see things like X-Frame-Options: DENY.
Help (please)!
Okay friends, here we go. It seems the above is now unreliable/broken at least occasionally as of August 2013. This is how I'm doing it now and it seems to work. It tries the above first, and if it fails, goes on to method #2.
final Account acct = am.getAccountsByType("com.google")[acctid];
final String tokenType = "weblogin:service=bookmarks&continue=https://www.google.com/bookmarks/";
am.getAuthToken(acct, tokenType, null, this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
final String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
if (accessToken.contains("WILL_NOT_SIGN_IN")) {
am.getAuthToken(acct, "SID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
sid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
am.getAuthToken(acct, "LSID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
lsid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
try {
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false");
Uri TOKEN_AUTH_URL = Uri.parse("https://www.google.com/accounts/TokenAuth");
final HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
String url = ISSUE_AUTH_TOKEN_URL.buildUpon().appendQueryParameter("SID", sid).appendQueryParameter("LSID", lsid).build().toString();
HttpPost getUberToken = new HttpPost(url);
HttpResponse response = httpclient.execute(getUberToken);
String uberToken = EntityUtils.toString(response.getEntity(), "UTF-8");
final String accessToken2 = TOKEN_AUTH_URL.buildUpon()
.appendQueryParameter("source", "android-browser")
.appendQueryParameter("auth", uberToken)
.appendQueryParameter("continue", "https://www.google.com/bookmarks/").build().toString();
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}, null);
}
}, null);
} else {
//do stuff
}
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
finish();
}
}
}, null);
Currently i need to make an application that can list all of Google Drive file.
i already did the account choosing and oauth process, an already get the token. but when i try to use API call to list all my file on Google Drive (By using drive.files.list) i didn't get any result, the arraylist of files which is supposed to hold all the file is still empty. i also got error :
java.net.unknownHostException www.googleapis.com cannot be resolved
this is my code :
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", got.name);
editor.commit();
account=got;
amf=accMgr.getAuthToken(account, authTokenType, true,
new AccountManagerCallback<Bundle>(){
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle result;
Intent i;
String token;
Drive a;
result = arg0.getResult();
if (result.containsKey(accMgr.KEY_INTENT)) {
i = (Intent)result.get(accMgr.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
}
else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(result
.getString(accMgr.KEY_AUTHTOKEN));
buildService(result
.getString(accMgr.KEY_AUTHTOKEN),API_KEY);
/*else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/
/*
* work with token
*/
// Remember to invalidate the token if the web service rejects it
// if(response.isTokenInvalid()){
// accMgr.invalidateAuthToken(authTokenType, token);
// }
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, handler);
}
private void buildService(final String authToken, final String ApiKey) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(ApiKey);
driveRequest.setOauthToken(authToken);
}
});
System.out.println(authToken);
service= b.build();
List<File> a=new ArrayList<File>();
try {
a = retrieveDriveFile(service);
System.out.println(a.size());
File c=a.get(0);
TextView ad=(TextView) findViewById(R.id.test);
ad.setText(c.getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> retrieveDriveFile(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error ssoccurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
This would typically happen if you don't have a working internet connection on your device.
Also don't forget to add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
This could happen also if you are behind a proxy. If that's the case please have a look at this question.
If you want to get all the file from Goolge Drive. Assume that you have already done the Account Choosing process and creating Drive (Drive mService) etc.
Now Under Button Click Event call this function
ButtonClickEvent
{
GetDriveData();
}
// FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
private void GetDriveData()
{
private List<File> mResultList;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.List request = null;
do
{
try
{
request = f1.list();
request.setQ("trashed=false");
com.google.api.services.drive.model.FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();//Calling to Populate Data to the List
}
});
t.start();
}
//Populating Retrieved data to List
private void populateListView()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mFileArray = new String[mResultList.size()];
int i = 0;
for(File tmp : mResultList)
{
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
button2.setText("yes");
}
});
}