How to sanitize request object in the #restcontroller - spring

I'm doing a static code analysis using checkmarx, which gave me medium vulnerabilities for #RequestBody.
Will place a sample code below, could someone help me fixing this issue.
#RestController
#RequestMapping("/api")
#Slf4j
#Validated
public class Myclass {
#Autowired
SplitClass split;
#PostMapping(path = "/something", consumes = "application/json", produces = "application/json")
public int splitter(#RequestBody SplitRequestVO **splitReq**) {
int response = 0;
try {
int value = split.methodName(splitReq);
if(value == 1) {
response = 1;
}else {
response = 0;
}
}catch(Exception e) {
log.error("Excpetion in the MY Class controller" +e.getMessage());
}
return response;
}
}
Every time it is showing error with this util class. please check whats wrong in this class.
#Slf4j
public class FileUtil {
private FileUtil() {
throw new IllegalArgumentException("FileUtil.class");
}
public static void createFileFromBytes(String fileName, byte[] bytes) throws IOException {
File file = new File(fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(bytes);
fos.flush();
} catch (IOException exc) {
log.error("Exception in creating file from bytes : "+exc.getMessage());
}
}
public static void deleteFile(String fileName) {
log.info("Entry into deleteFile method.");
try {
File file = new File(fileName);
if (file.exists()) {
Files.delete(file.toPath());
if (log.isDebugEnabled())
log.debug("file deleted:" + fileName);
}
} catch (Exception e) {
log.error("Exception in deleting the file : "+e.getMessage());
}
log.info("Exit from deleteFile method ");
}
public static byte[] getBytesFromFile(File file) throws IOException {
log.info("Entry into getBytesFromFile method");
byte[] bytes = null;
try (InputStream is = new FileInputStream(file)) {
long length = file.length();
if (length > 2147483647L) {
log.error("File Too large:" + file.getName());
}
bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)
offset += numRead;
if (offset < bytes.length)
throw new IOException("Could not completely read file " + file.getName());
} catch (Exception e) {
log.error("Exception in getBytesFromFile : "+e.getMessage());
}
log.info("Exit from getBytesFromFile method ");
return bytes;
}
public static byte[] getBytesFromFile(String fileName) throws IOException {
File file = new File(fileName);
return getBytesFromFile(file);
}
}
Here im facing the vulnerability issue to fix in the block letters. Appreciated foy help.
Thanks in advance.

Related

I want to upload file without using multipart in spring boot, would be great if I could get you valuable suggestions on this

