I am trying to test onResponse method. If I understand korrectly, when I call apolloQueryCall.enqueue , it should return response as response. When I run this code, it does not enter neither onResponse or onFailere. What am I missing? I could not find examples that work for me on the internet for Java.
String body = "{\n" +
" \"data\": {\n" +
" \"message\": \"kedi\"\n" +
" }\n" +
"}";
MockWebServer webServer = new MockWebServer();
MockResponse response = new MockResponse().setResponseCode(200).setBody(body);
webServer.enqueue(response);
var apolloClient = ApolloClient.builder()
.serverUrl(webServer.url("http://localhost/mock"))
.okHttpClient(okHttpClient)
.build();
var apolloQueryCall = apolloClient.query(query);
apolloQueryCall.enqueue(new ApolloCall.Callback<MyClass.Data>() {
#Override
public void onResponse(#NotNull Response<MyClass.Data> response) {
System.out.println("response:" + response);
}
#Override
public void onFailure(#NotNull ApolloException e) {
System.out.println(e.getMessage());
}
});
webServer.close();
Related
This is What i get as a response from the PlacesApi after making a request.
But the issue is that i cant get the value of "photo_reference".
The issue is also the Objects being in Arrays and all , the whole response looks confusing.
Below is what i have tried in android studio Java
private void getUserLocationImage(String mLocationName) {
String url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input="+mLocationName+"&inputtype=textquery&fields=photos&key="+R.string.google_api;
// prepare the Activities Request
JsonObjectRequest getWeatherRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("candidates");
JSONObject photosObj = dataArray.getJSONObject(0);
JSONArray photosArray = photosObj.getJSONArray("photos");
JSONObject photoRefObj = photosArray.getJSONObject(0);
String imageRef = photoRefObj.get("photo_reference").toString();
Toast.makeText(HomeLandingPageActivity.this, ""+imageRef, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the RequestQueue
queue.add(getWeatherRequest);
}
This is the Error
org.json.JSONException: Index 0 out of range [0..0)
This is what the response is in the Web
{
"candidates" : [
{
"photos" : [
{
"height" : 4160,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/111684034547030396888\"\u003eCaroline Wood\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ",
"width" : 3120
}
]
}
],
"status" : "OK"
}
Try to use Gson library for deserilization your response. http://tutorials.jenkov.com/java-json/gson.html
It's very simple way to get any values from response
At first need create class with response model
import java.util.List;
public class ResponseBody {
public List<Candidates> candidates;
public static class Candidates {
public List<Photos> photos;
public static class Photos {
public int height;
public int width;
public String photo_reference;
public List<String> html_attributions;
}
}
}
Then just get your response as String and deserilize it:
String json = "{\n" +
" \"candidates\" : [\n" +
" {\n" +
" \"photos\" : [\n" +
" {\n" +
" \"height\" : 4160,\n" +
" \"html_attributions\" : [\n" +
" \"\\u003ca href=\\\"https://maps.google.com/maps/contrib/111684034547030396888\\\"\\u003eCaroline Wood\\u003c/a\\u003e\"\n" +
" ],\n" +
" \"photo_reference\" : \"CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ\",\n" +
" \"width\" : 3120\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"status\" : \"OK\"\n" +
"}";
Gson gson = new Gson();
ResponseBody responseBody = gson.fromJson(json, ResponseBody.class);
System.out.println("responseBody = " + responseBody.candidates.get(0).photos.get(0).photo_reference);
I got this:
responseBody = CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ
I need to read JSON from file and replace few objects.
For example, I have class User.java
public class User {
String username;
String email;
String city;
String code;
}
and JSON:
{
"variables":
{
"user":
{
"value":
{
"username": "$USERNAME",
"email": "$EMAIL",
"city": "$CITY"
}
}
}
}
I have two questions:
How can I read JSON from file? Read JSON will be send by WebClient POST API.
How can I replace $USERNAME, $EMAIL and $CITY? I won't hardcode it.
I have register form. When someone complete form, it will be replaced for $...
Firsty, I got hardcode JSON to string but I need read it from file
class JSONClass {
static String toFormat(User user) {
String jsonUserRegister = "{\n" +
" \"variables\":\n" +
" {\n" +
" \"user\": \n" +
" {\n" +
" \"value\":\n" +
" {\n" +
" \"username\": \"" + user.getUsername() + "\",\n" +
" \"email\": \"" + user.getEmail() + "\",\n" +
" \"city\": \"" + user.getCity() + "\",\n" +
" \"code\": \"" + user.getCode() + "\"\n" +
" } }\n" +
" }\n" +
"}";
return jsonUserRegister;
This can be achieved using Spring Boot to set up the backend to receive client calls. So to get Task 1a working, we need below
#RestController
public class JsonReaderController {
#Autowired
private ResourceLoader resourceLoader;
#PostMapping(value = "/read-json")
public String fileContent() throws IOException {
return new String(Files.readAllBytes(
resourceLoader.getResource("classpath:data/json- sample.json").getFile().toPath()));
}
}
Above code simply reads file content and returns as String. Note default response is Json.
Now that we have the backend done, we need Task 1b - Sending the POST request.
private String readJsonFile() throws IOException {
final OkHttpClient client = new OkHttpClient();
final String requestUrl = "http://localhost:8080/read-json";
Request request = new Request.Builder()
.url(requestUrl)
.post(RequestBody.create(JSON, ""))
.build();
try (Response response = client.newCall(request).execute()) {
//we know its not empty given scenario
return response.body().string();
}
}
readJsonFile method makes a POST request - using OkHttp to our backend bit (done in Task 1a) and returns the content of the file as json.
And for Task 2 - replacing $USERNAME, $EMAIL and $CITY with appropriate values. For this, we will use the Apache commons-text library.
public static void main(String[] args) throws IOException {
String fileContent = new ReadJsonFromFile().readJsonFile();
User user = new User("alpha", "alpha#tesrt.com", "Bristol", "alpha");
Map<String, String> substitutes = new HashMap<>();
substitutes.put("$USERNAME", user.getUsername());
substitutes.put("$EMAIL", user.getEmail());
substitutes.put("$CITY", user.getCity());
substitutes.put("$CODE", user.getCode());
StringSubstitutor stringSubstitutor = new StringSubstitutor(substitutes);
//include double quote prefix and suffix as its json wrapped
stringSubstitutor.setVariablePrefix("\"");
stringSubstitutor.setVariableSuffix("\"");
String updatedContent = stringSubstitutor.replace(fileContent);
System.out.println(updatedContent);
}
Hope this helps.
In my app, I want to use Retrofit2 to connect to the server and get some data.
For this, I've written the code as shown below but it doesn't show the data. And for some reason, no (detailed) error is outputted.
private void getDetailData(String auctionID, final String jwtToken) {
showLoading(true);
Call<DetailResponse> call = apis.getDetainAuctions(auctionID, jwtToken, agent);
call.enqueue(new Callback<DetailResponse>() {
#Override
public void onResponse(Call<DetailResponse> call, final Response<DetailResponse> response) {
Log.e("detailLog", "OK");
Log.e("detailLog", response.message() + " --- " + response.errorBody());
if (response.isSuccessful()) {
}
}
#Override
public void onFailure(Call<DetailResponse> call, Throwable t) {
Log.e("detailLog", "Err : " + t.getMessage());
}
});
}
Logcat error:
E/detailLog: --- okhttp3.ResponseBody$1#cbf85bc
What does the error mean?
I am trying to change the current 'Test Message' String in a OneSignal push notification. I simply want to use a variable defined in my code, but cannot figure out how to do it.
try {
OneSignal.postNotification(new JSONObject("{'contents': ['en': 'Test Message'], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
I was able to achieve something similar in sending the notification to a selected user. Now I just want to change the text of the actual message.
Use this
String yourVaribale = " what ever you want to send"
OneSignal.postNotification(new JSONObject("{'contents': ['en': " + yourVariable + "], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
or you can try this way
String strJsonBody = "{"
+ " \"app_id\": \"ef42157d-64e7-4ce2-9ab7-15db224f441b\","
+ " \"included_segments\": [\"All\"],"
+ " \"data\": {\"foo\": \"bar\"},"
+ " \"contents\": {\"en\": \""+ description +"\"},"
+ " \"headings\": {\"en\": \""+ title +"\"},"
+ " \"big_picture\":\""+ imageurl +"\""
+ "}";
for second method follow this link
The solution below worked for me. The full name of the current user is concatenated to the string message " wants you to follow them." and is then sent to the selectedUser with the specific OneSignalID.
OneSignal.postNotification(new JSONObject("{'contents': {'en': \""+ currentUser.getFullName() +" wants you to follow them." +"\"}, 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
Firstly, let me say I not a java programmer, I am a programmer on the IBM Iseries. However, I've been tasked with changing a current java application that currently sends a stream of data to one URL that will allow that same stream of data to be sent to multiple URLs based on a properties file. Our java app runs on the Iseries and we are using the org.apache.commons.httpclient.HttpClient class to send the data and the response is processed. Everything works great right now, but I wanted to see if anyone could point me in the right direction to complete this task.
Essentially, I need to send the same block of data to multiple URLs within the same thread or instance. I'm not sure if its possible or the best way to try to complete this. So, is there a way to create multiple instances within the same thread that will send the same data stream to multiple URLs? Before you start commenting I will say again that I am not a java programmer and I wasn't even sure how to phrase the question.
Added code sample:
public class Replication_CC implements TextProcessor {
public static String VERSION = "v2014.1.0";
static Logger log = Logger.getLogger(Replication_CC.class);
String url;
int retries = 1;
public Replication_CC(Properties p) {
super();
url = p.getProperty("url");
log.info("Service URL set to " + url);
retries = PropertiesUtil.getOptionalIntProperty(p, "retries", 1);
log.info("Retries set to " + retries);
}
public static void main(String[] args) throws Exception {
log.info("Replication " + VERSION);
log.info("Initializing...");
Properties p = PropertiesUtil.loadProperties(Replication_CC.class.getResource("/Replication_CC.properties"));
DQServer server = new DQServer(p, new Replication_CC(p));
server.run();
}
public String process(String request) throws Exception {
long processStart = System.currentTimeMillis();
String response = null;
for (int i=0; i<=retries; i++) {
try {
response = send(request, url);
if (response!=null) break;
}
catch (Exception e) {
log.warn("Error processing: " + e.getMessage());
if (i<retries) {
log.warn("Trying again (retry " + (i+1) + "...");
}
else {
log.error("Giving up on this transaction.");
break;
}
}
}
long processFinished = System.currentTimeMillis();
log.info("Request was processed in " + (processFinished-processStart) + "ms.");
return response;
}
public String send(String request, String url) throws Exception {
log.debug("Creating request...");
HttpClientParams params = new HttpClientParams();
params.setParameter("http.useragent", "http-api / Replication");
HttpClient client = new HttpClient(params);
PostMethod post = new PostMethod(url);
/*
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : globalRequest.keySet()) {
params.add(nvp(key, globalRequest.get(key)));
}
*/
post.setRequestBody(request);
// Log the request
if (log.isDebugEnabled()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
post.getRequestEntity().writeRequest(baos);
baos.close();
log.debug("HTTP Request: \n" + StringUtils.repeat("*", 100) + "\n" + "Content Type: "
+ post.getRequestEntity().getContentType() + "\n" + "Content Length: "
+ post.getRequestEntity().getContentLength() + "\n" + "Request Headers: "
+ ArrayUtils.toString(post.getRequestHeaders()) + "\n" + "Request Params: " + baos.toString() + "\n" +
StringUtils.repeat("*", 100));
}
try {
log.info("Sending request...");
int responseCode = client.executeMethod(post);
//log.debug(String.format("Http Response Code [%s]", responseCode));
log.debug("Http Response Code [" + responseCode + "]");
if (responseCode == HttpStatus.SC_OK) {
String charset = post.getResponseCharSet();
log.debug("Response Character Set [" + charset + "]");
/*
byte[] body = post.getResponseBody();
String response = new String(body, charset);
*/
String response = IOUtils.toString(post.getResponseBodyAsStream());
log.debug("Response Body: \n" + response);
return response;
}
else {
throw new Exception(post.getStatusLine().toString());
}
}
catch (IOException ioe) {
log.error(ioe);
throw ioe;
}
finally {
post.releaseConnection();
}
}
One simple way is to include multiple URL's in the existing url property separated by a unique character. I chose "|" (pipe) in this example because it's highly unlikely to see a pipe in a normal url.
Java identifies methods by name and parameter signature. We can use that to our advantage by adding a String url parameter to the existing process method and creating a new process(String request) method that will split and iterate over the url's. The only downside is that it will only return the last response to the DQServer class.
public String process(String request) throws Exception {
String response;
for (String u : url.split("\\|")) {
response = process(request, u);
}
return response;
}
public String process(String request, String url) throws Exception {
long processStart = System.currentTimeMillis();
String response = null;
for (int i=0; i<=retries; i++) {
try {
response = send(request, url);
if (response!=null) break;
}
catch (Exception e) {
log.warn("Error processing: " + e.getMessage());
if (i<retries) {
log.warn("Trying again (retry " + (i+1) + "...");
}
else {
log.error("Giving up on this transaction.");
break;
}
}
}
long processFinished = System.currentTimeMillis();
log.info("Request was processed in " + (processFinished-processStart) + "ms.");
return response;
}
The complete sample is available on GitHub Gist.