Related
I need to send a json code, via the get method.
I tried to send through a JsonObjectRequest with the method, url and the parameters, the response was null and the json was not sent.
JSONObject request = new JSONObject();
try {
request.put("CodigoInicial", "1");
request.put("CodigoFinal", "2");
;
} catch (JSONException e) {
e.printStackTrace();
}
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, url2,request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d(TAG, response.toString() + " i am queen");
try {
JSONArray jsonArray = response.getJSONArray("LinhasClientes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
int codigo = employee.getInt("Codigo");
String Nome = employee.getString("Nome");
String NumContrib = employee.getString("NumContrib");
//textView.append(Nome + ", " + String.valueOf(codigo) + ", " + NumContrib + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
response.toString()+"i am queen", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("CodigoInicial","1");
headers.put("C`enter code here`odigoFinal","2");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
The problem is the implementation of the createHttpRequest method in com.android.volley.toolbox.HttpClientStack.java which will add the body only if the request method is POST, PUT or PATCH.
/**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
#SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST: {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Method.HEAD:
return new HttpHead(request.getUrl());
case Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Method.TRACE:
return new HttpTrace(request.getUrl());
case Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
So you have to use your own implementation of HttpStack.java or you override HttpClientStack class.
First of all your should replace your initialization of RequestQueue from
RequestQueue requestQueue = Volley.newRequestQueue(sContext);
to
String userAgent = "volley/0";
try {
String packageName = getContext().getPackageName();
PackageInfo info = getContext().getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException e) {}
HttpStack httpStack = new OwnHttpClientStack(AndroidHttpClient.newInstance(userAgent));
RequestQueue requesQueue = Volley.newRequestQueue(sContext, httpStack);
and write your own implementation of HttpClientStack where you change the case of "Method.POST:" in the method createHttpRequest(). You also have to create an Object like "OwnHttpDelete" as extention of HttpEntityEnclosingRequestBase to use the method setEntityIfNonEmptyBody().
public class OwnHttpClientStack extends com.android.volley.toolbox.HttpClientStack {
private final static String HEADER_CONTENT_TYPE = "Content-Type";
public OwnHttpClientStack(HttpClient client) {
super(client);
}
#Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
}
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
}
static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Request.Method.DEPRECATED_GET_OR_POST: {
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Request.Method.GET:
return new HttpGet(request.getUrl());
case Request.Method.DELETE:
OwnHttpDelete deleteRequest = new OwnHttpDelete(request.getUrl());
deleteRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(deleteRequest, request);
return deleteRequest;
case Request.Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Request.Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Request.Method.HEAD:
return new HttpHead(request.getUrl());
case Request.Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Request.Method.TRACE:
return new HttpTrace(request.getUrl());
case Request.Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static class OwnHttpDelete extends HttpPost {
public static final String METHOD_NAME = "DELETE";
public OwnHttpDelete() {
super();
}
public OwnHttpDelete(URI uri) {
super(uri);
}
public OwnHttpDelete(String uri) {
super(uri);
}
public String getMethod() {
return METHOD_NAME;
}
}
}
Special characters such as (“ ”,') gets converted into ? while applying
interceptor in retrofit2.While getting response from retrofit2 , i am getting special characters but the interceptor changes the special character to ? and displays ? instead of special characters
Adding retrofit in Interceptor:
CustomRequestInterceptor requestInterceptor = newCustomRequestInterceptor();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY :
HttpLoggingInterceptor.Level.NONE);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(requestInterceptor);
httpClient.addInterceptor(logging);
Interceptor class(CustomRequestInterceptor.java) for retrofit2:
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
Log.i(TAG, "Response edited: " + URLDecoder.decode(newResponseString));
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
byte[] ptext = res_JsonObject.toString().getBytes(ISO_8859_1);
String value = new String(ptext, UTF_16);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), value))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
Expected output:
{
"comment": "“hello”"
}
Actual output:
{
"comment": "?hello?"
}
The problem is in the return statement of intercept method,
when we call ResponseBody.create(), the responsebody class converts data to UTF-8 format and UTF-8 does not support characters like (“,”) so it gives us "?" sign because we have given response.body().contentType(), so it converts to UTF-8 which is default.
The solution is to not to pass response.body().contentType() to create() and give our own contentType.
Here is the updated class.
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
MediaType contentType = MediaType.parse(response.body().contentType() + "; charset=utf-32");
return response.newBuilder()
.body(ResponseBody.create(contentType, newResponseString.getBytes()))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
I am a beginner in this, i am facing an issue while invoking asp.net web service method (SignUp) from android. It works fine when i try it from browser but when i do it from the android it gives me some exception like
"
SoapFault - faultcode: 'soap:Client' faultstring: 'System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: SignUp.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)' faultactor: 'null' detail: org.kxml2.kdom."
This is my Java Signup class
String SOAP_ACTION1 = "http://tempuri.org/SignUp";
String METHOD_NAME1 = "SignUp";
btn = (Button)findViewById(R.id.btn_signup);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new WebService().execute(METHOD_NAME1,SOAP_ACTION1,txt_name.getText().toString(), txt_email.getText().toString(),txt_password.getText().toString(),
txt_address.getText().toString(),
txt_dob.getText().toString(),
txt_account.getText().toString(),
txt_cnic.getText().toString(),txt_pobox.getText().toString(),
txt_city.getText().toString(),txt_status.getText().toString());
This is My Java WebService Class
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://192.168.0.102/MyWebService/WebService1.asmx?WSDL";
protected String doInBackground(String... params) {
String s="";
String whichmethodcall = params[0];
switch(whichmethodcall){
case "SignUp":
s = signup(params);
break;
case "SignIn":
s = signin(params);
break;
}
return s;
}
public String signup(String[] arr){
String s = "";
SoapObject request = new SoapObject(NAMESPACE, arr[1]);
//Use this to add parameters
request.addProperty("cname",arr[2]);
request.addProperty("cemail",arr[3]);
request.addProperty("cpwd",arr[4]);
request.addProperty("caddress",arr[5]);
request.addProperty("cdob",arr[6]);
request.addProperty("caccount",arr[7]);
request.addProperty("cCnic",arr[8]);
request.addProperty("cpobox",arr[9]);
request.addProperty("cCity",arr[10]);
request.addProperty("cstatus",arr[11]);
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(arr[0], envelope);
// Get the SoapResult from the envelope body.
// SoapObject result = (SoapObject)envelope.bodyIn;
// SoapObject result = (SoapObject) envelope.getResponse();
if (envelope.bodyIn instanceof SoapFault) {
final SoapFault result = (SoapFault) envelope.bodyIn;
if (result != null) {
//Get the first property and change the label text
s = result.toString();
} else
s = "No response";
}
} catch (Exception e) {
e.printStackTrace();
s=e.getMessage().toString();
}
return s;
}
And This is My asp.net WebService method
public string SignUp(string cname, string caddress, string cdob, long caccount, long cCnic, int cpobox, string cCity, string cstatus,string cemail, string cpass)
{
bool check = ConnectDB(); // Opens the Connection to Insert The new User
string msg = "";
//DateTime dob = DateTime.ParseExact(cdob, "dd/mm/yyyy", null);
string query = "INSERT INTO Customers values('" + cname + "','" + caddress + "','" + cdob + "','" + caccount + "','" + cCnic + "','" + cpobox + "','" + cCity + "','" + cstatus + "','"+ cemail + "','"+ cpass + "')";
SqlCommand comm = new SqlCommand(query, con);
try{
if (check == true){
if (comm.ExecuteNonQuery() > 0)
msg = "you've signed up !";
else
msg = "sign up error";
}
else
msg = "Database not Connected";
}catch (SqlException ex){
msg = ex.Message.ToString();
con.Close();
}finally{
con.Close();
}
return msg;
}
Can you try this
instead of SoapObject request = new SoapObject(NAMESPACE, arr[1]);
use
SoapObject request = new SoapObject(NAMESPACE, arr[0]);
In the soap object you should pass just method name, without http://...
Im getting a not so rare error, which happens to many, the thing is that im not using threads in my app. Its just a loop, one task after the other, so i dont understand why im getting out of threads.
Basically for each line of the text file i make a GET request to an api, so i obtain some json data...
Here is the error log:
106
105
104
103
102
ene 06, 2016 4:08:39 PM org.jboss.netty.channel.DefaultChannelFuture
ADVERTENCIA: An exception was thrown by ChannelFutureListener.
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:306)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:290)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioChannelSink.execute(AbstractNioChannelSink.java:34)
at org.jboss.netty.channel.Channels.fireExceptionCaughtLater(Channels.java:504)
at org.jboss.netty.channel.AbstractChannelSink.exceptionCaught(AbstractChannelSink.java:47)
at org.jboss.netty.channel.Channels.close(Channels.java:821)
at org.jboss.netty.channel.AbstractChannel.close(AbstractChannel.java:194)
at org.jboss.netty.channel.ChannelFutureListener$2.operationComplete(ChannelFutureListener.java:52)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:385)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
ERROR en getML():/orders/1045232034
com.mercadolibre.sdk.MeliException: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.nubimedia.app.ml.Melis.get(Melis.java:264)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
Caused by: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyResponseFuture.abort(NettyResponseFuture.java:297)
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:104)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:390)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:100)
... 10 more
Caused by: java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.register(AbstractNioWorker.java:131)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:401)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
... 3 more
Hubo un error
101
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:159)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:121)
at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:512)
at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.execute(AsyncHttpClient.java:234)
at com.nubimedia.app.ml.Melis.get(Melis.java:262)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
And here is the code:
public static void main(String[] args) throws IOException, MeliException {
ModelML.getInstance().encontrarMailsLog(731);
}
public void encontrarMailsLog(int max) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("/Users/fabrizioguespe/Downloads/catalina.out"));
Set<String> resources=new TreeSet<String>();
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if(line.equals("Nueva Request!")){
String cliente=br.readLine();
String resource=br.readLine();
resources.add(cliente+"-"+resource);
}
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
} finally {
br.close();
}
Log.log(resources.size()+" Para procesar");
int i=resources.size();
for(String s: resources){
i--;
Log.log(i+"");
if(max>0)
if(i>max)continue;
String cliente=s.split("-")[0];
String resource=s.split("-")[1];
//Log.log("Cliente: "+cliente+" "+resource);
ModelML.getInstance().procesarRequest(Melis.getML(resource, null,cliente,false),resource);
}
}
UPDATED: As suggested, and makes sense. I may be doing async request, using the SDK provided by the API
Here is the class
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.MeliException;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;
import com.nubimedia.app.ModelML;
import com.nubimedia.app.util.HibernateUtil;
import com.nubimedia.app.util.Log;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class Melis {
public static String apiUrl = "https://api.mercadolibre.com";
private String accessToken;
private String refreshToken;
private Long clientId;
private String clientSecret;
//public static Map<String,UserML> clientes=new HashMap<String,UserML>();
public static UserML getCliente(String id) {//Solo para inicializar la aplicacion
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML where id = :id");
query.setString("id", id);
UserML q = (UserML) query.uniqueResult();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static List<UserML> getClientes() {
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML");
#SuppressWarnings("unchecked")
List<UserML> q = (List<UserML>) query.list();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static String preguntarML(String item,String pregunta,String idcliente){
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getToken());
String params="{\"text\":\""+pregunta.trim()+"\",\"item_id\":\""+item+"\"}";
String json=Melis.postML("/questions/"+item+"?access_token="+m.getAccessToken(), null, cliente, params);
return json;
}
public static String postML(String resource,FluentStringsMap params,UserML cliente,String json){
try {
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
Response respuesta = m.post(resource, params,json);
String jsons=respuesta.getResponseBody();
//jsons=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return jsons;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
public static String getUserId(String json){
try{
JsonParser parser = new JsonParser();
JsonObject venta= (JsonObject)parser.parse(json);
if(venta.isJsonNull())return null;
return venta.get("id").getAsString();
}catch(Exception e){
e.printStackTrace();
Log.log("ERROR al parsear json VENTA mercadolibre: ");
}
return null;
}
public static String setToken(String token,String refresh_token,String idcliente) {
UserML a=getCliente(idcliente);
if(a==null)return null;
a.setToken(token);
a.setRefresh_token(refresh_token);
a.setLast_modif(new Date());
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
s.saveOrUpdate(a);
s.flush();
s.getTransaction().commit();
s.close();
return null;
}
public static String getML2(String resource){
Client client = Client.create();
WebResource webResource = client.resource(apiUrl+resource);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200)
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
return response.getEntity(String.class);
}
public static String remokeAccess(String idcliente){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
String resource="/users/"+cliente+"/applications/"+ModelML.ml_appid+"?access_token="+cliente.getToken();
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken());
FluentStringsMap params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
Response respuesta = m.delete(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en removkeAccess():"+idcliente);
e.printStackTrace();
}
return null;
}
public static String getML(String resource,FluentStringsMap params,String idcliente,boolean access_final){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
if(access_final)resource+="?access_token="+cliente.getToken();
Response respuesta = m.get(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
private AsyncHttpClient http;
{
AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
.setUserAgent("MELIJAVASDK0.0.1").build();
http = new AsyncHttpClient(cf);
}
public Melis(Long clientId, String clientSecret ) {
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken, String refreshToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.refreshToken = refreshToken;
}
public String getAccessToken() {
return this.accessToken;
}
public Response get(String path) throws MeliException {
return get(path, new FluentStringsMap());
}
private BoundRequestBuilder prepareGet(String path, FluentStringsMap params) {
return http.prepareGet(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder prepareDelete(String path,
FluentStringsMap params) {
return http.prepareDelete(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder preparePost(String path,
FluentStringsMap params, String body) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePut(String path,
FluentStringsMap params, String body) {
return http.preparePut(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePost(String path, FluentStringsMap params) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
public Response get(String path, FluentStringsMap params) throws MeliException {
BoundRequestBuilder r = prepareGet(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
Log.log("ERROR al refrescar token");
return response;
}
params.replace("access_token", this.accessToken);
r = prepareGet(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public void refreshAccessToken() throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "refresh_token");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("refresh_token", this.refreshToken);
BoundRequestBuilder req = preparePost("/oauth/token", params);
parseToken(req);
}
public String getAuthUrl(String callback) {
try {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId
+ "&redirect_uri="
+ URLEncoder.encode(callback, "UTF8");
} catch (UnsupportedEncodingException e) {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId + "&redirect_uri=" + callback;
}
}
public String authorize(String code, String redirectUri) throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "authorization_code");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("code", code);
params.add("redirect_uri", redirectUri);
BoundRequestBuilder r = preparePost("/oauth/token", params);
return parseToken(r);
}
private String parseToken(BoundRequestBuilder r) throws AuthorizationFailure {
Response response = null;
String responseBody = "";
try {
response = r.execute().get();
responseBody = response.getResponseBody();
} catch (InterruptedException e) {
throw new AuthorizationFailure(e);
} catch (ExecutionException e) {
throw new AuthorizationFailure(e);
} catch (IOException e) {
throw new AuthorizationFailure(e);
}
JsonParser p = new JsonParser();
JsonObject object;
try {
object = p.parse(responseBody).getAsJsonObject();
} catch (JsonSyntaxException e) {
throw new AuthorizationFailure(responseBody);
}
if (response.getStatusCode() == 200) {
this.accessToken = object.get("access_token").getAsString();
this.refreshToken = object.get("refresh_token").getAsString();
String user_ID = object.get("user_id").getAsString();
Melis.setToken(this.accessToken, this.refreshToken,user_ID);//PERSISTO
return object.toString();
} else return object.get("message").getAsString();
}
private boolean hasRefreshToken() {
return this.refreshToken != null && !this.refreshToken.isEmpty();
}
public Response post(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePost(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePost(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response put(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePut(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePut(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response delete(String path, FluentStringsMap params)
throws MeliException {
BoundRequestBuilder r = prepareDelete(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = prepareDelete(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public BoundRequestBuilder head(String path) {
return null;
}
public BoundRequestBuilder options(String path) {
return null;
}
}
Disclaimer: AsyncHttpClient author here
First, I don't know why the answer above was validated, it's wrong.
I suspect that you're creating tons of Melis instances. But you completely missed the point that an AsyncHttpClient instance must be used as a singleton (except for very specific use cases).
As every Melis instance creates its own AsyncHttpClient instance, you end up creating tons of them, and you blow off resource usage.
Note that your AsyncHttpClient instance(s) must be closed when you shut your application down so underlying resources get freed.
This is not a memory problem, but an operating system resource problem,this has nothing to do with programming, or linux.
I'm developing (trying for now) portlet that will be integrated with LinkedIn.
Following the documentation about it:
http://developer.linkedin.com/docs/DOC-1008 -->
The first step to authorizing a LinkedIn member is requesting a requestToken. This request is done with an HTTP POST.
For the requestToken step, the following components should be present in your string to sign:
* HTTP Method (POST)
* Request URI (https://api.linkedin.com/uas/oauth/requestToken)
* oauth_callback
* oauth_consumer_key
* oauth_nonce
* oauth_signature_method
* oauth_timestamp
* oauth_version
I have already API(it's oauth_consumer_key) key and i need to generate specific URL string.
Have next java code for this URL and HTTP connection:
private void processAuthentication() {
Calendar cal = Calendar.getInstance();
Long ms = cal.getTimeInMillis();
Long timestamp = ms / 1000;
Random r = new Random();
Long nonce = r.nextLong();
String prefixUrl = "https://api.linkedin.com/uas/oauth/requestToken";
String oauthCallback = "oauth_callback=http://localhost/";
String oauthConsumerKey =
"&oauth_consumer_key=my_consumer_key";
String oauthNonce = "&oauth_nonce=" + nonce.toString();
String oauthSignatureMethod = "&oauth_signature_method=HMAC-SHA1";
String oauthTimestamp = "&oauth_timestamp=" + timestamp.toString();
String oauthVersion = "&oauth_version=1.0";
String mainUrl =
oauthCallback + oauthConsumerKey + oauthNonce + oauthSignatureMethod
+ oauthTimestamp + oauthVersion;
try {
prefixUrl =
URLEncoder.encode(prefixUrl, "UTF-8") + "&"
+ URLEncoder.encode(mainUrl, "UTF-8");
URL url = new URL(prefixUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
String msg = connection.getResponseMessage();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The question is next,for those, who had faced this problem:
How should really look URL string for connection and how response is received?
For URL, it's interested the example of URL, you generated.
And for response interested, method to get it.
As i understand, after HTTP connection been established,that response is:
connection.getResponseMessage();
#sergionni I found answer to your Question from linkedin-developer
As you know
The first step to authorizing a Linked-In member is requesting a requestToken. This request is done with an HTTP POST.
Your base string should end up looking something like this if you're using a callback:
POST&https%3A%2F%2Fapi.linkedin.com%2Fuas%2Foauth%2FrequestToken
&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Foauth_callback%26o
auth_consumer_key%3DABCDEFGHIJKLMNOPQRSTUVWXYZ%26
oauth_nonce%3DoqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU%26
oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1259178158%26
oauth_version%3D1.0
You then sign this base string with your consumer_secret, computing a signature. In this case, if your secret was 1234567890, the signature would be TLQXuUzM7omwDbtXimn6bLDvfF8=.
Now you take the signature you generated, along with oauth_nonce, oauth_callback, oauth_signature_method, oauth_timestamp, oauth_consumer_key, and oauth_version and create an HTTP Authorization header. For this request, that HTTP header would look like:
Authorization: OAuth
oauth_nonce="oqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU",
oauth_callback="http%3A%2F%2Flocalhost%2Foauth_callback",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1259178158",
oauth_consumer_key="ABCDEFGHIJKLMNOPQRSTUVWXYZ",
oauth_signature="TLQXuUzM7omwDbtXimn6bLDvfF8=",
oauth_version="1.0"
Please note, that the HTTP header is a single header -- not an HTTP header for each component. You can optionally supply a realm="http://api.linkedin.com".
As a response to your request for a requestToken, your requestToken will be in the "oauth_token" response field, a validation that we acknowledged your callback with the "oauth_callback_confirmed" field, an oauth_token_secret, and a oauth_expires_in, and a few other values.
(here us Your answaer) response would look like:
oauth_token=94ab03c4-ae2c-45e4-8732-0e6c4899db63
&oauth_token_secret=be6ccb24-bf0a-4ea8-a4b1-0a70508e452b
&oauth_callback_confirmed=true&oauth_expires_in=599
You might try out the OAuth libraries to handle the connection: http://code.google.com/p/oauth/
I created a plugin for Play Framework to easily integrated with LinkedIn's OAuth: geeks.aretotally.in/projects/play-framework-linkedin-module. Hopefully it can help. You should def check out Play, very very cool Java framework.
portlet body:
public class LinkedInPortlet extends GenericPortlet {
public static final String PAGE_PIN = "pin";
public static final String PAGE_EDIT = "edit";
public static final String PAGE_PROFILE = "profile";
public static final String PAGE_CONNECTIONS = "connections";
public static final String FORM_LINKEDIN_PREFERENCES = "preferencesLinkedInForm";
public static final String PAGE_VIEW_MY_PROFILE = "/WEB-INF/portlets/linkedin/myProfile.jsp";
public static final String PAGE_VIEW_MY_CONNECTIONS =
"/WEB-INF/portlets/linkedin/myConnections.jsp";
public static final String PAGE_PREFERENCES = "/WEB-INF/portlets/linkedin/edit.jsp";
public void doView(RenderRequest request, RenderResponse response) throws PortletException,
IOException {
String view = PAGE_VIEW_MY_PROFILE;
String page =
(String) request.getPortletSession().getAttribute(
"page_" + getPortletIdentifier(request), PortletSession.PORTLET_SCOPE);
String accessTokenToken =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN);
String accessTokenSecret =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET);
LinkedInContact profile = new LinkedInContact();
List<LinkedInContact> contacts = new ArrayList<LinkedInContact>();
if (PAGE_PIN.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_EDIT.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_CONNECTIONS.equals(page)) {
try {
contacts =
ServiceResolver.getResolver().getLinkedInService().getConnections(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_CONNECTIONS;
} else {
try {
profile =
ServiceResolver.getResolver().getLinkedInService().getProfile(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_PROFILE;
}
request.setAttribute("profile", profile);
request.setAttribute("contacts", contacts);
response.setContentType(request.getResponseContentType());
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(view);
rd.include(request, response);
}
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String action;
action = (String) request.getParameter("action");
String page = request.getParameter("page");
if (page == null) {
page = PAGE_PROFILE;
} else if ("auth".equals(action)) {
request.getPortletSession().setAttribute(
"requestToken_" + getPortletIdentifier(request),
ServiceResolver.getResolver().getLinkedInService().getRequestToken(),
PortletSession.APPLICATION_SCOPE);
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
} else if ("save".equals(action)) {
try {
try {
savePreferences(request, response);
} catch (ServiceException e) {
handleException(request, e);
}
} catch (PortletModeException e) {
handleException(request, e);
}
} else if ("myProfile".equals(action)) {
page = PAGE_PROFILE;
} else if ("myConnections".equals(action)) {
page = PAGE_CONNECTIONS;
}
if (page != null) {
request.getPortletSession().setAttribute("page_" + getPortletIdentifier(request), page,
PortletSession.PORTLET_SCOPE);
}
}
private void savePreferences(ActionRequest request, ActionResponse response)
throws PortletModeException, ServiceException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
if (validateForm(request, form)) {
LinkedInRequestToken requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
String pin = request.getParameter("pinCode");
LinkedInAccessToken accessToken;
try {
accessToken =
ServiceResolver.getResolver().getLinkedInService().getAccessToken(
requestToken, pin);
} catch (LinkedInOAuthServiceException ase) {
response.setPortletMode(PortletMode.EDIT);
throw new ServiceException("linkedin.authentication.failed");
}
String tokenToken = requestToken.getToken();
String secret = requestToken.getTokenSecret();
String tokenURL = requestToken.getAuthorizationUrl();
Properties configuration = new Properties();
configuration.setProperty(LinkedInPreferencesForm.PARAM_PIN, form.getPin());
configuration
.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, tokenToken);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, secret);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, tokenURL);
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, accessToken
.getToken());
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET,
accessToken.getTokenSecret());
ServiceResolver.getResolver().getPortalService().savePortletConfiguration(request,
configuration);
resetSessionForm(request, FORM_LINKEDIN_PREFERENCES);
response.setPortletMode(PortletMode.VIEW);
} else {
// store in session
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
logger.debug(FORM_LINKEDIN_PREFERENCES + " is in edit mode");
}
}
#Override
protected void addConfiguration(MessageSource messageSource, Locale locale,
Map<String, String> result) {
result.put(LinkedInPreferencesForm.PARAM_PIN, messageSource.getMessage(
"linkedIn.preferences.pin", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.requestTokenToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.requestTokenSecret", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, messageSource.getMessage(
"linkedIn.preferences.requestTokenURL", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.accessToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.accessTokenSecret", null, locale));
}
#Override
protected void addPreference(MessageSource messageSource, Locale locale,
Map<String, String> result) {
}
#Override
public String getAsyncTitle(RenderRequest request) {
return this.getTitle(request);
}
protected boolean validateForm(ActionRequest request, LinkedInPreferencesForm form) {
return form.validate();
}
protected String myEdit(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm();
form.setPin(getStringConfiguration(request, LinkedInPreferencesForm.PARAM_PIN));
form.setRequestTokenToken(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN));
form.setRequestTokenSecret(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET));
form.setRequestTokenURL(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL));
registerSessionForm(request, FORM_LINKEDIN_PREFERENCES, form);
LinkedInRequestToken requestToken;
requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
if (requestToken == null) {
requestToken =
new LinkedInRequestToken(form.getRequestTokenToken(), form
.getRequestTokenSecret());
requestToken.setAuthorizationUrl(form.getRequestTokenURL());
}
request.setAttribute("requestToken", requestToken);
return PAGE_PREFERENCES;
}
}