No NullPointerException on the logs - java

I have a strange behaviour in my java code I would like to ask some advice.
In a multithreading application I wrote this code:
scratchDir.resolve(directoryTree).toFile().mkdirs();
For a bug the Object scratchDir is null, I was expecting a stack trace on the logs but there's nothing about the error.
I have checked the code and I never try to catch the NullPointerException.
Here is the complete method code:
#Override
public void write(JsonObject jsonObject) throws FileSystemException {
Path directoryTree = getRelativePath();
scratchDir.resolve(directoryTree).toFile().mkdirs();
String newFileName = getHashFileName(jsonObject);
Path filePath = scratchDir.resolve(directoryTree).resolve(newFileName);
logger.debug("Write new file Json {} to persistent storage dir {}", newFileName, scratchDir);
File outputFile = filePath.toFile();
if (outputFile.exists()) {
throw new FileAlreadyExistsException(filePath.toString());
}
try (FileWriter fileWriter = new FileWriter(outputFile)) {
fileWriter.write(jsonObject.toString());
fileWriter.flush();
} catch (Exception e) {
logger.error(e);
}
}
Why I don't have the exception in my logs?

Why are you doing this?
The proper way to do this is:
Files.createDirectories(scratchDir.resolve(directoryTree));
don't mix old and new API. The old mkdirs() api DEMANDS that you check the return value; if it is false, the operation failed, and you do not get the benefit of an exception to tell you why. This is the primary reason for why there is a new API in the first place.
Are you sure you aren't confused - and that is the actual problem? The line as you have it will happily do absolutely nothing whatsoever (no directories, and no logs or exceptions). The line above will throw if it can't make the directories, so start there.
Then, if that line IS being run and nothing is logged, then you've caught the NPE and discarded it, someplace you didn't paste.

Related

Android Studio - FileWriter can't be assigned anything, remains null

I'm getting a null pointer exception in this method.
Taking a step by step debug and trying a couple different layouts and file writing methods I came to understand that my issue seems to be that I can't manage to find a way to properly assign value to a FileWriter object:
public void scriviEccezioneSuLog (String rigaDaScrivere){
try (FileWriter scrittoreFile = new FileWriter(fileLogUltimaEsecuzione, true)){ //TODO: null pointer exception
scrittoreFile.write("\n*ECCEZIONE: " + rigaDaScrivere);
} catch (IOException eccezioneScrituraFile) {
System.out.println("Eccezione nella scrittura del file di log.");
}
}
The fileLogUltimaEsecuzione File object is defined as:
private File fileLogUltimaEsecuzione = new File(Environment.getExternalStorageDirectory(), "/ultimaEsecuzione.log");
During debug the File object does indeed seem to have the intended value, so it is not null.
And yet after the try-with-resources:
FileWriter scrittoreFile = new FileWriter(fileLogUltimaEsecuzione, true)
scrittoreFile remains null.
Note:
I do not have this problem when trying the same code on a different java IDE (I tried running it on ApacheNetBeans and it is flawless).
EDIT:
Additional information:
The file ultimaEsecuzione.log is instantiated as a class variable and created in the constructor as follows:
try {
fileLogUltimaEsecuzione.createNewFile());
} catch (IOException ecccezioneIO) {
System.out.println("Eccezione IO nella creazione del file di log.");
}
However when I check .exists() on the file right after it should have been created I get "false".

Why can't I catch the TesseractException?

