Parsing ical format - Parse exception - java

I am using ical4j to parse the ical format on the Android.
My input ics is:
BEGIN:VCALENDAR
BEGIN:VEVENT
SEQUENCE:5
DTSTART;TZID=US/Pacific:20021028T140000
DTSTAMP:20021028T011706Z
SUMMARY:Coffee with Jason
UID:EC9439B1-FF65-11D6-9973-003065F99D04
DTEND;TZID=US/Pacific:20021028T150000
END:VEVENT
END:VCALENDAR
But when I try to parse this I get the exception:
Error at line 1: Expected [VCALENDAR], read [VCALENDARBEGIN]
The relevant code is:
HttpHelper httpHelper = new HttpHelper(
"http://10.0.2.2/getcalendar.php", params);
StringBuilder response = httpHelper.postData();
StringReader sin = new StringReader(response.toString());
CalendarBuilder builder = new CalendarBuilder();
Calendar cal = null;
try {
cal = builder.build(sin);
} catch (IOException e) {
Log.d("calendar", "io exception" + e.getLocalizedMessage());
} catch (ParserException e) {
Log.d("calendar", "parser exception" + e.getLocalizedMessage());
}
public class HttpHelper {
final HttpClient client;
final HttpPost post;
final List<NameValuePair> data;
public HttpHelper(String address, List<NameValuePair> data) {
client = new DefaultHttpClient();
post = new HttpPost(address);
this.data = data;
}
private class GetResponseTask extends AsyncTask<Void, Void, StringBuilder> {
protected StringBuilder doInBackground(Void... arg0) {
try {
HttpResponse response = client.execute(post);
return inputStreamToString(response.getEntity().getContent());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
}
public StringBuilder postData() {
try {
post.setEntity(new UrlEncodedFormEntity(data));
return (new GetResponseTask().execute()).get();
} catch (UnsupportedEncodingException e) {
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
Log.v("debug", "Line: " + line);
}
// Return full string
return total;
}
}

My guess would be the line endings in the response string are different from what ical4j expects.
The standard specifies you should use CRLF (aka '\r\n').

The input file is valid, the problem is with your method inputStreamToString(), which performs a readLine() on the input (which strips the newlines) and appends to a string without re-adding the newlines.
I would suggest either to use an alternative to readLine() (if you want to preserve newlines from the original file), or append your own newlines in the loop, eg:
while ((line = rd.readLine()) != null) {
total.append(line);
total.append("\r\n");
Log.v("debug", "Line: " + line);
}

Related

Converting CSV file to JSON in android studio. The CSV file has saved on the server side

InputStream is = getResources().openRawResource(R.raw.a);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String line = "";
try{
reader.readLine();
while ((line = reader.readLine()) != null)
{
String[] tokens = line.split(",");
WeatherSample sample = new WeatherSample();
sample.setLeftHipAngle(Double.parseDouble(tokens[0]));
sample.setLeftKneeAngle(Double.parseDouble(tokens[2]));
sample.setRightHipAngle(Double.parseDouble(tokens[4]));
sample.setRightKneeAngle(Double.parseDouble(tokens[6]));
sample.setRealTime(Double.parseDouble(tokens[8]));
weatherSamples.add(sample);
}
} catch (IOException e)
{
Log.wtf("MyActivity", "Error reading data file on line" + line, e);
e.printStackTrace();
}
This is my code. But in this case ,csv file has import to the resource folder. But I want to convert server side uploaded csv file into JSON format. Can you help me?
api1 = ApiClient.getClient().create(Stock1.class);
Call<ResponseBody> re = api1.getlist();
re.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("ttag", "chekc "+response.body().byteStream());
InputStream inputStream1 =response.body().byteStream();
String line = "";
try {
reader.readLine();
while ((line= reader.readLine())!=null) {
String[] token = line.split(",");
Log.d("TAG", this is 1st item of csv "+token[0]);
Log.d("TGAG", "this is 2 item of csv " + token[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});

How to extract XML data to a string via URL

I wanna convert xml data from URL to json using this library , but it doesn't handle xml from URLs..! only if it was a string or file, so I wanna convert the data inside the url into a string!
is it possible?
This fragment can help you
new Thread() {
public void run() {
URL url = null;
BufferedReader in = null;
try {
url = new URL("your url");
in = new BufferedReader(
new InputStreamReader(
url.openStream(),"UTF-8"));//in most cases there is utf 8
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
builder.append(inputLine);
String urlContent = builder.toString();
// process your received data somehow
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}.start();

json,CSV,json to csv

I want to convert JSON into CSV. I have written the following code; it's working fine for a small JSON file, but for another file (around 43MB), it's not working.
public class JSON2CSV
{
public static void main(String myHelpers[]) throws IOException{
BufferedReader br = null;
String line="";
int i=0;
br = new BufferedReader(new FileReader("tickets_1.txt"));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
{
i++;
System.out.println("loop"+i);
sb.append(line);
}
String resultstring = sb.toString();
String jsonString = "{\"infile\":"+resultstring+"}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("fromTicketsJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
br.close();
}
}
}

Extract value from Json using Gson

I am trying to extract values from JSON from the URL provided below using GSON java library:
http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json
I have successfully used the code provided below to extract data from URL below:
http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json
Code:
String url = "http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json";
String url2 = "http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json";
InputStream is = null;
try {
is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JsonElement je = new JsonParser().parse(jsonText);
System.out.println("Current Temperature:" + getAtPath(je, "current_observation/temp_c").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However I am getting exception trying to extract from url2 as per code below , it seems to be a more complicated json to get values from, any help please?
// below code not working
weather_icon_url = getAtPath(je, "current_observation/icon_url").getAsString();
is = new URL(url2).openStream();
BufferedReader rd2 = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText2 = readAll(rd2);
JsonElement je2 = new JsonParser().parse(jsonText2);
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
getAtPath code:
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
current = current.getAsJsonObject().get(ss[i]);
}
return current;
}
The problem you are facing is because there is an issue with the getAtPath implementation.
[{"date":{"epoch":"1459152000"... represents a JSONArray which the method is trying to access as JSONObject. Hence the IllegalStateException.
JsonObject com.google.gson.JsonElement.getAsJsonObject()
convenience method to get this element as a JsonObject. If the element
is of some other type, a IllegalStateException will result. Hence it
is best to use this method after ensuring that this element is of the
desired type by calling isJsonObject() first.
You can update and use something like below, as of now it returns only the first element.
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
if(current instanceof JsonObject){
current = current.getAsJsonObject().get(ss[i]);
} else if(current instanceof JsonArray){
JsonElement jsonElement = current.getAsJsonArray().get(0);
current = jsonElement.getAsJsonObject().get(ss[i]);
}
}
return current;
}
This should work:
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );

Read first text line of an URL

I am trying to read the first line of a URL.
Then i want to use that as a string later in the code.
Anyone can help me?
I already tried it with
public static String main(String[] args) {
try {
URL url = new URL("myurlhere");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
return line;
}
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
return null;
}
I just can't get a string out of it.
You can consider using jsoup for your purpose:
try {
Document doc = Jsoup.connect("http://popofibo.com/pop/swaying-views-of-our-past/").get();
Elements paragraphs = doc.select("p");
for(Element p : paragraphs) {
System.out.println(p.text());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Output:
It is indeed difficult to argue over the mainstream ideas of evolution of human civilizations...
If you want to read from a file on the internet using a URL you should use URLConnection
here is a simple example:
String string = "";
try {
URLConnection connection = new URL(
"http://myurl.org/mypath/myfile")
.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
while (scanner.hasNext()) {
string += scanner.next() + " ";
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
// Do something with the string.

Categories

Resources