Unable to Authorize LinkedIn app from Android - java

I am trying to Authorize a LinkedIn app to post status from my Android App to linkedin. But nothing comesup in my webview when I click for authorisation.
Here is my OwnAuthLinkPage.java:
public class OwnOuthLinkPage extends Activity implements SoapClient {
/** Called when the activity is first created. */
Button b;
WebView wb;
String ftoken,verifire,outh_token,verifire2,requesttokensecret,urlM,OuthT;
CookieManager cookieManager ;
public static SharedPreferences prefs;
public static Editor e;
private static final String API_KEY = "API_KEY_HERE";
//This is the private api key of our application
private static final String SECRET_KEY = "SECRET_KEY_HERE";
//This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "STATE_HERE";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases.
private static final String REDIRECT_URI = "http://smartprotech.com/1Push/WebService1.asmx";
/*********************************************/
//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/uas/oauth2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE ="code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkdin);
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
wb= (WebView)findViewById(R.id.webv);
final Activity OwnOuthLinkPage = this;
cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
String authUrl = getAuthorizationUrl();
wb.loadUrl(authUrl);
wb.setWebViewClient(new HelloWebViewClient());
wb.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
OwnOuthLinkPage.setTitle("Loading...");
OwnOuthLinkPage.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
OwnOuthLinkPage.setTitle(R.string.app_name);
}
});
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equalsIgnoreCase("http://smartprotech.com/1Push/WebService1.asmx"))
{
finish();
}
view.loadUrl(url);
try{
StringTokenizer t = new StringTokenizer(url,"=");
String s1 = t.nextToken();
String tokenHint = t.nextToken();//token
verifire = t.nextToken();//verifire
StringTokenizer t2 = new StringTokenizer(tokenHint,"&");
ftoken = t2.nextToken();
ftoken = ftoken.replace("oauth_token=","");
if(!verifire.equalsIgnoreCase("uas-continue")){
StringTokenizer cookies = new StringTokenizer(cookieManager.getCookie("http://smartprotech.com/1Push/Default.aspx"),";");
/* outh_token = cookies.nextToken();
verifire2 = cookies.nextToken();*/
requesttokensecret = cookies.nextToken();
requesttokensecret = cookies.nextToken();
requesttokensecret = requesttokensecret.replace(" TOKENSECREAT=", "");
// System.out.println("*secret**"+reqToken.replace(" requesttoken=", ""));
getToken();
}
}
catch(Exception e){}
return true;
}
}
/************************************************
* making SOAP request for getting nearby values.
************************************************/
public void getToken() {
SoapObject request = new SoapObject("http://tempuri.org/",
"getAccessTS");
request.addProperty("oauth_token", ftoken );
request.addProperty("oauth_Tokensecret",requesttokensecret );
request.addProperty("oauth_verifier",verifire);
SoapConnection connection = new SoapConnection((SoapClient) this, url,
"http://tempuri.org/getAccessTS");
connection.requestWith(request);
}
private static String getAccessTokenUrl(String authorizationToken){
return ACCESS_TOKEN_URL
+QUESTION_MARK
+GRANT_TYPE_PARAM+EQUALS+GRANT_TYPE
+AMPERSAND
+RESPONSE_TYPE_VALUE+EQUALS+authorizationToken
+AMPERSAND
+CLIENT_ID_PARAM+EQUALS+API_KEY
+AMPERSAND
+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI
+AMPERSAND
+SECRET_KEY_PARAM+EQUALS+SECRET_KEY;
}
/**
* Method that generates the url for get the authorization token from the Service
* #return Url
*/
private static String getAuthorizationUrl(){
return AUTHORIZATION_URL
+QUESTION_MARK+RESPONSE_TYPE_PARAM+EQUALS+RESPONSE_TYPE_VALUE
+AMPERSAND+CLIENT_ID_PARAM+EQUALS+API_KEY
+AMPERSAND+STATE_PARAM+EQUALS+STATE
+AMPERSAND+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI;
}
#Override
public void success(Object result) {
//SoapObject sobj = (SoapObject) result;
String accessToken,accessSecret;
StringTokenizer t2 = new StringTokenizer(result.toString(),";;");
accessToken = t2.nextToken();
accessSecret = t2.nextToken();
OwnOuthLinkPage.e = prefs.edit();
e.putString("Token", accessToken.replace("AccessToken=", ""));
e.putString("TokenSecret", accessSecret.replace("AccessTokenSecret =", ""));
e.putString("Verifire", verifire);
e.commit();
/* Intent i = new Intent(getApplicationContext(),Main.class);
startActivity(i);*/
finish();
}
#Override
public void error(Object error) {
System.out.println("*******Fail******" + error);
}
}
I am unable to solve. Please help.!