I am using Tess4j for using Tesseract-OCR technology and I have been using the following code:
During testing I wanted to test the catch close so I was feeding wrong information to Tesseract, which should result in TesseractException.
I managed to induce a TesseractException from the createDocuments() method.
Here is the stack trace:
Note that in the exception we can find doOcr()'s line 125, which is within the try-catch clause, but even though console shows a TesseractException being thrown, the code moves onto line 126 returning true.
I use net.sourceforge.tess4j.Tesseract to initiate the OCR proccess, but I tried net.sourceforge.tess4j.Tesseract1 too, which resulted the same red console output that is done by Tess4j, but no TesseractException.
My question is what am I doing wrong? I am just assuming there is an issue with my code, because TesseractExceptionis being thrown, but my code is not catching it.
Look at the source code of Tesseract.java:
#Override
public void createDocuments(String[] filenames, String[] outputbases, List<RenderedFormat> formats) throws TesseractException {
if (filenames.length != outputbases.length) {
throw new RuntimeException("The two arrays must match in length.");
}
init();
setTessVariables();
try {
for (int i = 0; i < filenames.length; i++) {
File workingTiffFile = null;
try {
String filename = filenames[i];
// if PDF, convert to multi-page TIFF
if (filename.toLowerCase().endsWith(".pdf")) {
workingTiffFile = PdfUtilities.convertPdf2Tiff(new File(filename));
filename = workingTiffFile.getPath();
}
TessResultRenderer renderer = createRenderers(outputbases[i], formats);
createDocuments(filename, renderer);
api.TessDeleteResultRenderer(renderer);
} catch (Exception e) {
// skip the problematic image file
logger.error(e.getMessage(), e);
} finally {
if (workingTiffFile != null && workingTiffFile.exists()) {
workingTiffFile.delete();
}
}
}
} finally {
dispose();
}
}
/**
* Creates documents.
*
* #param filename input file
* #param renderer renderer
* #throws TesseractException
*/
private void createDocuments(String filename, TessResultRenderer renderer) throws TesseractException {
api.TessBaseAPISetInputName(handle, filename); //for reading a UNLV zone file
int result = api.TessBaseAPIProcessPages(handle, filename, null, 0, renderer);
if (result == ITessAPI.FALSE) {
throw new TesseractException("Error during processing page.");
}
}
Exception is thrown at line 579. This method is called by a public method above - at line 551. This is inside the try-catch block with logger.error(e.getMessage(), e); in the catch body (line 555).
Now the question is what you really want to achieve?
If you don't want to see this log, you can configure slf4j to not print the log from this library.
If you want to get the actual exception, it is not possible as the library swallows it. I am not familiar with the library, but looking at the code it doesn't seem like there is any nice option - the method that throws the exception is private and is used only in this one place - under the try-catch block. However, the exception is thrown when api.TessBaseAPIProcessPages(...) returns ITessAPI.FALSE and api has a getter. So you could get it, call TessBaseAPIProcessPages(...) method and check for the result. This might be not ideal as you will probably be processing every image twice. Another solution is to fork the source code and modify it yourself. You might also want to contact the author and ask for advice - you could take it further and submit a pull request for them to approve and release.
Add pdf.ttf file to tessdata path (tessdata/pdf.ttf)
pdf.ttf

Verbose Rexster output/logging on error `null`

