Finding Latitude and Longitude via Zip Codes in Java - 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;
}
}

Related

Parsing JSON in Android, not getting value

I am able to parse everything i need, except for the target_id's in the field_exercis_arc. I get the nid, title and body. Not sure how to get the id's in the field_exercis_arc.
The JSON
[{
"nid": "26",
"title": "Question test",
"body": "xcvxcv",
"field_exercis_arc": ["25","27"]
}]
The Code
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ExerciseModel> exerciseModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
title_exi = finalObject.getString("title");
text_exi = finalObject.getString("body");
//This part is working.
ExerciseModel exerciseModel = new ExerciseModel();
exerciseModel.setTitle(finalObject.getString("title"));
exerciseModel.setNid(finalObject.getInt("nid"));
exerciseModel.setBody(finalObject.getString("body"));
//Problem with this part, not getting the target_id's.
List<ExerciseModel.Exer> exerList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("field_exercis_arc").length(); j++){
ExerciseModel.Exer exercis = new ExerciseModel.Exer();
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getJSONObject(j).getString("target_id"));
exerList.add(exercis);
}
exerciseModel.setExerList(exerList);
exerciseModelList.add(exerciseModel);
mDB.saveRecordEX(exerciseModel);
}
The model for the field_exercis_arc and target_id's fields
private List<Exer> exerList;
public List<Exer> getExerList() {
return exerList;
}
public void setExerList(List<Exer> exerList) {
this.exerList = exerList;
}
public static class Exer{
private String target_id;
public String getTarget_id() {
return target_id;
}
public void setTarget_id(String target_id) {
this.target_id = target_id;
}
}
Thanks in advance
I recommend you to use GSON library to get result from JSON. For that you will need Java class in order to parse result to object. For this you can use JSON to Java Class conversion here.
For you example classes would be:
public class Und
{
private String value;
public String getValue() { return this.value; }
public void setValue(String value) { this.value = value; }
}
public class Body
{
private ArrayList<Und> und;
public ArrayList<Und> getUnd() { return this.und; }
public void setUnd(ArrayList<Und> und) { this.und = und; }
}
public class Und2
{
private String target_id;
public String getTargetId() { return this.target_id; }
public void setTargetId(String target_id) { this.target_id = target_id; }
}
public class FieldExercisArc
{
private ArrayList<Und2> und;
public ArrayList<Und2> getUnd() { return this.und; }
public void setUnd(ArrayList<Und2> und) { this.und = und; }
}
public class RootObject
{
private String vid;
public String getVid() { return this.vid; }
public void setVid(String vid) { this.vid = vid; }
private String uid;
public String getUid() { return this.uid; }
public void setUid(String uid) { this.uid = uid; }
private String title;
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
private Body body;
public Body getBody() { return this.body; }
public void setBody(Body body) { this.body = body; }
private FieldExercisArc field_exercis_arc;
public FieldExercisArc getFieldExercisArc() { return this.field_exercis_arc; }
public void setFieldExercisArc(FieldExercisArc field_exercis_arc) { this.field_exercis_arc = field_exercis_arc; }
private String cid;
public String getCid() { return this.cid; }
public void setCid(String cid) { this.cid = cid; }
private String last_comment_timestamp;
public String getLastCommentTimestamp() { return this.last_comment_timestamp; }
public void setLastCommentTimestamp(String last_comment_timestamp) { this.last_comment_timestamp = last_comment_timestamp; }
}
You can convert result to RootObject. Fox example:
String json = "{\"vid\": \"26\",\"uid\": \"1\",\"title\": \"Question test\",\"body\": {\"und\": [{\"value\": \"xcvxcv\"}]},\"field_exercis_arc\": {\"und\": [{\"target_id\": \"25\"},{\"target_id\":\"27\"}]},\"cid\": \"0\",\"last_comment_timestamp\": \"1472217577\"}";
RootObject object = new Gson().fromJson(json, RootObject.class);
System.out.println("Title is: "+object.getTitle() );
Result is:
Title is: Question test
After this you can use your object to get any value from your JSON.
Also you should know that your JSON is not valid. You have commas on two places that should not exists. In string i gave you above those are fixed. You should check you JSON with: JSON Formatter
Use below code :
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getString(j));
JsonArray fieldArray=yourJsonObject.getJsonArray("field_exercis_arc");
for(int i=0;i<fieldArray.length;i++){
fieldArray.getString(i);
}
TO the parse the JSON you have to do it like this.
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
String title = finalObject.getString("title");
String body = finalObject.getString("body");
JSONArray arr = finalObject.getJSONArray("field_exercis_arc");
for(int x=0; x < arr.length(); x++){
String val = arr.getString(x);
}
}

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.

