Android Volley POST to Java EE not working - java

I'm trying to call a POST-Method on my Android Device to my Java EE Webapplication. Java Version 8, Android Application is on API Level 22 and i'm using a virtual device on my computer.
I can add the request to the Volley-queue but then it doesn't resolve my POST request.
This is the CustomerService on the Java EE Application:
#EJB
CustomerBean customerBean;
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/registration")
public Long registration(#FormParam("email") String email, #FormParam("password") String pw) {
Customer c = customerBean.registration(email, pw);
if(c == null) {
return (long) 0;
}
return c.getId();
}
And this is the called method on CustomerBean:
#PersistenceContext
private EntityManager em;
public Customer registration(String email, String password) {
Customer c = (Customer) em.createQuery("FROM " + Customer.class.getSimpleName() + " c WHERE c.email = :email")
.setParameter("email", email).getSingleResult();
if(c == null) {
c = new Customer();
c.setEmail(email);
c.setPassword(password);
em.persist(c);
em.flush();
return c;
}
else {
return null;
}
}
And this is my Android-Client, who's sending the POST Request (MainActivity):
private Long api_regist(final String email, final String password) throws IOException {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.0.2.2:8080/onlineshop-web/api/customer/registration";
final String[] result = new String[1];
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
result[0] = response;
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
while (result[0] == null){
Log.d("Result:", " Empty");
} //TODO return value afterwards
So the result[0] is allways null.

Related

How can I send notification to specific User using the user's token in Firebase?

I am developing an android app (java), I am using Firebase, for each registered user I have a token of the device, how can I send a notification to a specific user using his token ?
For sending a notification to users the only thing required is that user's token. You can send notification using FCM.
Here, I'm sharing my FCM class which can be used for this purpose. It is using Okhttp3 requests, so make sure you add its dependency.
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'
After adding this dependency, all you have to do is to use this FCM class.
FCMMessages.java
public class FCMMessages {
private Context context;
public void sendMessageSingle(Context context, final String recipient, final String title, final String body, final Map<String, String> dataMap)
{
this.context = context;
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("to", recipient);
if (dataMap != null)
rootMap.put("data", dataMap);
new SendFCM().setFcm(rootMap).execute();
}
public void sendMessageMulti(Context context, final JSONArray recipients, final String title, final String body, final Map<String, String> dataMap) {
this.context = context;
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("registration_ids", recipients);
if (dataMap != null)
rootMap.put("data", dataMap);
new SendFCM().setFcm(rootMap).execute();
}
#SuppressLint("StaticFieldLeak")
class SendFCM extends AsyncTask<String, String, String> {
private String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
private Map<String, Object> fcm;
SendFCM setFcm(Map<String, Object> fcm) {
this.fcm = fcm;
return this;
}
#Override
protected String doInBackground(String... strings) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, new JSONObject(fcm).toString());
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization","key=" + StaticConfig.myMessagingAuth)
.build();
Response response = new OkHttpClient().newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject resultJson = new JSONObject(result);
int success, failure;
success = resultJson.getInt("success");
failure = resultJson.getInt("failure");
//Toast.makeText(context, "Sent: " + success + "/" + (success + failure), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
}
}
}
}
Make sure you get the messagingAuth from your firebase project settings. To get the messagingAuth token, follow these steps:
Open Firebase Project > Project Settings > Cloud Messaging > Server key
Copy the value of server key and paste it as messagingAuth in your android project.
To send a notification to single user token use sendMessageSingle method. It would be like
String user_token = "wiubd92uhe91dik-q";
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageSingle(MainActivity.this, user_token, notification_title, notification_des, null);
To send a notification to multiple user tokens use sendMessageMulti method. It would be like
ArrayList<String> user_tokens = new ArrayList<>();
user_tokens.add(token_1);
user_tokens.add(token_2);
user_tokens.add(token_3);
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageMulti(MainActivity.this, new JSONArray(user_tokens), notification_title, notification_des, null);
Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series. And kindly mark this as the correct answer if this helps you.
Add the below dependency
`implementation 'io.reactivex.rxjava2:rxandroid:2.1.1`'
Now Create these classes :
Token Model This Model is used to retrieve token data( Token , Phone ). I have also a variable for the phone because I made this class according to my datastructure . Kindly modify the code according to your need
public class TokenModel {
private String phone,token;
public TokenModel() {
}
public TokenModel(String phone, String token) {
this.phone = phone;
this.token = token;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}}
FCM Send Data Model
public class FCMSendData {
private String to;
private Map<String,String> data;
public FCMSendData(String to, Map<String, String> data) {
this.to = to;
this.data = data;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}}
Create FCM Result Model
class FCMResult {
private String message_id;
public FCMResult() {
}
public String getMessage_id() {
return message_id;
}
public void setMessage_id(String message_id) {
this.message_id = message_id;
}}
Create RetrofitFCMClient
public class RetrofitFCMClient {
private static Retrofit instance;
public static Retrofit getInstance()
{
if(instance==null)
{
instance = new Retrofit.Builder().baseUrl("https://fcm.googleapis.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return instance;
}
return instance;
}}
Now we need to implement an interface
//Authorization key is server key of Cloud Messaging
public interface IFCMService {
#Headers({
"Content-Type:application/json",
"Authorization:key=**YOUR_AUTHORIZATION KEY HERE**"
})
#POST("fcm/send")
Observable<FCMResponse> sendNotification(#Body FCMSendData body);}
Now We are ready to use the firebase messaging just need to put data and use our retrofit to push it
TokenModel tokenModel = dataSnapshot.getValue(TokenModel.class);
//("FCM",tokenModel.getToken());
Map<String, String> notiData = new
HashMap<>();
notiData.put(Common.NOTI_TITLE, "YOUR NOTIFICATION TITLE");
notiData.put(Common.NOTI_CONTENT,"YOUR_NOTFICATION CONTENT );
FCMSendData sendData = new FCMSendData(tokenModel.getToken(),
notiData);
compositeDisposable
.add(ifcmService.sendNotification(sendData)
.subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<FCMResponse>() {
#Override
public void accept(FCMResponse
fcmResponse)
throws Exception {
if (fcmResponse.getSuccess()
== 1) {
Toast.makeText(getContext(),
"Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Failed
to Notify", Toast.LENGTH_LONG).show();
}
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable
throwable) throws Exception {
Toast.makeText(getContext(),
throwable.getMessage(), Toast.LENGTH_LONG).show();
}
}));
Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series

Send JSON body with JsonObjectRequest And GET request

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;
}
}
}