Related

Get String does not return value from the other class

So I have 4 classes
PrefUtil - Shared Preference to set and get data
public class PrefUtil {
private static final String TAG = "PrefUtil";
private SharedPreferences mSettings;
PrefUtil(SharedPreferences prefs) {
this.mSettings = prefs;
}
public String get_string(String key) {
try {
String value = this.mSettings.getString(key, null);
Log.d(TAG, String.format("get_string: %s='%s'", new Object[]{key, value}));
return value;
} catch (ClassCastException e) {
Log.d(TAG, String.format("get_string %s class cast exception", new Object[]{key}));
return "";
}
}
public void set_string(String key, String value) {
Editor editor = this.mSettings.edit();
editor.putString(key, value);
Log.d(TAG, String.format("set_string: %s='%s'", new Object[]{key, value}));
editor.apply();
}
}
OpenVPNService - uses PrefUtil to set data
private PrefUtil prefs;
prefs.set_string("payload", pl);
prefs.set_string("proxyhost", pr);
prefs.set_string("proxyport", String.valueOf(pport));
HTTPSupport - to get or fetch data
public class HTTPSupport
{
private Socket incoming;
private String netDataString;
private String[] bugHostRotate;
private String[] bugHostRotate2;
private String[] bugHostRotate3;
private int countRotate = 0;
private int countRotate2 = 0;
private int countRotate3 = 0;
private Random mRandom = new Random();
private int k = 0;
private int h = 0;
private int i = 0;
private Context mContext;
private Socket mSocket;
private PrinceUtil util;
public HTTPSupport(Socket in){
incoming = in;
}
public HTTPSupport(Context c){
mContext = c;
}
public Socket socket() {
Toast.makeText(mContext, util.getPayload(), Toast.LENGTH_LONG).show();
String trim;
Socket socket = null;
String remote = util.getProxyHost() + ":" + util.getProxyPort();
}
}
PrinceUtil - class to get data
public class PrinceUtil {
private PrefUtil prefs;
public String getPayload() {
return prefs.get_string("payload");
}
public String getProxyHost() {
return prefs.get_string("proxyhost");
}
public String getProxyPort() {
return prefs.get_string("proxyport");
}
}
The problem is that set string works it returns data when I debug it or toast it to MainActivity but in HTTPSupport when I call util.getProxyHost() it is null it doesn't return data. What I am doing wrong?
In the PrinceUtil class, the prefs field is never assigned. In Java, the default value of a reference type field is null, so attempts to call any methods on prefs will throw a NullPointerException. You can correct this by adding a constructor that allows an instance of PrefUtil to be supplied when creating an instance of PrinceUtil:
public PrinceUtil(PrefUtil prefs) {
this.prefs = prefs;
}
Note that this is similar to how PrefUtil has a constructor that accepts a SharedPreferences instance.
You'll also need to do the same for the util field in HTTPSupport. The current code includes two constructors in that class, one that sets incoming, and one that sets mContext. This means that in any instance of HTTPSupport, one of these fields will be unset, and util will always be unset. I would recommend combining these into one constructor that takes all three values:
public HTTPSupport(Socket incoming, Context mContext, PrinceUtil util){
this.incoming = incoming;
this.mContext = mContext;
this.util = util;
}
There are other unset fields in the source code provided, but they're also not used in any of the methods. I'm assuming that the code is incomplete, but these also need to be initialized before use.

Why I am getting this errors?

