How to integrate oauth with gwt? - facebook

Here is my code, how do I use oauth to get the data such as user_id or first and last name of the user and sign them to fields? Should I implement them in the onSuccess method?
private void addFacebookAuth(){
loginButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(FACEBOOK_AUTH_URL, FACEBOOK_APP_ID).withScopes(
FACEBOOK_EMAIL_SCOPE,
FACEBOOK_BIRTHDAY_SCOPE,
FACEBOOK_USERID_SCOPE,
FACEBOOK_USER_LAST_NAME_SCOPE,
FACEBOOK_USER_FIRST_NAME_SCOPE).withScopeDelimiter(",");
AUTH.login(req, new Callback<String, Throwable>(){
#Override
public void onFailure(Throwable reason) {
Window.alert("Error:\n" + reason.getMessage());
}
#Override
public void onSuccess(String token) {
// Window.alert("Got an OAuth token:\n" + token + "\n"
// + "Token expires in " + AUTH.expiresIn(req) + " ms\n");
RootPanel.get().remove(loginButton);
}
});
}
});
RootPanel.get().add(loginButton);
}

Related

Background service is not working in some devices like vivo , mi etc.. after app is clear from recent app

i am use the below code to send the location to the server but it is not working in some devices after app is clear from recent app. so what is best alternate way to start service when app is closed.
public class GpsService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private LocationCallback mLocationCallback;
SharePref sharePref;
#Override
public void onCreate() {
super.onCreate();
Log.e("sevice start", ">>>>>>>>>>>>>>>>>>>>>>>>>......");
sharePref = new SharePref(GpsService.this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
Toast.makeText(getBaseContext(), locationResult.toString(), Toast.LENGTH_LONG).show();
}
}
;
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("sevice start", "mGoogleApiClient >>>>>>>>>>>>>>>>>>>>>>>>>......");
mGoogleApiClient.connect();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
//Save your location
Log.e("GpsService Location lat", "Is change " + location.getLatitude());
Log.e("Gps Location long", "Is change " + location.getLongitude());
Log.e("GpsService userid", "Enter" + sharePref.getUserId());
Toast.makeText(GpsService.this, location.toString(), Toast.LENGTH_LONG).show();
sharePref.SetLat(String.valueOf(location.getLatitude()));
sharePref.SetLong(String.valueOf(location.getLongitude()));
String lati = String.valueOf(location.getLatitude());
String longi = String.valueOf(location.getLongitude());
HashMap<String, String> param = new HashMap<>();
param.put(PARAM_USER_ID, sharePref.getUserId());
param.put(PARAM_SESSION_ID, sharePref.getSessionId());
param.put(PARAM_LAT, lati);
param.put(PARAM_LONG, longi);
param.put(PARAM_PLATFORM, PLATFORM);
BikerService.addLatLong(GpsService.this, param, new APIService.Success<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
Log.e("Location Response-->", "" + response.toString());
BikerParser.AddLatLongResponse AddLatLongResponse = BikerParser.AddLatLongResponse.addLatLongResponse(response);
if (AddLatLongResponse.getStatusCode() == API_STATUS_FOUR_ZERO_ONE) {
stopService(new Intent(GpsService.this, GpsService.class));
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.e("sevice start", "startLocationUpdates >>>>>>>>>>>>>>>>>>>>>>>>>......");
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
}

Login Issue in Amazon Mobile Hub with Cognito

I am using Mobile Hub (amazon) in my android project and for sign-in providers i am using cognito and I have their sample code which they provide and I modify the code and the Login with Facebook is working but the issue which I am facing is onSuccess method when user login successfully called twice and I debugg it but I can not Figure it out how to fix that issue.
SplashActivity.java
public class SplashActivity extends AppCompatActivity implements SignInResultHandler {
IdentityManager identityManager;
private LottieAnimationView animationView;
private static final String LOG_TAG = SplashActivity.class.getSimpleName() + " : ";
private final StartupAuthResultHandler authResultHandler = new StartupAuthResultHandler() {
#Override
public void onComplete(final StartupAuthResult authResult) {
identityManager = authResult.getIdentityManager();
if (authResult.isUserSignedIn()) {
// User has successfully signed in with an identity provider.
final IdentityProvider provider = identityManager.getCurrentIdentityProvider();
Logger.d(LOG_TAG + "Signed in with " + provider.getDisplayName());
} else if (authResult.isUserAnonymous()) {
// User has an unauthenticated anonymous (guest) identity, either because the user never previously
// signed in with any identity provider or because refreshing the provider credentials failed.
// Optionally, you can check whether refreshing a previously signed in provider failed.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
if (errors.didErrorOccurRefreshingProvider()) {
final AuthException providerAuthException = errors.getProviderRefreshException();
Logger.d(LOG_TAG + String.format(
"Credentials for Previously signed-in provider %s could not be refreshed." +
providerAuthException.getProvider().getDisplayName()) +
providerAuthException);
}
Logger.d(LOG_TAG + "Continuing with unauthenticated (guest) identity.");
} else {
// User has no identity because authentication was unsuccessful due to a failure.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
Logger.e(LOG_TAG + "No Identity could be obtained. Continuing with no identity.",
errors.getUnauthenticatedErrorException());
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
animationView = (LottieAnimationView) findViewById(R.id.animation_view);
identityManager = AWSMobileClient.defaultMobileClient().getIdentityManager();
identityManager.doStartupAuth(this, authResultHandler);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (identityManager.isUserSignedIn()) {
goMain();
} else {
goSignIn();
}
}
}, 2000);
}
#Override
public void onStart() {
super.onStart();
animationView.setProgress(0f);
animationView.playAnimation();
}
#Override
public void onStop() {
super.onStop();
animationView.cancelAnimation();
}
/**
* Go to the main activity.
*/
private void goMain() {
startActivity(new Intent(this, MainActivity.class));
}
private void goSignIn() {
identityManager.signInOrSignUp(this, this);
finish();
}
/* This method is called two times and I also search in code it inoke only one time*/
#Override
public void onSuccess(Activity callingActivity, IdentityProvider provider) {
callingActivity.finish();
if(provider != null) {
IdentityProfile identityProfile = identityManager.getIdentityProfile();
Logger.d(LOG_TAG + " Name : " + identityProfile.getUserName());
Logger.d(LOG_TAG + " Email : " + identityProfile.getUserEmailAddress());
Logger.d(LOG_TAG + " ImageLink : " + identityProfile.getUserImageUrl());
Logger.d(LOG_TAG + " provider : " + provider.getProviderType());
}
goMain();
}
/**
* User cancelled signing in with a provider on the sign-in activity.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user canceled with.
*/
public void onIntermediateProviderCancel(Activity callingActivity, IdentityProvider provider) {
Logger.d(LOG_TAG + "onIntermediateProviderCancel() called with: callingActivity = " +
"[" + callingActivity + "], provider = [" + provider + "]");
}
/**
* User encountered an error when attempting to sign-in with a provider.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user attempted to sign-in with that encountered an error.
* #param ex the exception that occurred.
*/
public void onIntermediateProviderError(Activity callingActivity, IdentityProvider provider, Exception ex) {
Logger.d(LOG_TAG + "onIntermediateProviderError() called with: callingActivity = [" + callingActivity + "], " +
"provider = [" + provider + "], errorMesage = [" + ex.getMessage() + "]");
}
#Override
public boolean onCancel(Activity callingActivity) {
return false;
}
}
SignInActivity.java
public class SignInActivity extends AppCompatActivity {
private static final String LOG_TAG = SignInActivity.class.getSimpleName() + " : ";
private SignInManager signInManager;
/**
* SignInProviderResultHandlerImpl handles the final result from sign in.
*/
private class SignInProviderResultHandlerImpl implements SignInProviderResultHandler {
/**
* Receives the successful sign-in result and starts the main activity.
*
* #param provider the identity provider used for sign-in.
*/
#Override
public void onSuccess(final IdentityProvider provider) {
Logger.d(LOG_TAG + String.format("Sign-in with %s succeeded.", provider.getDisplayName()));
// The sign-in manager is no longer needed once signed in.
SignInManager.dispose();
final IdentityManager identityManager = signInManager.getIdentityManager();
final SignInResultHandler signInResultsHandler = signInManager.getResultHandler();
// Load user name and image.
identityManager.loadUserIdentityProfile(provider, new Runnable() {
#Override
public void run() {
// Call back the results handler.
signInResultsHandler.onSuccess(SignInActivity.this, provider);
finish();
}
});
}
/**
* Receives the sign-in result indicating the user canceled and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
*/
#Override
public void onCancel(final IdentityProvider provider) {
Logger.i(LOG_TAG + String.format("Sign-in with %s canceled.", provider.getDisplayName()));
signInManager.getResultHandler().onIntermediateProviderCancel(SignInActivity.this, provider);
}
/**
* Receives the sign-in result that an error occurred signing in and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
* #param ex the exception that occurred.
*/
#Override
public void onError(final IdentityProvider provider, final Exception ex) {
Logger.d(LOG_TAG + String.format("Sign-in with %s caused an error." +
provider.getDisplayName()) + ex);
signInManager.getResultHandler().onIntermediateProviderError(SignInActivity.this, provider, ex);
}
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> readPermissions = new ArrayList<>();
readPermissions.add("public_profile");
readPermissions.add("email");
loginButton.setReadPermissions(readPermissions);
signInManager = SignInManager.getInstance();
signInManager.setProviderResultsHandler(this, new SignInProviderResultHandlerImpl());
signInManager.initializeSignInButton(IdentityProviderType.FACEBOOK, loginButton);
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String permissions[],
#NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
signInManager.handleRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
signInManager.handleActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (signInManager != null) {
if (signInManager.getResultHandler().onCancel(this)) {
super.onBackPressed();
// Since we are leaving sign-in via back, we can dispose the sign-in manager, since sign-in was cancelled.
SignInManager.dispose();
}
}
finish();
}
}

