org.artofsolving.jodconverter.office.OfficeException: could not load document: asdf.doc - jodconverter

I want to do some document convert works use jodconverter & open office 4。
I have installed open office on my windows 7 at C:\Program Files (x86)\OpenOffice 4。
in task mgr I have seen the process of soffice.bin*32
when I run my demo to convert a doc file to html file。I occurred this exception:
log4j:WARN No appenders could be found for logger (org.artofsolving.jodconverter.office.OfficeManager).
log4j:WARN Please initialize the log4j system properly.
一月 07, 2016 10:27:49 上午 org.artofsolving.jodconverter.office.OfficeConnection connect
信息: connected: 'socket,host=127.0.0.1,port=8100,tcpNoDelay=1'
Exception in thread "main" org.artofsolving.jodconverter.office.OfficeException: could not load document: asdf.doc
at org.artofsolving.jodconverter.AbstractConversionTask.loadDocument(AbstractConversionTask.java:93)
at org.artofsolving.jodconverter.AbstractConversionTask.execute(AbstractConversionTask.java:53)
at org.artofsolving.jodconverter.office.ExternalOfficeManager.execute(ExternalOfficeManager.java:70)
at org.artofsolving.jodconverter.OfficeDocumentConverter.convert(OfficeDocumentConverter.java:72)
at org.artofsolving.jodconverter.OfficeDocumentConverter.convert(OfficeDocumentConverter.java:63)
at demo.OfficeDocumentManager.conveterOfficeDocument(OfficeDocumentManager.java:84)
at demo.Test.main(Test.java:9)
I check the source code of jodconverter:
private XComponent loadDocument(OfficeContext context, File inputFile) throws OfficeException {
if (!inputFile.exists()) {
throw new OfficeException("input document not found");
}
XComponentLoader loader = cast(XComponentLoader.class, context.getService(SERVICE_DESKTOP));
Map<String,?> loadProperties = getLoadProperties(inputFile);
XComponent document = null;
try {
document = loader.loadComponentFromURL(toUrl(inputFile), "_blank", 0, toUnoProperties(loadProperties));
} catch (IllegalArgumentException illegalArgumentException) {
throw new OfficeException("could not load document: " + inputFile.getName(), illegalArgumentException);
} catch (ErrorCodeIOException errorCodeIOException) {
throw new OfficeException("could not load document: " + inputFile.getName() + "; errorCode: " + errorCodeIOException.ErrCode, errorCodeIOException);
} catch (IOException ioException) {
throw new OfficeException("could not load document: " + inputFile.getName(), ioException);
}
if (document == null) {
throw new OfficeException("could not load document: " + inputFile.getName());
}
return document;
}
when I debug these code. I find the document always null. the file I want to load here is exist and readable。can anyone told me why I can't load the file??

I can close this question now,when you come up this question ,you can resave your document,then retry.I think this is because the inner error of the document that make XComponentLoader return null.

Related

Handle exception in case a file cannot be read in the network because the network path is not accessible

I am reading a file present on a network drive using dart. I want to return a blank list in case the file does not exist or the network cannot be accessed.
I have tried using try/catch and try/on blocks but I don't seem to be able to handle the exception.
Code
readJSONReport(String filePath) async {
/// If file exists on shared network folder,
/// read it and return the list. Else return blank list
List<dynamic> jsonList = [];
try {
File file = await File(filePath);
if (file.existsSync()) {
jsonList = json.decode(await file.readAsString());
}
} on FileSystemException {
print("File not found");
}
return jsonList;
}
Error Message
Unhandled exception:
FileSystemException: Cannot open file, path = '\\10.0.169.142\Users\Public\shared\reports\merged_report.json' (OS Error: The network path was not found.
, errno = 53)
#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
<asynchronous suspension>
Another way to ask the same thing would be:
How to check if a file exists on a network path using dart?
OP Here. Turns out, the exception was being raised from a different part of the code. Adding the code I use now to read a JSON file while checking whether the file exists or not.
import 'dart:io';
readJSONReport(String filePath) async {
/// read report file generated by JSON Reporter
/// if file exists, read it and return the list
/// if file does not exist, return empty list
List<dynamic> jsonList = [];
try {
File file = await File(filePath);
print("Reading $filePath");
if (await file.exists()) {
jsonList = json.decode(await file.readAsString());
} else {
print("File does not exist");
}
} catch (e, stacktrace) {
print("Exception occured: $e stackTrace: $stacktrace");
}
return jsonList;
}
Please note that the JSON I am reading starts as a list (as you can expect from a cucumber-json report).