I am trying to access to a method named sendHttpPost(final AsyncReponseHttpSending delegate, final String urlString, final Object data), which is in another class, and this class has a private constructor. However when I get the method like HttpSending postMethod = HttpSending.sendHttpPost() and I start to pass the same parameters than in the original class I get the error "delegate is always null" , "data is always null", delegate is an instance of the AsyncResponseHttpSending interface which have only one method void onHttpResult(int httpCode, String httpMessage, String body);what am I doing wrong?
Class from where I get the method
public class HttpSending {
private static final String TAG = "HttpSending: ";
private static final int TIMEOUT_CONNECTION = (int) (30 * UnitsConstants.SECOND_TO_MILISECOND);
private static final int TIMEOUT_READ = (int) (60 * UnitsConstants.SECOND_TO_MILISECOND);
private HttpSending() {
}
public static void sendHttpPost(final AsyncReponseHttpSending delegate, final String urlString, final Object data) {
new Thread(TAG) {
#Override
public void run() {
//BUNCH OF CODE
}
}.start();
}
Class where I do my request
public class HttpPost {
AsyncReponseHttpSending delegate = new AsyncReponseHttpSending() {
#Override
public void onHttpResult(int httpCode, String httpMessage, String body) {
}
};
final String url = "https://postman-echo.com/post";
final Object data = null;
HttpSending postMethod = HttpSending.sendHttpPost(delegate,url,data );
}
This line:
HttpSending postMethod = HttpSending.sendHttpPost(delegate,url,data );
should not compile because HttpSending.sendHttpPost is a void method.
Because you never instantiate delegate that's why you get the warnings for its null.

Can't override node settings in ES integration test

I am writing an integration test for elasticsearch 5.3.
public class ProtectedWordsIndexTests extends ESIntegTestCase {
private final WordDelimiterActionListener wordsListener =
WordDelimiterActionListener.getInstance();
private final static String INDEX_NAME = "protected_words";
private final static String TYPE_NAME = "word";
private final static String FILTER_NAME = "my_word_delimiter";
#Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singleton(WordDelimiterPlugin.class);
}
#Override
protected Settings nodeSettings(int nodeOrdinal) {
return builder()
.put("plugin.types", TYPE_NAME)
.put("plugin.dynamic_word_delimiter.refresh_interval", "500ms")
.put(super.nodeSettings(nodeOrdinal))
.build();
}
public void testAddWordToIndex() throws Exception {
Settings indexSettings = builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put("index.analysis.filter.my_word_delimiter.type", "dynamic_word_delimiter")
.build();
TokenFilterFactory filterFactory = filterFactory(indexSettings, FILTER_NAME);
createIndex(INDEX_NAME);
ensureGreen();
client().prepareIndex(INDEX_NAME, TYPE_NAME, "1")
.setSource("word", "1tb")
.execute();
Thread.sleep(TimeValue.timeValueSeconds(1).getMillis());
Set<String> protectedWords = wordsListener.getProtectedWords();
assertTrue(protectedWords.size() == 1);
}
}
When I am running testAddWordToIndex() I am getting the following error:
"java.lang.IllegalArgumentException: unknown setting
[plugin.dynamic_word_delimiter.refresh_interval] please check that any
required plugins are installed, or check the breaking changes
documentation for removed settings"
If I remove the following part and increase the refresh interval to be more than the default, the test passes. So I just can't override this.
.put("plugin.dynamic_word_delimiter.refresh_interval", "500ms")
The default refresh interval is declared here:
public class WordDelimiterRunnable extends AbstractRunnable {
public static final TimeValue REFRESH_INTERVAL = TimeValue.timeValueSeconds(20);
public static final String INDEX_NAME = "protected_words";
public static final String INDEX_TYPE = "word";
public static final int RESULTS_SIZE = 10000;
private volatile boolean running;
private final Client client;
private final String index;
private final long interval;
private final String type;
public WordDelimiterRunnable(Client client, Settings settings) {
this.client = client;
this.index = settings.get("plugin.dynamic_word_delimiter.protected_words_index", INDEX_NAME);
this.type = settings.get("plugin.dynamic_word_delimiter.protected_words_type", INDEX_TYPE);
this.interval = settings.getAsTime("plugin.dynamic_word_delimiter.refresh_interval", REFRESH_INTERVAL).getMillis();
}
// more code here
}
You need to register the setting using the SettingsModule#registerSettings(Setting) method as explain here:
https://www.elastic.co/guide/en/elasticsearch/reference/5.x/breaking_50_settings_changes.html#breaking_50_settings_changes

How to make a network call in Android without using an async call?