Android multiple input q parameters in Google Translate API , with volley java

How to send multiple q input texts? As I see, the API doesn't allow q[] type arrays, instead it uses multiple q parameters.
protected Map<String,String> getParams(){
List<String> textString = new ArrayList<>();
Map<String,String> params = new HashMap<String, String>();
params.put("key", "key");
params.put("target", "DE");
params.put("q", text);
return params;
}
};
I found the following helper class:
class HttpParams extends HashMap<String, List<String>> {
private static final long serialVersionUID = 1L;
public HttpParams() {
super();
}
public HttpParams(int capacity) {
super(capacity);
}
public HttpParams(Map<String, List<String>> map) {
super(map);
}
public HttpParams(int capacity, float loadFactor) {
super(capacity, loadFactor);
}
/*
* This is the method to use for adding post parameters
*/
public void add(String key, String value) {
if (containsKey(key)) {
get(key).add(value);
}
else {
ArrayList<String> list = new ArrayList<String>();
list.add(value);
put(key, list);
}
}
/**
* Converts the Map into an application/x-www-form-urlencoded encoded string.
*/
public byte[] encodeParameters(String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, List<String>> entry : entrySet()) {
String key = URLEncoder.encode(entry.getKey(), paramsEncoding);
for (String value : entry.getValue()) {
encodedParams.append(key);
encodedParams.append('=');
try {
encodedParams.append(URLEncoder.encode(value, paramsEncoding));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
encodedParams.append('&');
}
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
}
and then in Main class that extends Request overrided the getBody():
public void volleyPost(String text,OnServiceResponseListener onServiceResponseListener){
String URL = "Your Url here";
RequestQueue requestQueue = Volley.newRequestQueue(this);
HttpParams mParams = new HttpParams();
mParams.add("key", "key");
mParams.add("target", "languageCode");
String wordsArray [] = text.split(",");
for(int i = 0;i<wordsArray.length;i++) {
mParams.add("q", wordsArray[i]);
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
onServiceResponseListener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onServiceResponseListener.onFailed(error.getMessage());
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
if (mParams != null && mParams.size() > 0) {
Log.d(TAG,"mParams--->"+new Gson().toJson(mParams));
return mParams.encodeParameters(getParamsEncoding());
}
return null;
}
};
requestQueue.add(stringRequest);
}

Getting null in Environment variable

#Configuration
public class CustomRemoteTokenService implements ResourceServerTokenServices {
private static final Logger logger = LoggerFactory.getLogger(CustomRemoteTokenService.class);
#Resource
Environment environment;
private RestOperations restTemplate;
private String checkTokenEndpointUrl;
private String clientId;
private String clientSecret;
private String tokenName = "token";
private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
#Autowired
public CustomRemoteTokenService() {
restTemplate = new RestTemplate();
((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
#Override
// Ignore 400
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getRawStatusCode() != 400
&& response.getRawStatusCode() != 403 /* && response.getRawStatusCode() != 401 */) {
super.handleError(response);
}
}
});
}
public void setRestTemplate(RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setCheckTokenEndpointUrl(String checkTokenEndpointUrl) {
this.checkTokenEndpointUrl = checkTokenEndpointUrl;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) {
this.tokenConverter = accessTokenConverter;
}
public void setTokenName(String tokenName) {
this.tokenName = tokenName;
}
#Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException, GenericException {
/*
* This code needs to be more dynamic. Every time an API is added we have to add
* its entry in the if check for now. Should be changed later.
*/
HttpServletRequest request = Context.getCurrentInstance().getRequest();
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add(tokenName, accessToken);
formData.add("api", environment.getProperty("resource.api"));
/* formData.add("api", "5b64018880999103244f1fdd");*/
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
Map<String, Object> map = null;
try {
map = postForMap(checkTokenEndpointUrl, formData, headers);
} catch (ResourceAccessException e) {
logger.error("Socket Exception occured at " + System.currentTimeMillis() + "for client_id : " + clientId);
GenericException ge = new GenericException(
"Could not validate your access token. If this occurs too often please contact MapmyIndia support at apisupport#mapmyindia.com");
ge.setHttpErrorCode(504);
ge.setOauthError("Access Token validation failed");
throw ge;
}
if (map.containsKey("error")) {
logger.error("check_token returned error: " + map.get("error") + " for client id : " + clientId);
String temp = map.get("error").toString();
GenericException ge = new GenericException(map.get("error_description").toString());
ge.setHttpErrorCode(Integer.parseInt(map.get("responsecode").toString()));
ge.setOauthError(temp);
switch (temp) {
case "invalid_token":
throw new InvalidTokenException(accessToken);
default:
throw ge;
}
}
Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
return tokenConverter.extractAuthentication(map);
}
#Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
private String getAuthorizationHeader(String clientId, String clientSecret) {
String creds = String.format("%s:%s", clientId, clientSecret);
try {
return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Could not convert String");
}
}
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers)
throws RestClientException {
if (headers.getContentType() == null) {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
#SuppressWarnings("rawtypes")
Map map = restTemplate.exchange(path, HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
#SuppressWarnings("unchecked")
Map<String, Object> result = map;
return result;
}
}
I autowired Environment and getting null when I do environment.getProperty("resource.api");
It is always returning null but in another classes I autowire Environment and successfully retrieve the value from properties.
You have to take this steps :
1.Register a Properties
You need to register you properties file by #PropertySource("classpath:foo.properties") as :
#Configuration
#PropertySource("classpath:foo.properties")
public class CustomRemoteTokenService implements ResourceServerTokenServices {
//...
}
2.Injecting Properties
To obtain the value of a property with the Environment API:
#Autowired
private Environment env;

Explicit termination method 'close'

I am using volley and after a couple of hits below exception is thrown.
The application is crashing showing following error.
E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:180)
at java.net.AbstractPlainSocketImpl.create(AbstractPlainSocketImpl.java:103)
at java.net.Socket.createImpl(Socket.java:464)
at java.net.Socket.getImpl(Socket.java:530)
at java.net.Socket.setSoSndTimeout(Socket.java:1194)
at com.android.okhttp.Connection.setTimeouts(Connection.java:508)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:400)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:356)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:273)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:474)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:422)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:99)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
Below is the code snippet
public void processServiceResponseEntity(final String serviceName, final String serviceRequest,
final int method, final String key, final Map<String, String> queryParams, final Map<String, String> header,
final Map<String, String> pathVariables)
throws YaggerCustomException
{
DatabaseHandler databaseHandler = new DatabaseHandler(context);
final User user = databaseHandler.getUserDetails();
String url = serviceName;
Log.d(TAG, "URL: " + url);
StringRequest strReq = new StringRequest(method,
url, new Response.Listener<String>() {
#Override
public void onResponse(String res) {
Log.d(TAG, "Response: " + res);
if (currentObject != null) {
currentObject.postYaggerServiceCall(res, key);
}
// setResponse(res);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
showSnackbar(serviceName, serviceRequest, method, key, queryParams, header, pathVariables);
currentObject.postYaggerServiceCall(null, key);
setError(error.getMessage());
// ACRA.getErrorReporter().handleException(new YaggerCustomException(error.getMessage()));
}
}) {
#Override
public String getBodyContentType()
{
if (getContentType() == null)
{
return "application/json";
}
else
{
return getContentType();
}
}
#Override
public byte[] getBody() throws AuthFailureError
{
byte[] byt = null;
this.getParams();
if (serviceRequest != null)
byt = serviceRequest.getBytes();
return byt;
}
#Override
public Map<String, String> getHeaders()
throws AuthFailureError
{
Map<String, String> oauthHeader = new HashMap<>();
oauthHeader.put("Content-Type", "application/json");
if(user != null)
oauthHeader.put("Authorization", user.getTokenType() + " " + user.getToken());
if (header != null && !header.isEmpty()) {
oauthHeader.putAll(header);
}
oauthHeader.putAll(super.getHeaders());
return oauthHeader;
}
#Override
public Map<String, String> getParams()
throws AuthFailureError
{
if (queryParams == null)
return Collections.<String, String>emptyMap();
return queryParams;
}
#Override
public RetryPolicy getRetryPolicy()
{
return new DefaultRetryPolicy(AppConfig.DEFAULT_TIMEOUT_MS, AppConfig.DEFAULT_MAX_RETRIES,
AppConfig.DEFAULT_BACKOFF_MULT);
}
};
// Adding request to request queue
strReq.setRetryPolicy(new DefaultRetryPolicy(AppConfig.DEFAULT_TIMEOUT_MS, AppConfig.DEFAULT_MAX_RETRIES,
AppConfig.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(strReq, key == null ? serviceName : key);
}
Thanks

Categories