Scala: Java to Scala, how to eliminate setters and getters and reduce code size

Update: After suggestion from one of the experts here, I have cleaned up the following Java code:
There is a class called MyRespModifier and it holds two inner static classes called ResponseMail and Response
I have rewritten this code Scala as an exercise. Scala version: 2.11.2. I am not happy with the results. It resembles Java, and looks like it could do with a large dose of idiomatic Scala from the ground up. I would like to accomplish a reduction in the no of lines and also on inspection of the code it should stand out as elegant Scala code.At least my goal is to understand how some Java constructs can be rewritten in idiomatic Scala.
The Scala equivalent is posted after the Java code:
import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ContentType;
public class MyRespModifier {
private static final String VERSION = "1.0.0";
private static final String USER_AGENT = "myuseragent/"+ VERSION + "java";
private static final String ARG_TO = "to[%d]";
private static final String ARG_TONAME = "toname[%d]";
private static final String ARG_CC = "cc[%d]";
private static final String ARG_FROM = "from";
private static final String ARG_FROMNAME = "fromname";
private static final String ARG_REPLYTO = "replyto";
private static final String ARG_SUBJECT = "subject";
private static final String ARG_CONTENTS = "content[%s]";
private static final String ARG_MYSMTPAPI = "x-respModifierSmtpApi";
private String apikey;
private String apivalue;
private String apiUrlBasePath;
private String port;
private String endpoint;
private CloseableHttpClient client;
public MyRespModifier() {
this.apiUrlBasePath = "api/responseshaper/response";
this.endpoint = "/myapi/mymail.dispatch.json";
this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
}
public MyRespModifier setUrl(String url) {
this.apiUrlBasePath = apiUrlBasePath;
return this;
}
public MyRespModifier setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public MyRespModifier setClient(CloseableHttpClient client) {
this.client = client;
return this;
}
public HttpEntity constructRespBody(ResponseEmail respEmail) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("api_user", this.apikey);
builder.addTextBody("api_key", this.apivalue);
String[] tos = respEmail.getTos();
String[] tonames = respEmail.getToNames();
String[] ccs = respEmail.getCcs();
if (tos.length == 0) {
builder.addTextBody(String.format(ARG_TO, 0), respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
}
for (int i = 0, len = tos.length; i < len; i++)
builder.addTextBody(String.format(ARG_TO, i), tos[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = tonames.length; i < len; i++)
builder.addTextBody(String.format(ARG_TONAME, i), tonames[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = ccs.length; i < len; i++)
builder.addTextBody(String.format(ARG_CC, i), ccs[i], ContentType.create("text/plain", "UTF-8"));
if (respEmail.getContentIds().size() > 0) {
Iterator it = respEmail.getContentIds().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
builder.addTextBody(String.format(ARG_CONTENTS, entry.getKey()), (String) entry.getValue());
}
}
if (respEmail.getFrom() != null && !respEmail.getFrom().isEmpty())
builder.addTextBody(ARG_FROM, respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getFromName() != null && !respEmail.getFromName().isEmpty())
builder.addTextBody(ARG_FROMNAME, respEmail.getFromName(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getReplyTo() != null && !respEmail.getReplyTo().isEmpty())
builder.addTextBody(ARG_REPLYTO, respEmail.getReplyTo(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getSubject() != null && !respEmail.getSubject().isEmpty())
builder.addTextBody(ARG_SUBJECT, respEmail.getSubject(), ContentType.create("text/plain", "UTF-8"));
String tmpString = respEmail.respModifierSmtpApi.jsonString();
if (!tmpString.equals("{}"))
builder.addTextBody(ARG_MYSMTPAPI, tmpString, ContentType.create("text/plain", "UTF-8"));
return builder.build();
} //end of method constructRespBody
public MyRespModifier.Response send(ResponseEmail respMail) throws RespModifierException {
HttpPost httppost = new HttpPost(this.apiUrlBasePath + this.endpoint);
httppost.setEntity(this.constructRespBody(respMail));
try {
HttpResponse res = this.client.execute(httppost);
return new MyRespModifier.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
} catch (IOException e) {
throw new RespModifierException(e);
}
}
//*********************************************************************
public static class ResponseEmail {
private MyExperimentalApi respModifierSmtpApi;
private ArrayList<String> to;
private ArrayList<String> toname;
private ArrayList<String> cc;
private String from;
private String fromname;
private String replyto;
private String subject;
private String text;
private Map<String, String> contents;
private Map<String, String> headers;
public ResponseEmail () {
this.respModifierSmtpApi = new MyExperimentalApi();
this.to = new ArrayList<String>();
this.toname = new ArrayList<String>();
this.cc = new ArrayList<String>();
this.contents = new HashMap<String, String>();
this.headers = new HashMap<String, String>();
}
public ResponseEmail addTo(String to) {
this.to.add(to);
return this;
}
public ResponseEmail addTo(String[] tos) {
this.to.addAll(Arrays.asList(tos));
return this;
}
public ResponseEmail addTo(String to, String name) {
this.addTo(to);
return this.addToName(name);
}
public ResponseEmail setTo(String[] tos) {
this.to = new ArrayList<String>(Arrays.asList(tos));
return this;
}
public String[] getTos() {
return this.to.toArray(new String[this.to.size()]);
}
public ResponseEmail addSmtpApiTo(String to) {
this.respModifierSmtpApi.addTo(to);
return this;
}
public ResponseEmail addSmtpApiTo(String[] to) {
this.respModifierSmtpApi.addTos(to);
return this;
}
public ResponseEmail addToName(String toname) {
this.toname.add(toname);
return this;
}
public ResponseEmail addToName(String[] tonames) {
this.toname.addAll(Arrays.asList(tonames));
return this;
}
public ResponseEmail setToName(String[] tonames) {
this.toname = new ArrayList<String>(Arrays.asList(tonames));
return this;
}
public String[] getToNames() {
return this.toname.toArray(new String[this.toname.size()]);
}
public ResponseEmail addCc(String cc) {
this.cc.add(cc);
return this;
}
public ResponseEmail addCc(String[] ccs) {
this.cc.addAll(Arrays.asList(ccs));
return this;
}
public ResponseEmail setCc(String[] ccs) {
this.cc = new ArrayList<String>(Arrays.asList(ccs));
return this;
}
public String[] getCcs() {
return this.cc.toArray(new String[this.cc.size()]);
}
public ResponseEmail setFrom(String from) {
this.from = from;
return this;
}
public String getFrom() {
return this.from;
}
public ResponseEmail setFromName(String fromname) {
this.fromname = fromname;
return this;
}
public String getFromName() {
return this.fromname;
}
public ResponseEmail setReplyTo(String replyto) {
this.replyto = replyto;
return this;
}
public String getReplyTo() {
return this.replyto;
}
public ResponseEmail setSubject(String subject) {
this.subject = subject;
return this;
}
public String getSubject() {
return this.subject;
}
public ResponseEmail setText(String text) {
this.text = text;
return this;
}
public String getText() {
return this.text;
}
public JSONObject getFilters() {
return this.respModifierSmtpApi.getFilters();
}
public ResponseEmail addContentId(String attachmentName, String cid) {
this.contents.put(attachmentName, cid);
return this;
}
public Map getContentIds() {
return this.contents;
}
public ResponseEmail addHeader(String key, String val) {
this.headers.put(key, val);
return this;
}
public Map getHeaders() {
return this.headers;
}
public MyExperimentalApi getSMTPAPI() {
return this.respModifierSmtpApi;
}
}
public static class Response {
private int code;
private boolean success;
private String message;
public Response(int code, String msg) {
this.code = code;
this.success = code == 200;
this.message = msg;
}
public int getCode() {
return this.code;
}
public boolean getStatus() {
return this.success;
}
public String getMessage() {
return this.message;
}
}//end of class Response
You can change the imports to save some lines
import java.util.Arrays
import java.util.HashMap
import java.util.Iterator
becomes
import java.util.{Arrays, HashMap, Iterator}
The getters and setters can be generated for you. This is a feature of a Scala class if you declare the constructor parameter with val or var.
A simplified version of your class becomes:
class ResponseEmail(var to: ArrayList[String], var cc: ArrayList[String])
This getters are cc and to and the setters are cc_= and to_=
scala> res6.
asInstanceOf cc cc_= isInstanceOf to toString to_=

Loading an ArrayList from another serialized class to use in a ListView

I am still new to Android, I'm primarily an iOS developer.
I don't know why I can't test to see whether or not the ListArray is empty or not. I need to test and use the size of it anyways.
This is declared within the class:
Projects projects = new Projects();
The following code does not like projects.videos.size() being compared nil or 0.
try
{
if (projects != null)
{
int numberOfVideos = projects.videos.size();
if(numberOfVideos==0)
{
// myStringArray = new String[projects.videos.size()];
//
//
//
// for (int i = 0;i < projects.videos.size();i++)
// {
// myStringArray[i] = projects.videos.get(i);
// }
}
else
{
// myStringArray = new String[1];
// myStringArray[0] = "No projects";
}
}
else
{
System.out.println("Sucess");
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("somethingbad has happened");
System.out.println(projects.videos.size());
}
This is what the projects class looks like:
package com.example.musicvideomaker;
import java.util.ArrayList;
import java.util.UUID;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Projects implements Serializable{
public String projectName;
public String musicStuff;
public String songTitle;
public String guid;
public boolean isBuiltVideo;
public boolean isListOfBuiltVideos;
public int selectedIndex;
public ArrayList<String> videos;
public ArrayList<String> builtVideos;
public ArrayList<Number> tPoints;
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
public void setMusicStuff(String musicStuff)
{
this.musicStuff = musicStuff;
}
public void setSongTitle(String songTitle)
{
this.songTitle = songTitle;
}
public void setGuid()
{
UUID uuid = UUID.randomUUID();
this.guid = uuid.toString();
}
public void isBuiltVideo(boolean isBuiltVideo)
{
this.isBuiltVideo = isBuiltVideo;
}
public void isListOfBuiltVideos(boolean isListOfBuiltVideos)
{
this.isListOfBuiltVideos = isListOfBuiltVideos;
}
public void setSelectedIndex(int selectedIndex)
{
this.selectedIndex = selectedIndex;
}
public void addRecordedVideo(String recordedVideo)
{
this.videos.add(recordedVideo);
}
public void addBuiltVideo(String builtVideo)
{
this.builtVideos.add(builtVideo);
}
public void addTPoint(Number tPoint)
{
this.tPoints.add(tPoint);
}
}
I removed int numberOfVideos = projects.videos.size();
Instead of using if(numberOfVideos==0) I used projects.videos == null
I think it was because my projects are null so it crashes when trying to pull the size of the arrayList.

Malformed URL no protocol error [closed]

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

Categories