There is some gaps in android that I do not understand. There is a file I would like to make a network call in. I keep getting an error when I don't make a network call in either a activity or fragment.
public class Attraction {
public String name;
public String description;
public String longDescription;
public Uri imageUrl;
public Uri secondaryImageUrl;
public LatLng location;
public String city;
public Bitmap image;
public Bitmap secondaryImage;
public String distance;
public Attraction() {}
public Attraction(String name, String description, String longDescription, Uri imageUrl,
Uri secondaryImageUrl, LatLng location, String city) {
//I am looking to replace these variables with information from a website
this.name = "Hey";//name;
this.description = description;
this.longDescription = longDescription;
this.imageUrl = imageUrl;
this.secondaryImageUrl = secondaryImageUrl;
this.location = location;
this.city = city;
}
}
EVEN Better if I can make the network call here:
public class TouristAttractions extends Main2Activity{
public static final String CITY_SYDNEY = "Sydney";
public static final String TEST_CITY = CITY_SYDNEY;
private static final float TRIGGER_RADIUS = 2000; // 2KM
private static final int TRIGGER_TRANSITION = Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT;
private static final long EXPIRATION_DURATION = Geofence.NEVER_EXPIRE;
public static final Map<String, LatLng> CITY_LOCATIONS = new HashMap<String, LatLng>() {{
put(CITY_SYDNEY, new LatLng(-33.873651, 151.2068896));
}};
/**
* All photos used with permission under the Creative Commons Attribution-ShareAlike License.
*/
public static final HashMap<String, List<Attraction>> ATTRACTIONS =
new HashMap<String, List<Attraction>>() {{
//It would be perfect if I can make the network call here
put(CITY_SYDNEY, new ArrayList<Attraction>() {{
add(new Attraction(
"France",
"Lovely place",
"You should go",
Uri.parse("http://....png"),
Uri.parse("http://.....png"),
new LatLng(-33.858667, 151.214028),
CITY_SYDNEY
));
}});
}};
/**
* Creates a list of geofences based on the city locations
*/
public static List<Geofence> getGeofenceList() {
List<Geofence> geofenceList = new ArrayList<Geofence>();
for (String city : CITY_LOCATIONS.keySet()) {
LatLng cityLatLng = CITY_LOCATIONS.get(city);
geofenceList.add(new Geofence.Builder()
.setCircularRegion(cityLatLng.latitude, cityLatLng.longitude, TRIGGER_RADIUS)
.setRequestId(city)
.setTransitionTypes(TRIGGER_TRANSITION)
.setExpirationDuration(EXPIRATION_DURATION)
.build());
}
return geofenceList;
}
public static String getClosestCity(LatLng curLatLng) {
if (curLatLng == null) {
// If location is unknown return test city so some data is shown
return TEST_CITY;
}
double minDistance = 0;
String closestCity = null;
for (Map.Entry<String, LatLng> entry: CITY_LOCATIONS.entrySet()) {
double distance = SphericalUtil.computeDistanceBetween(curLatLng, entry.getValue());
if (minDistance == 0 || distance < minDistance) {
minDistance = distance;
closestCity = entry.getKey();
}
}
return closestCity;
}
}
Simply, you cannot make network operations on UI thread. Why would you like to do it anyway? Network call will block UI message loop - possibly for serveral seconds - this will quickly cause ANR error. There are various APIs that make network operations very easy, ie. OkHTTP.
//It would be perfect if I can make the network call here
then you will have to split this part in async operation, this will require restructuring your code - there is no way around.

How to get AutoCompleteTextField to accept a substring

I can generate a list of strings used to select an item using AutoCompleteTextField but it puts the entire string in the edit control. I would like it to just insert the 'name' string.
Should I create a Model that contains the name string and the rendered string?
Which functions should I override to get the required string, to get a value or to handle the click?
private Model<String> groupToJoinModel = new Model<String>();
final AutoCompleteTextField<String> field = new AutoCompleteTextField<String>("ac", new Model<String>(""))
{
private static final long serialVersionUID = 1L;
#Override
protected Iterator<String> getChoices(String input)
{
List<String> choices = new ArrayList<String>(5);
// from a database: generate lookup items
// by concatenating strings: name, type, description
// code omitted
return choices.iterator();
}
};
form.add(field);
groupToJoinModel = (Model<String>) field.getDefaultModel();
// Create a button to perform an action
Button joinGroupsButton = new Button("joinGroupButton")
{
private static final long serialVersionUID = -4974389888115885756L;
#Override
public void onSubmit()
{
if (groupToJoinModel.getObject() != null)
{
// An action is performed on the contents of the edit control
}
}
};
form.add(joinGroupsButton);
You can use AbstarctAutoCompleteRenderer.
AbstractAutoCompleteRenderer<String> autoCompleteRenderer = new AbstractAutoCompleteRenderer<String>() {
private static final long serialVersionUID = 1L;
protected final String getTextValue(final String bean) {
String name;
// Do you logic to extract the name from the bean
...
...
...
return name;
}
#Override
protected final void renderChoice(final String object, final Response response, final String criteria) {
response.write(getTextValue(object));
}
};
final AutoCompleteTextField<String> autoComp = new AutoCompleteTextField<String>("item", new PropertyModel(str, "item"),
autoCompleteRenderer) {
private static final long serialVersionUID = 1L;
#Override
protected Iterator<String> getChoices(String arg0) {
// Your logic
...
...
...
return filteredList.iterator();
}
};
The renderer is passed in the Auto complete constructor.

Categories

Resources