How to Fetch MUC room occupants list Inside Openfire Plugin?

I am developing a openfire plugin and stuck at one point.
Below is my plugin code. I have implemented MUCEventListener and I am getting callbacks also. But now I want to fetch occupants list from roomJID in messageReceived() method. research a lot but no success. Please someone get me break through.
public class OfflineMessageTrigger implements Plugin,
MUCEventListener {
private static final Logger Log = LoggerFactory
.getLogger(OfflineMessageTrigger.class);
public OfflineMessageTrigger() {
}
// Plugin Interface
public void initializePlugin(PluginManager manager, File pluginDirectory) {
MUCEventDispatcher.addListener(this);
}
public void destroyPlugin() {
MUCEventDispatcher.removeListener(this);
}
#Override
public void roomCreated(JID roomJID) {
Log.debug("TASOL-OfflineMessageTrigger -> MUC -> roomCreated(): "
+ "RoomID : " + roomJID);
}
#Override
public void roomDestroyed(JID roomJID) {
Log.debug("TASOL-OfflineMessageTrigger -> MUC -> roomDestroyed(): "
+ "RoomID : " + roomJID);
}
#Override
public void occupantJoined(JID roomJID, JID user, String nickname) {
Log.debug("TASOL-OfflineMessageTrigger -> MUC -> occupantJoined(): "
+ "RoomID : " + roomJID + " UserID : " + user + " NickName : "
+ nickname);
}
#Override
public void occupantLeft(JID roomJID, JID user) {
Log.debug("TASOL-OfflineMessageTrigger -> MUC -> occupantLeft(): "
+ "RoomID : " + roomJID + " UserID : " + user);
}
#Override
public void nicknameChanged(JID roomJID, JID user, String oldNickname,
String newNickname) {
}
#Override
public void messageReceived(JID roomJID, JID user, String nickname,
Message message) {
// HERE I WANT TO FETCH OCCUPANTS LIST OF "roomJID". HOW TO GET?
}
#Override
public void privateMessageRecieved(JID toJID, JID fromJID, Message message) {
}
#Override
public void roomSubjectChanged(JID roomJID, JID user, String newSubject) {
}
}
Thanks
Biraj Zalavadia.
It seems like this question was resolved on Openfire forum. So here is the link to the thread just in case someone will search for solution on Stackoverflow: https://igniterealtime.jiveon.com/thread/52016

