Exceptions in J2ME - java-me

I am developing an mobile application using j2me.In that i am using kxml parser.In my application i have to call an url to get the data.When i am calling that url sometimes it showing:
java.lang.IllegalStateException: update of non-existent node Exception.
My sample code is:
InputStreamReader isr=null;
InputStream rssStream=null;
InputStream is = null;
HttpConnection conn=null;
try
{
conn = (HttpConnection)Connector.open(rssUrl);
rssStream = conn.openInputStream();---------->I think exception is shown here.
isr = new InputStreamReader( rssStream );
parser.setInput(isr);
parser.nextTag();

Better you replace the code
rssStream = conn.openInputStream();---------->I think exception is shown here.
isr = new InputStreamReader( rssStream );
with the following code
isr = conn.openInputStream();
Then try it.

The XML content returned by rssUrl is probably mal-formed. Download the content to a local file and check it.
If it is mal-formed, can you change the url content?

Related

How can I download file with HTTPBuilder (HttpClient)?

I need to download and save file. I'm trying to use HTTPBuilder because it has simple API and supports cookies. I have written following code:
//create new httpBuilder and set cookies
def httpBuilder = ...
def file = ...
def inputStream = httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY)
FileUtils.copyInputStreamToFile(inputStream)
How can I check that file is correctly downloaded (not only the part of the file)?
For large files exception java.lang.OutOfMemoryError: Java heap space occurs on line def inputStream = httpBuilder.get... How can I solve it?
May be it's not best choise to download files by HTTPBuilder. What is the best way to download file with cookies support?
Have you tried HttpBuilder GET request with custom response-handling logic:
httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY) {
resp, inputStream ->
FileUtils.copyInputStreamToFile(inputStream)
}
If HttpBuilder has problems which is strange then you can always use the tried and true Apache HttpClient API which has full cookie support.
HttpGet req = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(req);
// validate response code, etc.
InputStream inputStream = response.getEntity().getContent();
You can add a localContext when executing the request to manage cookies.

Displaying results of an SPLongOperation

I am using SPLongOperation to run a lengthy operation. After completing, the gears page redirects back to the original page from which the long operation was launched. I am not able to write anything to the oriignal page using SPLongOperation.Endscript. Here is the code I am using
using (SPLongOperation operation = new SPLongOperation(this.Page))
{
//.......................
//.......................
StringBuilder endScript = new StringBuilder();
endScript.Append("document.write('Success!!');");
operation.End(Request.Url.ToString(), SPRedirectFlags.UseSource, HttpContext.Current, String.Empty, endScript.ToString());
}
You won't be able to write anything to the calling page, a new http request has been made to show you the page with the spinning wheel while your operation is under progress and then you're redirected back to the specified url (using a new request).
The easiest way to show a success message is to pass a specific querystring to your calling url by replacing your string.empty parameter with something like
operation.End(Request.Url.ToString(), SPRedirectFlags.UseSource, HttpContext.Current, "success=1");
http://msdn.microsoft.com/en-us/library/ms450341.aspx
and then on the load event, check if you have this parameter and display the relevant message (it would be better to add an item to the HttpContext.Items or doing a post instead of a get to remove the querystring but the suggested implementation will prevent you from changing your long operation call and behaviour)
Hope this will help.
Try an alert - that worked for me..
Script.Append("alert('Success!!');");
This might be of help: http://www.sharepoint-tips.com/2012/07/reporting-code-errors-when-running-code.html
SPLongOperation longOp = new SPLongOperation(this.Page);
StringBuilder sbErrors = new StringBuilder();
longOp.Begin();try
{
throw new Exception("Sample");
}
catch(Exception ex)
{
sbErrors.Append("An error occurred: " + ex.MEssage);
}
if
(sbErrors.Length > 0)
{
longOp.EndScript("document.getElementById('s4-simple-card-content').innerHTML = \"Errors have occurred during the submission. Details: " + sbErrors.ToString() + " \";");
}
//close the dialog if there were no errors
longOp.EndScript("window.frameElement.commitPopup();");

Uploading file in sharepoint library throws an unhandled exception(hresult: 0x80020009, errorcode: -2147352567) with empty error message

