I am getting these error when retrieving ucoz.api.ru (oauth 1.0a) token using scribe library oauth (4.2.0) on android :
Caused by: com.github.scribejava.core.exceptions.OAuthException:
Response body is incorrect. Can't extract token and secret from this:
'{"oauth_token":"NAzoveaGm5XIlBvLcLRxUvamEK8P2.BAlQZ.M.aV","oauth_token_secret":"SJsqC0IfFAKS3BkdauQ3bY4ha01PDHTlFIy7GSro","oauth_callback_confirmed":"true"}'
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:42)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:32)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:19)
at
com.github.scribejava.core.oauth.OAuth10aService.getRequestToken(OAuth10aService.java:49)
at
com.vasyaevstropov.oauth10test.MainActivity.request(MainActivity.java:96)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:61)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:53)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
My source code:
final OAuth10aService service = new ServiceBuilder(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.debug()
.build(UcozApi.instance());
final Scanner in = new Scanner(System.in);
// Obtain the Request Token
final OAuth1RequestToken requestToken = service.getRequestToken(); // <<--- Error is in this place
System.out.println(service.getAuthorizationUrl(requestToken));
final String oauthVerifier = in.nextLine();
// Trade the Request Token and Verfier for the Access Token
OAuth1AccessToken accessToken = null;
try {
accessToken = service.getAccessToken(requestToken, oauthVerifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Ucozapi module:
public class UcozApi extends com.github.scribejava.core.builder.api.DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetrequesttoken";
private static final String ACCESS_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetaccesstoken";
protected UcozApi() {
}
private static final UcozApi INSTANCE = new UcozApi();
public static UcozApi instance() {
return INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return ACCESS_TOKEN_RESOURCE;
}
#Override
public String getRequestTokenEndpoint() {
return REQUEST_TOKEN_RESOURCE;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
Can somebody help me?
I answer my question. This code will work good with scribe-java library:
MainActivity:
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.vasyaevstropov.oauthtest.ucoz.UcozApi;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
Button button;
public WebView webView;
String verifier;
OAuth1RequestToken requestToken = null;
OAuth10aService service;
OAuth1AccessToken accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
service = new ServiceBuilder("murka1")
.apiSecret("DqUQJzeCPmwD9CRqbHo6sGBzKCb5U4")
.debug()
.build(UcozApi.instance());
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
String PROTECTED_RESOURCE_URL = "http://artmurka.com/uapi/shop/request?page=categories";
try {
requestToken = service.getRequestToken();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String url = service.getAuthorizationUrl(requestToken);
return url;
}
#Override
protected void onPostExecute(String result) {
loadURL(result);
}
}.execute();
}
});
}
public void loadURL(final String url) {
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (url.contains("oauth_verifier")) {
webView.setVisibility(webView.GONE);
Log.d("Log.d", url);
verifier = uri.getQueryParameter("oauth_verifier");
Toast.makeText(getApplicationContext(), verifier, Toast.LENGTH_SHORT).show();
getAccessToken();
}
return false;
}
});
webView.loadUrl(url);
}
private void getAccessToken() {
new AsyncTask<Void, Void, OAuth1AccessToken>() {
protected OAuth1AccessToken doInBackground(Void... params) {
try {
accessToken = service.getAccessToken(requestToken, verifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return accessToken;
}
#Override
protected void onPostExecute(OAuth1AccessToken result) {
Toast.makeText(getApplicationContext(), "Token = " + result.getToken() + "Secret = " + result.getTokenSecret(), Toast.LENGTH_LONG).show();
}
}.execute();
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
UcozApi
public class UcozApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken?oauth_token=%s";
protected UcozApi() {
}
private static class InstanceHolder {
private static final UcozApi INSTANCE = new UcozApi();
}
public static UcozApi instance() {
return InstanceHolder.INSTANCE; }
#Override
public String getAccessTokenEndpoint(){
return "http://uapi.ucoz.com/accounts/oauthgetaccesstoken"; }
#Override
public String getRequestTokenEndpoint() {
return "http://uapi.ucoz.com/accounts/oauthgetrequesttoken"; }
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken()); }
#Override
public TokenExtractor<OAuth1AccessToken> getAccessTokenExtractor() {
return OAuth1AccessUcozTokenExtractor.instance();
}
#Override
public TokenExtractor<OAuth1RequestToken> getRequestTokenExtractor() {
return OAuth1RequestUcozTokenExtractor.instance();
}
}
OAuth1RequestUcozTokenExtractor
import com.github.scribejava.core.model.OAuth1RequestToken;
public class OAuth1RequestUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1RequestToken> {
protected OAuth1RequestUcozTokenExtractor() {
}
#Override
protected OAuth1RequestToken createToken(String token, String secret, String response) {
return new OAuth1RequestToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1RequestUcozTokenExtractor INSTANCE = new OAuth1RequestUcozTokenExtractor();
}
public static OAuth1RequestUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
OAuth1AccessUcozTokenExtractor
public class OAuth1AccessUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1AccessToken> {
protected OAuth1AccessUcozTokenExtractor() {
}
#Override
protected OAuth1AccessToken createToken(String token, String secret, String response) {
return new OAuth1AccessToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1AccessUcozTokenExtractor INSTANCE = new OAuth1AccessUcozTokenExtractor();
}
public static OAuth1AccessUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
AbstractOauth1UcozTokenExtractor
public abstract class AbstractOauth1UcozTokenExtractor<T extends OAuth1Token> implements TokenExtractor<T> {
private Pattern OAUTH_TOKEN_PATTERN = Pattern.compile("\"oauth_token\"\\s*:\\s*\"(\\S*?)\"");
private Pattern OAUTH_TOKEN_SECRET_PATTERN = Pattern.compile("\"oauth_token_secret\"\\s*:\\s*\"(\\S*?)\"");
#Override
public T extract(Response response) throws IOException {
final String body = response.getBody();
Preconditions.checkEmptyString(body,
"Response body is incorrect. " + "Can't extract a token from an empty string");
final String token = extract(body, OAUTH_TOKEN_PATTERN);
final String secret = extract(body, OAUTH_TOKEN_SECRET_PATTERN);
return createToken(token, secret, body);
}
private String extract(String response, Pattern p) {
final Matcher matcher = p.matcher(response);
if (matcher.find() && matcher.groupCount() >= 1) {
return OAuthEncoder.decode(matcher.group(1));
} else {
throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '"
+ response + "'", null);
}
}
protected abstract T createToken(String token, String secret, String response);
}
Related
I know this is the answer, but I couldn't add it to my code.
How can I return value from function onResponse of Volley?
<------
like here I created interface.
I did it all.
I just don't know how to convert this my code to it, and how to use the return value in other activities.
public void priceDate(Context contex, final String coin) {
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
//String a =
//json_Parser = new JSONParser(_usd);
RequestQueue requestQueue = Volley.newRequestQueue(contex);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("Main",response.toString());}
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
try {
JSONObject Data = response.getJSONObject("Data");
JSONObject AggregatedData = Data.getJSONObject("AggregatedData");
try {
String Price = AggregatedData.getString("PRICE");
String formatPrice = formatter.format(Math.round(Float.valueOf(Price)));
_price.setText("Price :" + formatPrice);
} catch (Error e) {
_price.setText("Data Not Avvaliable");
}
try {
String Open = AggregatedData.getString("OPENDAY");
String formatOpen = formatter.format(Math.round(Float.valueOf(Open)));
_open.setText("Open :" + formatOpen);
} catch (Error e) {
_open.setText("Data Not Avvaliable");
}
try {
String Low = AggregatedData.getString("LOWDAY");
String formatLow = formatter.format(Math.round(Float.valueOf(Low)));
_low.setText("Low :" + formatLow);
} catch (Error e) {
_low.setText("Data Not Avvaliable");
}
try {
String High = AggregatedData.getString("HIGHDAY");
String formatHigh = formatter.format(Math.round(Float.valueOf(High)));
_high.setText("High :" + formatHigh);
} catch (Error e) {
_high.setText("Data Not Avvaliable");
}
try {
String Volume = AggregatedData.getString("VOLUMEDAY");
String formatVol = formatter.format(Math.round(Float.valueOf(Volume)));
_volume.setText("Volume :" + formatVol);
} catch (Error e) {
_volume.setText("Data Not Avvaliable");
}
try {
String LastUpdate = AggregatedData.getString("LASTUPDATE");
String convert = unix_time(Long.parseLong(LastUpdate));
_lastUpdate.setText("Last Update :" + LastUpdate);
} catch (Error e) {
_lastUpdate.setText("Data Not Avvaliable");
}
try {
String TradeId = AggregatedData.getString("LASTTRADEID");
_tradeId.setText("Trade Id :" + String.valueOf(Math.round(Float.parseFloat(TradeId))));
} catch (Error e) {
_tradeId.setText("Data Not Avvaliable");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
You can achieve this by using interface. Follow the below steps,
First create Interface in your application like,
public interface AsyncTaskListener {
void onRequestCompleted(JSONObject result, Integer statusCode);
}
And implement this interface in your activity where you want make request, Assume object of your volley class is objVolley, then your request will like below
public class YourActivity extends AppCompatActivity implements AsyncTaskListener {
public void priceDate(YourActivity.this, coin, YourActivity.this);
}
Then Your volley class and method like this,
public class PostDataHelper {
public void priceDate(Context contex, final String coin, final AsyncTaskListener asyncTaskListener) {
#Override
public void onResponse(JSONObject response) {
asyncTaskListener.onRequestCompleted(response, 200);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
asyncTaskListener.onRequestCompleted(response, 200);
}
});
}
}
Hope this will help you, Happy coding.
Your volley code is embedded into your activity code so there isn't much advantage to creating a interface.
You need to create a separate class for handling volley requests.
public class VolleyRequest {
VolleyCallback mResultCallback;
RequestQueue mRequestQueue;
public VolleyRequest(VolleyCallback resultCallback, Context context){
mResultCallback = resultCallback;
mRequestQueue = Volley.newRequestQueue(context);
}
public void cancelRequests(String TAG){
if(mRequestQueue != null){
mRequestQueue.cancelAll(TAG);
}
}
public void volleyGetRequest(String url, final String TAG) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (mResultCallback != null) {
mResultCallback.onSuccess(response, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mResultCallback != null) {
mResultCallback.onError(error, TAG);
}
}
});
jsonObjectRequest.setTag(TAG);
mRequestQueue.add(jsonObjectRequest);
}
}
Then create a interface class to handle the callbacks
public interface VolleyCallback {
void onSuccess(JSONObject response, String tag);
void onError(VolleyError error, String tag);
}
Then in your activity class
private void initvolley(){
VolleyCallback volleyCallback = new VolleyCallback() {
#Override
public void onSuccess(JSONObject response, String tag) {
switch (tag){
//add response handling code here
}
}
#Override
public void onError(VolleyError error, String tag) {
//handle error response here
}
};
VolleyRequest volleyRequest = new VolleyRequest(volleyCallback, this);
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
volleyRequest.volleyGetRequest(URL, request_tag/*Request tag incase you have multiple requests in same activity*/);
}
I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);
I am developing an app which would talk to the server which is developed using spring. I got to a point where we i was getting data from the google api and wanted to pass it to the spring server. But when i do pass it, the server accepts it but the data is not being stored in the mysql database.
Here is the code I am using:
This is the main spring application + controller:
#EnableJpaRepositories(basePackageClasses = StudentRepository.class)
#SpringBootApplication
public class Demo3Application {
public static void main(String[] args) {
SpringApplication.run(Demo3Application.class, args);
}
}
#RestController
class StudentController
{
#Autowired
public StudentRepository students;
#RequestMapping(value = "/getstudent", method = RequestMethod.GET)
public #ResponseBody List<Student> fetchStudents()
{
if(students.count() == 0)
{
Vector<VideoList> no_video = new Vector<VideoList>();
VideoList no_v = new VideoList("No Videos found", null, null, null);
no_video.add(no_v);
return no_video;
return null;
}
return null;
}
#RequestMapping(value = "/poststudent" , method = RequestMethod.POST)
public #ResponseBody String putStudents(#RequestBody Student v )
{
students.save(v);
return "Student Successfully Added";
}
#RequestMapping(value = "/searchstudent/{str}" , method = RequestMethod.GET)
public #ResponseBody String searchStudent(
#PathVariable("str") String searchQuery
)
{
if(students.existsByEmail(searchQuery)){
List<Student> sList = students.findEmail(searchQuery,new PageRequest(0, 1));
Student s = sList.get(0);
String str = "";
Vector<CourseList> c = s.getCourses();
Iterator<CourseList> it = c.iterator();
while(it.hasNext()){
str.concat(it.next().toString());
str.concat("\n");
}
return str;
}
return null ;
}
#RequestMapping(value = "/addcourse" , method = RequestMethod.POST)
public #ResponseBody String postCourse(#RequestParam String email, #RequestParam String course){
List<Student> sList = students.findEmail(email,new PageRequest(0, 1));
Student s = sList.get(0);
CourseList c = new CourseList();
c.setName(course);
s.addCourse(c);
students.save(s);
return null;
}
}
This is the Student class:
#Entity
#Table(name = "table1")
public class Student {
private String name;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String email;
private Vector<CourseList> courses = new Vector<CourseList>();//CourseList is just a class to store data about various courses.
public Student(){}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public Vector<CourseList> getCourses(){
return courses;
}
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public void setCourses(Vector<CourseList> courses){
this.courses = courses;
}
public void addCourse(CourseList c){
courses.add(c);
}
}
This is my repository:
#Repository
#Transactional
public interface StudentRepository extends CrudRepository<Student,String>{
#Query("SELECT s FROM Student s WHERE email = ?1")
public List<Student> findEmail(String searchQuery, Pageable pageable);
#Query("SELECT CASE WHEN COUNT(s) > 0 THEN 'true' ELSE 'false' END FROM Student s WHERE s.email = ?1")
public boolean existsByEmail(String searchQuery);
}
This is my application.properties file:
spring.datasource.url: jdbc:mysql://localhost/mydb
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.username: root
spring.datasource.password:root
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
And finally here is the android code to test the above:
public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private ImageView imgProfilePic;
private TextView txtName, txtEmail, course;
private LinearLayout llProfileLayout;
private Button SC;
private String personName;
private String personPhotoUrl;
private String personGooglePlusProfile;
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
course = (TextView) findViewById(R.id.txtCourses);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
SC=(Button)findViewById(R.id.Scourse);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
SC.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
getCourses();
SC.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
course.setText(" ");
SC.setVisibility(View.GONE);
}
}
private void getCourses(){
new StudentSearch().execute();
}
private class StudentSearch extends AsyncTask<String, Void, String >
{
String content = "";
#Override
protected String doInBackground(String... urls) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.49.8:8080/searchstudent/"+email);
StringBuffer studentString = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpget);
InputStream responseString = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseString));
String res = "";
if ((res = reader.readLine()) == null) {
studentString.append("");
HttpPost httpPost = new HttpPost("http://192.168.49.8:8080/poststudent/");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", personName);
jsonObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
try {
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
} else {
studentString.append(res);
studentString.append("\n");
while ((res = reader.readLine()) != null) {
studentString.append(res);
studentString.append("\n");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return studentString.toString();
}
#Override
protected void onPostExecute(String s) {
if (!s.isEmpty()){
course.setText("Courses Taken:\n"+s);}
else
course.setText("No Courses Taken!");
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName = currentPerson.getDisplayName();
personPhotoUrl = currentPerson.getImage().getUrl();
personGooglePlusProfile = currentPerson.getUrl();
email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.Scourse:
{
Intent intent=new Intent(MainActivity.this,SelectCourse.class);
startActivity(intent);
break;
}
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
I am a total newbie when it comes to developing spring code and would really appreciate some help.
I can parse an href url just following the documentation:
Document doc = Jsoup.connect("http://jsoup.org").get();
Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://jsoup.org/"
but i try to extract a link url from css in this webpage: http://multiplayer.it/notizie/133685-assassins-creed-unity-ecco-come-assassins-creed-unity-sfrutta-lhardware-di-nuova-generazione.html
i need take the link of image banner. The id is: id="content_heading" but the image is loaded by css.
<div id="content_heading" style="background: url(http://images.multiplayer.it/thumbs/images/2014/06/10/assassins_creed_unity_jpg_1600x0_upscale_q85.jpg) center center; background-size: cover;">
How can i extract the url? this is the Asynktask
private class ContentViewImgUrl extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
Element rootElement = doc.body().getElementById("top_ads_container");
Elements elements = rootElement.getElementsByTag("header");
for(Element element : elements){
imgUrlPost = element.select("div.content_heading").text();
}
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(SingleActivity.this, "url "+ imgUrlPost, Toast.LENGTH_SHORT).show();
}
}
The toast not works.. It returns only Url and nothing else.
Thanks
UDPATE:
private class ContentViewImgUrl extends AsyncTask<Void,Void,Void> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(Void... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
}
});
urlnew = new URL(matcher.group(1));
postBitmap = BitmapFactory.decodeStream(urlnew.openConnection().getInputStream());
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(SingleActivity.this, "url "+ urlnew, Toast.LENGTH_SHORT).show();
postImage = (ImageView) findViewById(R.id.postimage);
postImage.setImageBitmap(postBitmap);
}
}
where urlnew i declared it as public URL urlnew and postBitmap as Bitmap
SECOND UDPATE:
private class ContentViewImgUrl extends AsyncTask<Void,Void,Void> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(Void... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
if(matcher.find()){
System.out.println(matcher.group(1));
indirizzostringaimg = matcher.group(1);
imgloader = ImageLoader.getInstance();
imgloader.init(ImageLoaderConfiguration.createDefault(getActivity()));
System.out.println(urlnew);
} else {
Toast.makeText(getActivity(), "Pic url error", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(Void result) {
if(matcher.find()){
DisplayImageOptions opt = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.refresh)
.showImageForEmptyUri(R.drawable.refresh)
.cacheInMemory()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.cacheOnDisc()
.build();
imgloader.displayImage(indirizzostringaimg, postimage_main, opt);
} else {
Toast.makeText(getActivity(), "Pic url error", Toast.LENGTH_SHORT).show();
}
}
}
Here is a complete working example. Get the part that interests you.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Main {
public static void main(String[] args) {
String html = "<div id=\"content_heading\" style=\"background: url(http://images.multiplayer.it/thumbs/images/2014/06/10/assassins_creed_unity_jpg_1600x0_upscale_q85.jpg) center center; background-size: cover;\"></div>";
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
try {
Document doc = Jsoup.parse(html);
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Update
private class ContentViewImgUrl extends AsyncTask<String,String,String> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(SingleActivity.this, "url "+ imgUrlPost, Toast.LENGTH_SHORT).show();
}
}
I have an activity that creates an AsyncTask to test an ftp connection via an FTPHelper class. The Activity shows a Toast with the boolean status of the connection, either success or fail. How can I show the exact replycode or replystring in the Activity?
Activity:
TestConnection task = new TestConnection(NewSite.this,
_address, _user, _pass, p, new testConnInterface() {
#Override
public void testConnection(boolean result) {
if (result == true) {
Toast.makeText(NewSite.this,
"Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSite.this,
"Connection Failed:" + result,
Toast.LENGTH_LONG).show();
}
}
});
task.execute();
TestConection.java
public class TestConnection extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
private testConnInterface mListener;
private FTPHelper ftpHelper = new FTPHelper();
private String _address;
private String _user;
private String _pass;
private int _port;
ProgressDialog progressDialog;
public interface testConnInterface {
public void testConnection(boolean result);
}
public TestConnection(Context context, String address, String user,
String pass, int port, testConnInterface mListener) {
mContext = context;
_address = address;
_user = user;
_pass = pass;
_port = port;
this.mListener = mListener;
}
// declare other objects as per your need
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(mContext, "Please wait",
"Attempting to connect", true);
// do initialization of required objects objects here
};
#Override
protected Boolean doInBackground(Void... params) {
boolean status = ftpHelper.ftpConnect(_address, _user, _pass, _port);
return status;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (mListener != null)
mListener.testConnection(result);
progressDialog.dismiss();
};
}
FTPHelper.java
public class FTPHelper {
public static FTPClient mFTPClient = null;
public FTPHelper() {
// TODO Auto-generated constructor stub
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
/*
* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
* transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
showServerReply(mFTPClient);
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
public String ftpGetCurrentWorkingDirectory() {
try {
String workingDir = mFTPClient.printWorkingDirectory();
return workingDir;
} catch (Exception e) {
Log.i("Error working dir", e.toString());
}
return null;
}
Basically I want to know how to return the getReplyCode() to my Activity.