Android : Linkedin request token failed - linkedin

I have used the linkedin-j-android.jar of version 1.0.429 in my android project
here is the link for downloading patched linkedin-j-android.jar with scope fix
http://db.tt/yQjhqeq3
below is the code which i have used in my project:
class ShowNetWorkUtils{
public static final String CONSUMER_KEY = "xxxxx";
public static final String CONSUMER_SECRET = "yyyy";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "calback";
public String scopeParams="rw_nus+r_baseprofile";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
+ "://" + OAUTH_CALLBACK_HOST;
private void configureLinkedIn() {
new Thread(){
#Override
public void run() {
try {
Looper.prepare();
LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService (CONSUMER_KEY,CONSUMER_SECRET,scopeParams);
LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY,CONSUMER_SECRET);
LinkedInRequestToken liToken = oauthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
//LinkedInRequestToken liToken = oauthService.getOAuthRequestToken();
String url = liToken.getAuthorizationUrl();
/* For Linkedin dialog create and show */
LKDialog lkdDialog = new LKDialog(_context, url);
LKDialog lkdDialog.setDelegate(ShowNetWorkUtils.this);
LKDialog lkdDialog.show();
Looper.loop();
}
catch (Exception e) {
e.printStackTrace();
}
} //End run
}.start();
}
} //End Class
I am getting the exception when i request for the token in line "oauthService.getOAuthRequestToken(OAUTH_CALLBACK_URL)" and also i have used "oauthService.getOAuthRequestToken()" but i am getting the same exception in this case also.
The exception is :
com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: https://api.linkedin.com/uas/oauth/requestToken?scope=rw_nus+r_baseprofile
please provide me some solution to solve this..

Replace the following line in your code
public String scopeParams="rw_nus+r_baseprofile";
with
public String scopeParams="rw_nus+r_basicprofile";
Because the permission scope is r_basicprofile but you have written as r_baseprofile
Hope it will help you.

Related

how to handle http response streamly by vertx http client?

#Slf4j
public class DownloadImg {
private final WebClient webClient;
private final Vertx vertx;
public DownloadImg(Vertx vertx) {
WebClientOptions newOptions = new WebClientOptions();
newOptions.setDefaultPort(12345);
newOptions.setDefaultHost("localhost");
webClient = WebClient.create(vertx,newOptions);
this.vertx = vertx;
}
public void download(String scm, String version) {
String file = String.format("/%s_%s.tar.gz", scm.replace("/", "."), version);
webClient.get("url_for_file")
.send(it -> {
it.result();// i acully
});
}
}
I do get all the file data, but I want to handle those data by stream API in case the file is too large or OOM exception.
any idea?

'database is locked' using MobileServiceClient and MobileServiceSQLiteStore in xamarin project

I'm relatively new to mobile and async data access and I'm trying to build a line-of-business app from Xamarin starter "cross platform" template in VS2017. It seems that when I do database operations too frequently I get 'database is locked' (most questions deal with roll-your-own sqlite implementations). I had added pretty verbose logging (I have to support non-technical end mobile users).
I changed to (as suggested in other answers) a singleton model for database access which is producing non-traceable (meaning no exceptions are caught and no xamarin log entries) exceptions when calling table.ReadAsync (see below).
As a secondary question, having spent so much time on this and running into so many different roadblocks (no doubt of my own making) I'm wondering whether I'm not following some unspoken rule for mobile development such as "only one async object read per page and design UI for 100% async". Am I trying to do too much? Here is my current "singleton" data access class:
public static class MainDataStore
{
private static ReaderWriterLockSlim ReadLock = new ReaderWriterLockSlim();
public static bool IsInitialized { get; set; }
public static MobileServiceClient MobileService { get; set; }
public static bool UseAuthentication = true;
public static IMobileServiceSyncTable<User> UserTable;
public static IMobileServiceSyncTable<Showroom> ShowroomTable;
public static IEnumerable<User> Users { get; set; } //= new ObservableRangeCollection<User>();
public static IEnumerable<Showroom> Showrooms { get; set; }
public static void InitializeAsync()
{
try
{
if (IsInitialized)
return;
Logging.D("Starting to initialize main store.");
AuthenticationHandler handler = null;
handler = new AuthenticationHandler();
MobileService = new MobileServiceClient(App.AzureMobileAppUrl, handler)
{
SerializerSettings = new MobileServiceJsonSerializerSettings
{
CamelCasePropertyNames = true
}
};
var store = new MobileServiceSQLiteStore(Settings.DatabaseName);
store.DefineTable<User>();
store.DefineTable<Showroom>();
MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
UserTable = MobileService.GetSyncTable<User>();
ShowroomTable = MobileService.GetSyncTable<Showroom>();
Logging.D("Finished initializing main store.");
IsInitialized = true;
}
catch (Exception ex)
{
Logging.E(ex); // Debug.WriteLine("EXCEPTION: " + ex.Message + ". Stack: " + ex.StackTrace);
}
}
public static async void Load(ECarnavalObjectType type)
{
Logging.D("Reading lock entering. Read count: " + ReadLock.CurrentReadCount.ToString());
// ReadLock.EnterReadLock();
switch (type)
{
case ECarnavalObjectType.Users:
await GetUsersAsync();
Users = await UserTable.ToEnumerableAsync();
break;
case ECarnavalObjectType.Showrooms:
await GetShowroomsAsync();
Showrooms = await ShowroomTable.ToEnumerableAsync();
break;
}
// ReadLock.ExitReadLock();
}
public static async Task GetUsersAsync()
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
// await UserTable.ReadAsync<User>(UserTable.CreateQuery());
await UserTable.PullAsync($"all{typeof(User).Name}", UserTable.CreateQuery());
}
catch (Exception ex)
{
}
}
}
public static async Task GetShowroomsAsync()
{
await ShowroomTable.ReadAsync<Showroom>(ShowroomTable.CreateQuery());
}
}
In your code, you are not awaiting the InitializeAsync(), which means it is likely that the database is still locked and being set up when you go to synchronize it.
Arrange your code in a singleton, then have every single method (read/list/etc.) call await InitializeAsync() to initialize the database. Do an early return on the InitializeAsync() method if the database is already created (you've got some good code there for that).
For more info, see my book: https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter3/client/

how to resolve this error.....i am trying to implement custom firebase notification application

Error:(29, 44) error: cannot access AbstractSafeParcelable
class file for com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable not found
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Saving reg id to shared preferences
storeRegIdInPref(refreshedToken);
// sending reg id to your server
sendRegistrationToServer(refreshedToken);
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", refreshedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void sendRegistrationToServer(final String token) {
// sending gcm token to server
Log.e(TAG, "sendRegistrationToServer: " + token);
}
private void storeRegIdInPref(String token) {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("regId", token);
editor.commit();
}
}
In your Gradle file all the versions of google-play-service and firebase should all use the same version.
As you are using :
compile 'com.google.firebase:firebase-core:10.0.1'
You should use :
compile 'com.google.firebase:firebase-messaging:10.0.1' // and not 9.4.0
So if you are using google-play-services, please update the version to 10.0.1.