Issue with Google Contacts API

I'm running an issue with gwt-oauth and Google contacts API.
I use gwt-oauth to login and everything works fine.
While running the RPC for retrieving the contacts I get
WARNING: Authentication error: Unable to respond to any of these challenges: {}
java.lang.NullPointerException: No authentication header information
Here is the code in Client
Button button = new Button("Authenticate with Google");
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(K.GOOGLE_AUTH_URL, K.GOOGLE_CLIENT_ID).withScopes(K.CONTACTS_SCOPE, K.AUTH_SCOPE);
AUTH.expiresIn(req);
AUTH.login(req, new Callback<String, Throwable>() {
#Override
public void onSuccess(final String token) {
greetingService.loginDetails(token, new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
greetingService.getContactList(token, new AsyncCallback<Boolean>() {
#Override
public void onSuccess(Boolean result) {
Window.alert("oh");
}
#Override
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
});
And here the serverside for contacts:
try {
ContactsService s = new ContactsService(K.APPLICATION_NAME);
s.setProtocolVersion(ContactsService.Versions.V3);
s.setAuthSubToken(token);
s.setHeader("Authorization", "Bearer " + token);
for (ContactEntry entry : s.query(new Query(new URL(K.CONTACTS_SCOPE)), ContactFeed.class).getEntries())
System.out.println(entry.toString());
} catch (Exception e) {
e.printStackTrace();
}
return true;
This was working couple of weeks ago...
I assume is not a scope issue since loginDetails works properly...
Any idea?
Solved.
Scope for contacts in Auth was set to: https://www.google.com/m8/feeds/contacts/default/full/
Apparently this doesn't work anymore and I just set https://www.google.com/m8/feeds/ for auth
and the full url for querying in ContactService

How to stop the onLocationChanged() in my LocationListener

How to stop the onLocationChanged() in my LocationListener , when i press the button ,the Toastbox in onLocationChanged keep coming out and can not stop even i leave the application.
Button btn_location =(Button) findViewById(R.id.button4);
btn_location.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
});
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
you can apply this:
mlocManager.removeUpdates(mlocListener);
to a button or put in onDestroy() or onPause()
Ref:Android Activity
The following code worked for me:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
aLocationManager.removeUpdates(aLocationListener);
}
Just call removeUpdates() method wherever you want to stop update!