Elasticsearch index a document - java

I'm having serious issues trying to find the correct syntax to push a document into an elasticsearch index by type.
My code im using to do this is :
String url = "https://my_url/my_index_name";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
String site = jsonResponse.getString("site"),
network = jsonResponse.getString("network");
Log.d("Site: ", site + "\nNetwork: "+network);
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON EXCEPTION", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("type", "type_name");;
params.put("field1", field1_value);
params.put("field2", field2_value);
params.put("field3", field3_value);
params.put("field4", field4_value);
params.put("field5", field5_value);
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
It's hitting the server, as I'm getting 400 requests, but I just cant get it to go in using this.
12-14 16:19:04.533 12642-13089/? E/Volley﹕ [41831]
BasicNetwork.performRequest: Unexpected response code 400 for URL
Can some enlighten me as to what the correct syntax is, using java code, or tell me what I'm doing wrong?
I assumed the correct syntax was:
http:// url | index_name | type | body ?
EDIT: I've searched SO, elastic java api's, google groups and all over the internet for 3 days now, with no luck! Anything at all is greatly appreciated !
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("VOLLEY ERROR", "" + error.toString());
}
}
Results in : VOLLEY ERROR﹕ com.android.volley.ServerError
Any ideas?

Ok, so I managed to fix it.
There was two issues:
The first issue was with the URL which was:
String url = "https://my_url/my_index_name";
It should have been:
String url = "https://my_url/my_index_name/type%20-d";
The second issue was with the actual arguments:
params.put("type", "type_name");;
params.put("field1", field1_value);
params.put("field2", field2_value);
params.put("field3", field3_value);
params.put("field4", field4_value);
params.put("field5", field5_value);
return params;
I swapped this out for :
String urlParameters =
"{" +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"" +
"}";
And post by:
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Everything is working as I want now, thanks for the help.

Related

how to have gson expect an array of arrays of objects?

