Check for broken links using java code and link is not getting redirect - htmlunit

This code will check my link is broken or not and validateWebResourceUrl method will return 0 status .even if i get 200 status my link couldn't redirect to mozilla firefox when i call my api call.Below code will show u my api cal.
#RequestMapping(method = RequestMethod.POST, value = "/validate/fburl")
public ModelAndView validateFbLink(HttpServletRequest request,#RequestParam(value="key", required=true) String key ,#RequestParam(value = "link") String link, HttpServletResponse response) throws Exception {
ModelAndView jsonmodel = new ModelAndView("rest/model");
jsonmodel.addObject("model", httpFrameBreakChecker.validateHttpLink(link, key));
return jsonmodel;
}
This api call will go to check the link is broken or not ,if not it will go to redirect.I am trying to find the broken links and i am getting status 200 for that link but that link is not redirecting.Below is my code.
package org.ednovo.gooru.util;
import org.springframework.stereotype.Component;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
#Component
public class HttpFrameBreakChecker extends LinkChecker {
#Override
public Integer validateHttpLink(String resourceUrl, String key) {
Integer status = null;
status = validateWebResourceUrl(resourceUrl, getPageTesterPath());
putResourceStatus(status, key);
return status;
}
public synchronized Integer validateWebResourceUrl(String webURL, String pageTesterURL) {
WebClient webClient = null;
WebResponse webResponse = null;
try {
webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setCssEnabled(false);
webClient.setThrowExceptionOnScriptError(false);
webResponse = webClient.getPage(webURL).getWebResponse();
int i = webResponse.getStatusCode();
logger.info(i+"");
if (webResponse.getStatusCode() != 200) {
return null;
}
String urlToCheck = webURL + pageTesterURL;
// Now check if the page has a frame breaker.
webResponse = webClient.getPage(urlToCheck).getWebResponse();
int status = webResponse.getStatusCode();
logger.info(status+""+"frame");
String pageURL = webResponse.getWebRequest().getUrl().toString();
int validationStatus = (urlToCheck.equals(pageURL) && status == 200) ? 0 : 1;
logger.info(validationStatus+ " return statement of validateWebResourceUrl ");
return validationStatus;
} catch (Exception exception) {
logger.error("ERROR : Unable to start web driver : " + exception.getMessage());
return null;
} finally {
try {
if (webClient != null) {
webClient.closeAllWindows();
}
} catch (Exception ex) {
}
}
}
#Override
public void commitPage() {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/update/frameBreaker/" + getGlobalJobKey(), resourcesString);
postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString );
}
}
#Override
public String getType() {
return "FB";
}
}
And Below code will show you the LinkChecker class.
package org.ednovo.gooru.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public abstract class LinkChecker extends BaseComponent {
private int pageSize = 100;
private Map<String, String> configSettings;
private XStream xStream = new XStream(new DomDriver());
protected Map<Integer, List<String>> resources = new HashMap<Integer, List<String>>();
private String listResponse = null;
private Map<Long, String> resourceUrls = null;
public final synchronized void execute() {
reset();
ClientResource configResource = null;
Representation representation = null;
try {
configResource = createClientResource(getApiPath() + "/config-settings");
representation = configResource.get();
String settingsText = representation.getText();
configSettings = (Map<String, String>) xStream.fromXML(settingsText);
if (isLinkCheckerSchedulerEnabled()) {
run();
}
} catch (Exception exception) {
logger.error(exception.getMessage());
} finally {
releaseClientResources(configResource, representation);
}
}
public void run() throws Exception {
reset();
int page = 0;
while (true) {
++page;
listResponse = null;
resourceUrls = null;
final int currentPage = page;
ClientResourceExecuter clientResourceExecuter = new ClientResourceExecuter() {
#Override
public void run(ClientResource clientResource, Representation representation) throws Exception {
reset();
clientResource = createClientResource(getSearchApiPath() +"/search/resource-url-check?category="+getType()+"&pageSize="+pageSize+"&format=xml");
representation = clientResource.get();
listResponse = representation.getText();
if (listResponse != null || listResponse.length() > 1) {
try {
resourceUrls = (Map<Long, String>) xStream.fromXML(listResponse);
} catch (Exception ex) {
logger.error("Conversion of json to list failed in " + getType() + " validation");
}
logger.warn("Validating " + getType() + " Urls of Page : " + currentPage + " with size : " + (resourceUrls != null ? resourceUrls.size() : 0));
validateResourceUrls(resourceUrls);
}
}
};
clientResourceExecuter = null;
listResponse = null;
if (resourceUrls == null || resourceUrls.size() == 0) {
break;
}
if (getType().equals("HTTP") && page >= 5) {
break;
}else if (getType().equals("FB") && page >= 1) {
break;
}
}
}
public Integer validateHttpLink(String link, String key) {
URL url = null;
URLConnection connection = null;
HttpURLConnection httpConnection = null;
Integer responseCode = null;
try {
url = new URL(link);
connection = url.openConnection();
connection.connect();
httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(60000);
responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
logger.error("Url Checker validation fails for resource : " + link + " : " + responseCode);
}
} catch (MalformedURLException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (IOException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (Exception ex) {
logger.error("Error in link checker : " + link + " Message : " + ex.getMessage());
return null;
} finally {
try {
if (httpConnection != null) {
httpConnection.disconnect();
}
} catch (Exception ex) {
}
}
return responseCode;
}
protected void postData(String path, String url, String data) {
Form form = new Form();
form.add("data", data);
createAndRunClientResource(path, url, form);
}
public void validateResourceUrls(Map<Long, String> resourceUrls) throws Exception {
if (resourceUrls.size() > 0) {
Iterator<?> iterator = resourceUrls.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry<Long, String>) iterator.next();
String resourceUrl = entry.getValue();
if (getType().equals("FB")) {
Thread.sleep(1000);
} else {
Thread.sleep(900);
}
logger.debug("Validating " + getType() + " url - " + resourceUrl);
Integer status = validateHttpLink(resourceUrl, entry.getKey()+"");
putResourceStatus(status, entry.getKey()+"");
}
commitPage();
}
}
public void commitPage() throws Exception {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/checker/update/" + getGlobalJobKey(), resourcesString);
//postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString);
}
}
public void putResourceStatus(Integer status, String resourceId) {
if (status == null) {
status = -99;
}
List<String> resourceIds = null;
if (resources.containsKey(status)) {
resourceIds = resources.get(status);
} else {
resourceIds = new ArrayList<String>();
resources.put(status, resourceIds);
}
resourceIds.add(resourceId);
}
public void reset() {
resources.clear();
}
public boolean isLinkCheckerSchedulerEnabled() {
if (configSettings != null && configSettings.containsKey("urlChecker.scheduler.enabled")) {
return configSettings.get("urlChecker.scheduler.enabled").equals("true") ? true : false;
} else {
return false;
}
}
public abstract String getType();
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public XStream getxStream() {
return xStream;
}
public static void main(String args[]) {
}
}

