I have been given the task of implementing a way to convert a string received through a JSON object to an iCalendar object(ics). I found the iCal4j library and have been attempting to use that as my parser. however it seems that the CalendarBuilder takes an InputStream.
How do I proceed ?
String response = jsonObj.getString("icalendar");
CalendarBuilder calBuiler = new CalendarBuilder();
Calendar calendar = calBuilder.build("???");
....
Edit : Would this work?
public Calendar convertStringtoCalendar(String arg)
{
CalendarBuilder calBuiler = new CalendarBuilder();
InputStream is;
try {
is = new ByteArrayInputStream(arg.getBytes("UTF-8"));
return calBuiler.build(is);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Solved the problem by doing the following.
public static Component getCalendarEvent(String myCalendarString)
{
try {
StringReader sin = new StringReader(myCalendarString);
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(sin);
return (Component)calendar.getComponent("VEVENT");
} catch (Exception e) {e.printStackTrace();}
return null;
}
I suggest you try my new iCalendar API for Java called iCalendarFx. It can parse a string into any calendar element - VCALENDAR, VEVENT, etc.
You can check it out at http://jfxtras.org/
You can download it at https://github.com/JFXtras/jfxtras/tree/8.0/jfxtras-icalendarfx
Related
I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
i have a problem in my app. At start i will describe how it works. It send request to the server (which wasn't created by me), and in the response i am getting JSON string ( it's not so big average 10 records in JSONarray) there in one parameter there is URL to the picture which i download and save as a bitmap for every JSON object. To summarize i download a JSON which looks like:
{
"id":"125",
"description":"desc",
"type":"type",
"state":"state",
"date":"2012-09-22 10:40:46.0",
"lat":"52.321911",
"lng":"19.464111",
"author":"user",
"photo":"GetImage?size=small&id=0",
"comments":[
]
}
x 10 for example, and then i download from URL "photo" image for every object. Problem lies in the time of execution, it is really really long which it should't it is not big data. Here it is how i do this: AsyncClass that download image:
private class HttpGetImage extends AsyncTask<Object, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Object... obj) {
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url+photoUrl);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
BufferedHttpEntity httpEntity = null;
try {
httpEntity = new BufferedHttpEntity(responseEntity);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
ready=true; return null;
}
InputStream imageStream = null;
try {
imageStream = httpEntity.getContent();
m_orders.get((Integer)obj[1])
.setOrderBitmap(BitmapFactory.decodeStream(imageStream));
success = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} finally {
try {
imageStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
}
ready = true;
return null;
}
}
and AsyncClass for jsonString:
private class HttpGetNotifications extends AsyncTask<Double, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Double... params)
{
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url + Double.toString(params[0]) + "&longitude=" + Double.toString(params[1]) + "&radius="+distance);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
String entityContents="";
try {
entityContents = EntityUtils.toString(responseEntity);
loadNotifications(entityContents);
success = true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
ready = true;
return null;
}
public void loadNotifications(String jsonstring) throws JSONException
{
JSONObject jsonResponse = new JSONObject(jsonstring);
JSONArray notifi = jsonResponse.getJSONArray("notifications");
for (int i =0, count = notifi.length(); i <count; i++){
//storage of data
}
}
}
Maybe you guys have an idea how can i optimize that code to reduce a time of execution?
Put in some profiling to find what's taking the time. In each of your AsyncTasks:
private long time0, time1;
#Override protected void onPreExecute() {
time0 = System.currentTimeMillis();
}
#Override protected void onPostExecute(HttpResponse response) {
time1 = System.currentTimeMillis();
long deltaT = (time1 - time0);
Log.d(TAG, "Execute took "+deltaT+"ms");
}
And then go from there.
This question already has answers here:
Loading html file to webview on android from assets folder using Android Studio
(3 answers)
Closed 5 years ago.
try {
File f = new File( "file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)") ;
FileInputStream fis= new FileInputStream(f);
System.out.println("_______YOUR HTML CONTENT CODE IS BELLOW WILL BE PRINTED IN 2 SECOND _______");
Thread.sleep(2000);
int ch;
while((ch=fis.read())!=-1)
{
fileContent=fileContent+(char)ch; // here i stored the content of .Html file in fileContent variable
}
System.out.print(fileContent);
//}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my code. I want to read html content from asstes folder my file is available in asstes folder But it gives exception FileNotFoundException. So plz any one tell me how to read html content from asstes folder in android?
File f = new File( "file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)") ;
when i debug f gives= file:/android_asset/[2011]011TAXMANN.COM00167(PATNA)
plz tell me how to get corrct directory and where i m doing wrong it shud me coming file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)
This is the way to load HTML file from assets in WebView
webview.loadUrl("file:///android_asset/Untitled-1.html");
Untitled-1.html---File name that should be save first as .html extension
Edited
try this link
http://developer.android.com/reference/android/content/res/AssetManager.html
there is method from this doc
public final String[] list (String path)
You cat get InputStream by this code:
getResources().getAssets().open("you_file_name_goes_here");
you don't want to use
webview.loadUrl('file:///android_asset/htmlFile.html');
right?
try this i found it in a blog:
static String getHTMLDataBuffer(String url,Context context) {
InputStream htmlStream;
try {
if (Utils.isReferExternalMemory() && url.contains("sdcard")) {
String tempPath = url.substring(7, url.length());//remove file:// from the url
File file = new File(tempPath);
htmlStream = new FileInputStream(file);
}else{
String tempPath = url.replace("file:///android_asset/", "");
htmlStream = context.getAssets().open(tempPath);
}
Reader is = null;
try {
is = new BufferedReader(new InputStreamReader(htmlStream, "UTF8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read string from reader
final char[] buffer = new char[1024];
StringBuilder out = new StringBuilder();
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
return out.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
usage:
String data = getHTMLDataBuffer("file:///android_asset/yourHtmlFile",this);
webview.loadDataWithBaseURL("http://example.com", data, "text/html", "utf-8", null);
Sorry for my bad english :)
Having some issue with Android 2.3 not picking up the Content-Encoding header from our server.
See http://pastebin.com/v0Jvn0nD for a comparison with 2.2 and 2.3.
So, I am trying to get a workaround so Android can handle the GZIP, at the moment it just fails. Here is the connection logic:
Any help would be cool. Many thanks
URL test = null;
try {
test = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection connection = null;
try {
connection = test.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = null;
try {
stream = connection.getInputStream();
Log.d("HttpHelper","getContentEncoding: " + connection.getContentEncoding()); // RETURNING NULL ON 2.3
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("gzip".equals(connection.getContentEncoding())) { // NULL HERE ON 2.3
try {
stream = new GZIPInputStream(stream);
responseString = textHelper.getText(stream);
globallistener.onComplete(responseString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}