I use Titan in a small Ubuntu server cloud with size 3 and deployed a Rexster extension to to $TITAN_HOME/ext. However, if I try to call an endpoint of the extension I get
{"message":"An error occurred while generating the response object","error":null}
which is not very helpful. How can I get more verbose output to see what is going wrong here? In addition, error null seems strange to me. Any ideas what can cause it?
edit:
I wrapped the whole execution of the extension that causes the errors in a try-catch-everything block:
#ExtensionNaming(
namespace = GraphityExtension.EXT_NAMESPACE,
name = "unfollow")
public class RemoveFollowshipExtension extends GraphityExtension {
#ExtensionDefinition(
extensionPoint = ExtensionPoint.GRAPH)
#ExtensionDescriptor(
description = "Removes a followship between two users.")
public
ExtensionResponse
unfollow(
#RexsterContext RexsterResourceContext content,
#RexsterContext Graph graph,
#ExtensionRequestParameter(
name = "following",
description = "identifier of the user following") String idFollowing,
#ExtensionRequestParameter(
name = "followed",
description = "identifier of the user followed") String idFollowed) {
try {
Graphity graphity = getGraphityInstance((TitanGraph) graph);
Map<String, String> map = new HashMap<String, String>();
try {
map.put(KEY_RESPONSE_VALUE, String.valueOf(graphity
.removeFollowship(idFollowing, idFollowed)));
return ExtensionResponse.ok(new JSONObject(map));
} catch (UnknownFollowingIdException | UnknownFollowedIdException e) {
return ExtensionResponse.error(e);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return ExtensionResponse.error(sw.toString());
}
}
but keep getting
{"message":"","error":null}
on client side. The rexstitan.log contains warnings concerning these errors:
com.tinkerpop.rexster.GraphResource - The [graphity:unfollow+*] extension raised an error response.
which is nice to know but not very detailed.
You usually get that error if there is some failure during invocation of your extension. Usually, the console where Rexster is running should provide some log messages that explain the cause and have a stack trace.
In the event that you are not seeing those for some reason, I would try to do your own logging in your extension and possibly trap exceptions in your code more generally (and logging in the catch clause) until you can see the error.

How can I write a string to a .html file?

I am creating a HTML Webpage Generator as part of a college assignment. What I am trying to do is set the header by taking in the users text and saving it to string through the use of a get / set class. However when I try to output the text to file I get an error.
The code I am using to try and output the string is the following
public static void main(String[] args) throws IOException {
try {
File f = new File("C:\\Users\\David\\Desktop\\output.html");
if(!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f);
fw.write(getHeader());
fw.close();
}catch(IOException io) {
Logger.getLogger(webPage.class.getName()).log(Level.SEVERE, null, io);
}
}
The error that Eclipse is giving me is
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at webPage.main(webPage.java:49)
Can anyone help me correct this please?
As JB Nizet's comment mentions, FileWriter.write() will throw an exception if the argument is null.
If you replace your write with fw.write("Hello World"), you will find no NPE.
So you need to figure out why getHeader() is returning null and fix that.

JXL library call

i am a barely new to the java (was always on c# before) and need to create a swing application where i need to read a data from xls file. So i use jXL.
I have a class, which returns name of a first sheet from excel file, choosen in jFileChooser. Here is the code:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
public class ExcelObject
{
private String filename = null;
private Workbook wb = null;
private Sheet sheet = null;
public ExcelObject(String f)
{
filename = f;
}
public String getSheetName()
{
String sheet_name = null;
try
{
wb = Workbook.getWorkbook(new File(filename));
sheet = wb.getSheet(0);
sheet_name = sheet.getName();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
wb.close();
}
return sheet_name;
}
}
in the program call looks like :
ExcelObject ex = new ExcelObject(filename);
String s = ex.getSheetName();
lblReport.setText(s);
So the issue is : when ran in the eclipse (3.4.2) i am getting a correct value, when jar is compiled, NO VALUE IS RETURNED! I mean lblReport is empty, with no exceptions and warnings.
Keep in mind : all other external jars work fine.
I tried a lot of things but none is working.
Also, if i do something like
ExcelObject ex = new ExcelObject(filename);
String s = ex.getSheetName();
// lblReportRun.setText(s);
lblReportRun.setText("Test");
lblAnyOtherLabel.setText("Test");
no text is displayed in the labels either, in compiled jar, and fine in eclipse.
This is probably because if some exception occurs when opening the workbook, you catch it, print the stack trace, and then close the workbook in the finally block. But since an exception occurred when calling Workbook.getWorkbook, the wb variable is still null, and you're trying to invoke close on it. So a NullPointerException happens while in the finally block.
Watch your console, you must have some exception popping up.
Also, note that fileName should be the only instance variable of your class, that Java variable normally don't contain underscores and use camelCase, and thet the fileName variable should be of type File, rather than String : you get a File from the file chooser, transform it into a string, and then transform it back to a File.
Another possibility, since it works in Eclipse and not when run externally, is that you forgot to put the jXL jar in the classpath, which causes some ClassNotFoundException when trying to use the ExcelObject class.

Categories