Malformed URL no protocol error [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}

First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.

You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction

This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction

Related

Vaadin grid.setItems not working in propertyChange methode

I have created a vaadin application using vaadin 14, i have a class accordion that passes an object HandlerTest to class Grid using a propertyChange listener. The object do pass to the grid class but when i try to use grid.setItems to show it it doesn't work. grid.setItems does add the object if i add it from the constructer but don't if i add it from the propertyChange methode.
Here is the code i used for bothe classes and the main class:
the Grid class:
`
package org.vaadin.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
#Route("grid")
public final class GridClass extends VerticalLayout implements PropertyChangeListener {
HandlerTest ht = new HandlerTest();
List<HandlerTest> list = new ArrayList<>();
Grid<HandlerTest> grid = new Grid<>();
public GridClass() {
grid.addColumn(HandlerTest::getPattern).setHeader("Pattern");
grid.addColumn(HandlerTest::getModuleName).setHeader("Module");
grid.setItems(list);
grid.getDataProvider().refreshAll();
grid.setAllRowsVisible(true);
grid.setHeight("480px");
add(grid);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
HandlerTest newHandler = (HandlerTest) evt.getNewValue();
ht = newHandler;
list.add(ht);
Notification.show("Value of obj :" + evt.getNewValue());
grid.getDataProvider().refreshAll();
}
}
`
here is the HandlerTest class:
`
package org.vaadin.example;
public class HandlerTest implements java.io.Serializable{
private String moduleName;
private String pattern;
private String method;
private String sourceType;
private String itemsPerPage;
private String mimesAllowed;
private String comments;
private String pSource;
public HandlerTest(String moduleName, String pattern, String method, String sourceType, String itemsPerPage, String mimesAllowed, String comments, String pSource) {
this.moduleName = moduleName;
this.pattern = pattern;
this.method = method;
this.sourceType = sourceType;
this.itemsPerPage = itemsPerPage;
this.mimesAllowed = mimesAllowed;
this.comments = comments;
this.pSource = pSource;
}
public HandlerTest() {
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getItemsPerPage() {
return itemsPerPage;
}
public void setItemsPerPage(String itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
public String getMimesAllowed() {
return mimesAllowed;
}
public void setMimesAllowed(String mimesAllowed) {
this.mimesAllowed = mimesAllowed;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getpSource() {
return pSource;
}
public void setpSource(String pSource) {
this.pSource = pSource;
}
#Override
public String toString() {
return moduleName + "/" + pattern + "/" + method + "/" + sourceType + "/" + itemsPerPage + "/" + mimesAllowed
+ "/" + comments + "/" + pSource ;
}
public HandlerTest createHandlerFromString(HandlerTest h){
String[] handlerText = (h.toString()).split("/");
HandlerTest handler = new HandlerTest(handlerText[0], handlerText[1], handlerText[2], handlerText[3],
handlerText[4], handlerText[5], handlerText[6], handlerText[7]);
return handler;
}
}
`
i was expecting the grid to be refreshed and the item is added but nothing happened. The notification shows the object to display but the grid don't add it.

RestTemplate returning null when serialized to POJO

I was following the start-up guide of at spring website https://spring.io/guides/gs/consuming-rest/.
I am not following the exact tutorial in the sense that I am using another endpoint: http://www.omdbapi.com?s=rush.
I am having an issue with JSON conversion to POJO. I am not getting any error or exceptions. Could someone point out where am I going wrong?
You can find the complete code here
Here are my POJOs:
package com.sample.restapi.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResponse {
private List<Search> search;
private String totalResults;
private String response;
public SearchResponse() {
}
public List<Search> getSearch() {
return search;
}
public void setSearch(List<Search> search) {
this.search = search;
}
public String getTotalResults() {
return totalResults;
}
public void setTotalResults(String totalResults) {
this.totalResults = totalResults;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#Override
public String toString() {
return "SearchResponse [search=" + search + ", totalResults=" + totalResults + ", response=" + response + "]";
}
}
Here is the Search.java
package com.sample.restapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Search {
private String title;
private String year;
private String imdbID;
private String type;
private String poster;
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Search [title=" + title + ", year=" + year + ", imdbID=" + imdbID + ", type=" + type + ", poster="
+ poster + "]";
}
}
Here is the driver class.
package com.sample.restapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
import com.sample.restapi.model.SearchResponse;
#SpringBootApplication
public class ConsumerApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumerApplication.class);
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SearchResponse searchResponse = restTemplate.getForObject("http://www.omdbapi.com?s=rush", SearchResponse.class);
log.info(searchResponse.toString());
}
}
The console output is :
14:34:12.941 [main] INFO com.sample.restapi.ConsumerApplication - SearchResponse [search=null, totalResults=344, response=null]
You are missing correct identifiers for the properties in the json, there are differences in the response and your classes in the Capital and lower case letters. Use #JsonProperty in your classes.
#JsonProperty("Search")
private List<Search> search = new ArrayList<Search>();
private String totalResults;
#JsonProperty("Response")
private String response;
you should also add #JsonProperty annotations in the Search class.