I m using following code sample to upload multiple files (using sharepoint Object Model, no webservice) in a document library, but some times it throws exception hresult: 0x80020009, with error code -2147352567 and error message is empty (empty string) while file is upload successfully to the document library. And mostly it occurs only first time mean it occurs when uploading first document after that all process goes smoothly no exception occurs after first time occured. If i eat that exception it works fine. Can any one help me to trace the problem, I can't understand why it throws exception while file has been uploaded to document library. I want to know What's the actual reason and what should I do to avoid that problem.
Code:
.....
SPFolder folder = web.GetFolder(folderUrl);
foreach(.....)
{
folder.Files.Add(folderUrl + "/" + fileName, file.Data, true);
}
try using the code provided below that will help you out
using (SPSite spsite = new SPSite("http://SPS01"))
{
using (SPWeb spweb = spsite.OpenWeb())
{
spweb.AllowUnsafeUpdates = true;
SPFolder spfolder = spweb.Folders[Site + "/Shared Documents/"];
byte[] content = null;
using (FileStream filestream = new FileStream("C:/Sample.docx", System.IO.FileMode.Open))
{
content = new byte[(int)filestream.Length];
filestream.Read(content, 0, (int)filestream.Length);
filestream.Close();
}
SPFile spfile = spfolder.Files.Add("Sample.docx", content, true);
//Upload file in subfolder.
//SPFile spfile = spfolder.SubFolders["Demonstration Folder"].Files.Add("Sample.docx", content, true);
spfile.Update();
}
}

Image Handler for Sharepoint Not Working

My ImageHandler.ashx is not working when the webpart is calling it. any ideas on what is the correct way on calling or adding a handler in sharepoint? Thanks in advance
Here My ImageHandler.ashx code
byte[] buffer = (byte[])image.ImageData;
context.Response.ContentType = "image/jpeg";
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
In my webpart
imgcontrol.ImageUrl = "ImageHandler.aspx?id=1";
Check the Location where you have Deployed the ImageHandler.ashx. I have done similar thing in past and was able to get it working without any issues.
I deployed to _Layouts folder
imgcontrol.ImageUrl="_Layouts\x.ashx";
I assume that the code in your question is just a typo.
imgcontrol.ImageUrl = "ImageHandler.ashx?id=1";
this is a fragment from my own image handler that we use to load map pins in a sharepoint mapping webpart. We load the image, modify it, then return it.
Bitmap bmpPin = Bitmap.FromFile("myImageFile.jpg") as Bitmap
using (MemoryStream memStream = new MemoryStream())
{
this.m_Context.Response.ContentType = "image/png";
bmpPin.Save(memStream, ImageFormat.Png);
memStream.WriteTo(context.Response.OutputStream);
memStream.Close();
memStream.Dispose();
}
bmpPin.Dispose();

JavaMail BaseEncode64 Error

I'm currently developing an application which download attachment from gmail account.
Right now, I got error whenever downloading zipped attachment. But, not all, some I can retrieve it without error. Here's the Exception message:
Exception in thread "main" com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 1 before EOF, the 10 most recent characters were: "Q3w5ilxj2P"
FYI: I was able to download the attachment via gmail web interface.
Here's the snippet:
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getFileName().toLowerCase().endsWith("zip") ||
bodyPart.getFileName().toLowerCase().endsWith("rar")) {
InputStream is = bodyPart.getInputStream();
File f = new File("/tmp/" + bodyPart.getFileName());
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[bodyPart.getSize()];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
}
}
}
Anyone have idea, how to work around this problem?
From a list of the known limitations, bugs, issues of JavaMail:
Certain IMAP servers do not implement
the IMAP Partial FETCH functionality
properly. This problem typically
manifests as corrupt email attachments
when downloading large messages from
the IMAP server. To workaround this
server bug, set the
"mail.imap.partialfetch" property to
false. You'll have to set this
property in the Properties object that
you provide to your Session.
So you should just turn off partial fetch in imap session. For example:
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.partialfetch", "false");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>","<password>");
source: https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html
If You Are Using java mail API then add these lines while you are connectin the imap server......
Properties prop = new Properties();
prop.put("mail.imaps.partialfetch", false);
Session session = Session.getDefaultInstance(prop, null);
........
.... your code ..
......
it should work.

Resources