Related

Spring Error while using filter and wrapper

I'm using the filter to check user rights.
Problem in comparing session value to param value is occurred and resolution load is applied using wrapper.
However, the following error message came out.
List<Map<String,Object>> loginInfo = (List<Map<String,Object>>)session.getAttribute("loginSession");
if loginInfo.get(0).get("user_type").equals("1") || loginInfo.get(0).get("user_type").equals("2"))
{
chain.doFilter(req, res);
}
else
{
RereadableRequestWrapper wrapperRequest = new RereadableRequestWrapper(request);
String requestBody= IOUtils.toString(wrapperRequest.getInputStream(), "UTF-8");
Enumeration<String> reqeustNames = request.getParameterNames();
if(requestBody == null) {
}
Map<String,Object> param_map = new ObjectMapper().readValue(requestBody, HashMap.class);
String userId_param = String.valueOf(param_map.get("customer_id"));
System.out.println(userId_param);
if( userId_param == null || userId_param.isEmpty()) {
logger.debug("error, customer_id error");
}
if (!loginInfo.get(0).get("customer_id").equals(userId_param))
{
logger.debug("error, customer_id error");
}
chain.doFilter(wrapperRequest, res);
}
/////////////////////////
here is my wrapper Code.
private boolean parametersParsed = false;
private final Charset encoding;
private final byte[] rawData;
private final Map<String, ArrayList<String>> parameters = new LinkedHashMap<String, ArrayList<String>>();
ByteChunk tmpName = new ByteChunk();
ByteChunk tmpValue = new ByteChunk();
private class ByteChunk {
private byte[] buff;
private int start = 0;
private int end;
public void setByteChunk(byte[] b, int off, int len) {
buff = b;
start = off;
end = start + len;
}
public byte[] getBytes() {
return buff;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public void recycle() {
buff = null;
start = 0;
end = 0;
}
}
public RereadableRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
String characterEncoding = request.getCharacterEncoding();
if (StringUtils.isBlank(characterEncoding)) {
characterEncoding = StandardCharsets.UTF_8.name();
}
this.encoding = Charset.forName(characterEncoding);
// Convert InputStream data to byte array and store it to this wrapper instance.
try {
InputStream inputStream = request.getInputStream();
this.rawData = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
throw e;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.rawData);
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
#Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setReadListener(ReadListener listener) {
// TODO Auto-generated method stub
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream(), this.encoding));
}
#Override
public ServletRequest getRequest() {
return super.getRequest();
}
#Override
public String getParameter(String name) {
if (!parametersParsed) {
parseParameters();
}
ArrayList<String> values = this.parameters.get(name);
if (values == null || values.size() == 0)
return null;
return values.get(0);
}
public HashMap<String, String[]> getParameters() {
if (!parametersParsed) {
parseParameters();
}
HashMap<String, String[]> map = new HashMap<String, String[]>(this.parameters.size() * 2);
for (String name : this.parameters.keySet()) {
ArrayList<String> values = this.parameters.get(name);
map.put(name, values.toArray(new String[values.size()]));
}
return map;
}
#SuppressWarnings("rawtypes")
#Override
public Map getParameterMap() {
return getParameters();
}
#SuppressWarnings("rawtypes")
#Override
public Enumeration getParameterNames() {
return new Enumeration<String>() {
#SuppressWarnings("unchecked")
private String[] arr = (String[])(getParameterMap().keySet().toArray(new String[0]));
private int index = 0;
#Override
public boolean hasMoreElements() {
return index < arr.length;
}
#Override
public String nextElement() {
return arr[index++];
}
};
}
#Override
public String[] getParameterValues(String name) {
if (!parametersParsed) {
parseParameters();
}
ArrayList<String> values = this.parameters.get(name);
String[] arr = values.toArray(new String[values.size()]);
if (arr == null) {
return null;
}
return arr;
}
private void parseParameters() {
parametersParsed = true;
if (!("application/x-www-form-urlencoded".equalsIgnoreCase(super.getContentType()))) {
return;
}
int pos = 0;
int end = this.rawData.length;
while (pos < end) {
int nameStart = pos;
int nameEnd = -1;
int valueStart = -1;
int valueEnd = -1;
boolean parsingName = true;
boolean decodeName = false;
boolean decodeValue = false;
boolean parameterComplete = false;
do {
switch (this.rawData[pos]) {
case '=':
if (parsingName) {
// Name finished. Value starts from next character
nameEnd = pos;
parsingName = false;
valueStart = ++pos;
} else {
// Equals character in value
pos++;
}
break;
case '&':
if (parsingName) {
// Name finished. No value.
nameEnd = pos;
} else {
// Value finished
valueEnd = pos;
}
parameterComplete = true;
pos++;
break;
case '%':
case '+':
// Decoding required
if (parsingName) {
decodeName = true;
} else {
decodeValue = true;
}
pos++;
break;
default:
pos++;
break;
}
} while (!parameterComplete && pos < end);
if (pos == end) {
if (nameEnd == -1) {
nameEnd = pos;
} else if (valueStart > -1 && valueEnd == -1) {
valueEnd = pos;
}
}
if (nameEnd <= nameStart) {
continue;
// ignore invalid chunk
}
tmpName.setByteChunk(this.rawData, nameStart, nameEnd - nameStart);
if (valueStart >= 0) {
tmpValue.setByteChunk(this.rawData, valueStart, valueEnd - valueStart);
} else {
tmpValue.setByteChunk(this.rawData, 0, 0);
}
try {
String name;
String value;
if (decodeName) {
name = new String(URLCodec.decodeUrl(Arrays.copyOfRange(tmpName.getBytes(), tmpName.getStart(), tmpName.getEnd())), this.encoding);
} else {
name = new String(tmpName.getBytes(), tmpName.getStart(), tmpName.getEnd() - tmpName.getStart(), this.encoding);
}
if (valueStart >= 0) {
if (decodeValue) {
value = new String(URLCodec.decodeUrl(Arrays.copyOfRange(tmpValue.getBytes(), tmpValue.getStart(), tmpValue.getEnd())), this.encoding);
} else {
value = new String(tmpValue.getBytes(), tmpValue.getStart(), tmpValue.getEnd() - tmpValue.getStart(), this.encoding);
}
} else {
value = "";
}
if (StringUtils.isNotBlank(name)) {
ArrayList<String> values = this.parameters.get(name);
if (values == null) {
values = new ArrayList<String>(1);
this.parameters.put(name, values);
}
if (StringUtils.isNotBlank(value)) {
values.add(value);
}
}
} catch (DecoderException e) {
// ignore invalid chunk
}
tmpName.recycle();
tmpValue.recycle();
}
}
and Error Message is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
I Don't know why this problem happened...

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

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)