Basic Authentication with Retrofit

I am trying to build a client for a REST API using Retrofit. The API uses basic auth and I have been unable to authenticate using Retrofit.
I tested the API using the curl below and it works as expected
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{some_json}' -u api_key: https://apitest.com/api/v1/customers
Below is the Retrofit client
public interface UserService {
String HOST = "https://apitest.com";
public static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(HOST)
.addConverterFactory(GsonConverterFactory.create());
/*
* CREATE/UPDATE User
*/
#POST("api/v1/customers")
Call<UserAPIResponse> userUpdate(#Body UserUpdateRequest userUpdateRequest);
static UserService newInstance(String userAPIKey) {
String credentials = userAPIKey + ":";
final String basic = "Basic "+ Base64.encodeBase64(credentials.getBytes());
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", basic);
requestBuilder.header("Accept", "application/json");
requestBuilder.method(original.method(),original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(BlueshiftUserService.class);
}
When I call updateUser on the UserService
Response<UserAPIResponse> response = UserService.userUpdate(userUpdateRequest).execute();
The response.code is 401 (unauthorized/authentication failed)
The curl command with -u and the same credentials works as expected.
The issue was with the credentials encoding. I wasnt sending it as string.
byte[] encodedAuth= Base64.encodeBase64(credentials.getBytes());
final String basic = "Basic " + new String(encodedAuth);
use these libraries in Gradle file
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.cookpad.android.rxt4a:rxt4a:0.9.0'
compile 'io.reactivex:rxjava:1.0.12'
and put this classes in your project
public class ServiceGenerator {
private static final String TAG = erviceGenerator.class.getSimpleName();
public static final int READ_TIMEOUT = 10000;
public static final int CONNECT_TIMEOUT = 100000;
// No need to instantiate this class.
private ServiceGenerator(){}
public static <S> S createService(Class<S> serviceClass, String
endpoint) {
// Call basic auth generator method without user and pass
return createService(serviceClass, endpoint, null, null); }
public static <S> S createService(Class<S> serviceClass, String
endpoint, String username, String password) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
// Set endpoint url and use OkHTTP as HTTP client
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(endpoint)
.setConverter(new GsonConverter(new Gson()))
.setClient(new OkClient(okHttpClient));
if (username != null && password != null) {
// Concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
// Create Base64 encoded string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", string);
request.addHeader("Accept", "application/json");
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass); } }
and this interface
public class TodolyClient {
private static final String TAG = TodolyClient.class.getSimpleName();
public static final String ENDPOINT = "your base URL";
public interface TodolyService {
#GET("/wp-json/wc/v2/products")(your remaining url)
Observable<Object> isAuthenticated();
}
}
and call the below method in your main activity
private void createProject() {
final TodolyClient.TodolyService service =ServiceGenerator.createService(
TodolyClient.TodolyService.class, TodolyClient.ENDPOINT, "your user name",
"your password");
Observable<Object> observable = service.isAuthenticated();
AndroidCompositeSubscription compositeSubscription = new AndroidCompositeSubscription();
observable
.lift(new OperatorAddToCompositeSubscription<Object>(compositeSubscription))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
#Override
public void onNext(Object project) {
android.util.Log.d(TAG, "onNext: "+project.toString());
}
#Override
public void onCompleted() {
android.util.Log.d(TAG, "onNext:commm " );
}
#Override
public void onError(Throwable e) {
android.util.Log.d(TAG, "onNext: eeeeeeeee"+e.getMessage());
}
});
}
This is so far the easiest method i have ever tried for "Basic Authentication".
Use the below code to generate the auth header (API/Repository class), You can add any character set for encoding as the third parameter here.
var basic = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD")
Pass this as header to the webservice call (API/Repository class)
var retrofitCall = myWebservice.getNewsFeed(basic)
Add the basic header as parameter (Retrofit Webservice interface class)
#GET("newsfeed/daily")
fun getNewsFeed(#Header("Authorization") h1:String):Call<NewsFeedResponse>
Sorry, my code is in Kotlin, but can be easily translated to Java.
References: https://mobikul.com/basic-authentication-retrofit-android/

401 Error using Google Drive API within Google Domain from ASP.NET

I am currently trying to add functionality to our company's ASP.NET website which will allow end users to upload files generated from the website into their own Google Drive (within the same company).
The company has it's own Google Domain which includes Mail, Drive, Contacts, Calendar (and pretty much everything else). It uses SAML to authenticate with our Active Directory set up which links in to Google.
It should be noted that this code works OK with my #gmail.com account. With the companies Google App Domain account, I get the invalid credentials error (shown at the bottom). I have spoken with our Google Admin who claims that I have no restrictions on my account with regards to Drive API access. Please also bear in mind that the API ID/Secret's were created with my company account rather than a Gmail account.
using System;
using System.IO;
using System.Text;
using System.Web;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Util;
namespace GoogleTesting
{
public partial class GoogleAuth : System.Web.UI.Page
{
private static readonly string CLIENTID = "xxxxxxxxx.apps.googleusercontent.com";
private static readonly string CLIENTSECRET = "xxxxxxxxxxxxxxxxxxxxxx";
private static readonly string APIKEY = "xxxxxxxxxxx";
private static readonly string REDIRECTURI = http://localhost:61111/default.aspx";
private static readonly string[] SCOPES = new[] { DriveService.Scopes.Drive.GetStringValue() };
private static DriveService driveService;
private static OAuth2Authenticator<WebServerClient> authenticator;
private static IAuthorizationState _state;
private IAuthorizationState AuthState
{
get
{
return _state ?? HttpContext.Current.Session["GoogleAuthState"] as IAuthorizationState;
}
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
var provider = new WebServerClient(GoogleAuthenticationServer.Description, CLIENTID, CLIENTSECRET);
var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
return authenticator;
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
IAuthorizationState state = AuthState;
if (state != null)
{
if (state.AccessTokenExpirationUtc.Value.CompareTo(DateTime.Now.ToUniversalTime()) > 0)
return state;
else
state = null;
}
state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
{
if (state.RefreshToken == null)
state.RefreshToken = "";
HttpContext.Current.Session["GoogleAuthState"] = _state = state;
return state;
}
client.RequestUserAuthorization(SCOPES, "", HttpContext.Current.Request.Url);
return null;
}
protected void Page_Load(object sender, EventArgs e)
{
if(authenticator == null)
authenticator = CreateAuthenticator();
if (driveService == null)
{
driveService = new DriveService(authenticator);
driveService.Key = APIKEY;
}
//We should now be authenticated and ready to use Drive API.
UploadFile();
}
private void UploadFile()
{
Google.Apis.Drive.v2.Data.File newFile = new Google.Apis.Drive.v2.Data.File { Title = "Test File", MimeType = "text/plain" };
byte[] byteArray = Encoding.ASCII.GetBytes("Body of the document.");
MemoryStream stream = new MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = driveService.Files.Insert(newFile, stream, newFile.MimeType);
request.Convert = true;
request.Upload();
}
}
}
The problem occurs on the "request.Upload" line with the following exception.
Exception Details: System.Exception: Invalid Credentials
Source Error: Line 85: request.Upload();
Source File: C:\TMGGoogle\TMGGoogle\TMGGoogle\GoogleAuth.aspx.cs
Line: 85
Stack Trace:
[Exception: Invalid Credentials]
Google.Apis.Upload.ResumableUpload`1.Upload() +722
GoogleTesting.GoogleAuth.UploadFile()
Any help is much appreciated. Thanks.
Well, I figured out the root cause of the problem. It turns out that our company's Google Apps account had Docs API access turned off.
Our Google Apps Administrator has since turned it on and this has resolved the issue.

Resources