Gson conversion returning null java object

I am trying to convert json string in java bean using Gson but it is returnig null value.
public static void convert(String args) {
String json =
"{"body":{"response":{"total":"294","num":"294","filelist":[{"id":"56712","camname":"Camera1","camid":"514","start":"2016-07-08 12:00:38","end":"2016-07-08 12:03:00","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg","nvrip":"192.168.0.200:8095"},{"id":"56708","camname":"Camera1","camid":"514","start":"2016-07-08 11:58:14","end":"2016-07-08 12:00:36","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg","nvrip":"192.168.0.200:8095"},{"id":"56705","camname":"Camera1","camid":"514","start":"2016-07-08 11:55:49","end":"2016-07-08 11:58:11","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg","nvrip":"192.168.0.200:8095"},{"id":"56702","camname":"Camera1","camid":"514","start":"2016-07-08 11:53:25","end":"2016-07-08 11:55:47","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg","nvrip":"192.168.0.200:8095"},{"id":"56699","camname":"Camera1","camid":"514","start":"2016-07-08 11:51:00","end":"2016-07-08 11:53:22","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg","nvrip":"192.168.0.200:8095"}],"status":"OK"}}}";
// Now do the magic.
RecordingListResponseDTO data = new Gson().fromJson(json, RecordingListResponseDTO .class);
// Show it.
System.out.println("converted data :"+data);
}
My Bean Class is following.
RecordingListResponseDTO
public class RecordingListResponseDTO implements Serializable {
private String status;
private int total;
private int num;
List<FileListDTO> fileList;
public RecordingListResponseDTO(){
}
public RecordingListResponseDTO(String status, int total, int num, List<FileListDTO> fileList) {
this.status = status;
this.total = total;
this.num = num;
this.fileList = fileList;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List<FileListDTO> getFileList() {
return fileList;
}
public void setFileList(List<FileListDTO> fileList) {
this.fileList = fileList;
}
#Override
public String toString() {
return "RecordingListResponseDTO{" +
"status='" + status + '\'' +
", total=" + total +
", num=" + num +
", fileList=" + fileList +
'}';
}}
FileListDTO.java
public class FileListDTO {
private int id;
private String camname;
private int camid;
private Date start;
private Date end;
private int stream;
private String recReason;
private String filename;
private String snapshot;
private String nvrip;
public FileListDTO(int id, String camname, Date start, int camid, Date end, int stream, String recReason, String filename, String snapshot, String nvrip) {
this.id = id;
this.camname = camname;
this.start = start;
this.camid = camid;
this.end = end;
this.stream = stream;
this.recReason = recReason;
this.filename = filename;
this.snapshot = snapshot;
this.nvrip = nvrip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCamname() {
return camname;
}
public void setCamname(String camname) {
this.camname = camname;
}
public int getCamid() {
return camid;
}
public void setCamid(int camid) {
this.camid = camid;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public int getStream() {
return stream;
}
public void setStream(int stream) {
this.stream = stream;
}
public String getRecReason() {
return recReason;
}
public void setRecReason(String recReason) {
this.recReason = recReason;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getSnapshot() {
return snapshot;
}
public void setSnapshot(String snapshot) {
this.snapshot = snapshot;
}
public String getNvrip() {
return nvrip;
}
public void setNvrip(String nvrip) {
this.nvrip = nvrip;
}
#Override
public String toString() {
return "FileListDTO{" +
"id=" + id +
", camname='" + camname + '\'' +
", camid=" + camid +
", start=" + start +
", end=" + end +
", stream=" + stream +
", recReason='" + recReason + '\'' +
", filename='" + filename + '\'' +
", snapshot='" + snapshot + '\'' +
", nvrip='" + nvrip + '\'' +
'}';
}}
I am getting null value after converting Json string to Java object.
what I am doing wrong please suggest me.
Thank in advance.
Prerequisites:
Following JSON has been used:
{
"body":{
"response":{
"total":294,
"num":294,
"filelist":[
{
"id":56712,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 12:00:38",
"end":"2016-07-08 12:03:00",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56708,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:58:14",
"end":"2016-07-08 12:00:36",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56705,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:55:49",
"end":"2016-07-08 11:58:11",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56702,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:53:25",
"end":"2016-07-08 11:55:47",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56699,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:51:00",
"end":"2016-07-08 11:53:22",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg",
"nvrip":"192.168.0.200:8095"
}
],
"status":"OK"
}
}
}
Step 1:
Modify the declaration of private List<FileListDTO> fileList in RecordingListResponseDTO.java as follows:
#SerializedName("filelist")
private List<FileListDTO> fileList
Step 2:
Define following class MyDateTypeAdapter.java:
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class MyDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private DateFormat dateFormat;
public MyDateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
#Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
#Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Step 3:
Modify the method convert(String args) as follows:
public static void convert(String args) {
JsonParser parser = new JsonParser();
String json = parser.parse(args)
.getAsJsonObject()
.getAsJsonObject("body")
.getAsJsonObject("response")
.toString();
// Now do the magic.
RecordingListResponseDTO data = new GsonBuilder()
.registerTypeAdapter(Date.class, new MyDateTypeAdapter())
.create().fromJson(json, RecordingListResponseDTO.class);
// Show it.
System.out.println("converted data :"+data);
}
For testing purpose, you may try storing the JSON in a file i.e. D:/test.json and call the method by:
String json = new String(Files.readAllBytes(Paths.get("D:/test.json")));
convert(json);
something you need to change the models class like,
Initially in your json response data contains "body" tag that's represents to object, initially you need to create the class for object tag,then all data contains inside your "body" tag, so parse all data inside from body data,
may help this code,
public class RecordingListResponseDTO implements Serializable {
Recordinglist body;
public class Recordinglist(){
Recordresponse response;
public class Recordresponse(){
String total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
}
}

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

Finding Latitude and Longitude via Zip Codes in Java

I'm having trouble retrieving latitude and longitude values from a given zip code. I'm attempting to do this via a Servlet, i.e. a zip code value is passed into the Servlet, and the Java code then uses the Google Geocode API to retrieve the latitude and longitude values, preferably in a String.
I've roamed all over the net for a simple sample, but there seems to be more Javascript and PHP methods for this than Java.
Could someone please paste a simple sample of how to extract the lat/long values in this manner?
Thanks in advance!!
-Rei
OK long answer. This is some code I have used succesfully to interrogate Google Geocode API. It requires to work with GSon but alternatively you can probably decode the answers manually if you don't want to use GSon:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.slf4j.Logger;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
public class GeoCoder {
private Gson gson = new Gson();
private volatile long lastRequest = 0L;
public GeocodeResponse getLocation(String... addressElements) throws JsonSyntaxException, JsonIOException, MalformedURLException,
IOException {
StringBuilder sb = new StringBuilder();
for (String string : addressElements) {
if (sb.length() > 0) {
sb.append('+');
}
sb.append(URLEncoder.encode(string.replace(' ', '+'), "UTF-8"));
}
String url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + sb.toString();
// Google limits this web service to 2500/day and 10 requests/s
synchronized (this) {
try {
long elapsed = System.currentTimeMillis() - lastRequest;
if (elapsed < 100) {
try {
Thread.sleep(100 - elapsed);
} catch (InterruptedException e) {
}
}
return gson.fromJson(new BufferedReader(new InputStreamReader(new URL(url).openStream())), GeocodeResponse.class);
} finally {
lastRequest = System.currentTimeMillis();
}
}
}
}
And the other classes:
GeocodeResponse:
import java.util.List;
public class GeocodeResponse {
public enum Status {
OK, ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED, INVALID_REQUEST;
}
public static class Result {
public static enum Type {
street_address,
route,
intersection,
political,
country,
administrative_area_level_1,
administrative_area_level_2,
administrative_area_level_3,
colloquial_area,
locality,
sublocality,
neighborhood,
premise,
subpremise,
postal_code,
natural_feature,
airport,
park,
point_of_interest,
post_box,
street_number,
floor,
room;
}
public static class AddressComponent {
private String long_name;
private String short_name;
private Type[] types;
public String getLong_name() {
return long_name;
}
public void setLong_name(String long_name) {
this.long_name = long_name;
}
public String getShort_name() {
return short_name;
}
public void setShort_name(String short_name) {
this.short_name = short_name;
}
public Type[] getTypes() {
return types;
}
public void setTypes(Type[] types) {
this.types = types;
}
}
private String formatted_address;
private List<AddressComponent> address_components;
private Geometry geometry;
private Type[] types;
public Type[] getTypes() {
return types;
}
public void setTypes(Type[] types) {
this.types = types;
}
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
public List<AddressComponent> getAddress_components() {
return address_components;
}
public void setAddress_components(List<AddressComponent> address_components) {
this.address_components = address_components;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
}
public static class Geometry {
public static enum LocationType {
ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE;
}
public static class ViewPort {
private Location northeast;
private Location southwest;
public Location getNortheast() {
return northeast;
}
public void setNortheast(Location northeast) {
this.northeast = northeast;
}
public Location getSouthwest() {
return southwest;
}
public void setSouthwest(Location southwest) {
this.southwest = southwest;
}
}
private Location location;
private LocationType location_type;
private ViewPort viewport;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public LocationType getLocation_type() {
return location_type;
}
public void setLocation_type(LocationType location_type) {
this.location_type = location_type;
}
public ViewPort getViewport() {
return viewport;
}
public void setViewport(ViewPort viewport) {
this.viewport = viewport;
}
}
private Status status;
private List<Result> results;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Location:
public class Location {
private double lat;
private double lng;
public Location() {
}
public Location(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}
This isn't as elegant as Guillaume Polet's answer, however it doesn't need additional libraries.
With the argument:
"1600 Amphitheatre Parkway, Mountain View, CA"
It prints the answer:
Latitude: 37.42207610
Longitude: -122.08451870
Here is the code:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class GoogleGeoCode
{
private static final String GEO_CODE_SERVER = "http://maps.googleapis.com/maps/api/geocode/json?";
public static void main(String[] args)
{
String code = args[0];
String response = getLocation(code);
String[] result = parseLocation(response);
System.out.println("Latitude: " + result[0]);
System.out.println("Longitude: " + result[1]);
}
private static String getLocation(String code)
{
String address = buildUrl(code);
String content = null;
try
{
URL url = new URL(address);
InputStream stream = url.openStream();
try
{
int available = stream.available();
byte[] bytes = new byte[available];
stream.read(bytes);
content = new String(bytes);
}
finally
{
stream.close();
}
return (String) content.toString();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private static String buildUrl(String code)
{
StringBuilder builder = new StringBuilder();
builder.append(GEO_CODE_SERVER);
builder.append("address=");
builder.append(code.replaceAll(" ", "+"));
builder.append("&sensor=false");
return builder.toString();
}
private static String[] parseLocation(String response)
{
// Look for location using brute force.
// There are much nicer ways to do this, e.g. with Google's JSON library: Gson
// https://sites.google.com/site/gson/gson-user-guide
String[] lines = response.split("\n");
String lat = null;
String lng = null;
for (int i = 0; i < lines.length; i++)
{
if ("\"location\" : {".equals(lines[i].trim()))
{
lat = getOrdinate(lines[i+1]);
lng = getOrdinate(lines[i+2]);
break;
}
}
return new String[] {lat, lng};
}
private static String getOrdinate(String s)
{
String[] split = s.trim().split(" ");
if (split.length < 1)
{
return null;
}
String ord = split[split.length - 1];
if (ord.endsWith(","))
{
ord = ord.substring(0, ord.length() - 1);
}
// Check that the result is a valid double
Double.parseDouble(ord);
return ord;
}
}

Categories