Expected BEGIN_OBJECT but was BEGIN_ARRAY
I get this error because gson expects an object but since response from API starts with array it throws error. I 've looked at many answers on these questions but none seem to work/are understandable. the API returns an array of arrays of objects. (an array of objects for every sensor: temperature, humidity, ...). how should I change my code so it expects an array of arrays of objects?
[[
{"_id":"6022366801ad473cd0160e5d","time":"2020-03-11T18:07:44.000Z","value":"15","unit":"°C"},
{"_id":"602238f413fadf4bf04df86f","time":"2020-03-11T18:07:44.000Z","value":"15","unit":"°C"},
{"_id":"602238f613fadf4bf04df870","time":"2020-03-11T18:07:44.000Z","value":"15","unit":"°C"},
{"_id":"602934f9f8686e39800e4d2b","time":"2020-03-11T19:07:44.000Z","value":"15","unit":"°C"},
{"_id":"602934fdf8686e39800e4d2c","time":"2020-03-11T19:07:44.000Z","value":"15","unit":"°C"},
{"_id":"602934fef8686e39800e4d2d","time":"2020-03-11T19:07:44.000Z","value":"15","unit":"°C"},
{"_id":"60293589f8686e39800e4d36","time":"2020-03-11T18:07:44.000Z","value":"-2","unit":"°C"},
{"_id":"60293589f8686e39800e4d37","time":"2020-03-11T18:07:44.000Z","value":"-2","unit":"°C"},
{"_id":"602935adf8686e39800e4d43","time":"2020-03-11T18:07:44.000Z","value":"-2","unit":"°C"}
],[...]]
.
public void GetDayFromAPI(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.106:3000/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceholderApi jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi.class);
Call<List<SensorPost>> call = jsonPlaceholderApi.getposts();
call.enqueue(new Callback<List<SensorPost>>() {
#Override
public void onResponse(Call<List<SensorPost>> call, Response<List<SensorPost>> response)
{
if(!response.isSuccessful()){
textViewResult.setText("code: " + response.code());
return;
}
List<SensorPost> posts = response.body();
for (SensorPost post : posts){
String content = "";
content += "Unit: " + post.getUnit() + "\n";
content += "Value: " + post.getValue() + "\n";
content += "Time: " + post.getTime() + "\n\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<SensorPost>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}

Error inserting DateTime values on database

I searched for this online and some posts even here on StackOverflow talk about this but never resolve to my problem.
I am having a problem inserting DateTime into the database. The first problem is that I only know how to make StringRequests from java, so I convert date to String (output example: "2000-04-23 10:25:06").
This is my java code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, testInserirPontoURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {}
}) {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String codColab = getIntent().getStringExtra("codigo colaborador");
LocalDate ldHoraEntrada = LocalDate.of(ponto.getEntrada().get(Calendar.YEAR), ponto.getEntrada().get(Calendar.MONTH) + 1, ponto.getEntrada().get(Calendar.DAY_OF_MONTH));
String horaEntrada = ldHoraEntrada + " " + sdfHora2.format(ponto.getEntrada().getTime());
LocalDate ldSaidaAlmoco = LocalDate.of(ponto.getSaidaAlmoco().get(Calendar.YEAR), ponto.getSaidaAlmoco().get(Calendar.MONTH) + 1, ponto.getSaidaAlmoco().get(Calendar.DAY_OF_MONTH));
String saidaAlmoco = ldSaidaAlmoco + " " + sdfHora2.format(ponto.getSaidaAlmoco().getTime());
LocalDate ldEntradaTarde = LocalDate.of(ponto.getEntradaTarde().get(Calendar.YEAR), ponto.getEntradaTarde().get(Calendar.MONTH) + 1, ponto.getEntradaTarde().get(Calendar.DAY_OF_MONTH));
String entradaTarde = ldEntradaTarde + " " + sdfHora2.format(ponto.getEntradaTarde().getTime());
LocalDate ldHoraSaida = LocalDate.of(ponto.getSaida().get(Calendar.YEAR), ponto.getSaida().get(Calendar.MONTH) + 1, ponto.getSaida().get(Calendar.DAY_OF_MONTH));
String horaSaida = ldHoraSaida + " " + sdfHora2.format(ponto.getSaida().getTime());
Map<String, String> map = new HashMap<String, String>();
map.put("horaEntrada", horaEntrada);
map.put("saidaAlmoco", saidaAlmoco);
map.put("entradaTarde", entradaTarde);
map.put("horaSaida", horaSaida);
map.put("cod_colab", codColab);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(PontoActivity.this);
requestQueue.add(stringRequest);
note: The codColab is a String in here but an int in the database, but it works just fine because I already use it for login.
This is my php code:
if($_SERVER['REQUEST_METHOD']=='GET'){
$horaEntrada = $_GET['horaEntrada'];
$saidaAlmoco = $_GET['saidaAlmoco'];
$entradaTarde = $_GET['entradaTarde'];
$horaSaida = $_GET['horaSaida'];
$cod_colab = $_GET['cod_colab'];
$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('".$horaEntrada."', '".$saidaAlmoco."', '".$entradaTarde."', '".$horaSaida."', '".$cod_colab."')";
//$sql= "INSERT INTO `ponto` (`id`, `hora_entrada`, `saida_almoco`, `entrada_tarde`, `hora_saida`, `cod_colab`) VALUES (NULL, '2019-05-15 10:25:41', '2019-05-09 14:25:37', '2019-05-16 11:20:13', '2019-05-09 13:25:30', '1')";
//$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('$horaEntrada', '$saidaAlmoco', '$entradaTarde', '$horaSaida', '$cod_colab')";
if (mysqli_query($conn, $sql)){
echo "registado";
} else {
echo "erro a registar";
}
Note: the comment lines are the ones I tried. the 1st comment line works but I want the values of the variables
Since $horaSaida can be NULL the output will be something like this:
INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('',...)
and '' isn't a right datatime value
You could this to get the right SQL:
$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES (". (null === $horaEntrada ? "NULL" : "'$horaEntrada'") . ", '".$saidaAlmoco."', '".$entradaTarde."', '".$horaSaida."', '".$cod_colab."')";

OkHttp3Connection code 403 error

I have done some queries to the database and they usually work but when I am trying to do it in the current class, I get the following error:
{"code":403,"success":false,"message":"Forbidden, No token provided"}
Both classes are too long to post here, and thus I think this is all I can provide:
SET_USER_STAR_COUNT = URL + "setUserProfileStars";
JSONObject request_data=new JSONObject();
try
{
request_data.put("newscore",newStars);
} catch (JSONException e)
{
e.printStackTrace();
}
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.SET_USER_STAR_COUNT, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String user_tag) {
System.out.println("oO" + result);
}
#Override
public void onError(String error, String user_tag)
{}
});
And here is the controller:
Router.post('/setUserProfileStars', function (req, res) {
var username = req.decoded.name;
var newStars = req.decoded.newscore;
var response = [];
var addStars = 'MATCH (n:User) WHERE n.username = "' + username + '" SET n.stars = "'+ newStars +'" RETURN n.stars AS totalStars';
dbneo4j.cypher({
query: addStars
}, function (err, data) {
if (err) {
return res.send({
code: 9325,
message: 'error encountered',
error: err
}).status(9325);
}
response.push(data);
res.send({
code: 200,
message: 'success',
data: response
}).status(200);
});
});
If there is anything else I can provide then I will do so.
The error comes when I try to print the result. My question is why is it doing so and how can I debug and check what is wrong with it?
403 Forbidden indicates that the server is refusing to process your request because you are not authorized. According to the message details, the server expects an authorization token to be passed as a header. You will have to work with the server to determine what "token" it expects.

Error with sending PushNotifications with OneSignal android

I am working on a Messaging Android App. Users should be notified with a push notification.
At the time I have this code:
public void notifyUser(String user_id, String message) {
try {
OneSignal.postNotification(new JSONObject("{'contents': {'en':['" + message + "']}, " +
"'include_player_ids': ['" + user_id + "'], " +
"'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " +
"'data': {'openURL': 'https://imgur.com'}," +
"'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.d("LOL", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.d("LOL", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get an Error in Log:
D/LOL: postNotification Failure: {"errors":["Notification contents for each language must be a string"]}
I searched threw the Internet but didn't find a solution for my Problem.
I hope you can help me...
Thanks in advance.
I believe the error you're seeing is because you're sending up the message inside an array when it should just be a string.
"{'contents': {'en':['" + message + "']} should be "{'contents': {'en':'" + message + "'} (removed the brackets).

Volley request always get into Error Listener

JAVA CODE:-
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://sikkimexpress.itstunner.com/api/homenewslist/topnews", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
for (int i = 0; i<jsonArray.length();i++){
JSONObject homenews = jsonArray.getJSONObject(i) ;
String newsId = homenews.getString("NewsId");
String dateTime = homenews.getString("DateTime");
String newsType = homenews.getString("NewsType");
String title = homenews.getString("Title");
String description = homenews.getString("Description");
String mainImageURL = homenews.getString("MainImageThumbnail");
System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
requestQueue.add(jsonObjectRequest);
JSON:-
{
"Status": 0,
"Message": "Sucess"
"HomeNews": [
{
"NewsId": 13,
"DateTime": null,
"NewsType": "latest",
"Title": "Jat quota row: Haryana CM calls all-party meet as stir continues",
"Description": "<p>Jat students block the Rohtak-Delhi road in Rohtak as part of the quota agitation. (Manoj Dhaka/HindustanTimes ). Share. Share. Share.</p>",
"MainImageThumbnail": "http://ste.india.com/sites/default/files/2016/02/19/461939-haryana-jat-protest.jpg",
"ReferenceURL": ""
},
{
"NewsId": 15,
"DateTime": null,
"NewsType": "latest",
"Title": "Sports quiz of the week",
"Description": "<p>Which snooker player competing at the Welsh Open said: \"I get so bored at these tournaments. Maybe they should stick an adult creche here to keep us entertained because I just want to go home now.\r\n\r\n\"Today I've had a haircut, I've been in the Chinese, I've been for a coffee, I went to Bill's cafe for a couple of hours, I've had a kip, I went to Marks' and bought a bit of grub. What a day. It's certainly not glamorous.\"?</p>",
"MainImageThumbnail": "http://news.files.bbci.co.uk/vj/live/idt-images/quizzes-sports_weekly_quiz_week7/Snooker_comp_getty_k4960.jpg",
"ReferenceURL": ""
},
]
}
I want to parse the json but always its coming to the Response.ErrorListener. If the status = 0 and the message is success then the value of NewsId, DateTime, title, description will be retrieve. Can anybody help, please? I take permission of Internet and I check the URL and it's working.
I am able to get correct response. If you are getting error, how about logging
Log.e("VOLLEY", error.getMessage());
One issue might be you are not using correct constructor for JsonObjectRequest. You should ideally use, where for you 3rd argument jsonRequest could be passed as null.
com.android.volley.toolbox.JsonObjectRequest.JsonObjectRequest(int
method, String url, JSONObject jsonRequest, Listener<JSONObject>
listener, ErrorListener errorListener)
Else everything is in workable condition.

Categories