date fields are transformed to different format when a java object stored to the elastic search? - elasticsearch

Hi I am having a spring boot java application and I am trying to integrate elastic search capabilities into it .I have written a junit test where i start an embedded elastic search , then i read a json file containing an array of json objects and then trying to insert these object into the elastic search as document under an index.
However the problem is when i insert a java object containing an Instant field i am loosing the format.
MessageHistoryReportingResourceIntTest
#RunWith(SpringRunner.class)
#SpringBootTest(classes = PrimecastApp.class)
public class MessageHistoryReportingResourceIntTest {
#Autowired
private MessageHistoryReportingService messageHistoryReportingService;
#Autowired
private HttpMessageConverter[] httpMessageConverters;
#Autowired
private ExceptionTranslator exceptionTranslator;
#Value("${elasticsearch.configuration.host}")
private String host;
#Value("${elasticsearch.configuration.port}")
private int port;
private MockMvc restMvc;
private EmbeddedElastic embeddedElastic;
private RestHighLevelClient client;
#Before
public void startElasticServer() {
try {
embeddedElastic = EmbeddedElastic.builder().withElasticVersion("6.6.1")
.withSetting(PopularProperties.HTTP_PORT, port)
.withSetting(PopularProperties.CLUSTER_NAME, "my_cluster").withStartTimeout(5, TimeUnit.MINUTES)
.build()
// .withIndex("mep-report-today",
// IndexSettings.builder().withType("mep-report-mapping.json",
// getJsonResourceAsStream1()).build()).build()
.start();
client = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, "http")));
ObjectMapper objMapper = new ObjectMapper();
objMapper.registerModule(new JavaTimeModule());
List<MessageHistory> messageHistories = objMapper.readValue(getMessageHistoryResourceAsStream(),
objMapper.getTypeFactory().constructCollectionType(List.class, MessageHistory.class));
BulkRequest request = new BulkRequest();
for (int i = 0; i < messageHistories.size(); i++) {
request.add(new IndexRequest("mep-report-today", "doc", String.valueOf(i))
.source(objMapper.writeValueAsString(messageHistories.get(i)), XContentType.JSON));
}
request.timeout(TimeValue.timeValueMinutes(5));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
MockitoAnnotations.initMocks(this);
MessageHistoryReportingResource messageHistoryReportingResource = new MessageHistoryReportingResource(
messageHistoryReportingService);
this.restMvc = MockMvcBuilders.standaloneSetup(messageHistoryReportingResource)
.setMessageConverters(httpMessageConverters).setControllerAdvice(exceptionTranslator).build();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static InputStream getMessageHistoryResourceAsStream() throws FileNotFoundException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("files/messageHistories.json");
return is;
}
#Test
public void test() {
GetRequest getRequest = new GetRequest("mep-report-today", "doc", "1");
try {
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
System.out.print(response.getSourceAsString());
SearchRequest searchRequest = new SearchRequest("mep-report-today");
searchRequest.types("doc");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.timeout(TimeValue.timeValueMinutes(3));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
System.out.println("********");
for (SearchHit hit : hits) {
System.out.println(hit.getId() + " -----" + hit.getSourceAsString());
}
System.out.println("********");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
messageHistories.json
[
{
"inventory": "MMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-14T07:59:42.000Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": 420736408283,
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": 8800111,
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1
},
{
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-08T08:47:02.000Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": 420736408283,
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": 8800111,
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1
}]
MessageHistory.java
package com.openmind.primecast.domain.elasticsearch;
import java.time.Instant;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MessageHistory {
#JsonProperty("inventory")
private String inventory;
#JsonProperty("msg_text")
private String messageText;
#JsonProperty("status")
private String status;
#JsonProperty("#timestamp")
private Instant timeStamp;
#JsonProperty("o_error")
private String error;
#JsonProperty("flight_id")
private UUID flightId;
#JsonProperty("recipient")
private String recipient;
#JsonProperty("account_id")
private UUID accountId;
#JsonProperty("sender")
private String sender;
#JsonProperty("campaign_id")
private UUID campaignId;
#JsonProperty("nof_segments")
private Integer segmentCount;
#JsonProperty("#version")
private Integer version;
public String getInventory() {
return inventory;
}
public void setInventory(String inventory) {
this.inventory = inventory;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Instant getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Instant timeStamp) {
this.timeStamp = timeStamp;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public UUID getFlightId() {
return flightId;
}
public void setFlightId(UUID flightId) {
this.flightId = flightId;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public UUID getAccountId() {
return accountId;
}
public void setAccountId(UUID accountId) {
this.accountId = accountId;
}
public UUID getCampaignId() {
return campaignId;
}
public void setCampaignId(UUID campaignId) {
this.campaignId = campaignId;
}
public Integer getSegmentCount() {
return segmentCount;
}
public void setSegmentCount(Integer segmentCount) {
this.segmentCount = segmentCount;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
#Override
public String toString() {
return "MessageHistory [inventory=" + inventory + ", messageText=" + messageText + ", status=" + status
+ ", timeStamp=" + timeStamp + ", error=" + error + ", flightId=" + flightId + ", recipient="
+ recipient + ", accountId=" + accountId + ", sender=" + sender + ", campaignId=" + campaignId
+ ", segmentCount=" + segmentCount + ", version=" + version + "]";
}
}
so in the messageHistories.json file each object there is a field named #timestamp, so when i map these array to java objects and i store these objects as documents under an index i am loosing the formatting . In other words when i run the integration test I get this output. in other words the #timestamp is stored in elastic search like this "#timestamp":1.568447982E9 . what i want is the like this in the elastic search "#timestamp":"2019-09-08T08:47:02.000Z"
********
0 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568447982E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
14 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.56851715E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
19 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.56767748E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
22 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568710029E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
24 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568629248E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
25 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.569413823E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
26 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568528127E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
29 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.569124502E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
40 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568546145E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
41 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568088436E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
********
any idea how can i achieve it ?

After i set my ObjectMapper with SerializationFeature.WRITE_DATES_AS_TIMESTAMPS it is good .
ObjectMapper objMapper = new ObjectMapper();
objMapper.registerModule(new JavaTimeModule());
objMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

Related

How to import data from csv to elasticsearch in java without using logstash?

I want to import data from a csv file to elasticsearch. But I don't want to use logstatsh. So, what are the ways I can do this ?
Any blogs ? Docs ?
I came across TransportClient, but I'm not getting the point from where to start .
Thanks in advance.
very late answer, however :) ….This is for elasticsearch 7.6.0
//this class for keeping csv each row values
public class Document {
private String id;
private String documentName;
private String name;
private String title;
private String dob;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getName() {
return name1;
}
public void setName(String name1) {
this.name1 = name1;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
public void bulkInsert() {
long starttime = System.currentTimeMillis();
logger.debug("ElasticSearchServiceImpl => bulkInsert Service Started");
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
BulkRequest request;
Document document;
//elastic Search Index Name
String esIndex = "post";
try {
br = new BufferedReader(new FileReader(<path to CSV>));
request = new BulkRequest();
while ((line = br.readLine()) != null) {
// use comma as separator
String[] row = line.split(cvsSplitBy);
if(row.length >= 1) {
//filling Document object using csv columns array
document = getDocEntity(row);
//adding each filled obect into BulkRequest
request.add(getIndexRequest(document, esIndex));
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : null row ="+row.toString());
}
}
br.close();
if(request.numberOfActions()>0) {
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
if(bulkResponse.hasFailures()) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Some of the record has failed.Please reinitiate the process");
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : Success");
}
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : No request for BulkInsert ="+request.numberOfActions());
}
} catch (Exception e) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Exception =" + e.getMessage());
}
long endTime = System.currentTimeMillis();
logger.info("ElasticSearchServiceImpl => bulkInsert End" + Util.DB_AVG_RESP_LOG + "" + (endTime - starttime));
}
public static Document getDocEntity(String[] row)throws Exception {
Document document = new Document();
document.setId(UUID.randomUUID().toString());
for(int i=0;i<row.length;i++) {
switch (i) {
case 0:
document.setDocumentName(row[i]);
break;
case 1:
document.setName(row[i]);
break;
case 7:
document.setTitle(row[i]);
break;
case 8:
document.setDob(row[i]);
break;
}
return document;
}
public static IndexRequest getIndexRequest(Document document,String index)throws Exception {
IndexRequest indexRequest = null;
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("doc_name",document.getDocumentName());
jsonMap.put("title",document.getTitle());
jsonMap.put("dob",document.getDob());
indexRequest = new IndexRequest(index).id(document.getId()).source(jsonMap);
return indexRequest;
}
If you need to show each response, you can use the following code for responses
for (BulkItemResponse bulkItemResponse : bulkResponse) {
DocWriteResponse itemResponse = bulkItemResponse.getResponse();
switch (bulkItemResponse.getOpType()) {
case INDEX:
case CREATE:
IndexResponse indexResponse = (IndexResponse) itemResponse;
break;
}
}
For more information please read official link

How to update/refresh list items of list view in oracle maf?

I have list of tasks. When I delete my one of the task my list still shows that task in the list but on server side i have updated list I am not able to refresh my list. I am getting new task array from server but not able to show it. When I launched my app again then it is showing the updated list. How can I get updated list without killing the app? Both the times I have updated array but not able to show it on the view.
public class ModelClass {
private String message;
private String statusCode;
private Response[] res = null;
protected transient PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
public ModelClass() {
super();
clickEvent(new ActionEvent());
}
public static String taskId;
public void setTaskId(String taskId) {
System.out.print(taskId);
this.taskId = taskId;
}
public String getTaskId() {
return taskId;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return _propertyChangeSupport;
}
public void setMessage(String message) {
String oldMessage = this.message;
this.message = message;
_propertyChangeSupport.firePropertyChange("message", oldMessage, message);
}
public String getMessage() {
return message;
}
public void setStatusCode(String statusCode) {
String oldStatusCode = this.statusCode;
this.statusCode = statusCode;
_propertyChangeSupport.firePropertyChange("statusCode", oldStatusCode, statusCode);
}
public String getStatusCode() {
return statusCode;
}
public void setRes(Response[] res) {
Response[] oldRes = this.res;
this.res = res;
System.out.println(res);
_propertyChangeSupport.firePropertyChange("res", oldRes, res);
System.out.println("refreshing here ");
}
public Response[] getRes() {
return res;
}
#Override
public String toString() {
return "ClassPojo [response = " + res + ", message = " + message + ", statusCode = " + statusCode + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
public class Response {
private String taskId;
private String taskType;
private Integer taskTime;
private String taskName;
private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
Response(String taskId, String taskType, String taskName) {
super();
this.taskId = taskId;
this.taskType = taskType;
this.taskName = taskName;
}
public void setTaskId(String taskId) {
String oldTaskId = this.taskId;
this.taskId = taskId;
_propertyChangeSupport.firePropertyChange("taskId", oldTaskId, taskId);
}
public String getTaskId() {
return taskId;
}
public void setTaskType(String taskType) {
String oldTaskType = this.taskType;
this.taskType = taskType;
_propertyChangeSupport.firePropertyChange("taskType", oldTaskType, taskType);
}
public String getTaskType() {
return taskType;
}
public void setTaskTime(Integer taskTime) {
Integer oldTaskTime = this.taskTime;
this.taskTime = taskTime;
_propertyChangeSupport.firePropertyChange("taskTime", oldTaskTime, taskTime);
}
public Integer getTaskTime() {
return taskTime;
}
public void setTaskName(String taskName) {
String oldTaskName = this.taskName;
this.taskName = taskName;
_propertyChangeSupport.firePropertyChange("taskName", oldTaskName, taskName);
}
public String getTaskName() {
return taskName;
}
#Override
public String toString() {
return "ClassPojo [taskId = " + taskId + ", taskType = " + taskType + ", taskTime = " + taskTime +
", taskName = " + taskName + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
}
protected transient ProviderChangeSupport providerChangeSupport = new ProviderChangeSupport(this);
public void addProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.addProviderChangeListener(l);
}
public void removeProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.removeProviderChangeListener(l);
}
public void clickEvent(ActionEvent actionEvent) {
try {
JSONObject paramsMap = new JSONObject();
paramsMap.put("userId", "1");
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/#########");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(120000);
httpURLConnection.setConnectTimeout(120000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
os.write(paramsMap.toString().getBytes());
bufferedWriter.flush();
bufferedWriter.close();
os.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line + "\n");
line = bufferedReader.readLine();
}
is.close();
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println(builder.toString());
JSONObject json = new JSONObject(builder.toString());
String status = json.optString("statusCode");
String message = json.optString("message");
String response = json.optString("response");
System.out.println(status);
System.out.println(message);
// System.out.println(response);
JSONArray objarr = json.optJSONArray("response");
Response[] temp_res = new Response[objarr.length()];
for (int i = 0; i < objarr.length(); i++) {
System.out.println(objarr.getJSONObject(i));
JSONObject obj = objarr.getJSONObject(i);
String task = obj.optString("taskName");
taskId = obj.optString("taskId");
String taskType = obj.optString("taskType");
System.out.println(task);
System.out.println(taskId);
System.out.println(taskType);
temp_res[i] = new Response(taskId, taskType, task);
}
setRes(temp_res);
} else {
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println("Invalid response from the server");
}
} catch (Exception e) {
e.printStackTrace();
if (httpURLConnection != null)
httpURLConnection.disconnect();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to add providerChangeSupport.fireProviderRefresh("res");
and you have to make public method for providerChangeSupport.
Here is the link : https://community.oracle.com/message/13203364#13203364
Other than the fix suggested by Rashi Verma, there is one more change required.
The code snippet:
res = (Response[]) res_new.toArray(new Response[res_new.size()]);
setRes(res);
needs to be changed to:
Response[] temp_res;
temp_res = (Response[]) res_new.toArray(new
Response[res_new.size()]);
setRes(temp_res);
Currently, because the value of res is changed before invoking setRes, the propertyChangeEvent is not fired inside setRes. Both this propertyChangeEvent and the providerRefresh are needed for the changes you are making to start reflecting on the UI.

Using one progressDialog in two or more android stringRequest Volley

In my code I have to stringRequest Volley that works just fine, but now I want to use a progressDialog. I have create 1 method to put the progressDialog like this
private void showProgress(String message) {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
and I have these 2 stringRequest like this:
private void fetchDataPoMurni(final String tipe, final String user_id, final String last_date) {
showProgress("Murni");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA MURNI: ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoMurni(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
and the other request:
private void fetchDataPoDapat(final String tipe, final String user_id, final String last_date) {
showProgress("Dapat");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA DAPAT : ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoDapat(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
I execute the 2 request through a method like this:
private void exeRequest() {
fetchDataPoMurni(valuea,value2,value3);
fetchDataPoDapat(valueb,value2,value3);
}
the progressDialog is showing, and the message is changing, but the problem is when reach the second request the progressDialog doesn't want to dismiss.
Whats wrong with my code above, and how to achieve what I want?
private void showProgress(String message) {
progressDialog=null;// Initialize to null
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
Try this .. Initialize all instances of the progressDialog to null as soon as you create a new progress dialog

Regarding DataControl in adf

I am developing an ADF web application with Oracle EBS as the backend to call the procedure(Jdeveloper 12 c).
I have invoked a method calling EBS procedure (return type is list) and the result is stored in arraylist. the list is used to create Data control.
What my problem is i have set values to the data control but when i added that dc to view it shows nothing. But on debugging it shows all the values are set in the array list.
Bean class calling EBS procedure in ApplicationModule
BindingContainer bindings = getBindings();
OperationBinding operationBinding = (OperationBinding) bindings.getOperationBinding("getIexpenseLogin");
List<EmployeePojo> result = (List<EmployeePojo>) operationBinding.execute();
System.out.println("Result= " + result);
employeeDC.getEmployeeLogin(result); // Here the list is passed to the Employee DC class to create data controll.
ApplicationModule Containing Custom Procedure
public List getIexpenseLogin(String username,String password){
CallableStatement cs=null;
List<EmployeePojo> empList=new ArrayList<>();
try{
cs=getDBTransaction().createCallableStatement("begin xx_oie_mob_login.oie_mob_login(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); end;",0);
cs.setString(1,username);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.VARCHAR);
cs.registerOutParameter(5, Types.VARCHAR);
cs.registerOutParameter(6, Types.NUMERIC);
cs.registerOutParameter(7, Types.VARCHAR);
cs.registerOutParameter(8, Types.NUMERIC);
cs.registerOutParameter(9, Types.VARCHAR);
cs.registerOutParameter(10, Types.NUMERIC);
cs.registerOutParameter(11, Types.VARCHAR);
cs.registerOutParameter(12, Types.NUMERIC);
cs.registerOutParameter(13, Types.BLOB);
cs.registerOutParameter(14, Types.VARCHAR);
cs.registerOutParameter(15, Types.VARCHAR);
cs.executeUpdate();
if(cs!=null)
{
EmployeePojo ePojo=new EmployeePojo();
ePojo.setEmployeeId(cs.getString(3));
ePojo.setEmployeeName(cs.getString(4));
ePojo.setEmployeeNumber(cs.getString(5));
ePojo.setManagerId(cs.getString(6));
ePojo.setManagerName(cs.getString(7));
ePojo.setJobId(cs.getString(8));
ePojo.setJobName(cs.getString(9));
ePojo.setOrgId(cs.getString(10));
ePojo.setOrgName(cs.getString(11));
ePojo.setImgId(cs.getString(12));
ePojo.setImage(cs.getBlob(13));
empList.add(ePojo);
}
return empList;
}catch(SQLException e){
throw new JboException(e);
}
}
EmployeeDC class used to create Data controll
public class EmployeeDC {
public EmployeeDC() {
super();
}
BindingContainer bindings = null;
private List<EmployeePojo> employee_data_controll=null;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setEmployee_data_controll(List<EmployeePojo> employee_data_controll) {
List<EmployeePojo> oldEmployee_data_controll = this.employee_data_controll;
this.employee_data_controll = employee_data_controll;
propertyChangeSupport.firePropertyChange("employee_data_controll", oldEmployee_data_controll,
employee_data_controll);
}
public List<EmployeePojo> getEmployee_data_controll() {
return employee_data_controll;
}
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
PropertyChangeSupport oldPropertyChangeSupport = this.propertyChangeSupport;
this.propertyChangeSupport = propertyChangeSupport;
propertyChangeSupport.firePropertyChange("propertyChangeSupport", oldPropertyChangeSupport,
propertyChangeSupport);
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void getEmployeeLogin(List<EmployeePojo> result) {
setEmployee_data_controll(result);
getEmployee_data_controll();
System.out.println("DataControl=>"+getEmployee_data_controll().get(0));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
EmployeePojo Class
public class EmployeePojo {
private String employeeId;
private String employeeName;
private String employeeNumber;
private String managerId;
private String managerName;
private String jobId;
private String jobName;
private String orgId;
private String orgName;
private String imgId;
private Blob image;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
this.propertyChangeSupport = propertyChangeSupport;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void setEmployeeId(String employeeId) {
String oldEmployeeId = this.employeeId;
this.employeeId = employeeId;
propertyChangeSupport.firePropertyChange("employeeId", oldEmployeeId, employeeId);
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeName(String employeeName) {
String oldEmployeeName = this.employeeName;
this.employeeName = employeeName;
propertyChangeSupport.firePropertyChange("employeeName", oldEmployeeName, employeeName);
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeNumber(String employeeNumber) {
String oldEmployeeNumber = this.employeeNumber;
this.employeeNumber = employeeNumber;
propertyChangeSupport.firePropertyChange("employeeNumber", oldEmployeeNumber, employeeNumber);
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setManagerId(String managerId) {
String oldManagerId = this.managerId;
this.managerId = managerId;
propertyChangeSupport.firePropertyChange("managerId", oldManagerId, managerId);
}
public String getManagerId() {
return managerId;
}
public void setManagerName(String managerName) {
String oldManagerName = this.managerName;
this.managerName = managerName;
propertyChangeSupport.firePropertyChange("managerName", oldManagerName, managerName);
}
public String getManagerName() {
return managerName;
}
public void setJobId(String jobId) {
String oldJobId = this.jobId;
this.jobId = jobId;
propertyChangeSupport.firePropertyChange("jobId", oldJobId, jobId);
}
public String getJobId() {
return jobId;
}
public void setJobName(String jobName) {
String oldJobName = this.jobName;
this.jobName = jobName;
propertyChangeSupport.firePropertyChange("jobName", oldJobName, jobName);
}
public String getJobName() {
return jobName;
}
public void setOrgId(String orgId) {
String oldOrgId = this.orgId;
this.orgId = orgId;
propertyChangeSupport.firePropertyChange("orgId", oldOrgId, orgId);
}
public String getOrgId() {
return orgId;
}
public void setOrgName(String orgName) {
String oldOrgName = this.orgName;
this.orgName = orgName;
propertyChangeSupport.firePropertyChange("orgName", oldOrgName, orgName);
}
public String getOrgName() {
return orgName;
}
public void setImgId(String imgId) {
String oldImgId = this.imgId;
this.imgId = imgId;
propertyChangeSupport.firePropertyChange("imgId", oldImgId, imgId);
}
public String getImgId() {
return imgId;
}
public void setImage(Blob image) {
Blob oldImage = this.image;
this.image = image;
propertyChangeSupport.firePropertyChange("image", oldImage, image);
}
public Blob getImage() {
return image;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}

AsyncTask Crashing on postExecute

I have a problem when using asyntask to query all the data in a table and put it in an array List and then send it to the server. I am able to send the data to the server successfully. But the application crashes on the postexecute of the asynctask giving the following error:
(W/System.err﹕ org.json.JSONException: Value ["com.atlantis.eclectics.agentbank.SyncMembersActivity$MemberRecords#41b06d18","com.atlantis.eclectics.agentbank.SyncMembersActivity$MemberRecords#41b070b8"] of type org.json.JSONArray cannot be converted to JSONObject)..
What could be problem? Where am i getting it wrong. Someone please help...Thanks very much.
package com.practical.tasks.school;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
#SuppressWarnings("deprecation")
public class SyncMembersActivity extends ActionBarActivity {
CustomHttpClient jParser = new CustomHttpClient();
ListView lstView;
public MainDB dbs;
public SQLiteDatabase db;
public static String fname;
String username = "atlantis";
String password = "#t1#ntis";
Button submit;
String statusN = "NO";
String statusY = "YES";
String url = "http://123.456.78.90:1234/Api/create/Post";
String FirstName = "";
String SecondName = "";
String MobileNumber = "";
String DateofBirth = "";
String Gender = "";
String GroupName = "";
String GroupAccountNo = "";
String IdentificationID = "";
String IdentificationType = null;
String CreatedBy = null;
String Residence = "";
private int notificationIdOne = 111;
private int numMessagesOne = 0;
private NotificationManager myNotificationManager;
String account_statusY = "True";
private ProgressDialog prgDialog;
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_members);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeActionContentDescription("Services");
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#5A92F7")));
lstView = (ListView) findViewById(R.id.lstSample);
submit = (Button) findViewById(R.id.upload);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isNetworkAvailable(getApplicationContext())) {
new HttpAsyncTask().execute(FirstName, SecondName, MobileNumber, DateofBirth, Gender, GroupName, GroupAccountNo, IdentificationID, IdentificationType, CreatedBy, Residence);
} else {
showAlert("No internet Connectivity...");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sync_members, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MemberRecords {
String FirstName;
String SecondName;
String MobileNumber;
String DateofBirth;
String Gender;
String GroupName;
String GroupAccountNo;
String IdentificationID;
String IdentificationType;
String CreatedBy;
String Residence;
public String getFirstName() {
return FirstName;
}
public String getSecondName() {
return SecondName;
}
public String getMobileNumber() {
return MobileNumber;
}
public String getDateofBirth() {
return DateofBirth;
}
public String getGender() {
return Gender;
}
public String getGroupName() {
return GroupName;
}
public String getGroupAccountNo() {
return GroupAccountNo;
}
public String getIdentificationID() {
return IdentificationID;
}
public String getIdentificationType() {
return IdentificationType;
}
public String getCreatedBy() {
return CreatedBy;
}
public String getResidence() {
return Residence;
}
public void setFirstName(String newfirstName) {
FirstName = newfirstName;
}
public void setSecondName(String newSecondName) {
SecondName = newSecondName;
}
public void setMobileNumber(String mobileNumber) {
MobileNumber = mobileNumber;
}
public void setDateofBirth(String dateofBirth) {
DateofBirth = dateofBirth;
}
public void setGender(String gender) {
Gender = gender;
}
public void setGroupName(String groupName) {
GroupName = groupName;
}
public void setGroupAccountNo(String groupAccountNo) {
GroupAccountNo = groupAccountNo;
}
public void setIdentificationID(String identificationID) {
IdentificationID = identificationID;
}
public void setIdentificationType(String identificationType) {
IdentificationType = identificationType;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public void setResidence(String residence) {
Residence = residence;
}
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
public static String POST(String url, MemberRecords my) {
InputStream inputStream;
String result = "";
String username = "atlantis";
String password = "#t1#ntis";
Integer n;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://41.186.47.26:4433/Api/Account/PostAddSignatory");
String json = "";
Log.e("Url", "Url Here:" + url);
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("FirstName", my.getFirstName());
jsonObject.accumulate("SecondName", my.getSecondName());
jsonObject.accumulate("MobileNumber", my.getMobileNumber());
jsonObject.accumulate("DateofBirth", my.getDateofBirth());
jsonObject.accumulate("Gender", my.getGender());
jsonObject.accumulate("GroupName", my.getGroupName());
jsonObject.accumulate("GroupAccountNo", my.getGroupAccountNo());
jsonObject.accumulate("IdentificationID", my.getIdentificationID());
jsonObject.accumulate("IdentificationType", my.getIdentificationType());
jsonObject.accumulate("CreatedBy", my.getCreatedBy());
jsonObject.accumulate("Residence", my.getResidence());
json = jsonObject.toString();
Log.e("Url", "Request:" + json);
StringEntity se = new StringEntity(json);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
Header header = new BasicScheme().authenticate(credentials, httpPost);
httpPost.addHeader(header);
httpPost.setEntity(se);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.e("InputStream", e.getLocalizedMessage());
//e.printStackTrace();
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException, JSONException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
Log.e("Url", "Response:" + result);
inputStream.close();
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prgDialog.show();
}
#Override
protected String doInBackground(String... urls) {
dbs = new MainDB(SyncMembersActivity.this);
db = dbs.getWritableDatabase();
Integer n=null;
MemberRecords my = new MemberRecords();
List<MemberRecords> member_list = new ArrayList<>();
try {
Cursor cursor = db.rawQuery("SELECT * FROM tbl_memberData" +
" where sync_status = '" + statusN + "' AND account_status = '" + account_statusY + "'", null);
if (cursor.moveToFirst()) {
do {
my = new MemberRecords();
my.setGroupName(cursor.getString(1));
my.setIdentificationID(cursor.getString(2));
my.setIdentificationType(cursor.getString(3));
my.setFirstName(cursor.getString(4));
my.setSecondName(cursor.getString(5));
my.setDateofBirth(cursor.getString(6));
my.setMobileNumber(cursor.getString(7));
my.setGender(cursor.getString(8));
my.setGroupAccountNo(cursor.getString(9));
my.setCreatedBy(cursor.getString(10));
my.setResidence(cursor.getString(11));
member_list.add(my);
} while (cursor.moveToNext());
}
cursor.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
for ( n = 0; n < member_list.size(); n++) {
POST(url, member_list.get(n));
}
db.close();
return String.valueOf(member_list);
}
//onPostExecute displays the results of the AsyncTask.
//Response format
//Response:{"ResponseCode":"00","ResponseMsg":"Successful"}
//Response:{"ResponseCode":"01","ResponseMsg":"Failed"}
#Override
protected void onPostExecute (String result){
prgDialog.dismiss();
Toast.makeText(getBaseContext(),"Saved Successfully",Toast.LENGTH_LONG).show();
dbs = new MainDB(SyncMembersActivity.this);
db = dbs.getWritableDatabase();
String updateQuery = "Update tbl_memberData set sync_status = '" + statusY + "' where account_status='" + account_statusY + "'";
db.execSQL(updateQuery);
String success="";
String message="";
try {
JSONObject jsonBreaker = new JSONObject(result);
success = jsonBreaker.getString("ResponseCode");
message = jsonBreaker.getString("ResponseMsg");
if (success.equalsIgnoreCase("00")) {
prgDialog.dismiss();
showAlert(message);
} else if (success.equalsIgnoreCase("01")) {
prgDialog.dismiss();
//do
showAlert(message);
} else {
prgDialog.dismiss();
Toast.makeText(getBaseContext(), "Error, Please try again...", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Server")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
If you would baste stacktrace and opoint where rxception is thrown would be much easier.
Anyway
Your result is probably and JSONArray not an JSONObject so this
JSONObject jsonBreaker = new JSONObject(result);
Is causing the exception. Construct JSONArray insteed of JSONObject and this shoult be fine (this is my blind guess cuz no viable info here)

Resources