exception inside of OnException

I created a custom attribute, inheriting from HandleErrorAttribute:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
Utility.LogAndNotifyOfError(filterContext.Exception, null, true);
}
catch(Exception ex)
{
filterContext.Exception = ex;
}
}
}
, and then registered with:
filters.Add(new CustomHandleErrorAttribute());
This has always worked as intended. However a common problem with my log method is that it uses a custom event log source when writing to the event log, which the app pool account typically doesn't have the permissions to create. Creating the event log source is a simple powershell script, however I wanted to actually include that tidbit in the error:
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
The problem is that the catch in the OnException is never hit. When debugging, the custom error I throw from LogAndNotifyOfError instead triggers a second call to OnException, and the detail of my ErrorHandlerException is never seen. I want the asp.net error page that comes up to be with my custom error detail rather than the SecurityException that was originally raised.
You can even see the surrounding try in the displayed error:
Edit: Entire log method listed:
public static void LogAndNotifyOfError(Exception ex, String extraInfo, Boolean sendEmail)
{
//if the error handler itself faulted...
if (ex is ErrorHandlerException)
return;
string eventLogName = "Application";
string eventLogSource = "MySourceName";
String error = ex.ToString();
if (error.Length > 28000)
error.Substring(0, 28000);//event log is limited to 32k
error += "\r\n\r\nAdditional Information: \r\n"
+ "Machine Name: " + Environment.MachineName + "\r\n"
+ "Logged in user:" + App.CurrentSecurityContext.CurrentUser?.UserId + "\r\n"
+ extraInfo + "\r\n";
EventLog log = new EventLog(eventLogName);
log.Source = eventLogSource;
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{//this doesn't work - for some reason, OnError still reports the original error.
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
//if the email-to field has been set...
if (!String.IsNullOrEmpty(App.Config.General.ErrorHandlerSendToAddresses) && sendEmail)
{
//...then send the email
MailMessage email = new MailMessage();
email.To.Add(App.Config.General.ErrorHandlerSendToAddresses);
email.IsBodyHtml = false;
email.Subject = String.Format("Error in {0}", eventLogSource);
email.Body = email.Subject + "\r\n\r\n"
//+ "Note: This error may be occuring continuously, but this email is only sent once per hour, per url, in order to avoid filling your mailbox. Please check the event log for reoccurances and variations of this error.\r\n\r\n"
+ "The error description is as follows: \r\n\r\n"
+ error + "\r\n\r\n";
SmtpClient smtp = new SmtpClient();
smtp.Send(email);
}
}
I figured it out (sort of). It would appear that when the newly throw exception has an inner exception, it is only displaying that inner exception. It does not matter what the type is on the outer or inner exception.

Premature end of file using JAXB and Unmarshaller. The xml fromt he response looks valid to me

I don't know what to do anymore. Everything seems correct; input/output.
I generate xml file and send to some service to validate.
The response is:
11:10:34,922 INFO [STDOUT] printing out the input stream
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Response>
<Method name="XML/Release/New" time="2013-04-23T15:10:35.1446238Z">
<ResponseStatus>100</ResponseStatus>
</Method>
</Response>
finished printing out the input stream
11:10:34,922 INFO [STDOUT] got the unmarshaller
11:10:34,925 ERROR [PRNDataAccessUtil] Caught an error: javax.xml.bind.UnmarshalException
- with linked exception: [org.xml.sax.SAXParseException: Premature end of file.] : null
The code:
try {
out = connection.getOutputStream();
ByteArrayOutputStream bos = PRNPostNewsReleaseUtil.createNewsReleaseXml(newsRelease);
bos.writeTo(out);
JAXBContext context = JAXBContext.newInstance(Response.class.getPackage().getName());
in = connection.getInputStream();
BufferedReader inp = new BufferedReader(new InputStreamReader(in));
System.out.println("printing out the input stream");
String line;
while((line = inp.readLine()) != null) {
System.out.println(line);
}
System.out.println("finished printing out the input stream");
Unmarshaller unmarshaller = context.createUnmarshaller();
response = (Response) unmarshaller.unmarshal(in);
} catch (Exception ex) {
log.error("Caught an error: " + ex + " : " + ex.getMessage());
return null;
} finally {
if (null != in) connection.disconnect();
}
You are getting the error because the InputStream has been advanced to the end during the output. Assuming the buffer in your BufferedReader is large enough to contain the whole XML document you can reset it after outputting and then unmarshal that.
One time happened to me that I was using the wrong class name to build the JAXBContext object, so when I tried to marshall an object, an empty XML file was created, thus making the unmarshaller fail.
So make sure the JAXBContext object is instantiated with the class you're trying to marshall.
Another thing to note here is even if you are not reading the buffer explicitly in code but have a expression watch that reads the input, it would end up having the same effect of incrementing the stream head. Figured that out after spending hours on debugging this exception.

Struts file uploaded to certain directory, not able to retrieve back?

I am running Eclipse Java EE and tomcat for running my webapp. I used the following code to store an image file to the upload/images/profilepics directory:
public String uploadPhoto() {
try {
//get path to upload photo
String filePath = servletRequest.getSession().
getServletContext().getRealPath("/uploads/profilepics");
System.out.println("Server path:" + filePath);
//creating unique picture name
Map sess = (Map) ActionContext.getContext().get("session");
Integer uid = (Integer) sess.get("uid");
String profilePictureName = uid + "-" +
MyUtilityFunctions.createVerificationUrl() + this.userImageFileName;
//update user record
//tobe done
String imgUrl = filePath + profilePictureName;
ViewProfileModel pofilePictureUpdate = new ViewProfileModel();
pofilePictureUpdate.updateUserPhotoUrl(imgUrl, uid);
//create new File with new path and name
File fileToCreate = new File(filePath, profilePictureName);
//copy file to given location and with given name
FileUtils.copyFile(this.userImage, fileToCreate);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
after printing filePath I got the following result:
Server Path: /home/bril/webspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/picvik/uploads/profilepics
Now the problem is, I am not able to get the image or if I give the same url to <img src=""> nothing is getting displayed.
Please correct where I am doing wrong.
There are suggestions:
there are lots of reason, that you shouldn't save user images in this way, just like #DaveNewton mentioned in another question. There
are some post to help you make your decision:
Post1
Post2
My personal opinion is to save them into DB, because you don't want
to let your user lost their images.
If you need access session, you can check out SessionAware. This should be a better way to access session.
You are using tomcat as application container, you can configure the server to use its local installation, which makes you easier to track the problem in this case. check out this picture below
Back to your question, There are different ways to do this:
if you cannot find the image user just uploaded, you can check it
manual, see 3.
Otherwise, you could try <img src="/uploads/profilepics/<s:property
value='profilePictureName'/>"
Or you can get this picture using stream, here is the snippet:
JSP:
<img src="
<s:url var="profilePic" action="customer-image-action">
<s:param name="uid" value="%{uid}"/>
</s:url>
" alt="kunden logo" />
Action:
public String execute() throws Exception {
// filename = somehow(uid);
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
imgPath = request.getSession().getServletContext().getRealPath("/uploads/profilepics/")+filename;
log.debug("context-path: " + imgPath);
try {
inputStream = FileUtils.openInputStream(new File(imgPath));
} catch (IOException e) {
log.error(e.getCause(), e);
}
return SUCCESS;
}

Validation failed for one or more entities

I have following code in my asp.net MVC3 application:
string msg = "Beginning report run for: ";
msg += " Obligor Registry ID: " + obligorID;
msg += " Requesting Organization Registry ID:" + requestingOrgID;
msg += " Requesting Agent Registry ID: " + requestingAgentID;
TransactionLog lg = new TransactionLog();
lg.TransactionTypeId = 2;
lg.Message = msg;
context.TransactionLogs.Add(lg);
long referenceNumber = context.SaveChanges();
return referenceNumber;
and I am getting following error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
You need the namespace: System.Data.Entity.Validation
#GONeale helped me out in this regard. Moreover cause for this exception in my case is that I have certain not null db fields which I didnt included in the partial response update for certain transaction. context.Database.ExecuteSQLCommand would be my suggestion in this case.

Resources