How to use accesslog_parser.pl Kannel access log parser?

I have found kannel access log parser accesslog_parser.pl in utils folder.
How to use this file for parse.
Also i want convert kannel_access.log in csv format. Please help me.
Assuming Kannel log is at /var/log/kannel/access.log
This should do
cat /var/log/kannel/access.log |accesslog_parser.pl
May be an old question but I'd like to share this small tool a wrote in java for parsing kannel log files and outputing the results in csv format:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
/**
*
* #author bashizip
*/
public class KannelLogsParser {
static String fileName;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// fileName = args[0];
fileName = "access_kannel.txt";
String allLines = readLines(fileName);
parseAndWriteToCsv(allLines);
}
static String readLines(String fileName) {
BufferedReader br = null;
String sCurrentLine = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return sb.toString();
}
private static void parseAndWriteToCsv(String allLines) throws IOException {
String[] lines = allLines.split("\n");
System.out.println("lines to parse : " + lines.length);
StringTokenizer st;
StringBuilder output = new StringBuilder();
output.append("DATE;Heure;sent;SMS; SMSC; SVC; ACT; BINF; FID; from; to; flags; msg;;udh"+"\n");
int count = 0;
for (String line : lines) {
count++;
System.out.println("Parsing ..." + 100 * count / lines.length + "%");
st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
boolean messageToken = false;
boolean afterMessageToken = false;
if (currentToken.startsWith("[")) {
System.out.println(currentToken);
messageToken = currentToken.startsWith("[msg");
try {
currentToken = currentToken.substring(currentToken.indexOf(":") + 1, currentToken.indexOf("]"));
} catch (Exception e) {
System.err.println(e.getMessage());
messageToken = true;
currentToken = currentToken.substring(currentToken.indexOf(":") + 1);
}
}
currentToken = currentToken.replace("[", "");
currentToken = currentToken.replace("]", "");
output.append(currentToken);
if (!messageToken) {
output.append(";");
} else if (afterMessageToken) {
afterMessageToken = false;
output.append(" ");
} else {
output.append(" ");
afterMessageToken = true;
}
}
output.append("\n");
}
Files.write(Paths.get(fileName + ".csv"), output.toString().getBytes());
System.out.println("Output CVS file: " + fileName + ".csv");
System.out.println("Finished !");
}
}
Hope it can help someone one day :-)

Resources