Reading a file from /etc/designs in java - aem

I'm in need of storing a string in JCR that'll be used in an OSGi bundle(so that it can be modified as needed in CRXde)
I have stored my string at the location /etc/designs/shc/components/linkcheck/regex.txt/jcr:content, where regex.txt is the file that contains my regex string.
I'm using the following code to read that String in a bundle but with no luck. It is throwing NullPointerException at resourceResolver.getResource
Resource dataResource = resourceResolver.getResource("/etc/designs/shc/components/linkcheck/regex.txt/jcr:content");
Node node = dataResource.adaptTo(Node.class);
String regex = node.getProperty("jcr:data").getValue().toString();
regex.txt is of type nt:file and the data is visible in CRXde but the code fails.
Any direction will be highly appreciated!

this should work-
Resource dataResource = resourceResolver.getResource("/etc/designs/shc/components/linkcheck/regex.txt");
Node jcnode = dataResource.adaptTo(Node.class).getNode("jcr:content");
InputStream is = jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
//do something
}
//do whatever with sb

Since the NullPointerException is thrown at resourceResolver.getResource(...), please check the resourceResolver is not null.

Related

MalformedInputException: Input length = 1 while reading text file with Files.readAllLines(Path.get("file").get(0);

Why am I getting this error? I'm trying to extract information from a bank statement PDF and tally different bills for the month. I write the data from a PDF to a text file so I can get specific data from the file (e.g. ASPEN HOME IMPRO, then iterate down to what the dollar amount is, then read that text line to a string)
When the Files.readAllLines(Path.get("bankData").get(0) code is run, I get the error. Any thoughts why? Encoding issue?
Here is the code:
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\wmsai\\Desktop\\BankStatement.pdf");
PDFTextStripper stripper = new PDFTextStripper();
BufferedWriter bw = new BufferedWriter(new FileWriter("bankData"));
BufferedReader br = new BufferedReader(new FileReader("bankData"));
String pdfText = stripper.getText(Loader.loadPDF(file)).toUpperCase();
bw.write(pdfText);
bw.flush();
bw.close();
LineNumberReader lineNum = new LineNumberReader(new FileReader("bankData"));
String aspenHomeImpro = "PAYMENT: ACH: ASPEN HOME IMPRO";
String line;
while ((line = lineNum.readLine()) != null) {
if (line.contains(aspenHomeImpro)) {
int lineNumber = lineNum.getLineNumber();
int newLineNumber = lineNumber + 4;
String aspenData = Files.readAllLines(Paths.get("bankData")).get(0); //This is the code with the error
System.out.println(newLineNumber);
break;
} else if (!line.contains(aspenHomeImpro)) {
continue;
}
}
}
So I figured it out. I had to check the properties of the text file in question (I'm using Eclipse) to figure out what the actual encoding of the text file was.
Then, when creating the file in the program, encode the text file to UTF-8 so that Files.readAllLines could read and grab the data I wanted to get.

iText7: Error at file pointer when merging two pdfs

We are in the last steps of evaluating iText7. We use iText 7.1.0 and html2pdf 2.0.0.
What we do: we send a json_encoded collection with pdf-data (which includes html for header, body and footer) to our Java app. There we iterate over the collection, create a byteArrayOutputStream for each pdf-data element and merge them together. We then send the results to a script which echoes it to e.g. a browser. Although the pdf is displayed correctly, we encounter errors while creating it:
com.itextpdf.io.IOException: Error at file pointer 226,416.
...
Caused by: com.itextpdf.io.IOException: xref subsection not found.
... 73 common frames omitted
If we create only one part of the collection, no error is thrown.
Iterate over collection and merge:
#RequestMapping(value = "/pdf", method = RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE)
public byte[] index(#RequestBody PDFDataModelCollection elements, Model model) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
try (PdfDocument resultDoc = new PdfDocument(writer)) {
for (PDFDataModel pdfDataModel : elements.getElements()) {
PdfReader reader = new PdfReader(new ByteArrayInputStream(creationService.createDatasheet(pdfDataModel)));
try (PdfDocument sourceDoc = new PdfDocument(reader)) {
int n = sourceDoc.getNumberOfPages(); //<-- IOException on second iteration
for (int i = 1; i <= n; i++) {
PdfPage page = sourceDoc.getPage(i).copyTo(resultDoc);
resultDoc.addPage(page);
}
}
}
}
return byteArrayOutputStream.toByteArray(); //outputs the final pdf
}
Creation of part:
public byte[] createDatasheet(PDFDataModel pdfDataModel) throws IOException {
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
//Initialize PDF document
PdfDocument pdfDoc = new PdfDocument(writer);
try (
Document document = new Document(pdfDoc)
) {
//header, footer, etc
//body
for (IElement element : HtmlConverter.convertToElements(pdfDataModel.getBody(), this.props)) {
document.add((IBlockElement) element);
}
footer.writeTotalNumberOnPages(pdfDoc);
}
return byteArrayOutputStream.toByteArray();
}
We are grateful for any suggestion.
In createDatasheet you appear to re-use some byteArrayOutputStream without clearing it first.
In the first iteration, therefore, everything works as desired, at the end of createDatasheet you have a single PDF file in it.
In the second iteration, though, you have two PDF files in that byteArrayOutputStream, one after the other. This concatenation does not form a valid single PDF.
Thus, byteArrayOutputStream.toByteArray() returns something broken.
To fix this, either make the byteArrayOutputStream local to createDatasheet and create a new instance every time or alternatively reset byteArrayOutputStream at the start of createDatasheet:
public byte[] createDatasheet(PDFDataModel pdfDataModel) throws IOException {
byteArrayOutputStream.reset();
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
[...]

java.io.FileNotFoundException - Can't read my properties file

Eclipse/Linux - Java Web Application.
I added a file named dao.properties to my project. I put it in a package : com.cdp.dao . My class which uses this file is in the same package.
When I try to load it I have a
java.io.FileNotFoundException
/myproject/src/com/cdp/dao/dao.properties (No such file or directory) OR
dao.properties (No such file or directory)
This my code :
Properties prop;
FileInputStream fis;
File file = new File("/myproject/src/com/cdp/dao/dao.properties");
//File file = new File("dao.properties"); doesn't work either
try {
prop = new Properties();
fis = new FileInputStream(file);
prop.load(fis);
dbUrl = prop.getProperty("dbUrl");
user = prop.getProperty("user");
pwd = prop.getProperty("pwd");
driver = prop.getProperty("driver");
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use
this.getClass().getResourceAsStream("dao.properties");
to load the properties file
From Class, the path is relative to the package of the class unless
you include a leading slash, so if you don't want to use the current package,
include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/dir/SomeTextFile.txt");
but if you need to use classpath use just filename like below
InputStream in = this.getClass().getResourceAsStream("dao.properties");

Need some eclipse search/replace regex help to speed things up

So I have had an issue for a while now and thought it was worth the time to ask the more experienced regex guys if there was a way to fix this issue with a quick search and replace.
So i use a tool which generates java code(not written in java or I would manually fix the cause directly), however, it has an issue calling variables before an object is created.
This always occurs only once per object, but not for every object, the object name is unknown, and the error is always the line directly before the constructor is called. This is the format the error is always in:
this.unknownObjectName.mirror = true;
this.unknownObjectName = new Model(unknown, parameter, values);
I know there should be a trick to fix this, as a simple string replace simply will not work since 'unknownObjectName' is unknown.
Would this even be possible with regex, if so, please enlighten me :)
This is how the code SHOULD read:
this.unknownObjectName = new Model(unknown, parameter, values);
this.unknownObjectName.mirror = true;
For complex models, this error may happen hundreds of times, so this will indeed save a lot of time. That and I would rather walk on hot coals then do mindless busy work like fixing all these manually :)
Edit:
I through together a java app that does the job.
public static void main(String args[]){
File file = new File(args[0]);
File file2 = new File(file.getParentFile(), "fixed-" + file.getName());
try {
if(file2.exists()) {
file2 = new File(file.getParentFile(), "fixed-" + System.currentTimeMillis() + "-" + file.getName());
}
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line, savedline = null, lastInitVar = "";
while((line = br.readLine()) != null){
if(line.contains("= new ")){
String varname = line.substring(0, line.indexOf("=")).trim();
lastInitVar = varname;
}else if(line.contains(".mirror")){
String varname = line.substring(0, line.indexOf(".mirror")).trim();
if(!lastInitVar.equals(varname)){
savedline = line;
continue;
}
}else if(savedline != null && savedline.contains(lastInitVar)){
bw.write(savedline + "\n");
savedline = null;
}
bw.write(line + "\n");
}
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Over thinking it
Write a program to read line by line and when you see a object access before a constructor don't write it out, write out the next line and then write out the buffered line, rinse repeat.
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems. - Jamie Zawinski
Regular Expressions are for matching patterns not state based logic.

Does exists Eclipse plugin for log files?

I have check very long logs after each start of Tomcat (from Eclipse).
Does exist a plugin or editor that I can use inside Eclipse? At least it must have colored for errors, debug and info messages.
Thanks.
I would recommend using Log4j:
http://logging.apache.org/log4j/1.2/
http://en.wikipedia.org/wiki/Log4j
It works great with eclipse and has the color scheme built in. It's highly customizable, takes some time to figure out but it's worth it.
The code to do this is rather simple, aside from syntax coloring. Just start a plugin project, add dependancies for org.eclipse.ui.console and do something like this:
public void log() {
BufferedReader br = new BufferedReader(new FileReader("path of log file"));
String line = null;
while (br.nextLine ) {
line = br.readLine();
if (line == null) {
Thread.sleep(1000);
}
else {
MessageConsole console = findConsole("tomcat log");
MessageConsoleStream stream = console.newMessageStream();
stream.println(message);
}
}
}
private MessageConsole findConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (IConsole element : existing)
if (name.equals(element.getName()))
return (MessageConsole) element;
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}