Shall I remove this from application.properties
spring.http.multipart.enabled=true
What should be my approach towards this file upload without using multipart?
This way, I'm able to uploading file using where I'm using multipart.
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam(value = "picture", required = false) MultipartFile multipartFile,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!multipartFile.isEmpty()) {
String multipartFileName = multipartFile.getOriginalFilename();
String format = multipartFileName.substring(multipartFileName.lastIndexOf("."));
try {
Path path = Paths.get(DOG_IMAGES_BASE_LOCATION + "/" + name + format);
byte[] bytes = multipartFile.getBytes();
File file = new File(path.toString());
file.createNewFile();
Files.write(path, bytes);
if (file.length() == 0) {
response = utility.createResponse(500, Keyword.ERROR, "Image upload failed");
} else {
String dbPath = path.toString().replace('\\', '/');
dog = new Dog();
dog.setName(name);
dog.setPicture(dbPath);
dog = dogService.dogCreation(dog);
response = utility.createResponse(200, Keyword.SUCCESS, "Image upload successful");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I want to do it without using multipart, what would you suggest?
This is what I've done till now to solve this
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam("picture") String picture,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!picture.isEmpty()) {
String dogPicture = picture;
byte[] encodedDogPicture = Base64.encodeBase64(dogPicture.getBytes());
String format = dogPicture.substring(picture.lastIndexOf("."));
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I just have to say that this should probably only be used as a workaround.
On your frontend, convert the file to base64 in js:
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt) {
console.log(evt.target.result);
//do POST here - something like this:
$.ajax("/upload64", {
method: "POST",
contentType: "application/text"
data: evt.target.result
}
};
On the server with an example of a decoder - more decoding options here Decode Base64 data in Java
import sun.misc.BASE64Decoder;
#PostMapping("/upload64")
public String uploadBase64(#RequestBody String payload){
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
//use your bytes
}

JSON Array With Volley Showing Only One data

I am trying to display array data using JSON Volley in PostsBasedOnCategory.java. Array data that I want to display are, Title post, and excerpt based on specific category from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But unfortunately, it only showing one result.
Below you can check my code
DaftarCategories.java
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) { //ambil semua objek yang ada
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(0); //ambil satu objek saja
String postCategoryUrl = postCategoryIndex.getString("href"); //satu objek yang dimaksud adalah href
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonArrayRequest getKonten = new JsonArrayRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray respon) {
Log.d(TAG, respon.toString() + "Size: "+respon.length());
for(int d=0; d<respon.length(); d++) {
try {
//Log.d(TAG, "Object at " + i + respon.get());
JSONObject objek = respon.getJSONObject(d); //ambil semua artikel yang tersedia di postCategoryUrl
post.setId(objek.getInt("id"));
post.setCreatedAt(objek.getString("date"));
post.setPostURL(objek.getString("link"));
//Get category title
JSONObject titleObj = objek.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get excerpt
JSONObject exerptObj = objek.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get content
JSONObject contentObj = objek.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
}// for category
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
//gambar = click.getPostImg();
judul = click.getJudul();
//url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("judul", judul);
//bundle.putString("gambar", gambar);
//bundle.putString("url", url);
bundle.putString("content", content);
bundle.putString("excerpt", excerpt);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory.java
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
typeForPosts = new ArrayList<CategoriesModel>();
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
loadData();
}
public void loadData() {
Bundle bundel = this.getArguments();
long id = bundel.getLong("id");
String kategori = bundel.getString("kategori");
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel list = new CategoriesModel();
list.setId(id);
list.setCategory(kategori);
list.setJudul(title);
list.setExcerpt(excerpt);
list.setPostImg(pict);
list.setPostURL(url);
list.setContent(konten);
typeForPosts.add(list);
}
Logcat
2019-09-07 12:01:27.941 11246-11246/com.kursusarabic.arabicforfun D/postFrag: [{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":26,"count":8,"description":"","link":"https:\/\/kisahmuslim.com\/category\/download","name":"Download","slug":"download","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/26"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=26"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":1812,"count":9,"description":"","link":"https:\/\/kisahmuslim.com\/category\/info","name":"Info","slug":"info","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/1812"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1812"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":17,"count":3,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-birrul-walidain","name":"Kisah Birrul Walidain","slug":"kisah-birrul-walidain","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/17"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=17"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":25,"count":31,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-hidayah-islam","name":"Kisah Hidayah Islam","slug":"kisah-hidayah-islam","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/25"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":16,"count":49,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-kaum-durhaka","name":"Kisah Kaum Durhaka","slug":"kisah-kaum-durhaka","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/16"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: Object at 0{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
You cannot call network requests in loop, Use async processing or
Retrofit & RxJava multiple requests complete
and after updating typeForPosts, there is no need to setAdapter on recyclerview just call adapter.notifyDataSetChanged()

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.

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

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[]) {
}
}

How do I get to load image in J2ME?

I am using TimerTask and ImageLoader class to load n image to an image item.
public class Imageloader implements Runnable{
private ImageItem item=null;
private String url=null;
/*
* initializes the imageItem
*/
public Imageloader(ImageItem item,String url){
this.item=item;
this.url=url;
}
private Image getImage(String url) throws IOException {
item.setLabel(item.getLabel()+12);
System.out.println("Test 5");
HttpConnection connection = null;
DataInputStream inp = null;
int length;
byte[] data;
try {System.out.println("Test 6");
connection = (HttpConnection) Connector.open(url);
item.setLabel(item.getLabel()+13);
connection.getResponseMessage();
System.out.println("Test 7");
length = (int) connection.getLength();
item.setLabel(item.getLabel()+14);
System.out.println("Length is "+length);
System.out.println("Test 8");
data = new byte[length];
inp = new DataInputStream(connection.openInputStream());
item.setLabel(item.getLabel()+15);
System.out.println("Test 9");
inp.readFully(data);
item.setLabel(item.getLabel()+16);
System.out.println("Test 10");
return Image.createImage(data, 0, data.length);
}
finally {
if (connection != null) connection.close();
if (inp != null)inp.close();
}
}
public void run() {
System.out.println("Test 1");
Image image=null;
try{
if (url!=null){
System.out.println("Test 2");
image=getImage(url);
System.out.println("Test 3");
item.setImage(image);
item.setLabel(item.getLabel()+17);
System.out.println("Test 4");
}
else{
item.setAltText("Map address specified is incorrect");
}
}
catch(IOException e){
item.setAltText("Map cannot be loaded now");
}
}
}
public class MapTimer extends TimerTask{
DatagramConnection connection=null;
String message=null;
Imageloader imageretriever;
ImageItem item=null;
MapTimer (DatagramConnection connection,String message,ImageItem Img_map ){
this.connection=connection;
this.message=message;
this.item=Img_map;
item.setLabel(item.getLabel()+1);
System.out.println("Map is initizlized...");
}
public void run() {
System.out.println("Map starting...");
item.setLabel(item.getLabel()+2);
String serverquery=null;
try {
item.setLabel(item.getLabel()+3);
sendMessage(message);
item.setLabel(item.getLabel()+4);
//serverquery=receiveMessage() ;
item.setLabel(item.getLabel()+5);
//item.setLabel(" Loading...." );
//formatmessage(serverquery);
String url="http://maps.google.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=14&size=512x512&maptype=roadmap"+
"&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318"+
"&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false";
Imageloader Im=new Imageloader(item,url);
item.setLabel(item.getLabel()+6);
(new Thread(Im)).start();
item.setLabel(item.getLabel()+7);
System.out.println("server map query is::: "+serverquery);
} catch (IOException ex) {
System.out.println("Error2"+ex);
}
catch(Exception e){
System.out.println("Error3"+e);
}
}
/*
* Sends a message via UDP to server
*/
private void sendMessage(String message) throws IOException{
Datagram packet_send=null;
if (connection != null){
byte[] packetsenddata=message.getBytes();
packet_send = connection.newDatagram(packetsenddata,packetsenddata.length);
connection.send(packet_send);
packet_send = null;
}
}
}
This is how I set the Timer;
MapTimer maptimer=new MapTimer (connection,mapquery ,Img_map );
Timer timer=new Timer();
timer.schedule(maptimer, 5000, 100000);
It's working fine with the enulator but as I deploy it on my mob,the image is not loading..
The image label is somewhat like Stopping 234567234567 which implies that my timer is running fine. It is not entering the ImageLoader class... How do get to load this image?
This is difficult to say without further debuggind. I recommend you to use Micrologger + a web server, in order to debug your midlets on the device.
Looking to your code, I suspect of this line length = (int) connection.getLength();. Could it fail on Nokia's IO library implementation?

Resources