IText keep pfm file open in Ubuntu - tomcat7

We have a web app running on Tomcat/Ubuntu and using iText7.1.8 to generate pdf documents (Invoices). We noticed that our Tomcat crashed many times and then after investigations found that it was iText the problem. Here is the exception
SEVERE: Socket accept failed
org.apache.tomcat.jni.Error: 24: Too many open files
at org.apache.tomcat.jni.Socket.accept(Native Method)
at org.apache.tomcat.util.net.AprEndpoint$Acceptor.run(AprEndpoint.java:992)
at java.lang.Thread.run(Thread.java:745)
When we run this command: sudo ls -l /proc/Tomcat-PID/fd we notice that most of the files opened are with extension .pfm (ex: /usr/share/fonts/type1/gsfonts/n022004l.pfm) and never released. This number continue to increase till reaches the max number of opened files.
Here is the code in Java used to generate the pdf.
public static File convertToPDF(File pdfFile,URL webURL){
InputStream htmlStream=null;
FileOutputStream pdfStream=null;
try {
htmlStream=webURL.openStream();
pdfStream=new FileOutputStream(pdfFile);
ConverterProperties properties = new ConverterProperties();
properties.setFontProvider(new DefaultFontProvider(true, true, true));
HtmlConverter.convertToPdf(htmlStream, pdfStream,properties);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(htmlStream!= null){
htmlStream.close();
}
if(pdfStream!= null){
pdfStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pdfFile;
}
Should we use a singleton to avoid multi instance, of this process which generates pdf, and the multiple files opened?
Environment:
Ubuntu 14.04
Tomcat 7.0.52
Java 1.7.0_80-b15
itext 7.1.8
Thank you

Fixed issue.
Use a singleton to get converter properties:
private static ConverterProperties properties;
private static DefaultFontProvider defaultFontProvider;
...
defaultFontProvider= new DefaultFontProvider(true, true, true);
properties.setFontProvider(defaultFontProvider);

Related

update profile image functionality is not working while hosting as jar

Hi I am new to Springboot I was trying to develop a application, One of its functionality is to upload profile Image. It was working fine in STS but when I pack it in jar and hosting it on AWS EC2 envirnment I am getting some error while processing that image
Error:
handler for profile picture:
#PostMapping("/process-contact")
public String processContact(#ModelAttribute Contact contact, #RequestParam("profileImage") MultipartFile file,
HttpSession session) {
try {
contact.setUser(user);
user.getContacts().add(contact);
// processing and uploading photo
if (file.isEmpty()) {
System.out.println("File is empty");
contact.setImage("contact.png");
} else {
//Processing Image
InputStream inputStream = file.getInputStream();
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
Files.copy(inputStream, paths, StandardCopyOption.REPLACE_EXISTING);
contact.setImage(file.getOriginalFilename());
}
// Success Message
session.setAttribute("message", new Message("Your contact is added...", "success"));
this.userRepository.save(user);
System.out.println("Successfully Added");
} catch (Exception E) {
E.printStackTrace();
// Failed message
session.setAttribute("message", new Message("Something went wrong "+E.getMessage(), "danger"));
}
return "normal/add_contact_form";
}
It is working fine in IDE after some research I found way of writing data in jar is diffrent could some please help me how can I implemenr it for jar also.
Thankyou
all you need to do is replace this line:
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
With:
Path paths = Paths.get(new FileSystemResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
THat will work like charm.

spring write string to file - spacing error

In my Spring boot application, I receive String, now I want to save them as files in a specific directory.
How can I do so ?
I have gone through this, but it is receiving file and saving, but I want to write to those files.
I'm using this code, raw JAVA:
PrintWriter writer = null;
try {
writer = new PrintWriter("file.txt", "UTF_32");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(data);
writer.close();
But it not how everyone will probably want, take a look:
It looks like it's your character encoding, UTF_32.
Notepad does not support UTF_32, only ansi, UTF_8, UTF_16.
See:
Can Notepad read UTF-32?

LibVLC Android playMRL method Exception Catch

We are trying the Android VLC LIb from the URL.
We won't able to catch exception if play rtsp stream fails.
Code: mMediaPlayer.play();
How can we catch exception if anything fails in calling above method.
Just explored bit more, It seems Latest version of Android VLC SDK Wrapper 1.9.8 have support of tracking events.(https://github.com/mrmaffen/vlc-android-sdk)
Code:
try {
options = new ArrayList<String>();
options.add("-vvv"); // verbosity
options.add("--extraintf=logger");
options.add("--verbose=0");
options.add("--log-verbose=0");
options.add("--rtsp-tcp");
mLibVLC = new LibVLC(options);
mMediaPlayer = new MediaPlayer(mLibVLC);
mMediaPlayer.setEventListener(mPlayerListener);
videoView.setVideoPath(mMediaUrl);
videoView.setVideoURI(Uri.parse(mMediaUrl));
videoView.setMediaController(new MediaController(this));
videoView.setOnPreparedListener(new android.media.MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d("TAG", "OnPrepared called");
}
});
videoView.start();
} catch (Exception e){
Log.e(TAG, e.toString());
}
Logs attached below:

How to get rid of NullPointerException in Flume Interceptor?

I have an interceptor written for Flume code is below:
public Event intercept(Event event) {
byte[] xmlstr = event.getBody();
InputStream instr = new ByteArrayInputStream(xmlstr);
//TransformerFactory factory = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS,TRANSFORMER_FACTORY_CLASS.getClass().getClassLoader());
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("removeNs.xslt"));
Transformer transformer = null;
try {
transformer = factory.newTransformer(xslt);
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Source text = new StreamSource(instr);
OutputStream ostr = new ByteArrayOutputStream();
try {
transformer.transform(text, new StreamResult(ostr));
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
event.setBody(ostr.toString().getBytes());
return event;
}
I'm removing NameSpace from my source xml with removeNs.xslt file. So that I can store that data into HDFS and later put into hive. When my interceptor run it throw below error :
ERROR org.apache.flume.source.jms.JMSSource: Unexpected error processing events
java.lang.NullPointerException
at test.intercepter.App.intercept(App.java:59)
at test.intercepter.App.intercept(App.java:82)
at org.apache.flume.interceptor.InterceptorChain.intercept(InterceptorChain.java:62)
at org.apache.flume.channel.ChannelProcessor.processEventBatch(ChannelProcessor.java:146)
at org.apache.flume.source.jms.JMSSource.doProcess(JMSSource.java:258)
at org.apache.flume.source.AbstractPollableSource.process(AbstractPollableSource.java:54)
at org.apache.flume.source.PollableSourceRunner$PollingRunner.run(PollableSourceRunner.java:139)
at java.lang.Thread.run(Thread.java:745)*
Can you suggest me what and where is the problem?
I found the solution. The problem was not anything else than new File("removeNs.xslt"). It was not able to find the location as I's not sure where to keep this file but later I get the flume agent path but as soon as I restart the flume agent it deletes all files which I kept in the flume agent dir. So I changed the code and kept the file material into my java code.

Birt Images with IText never ends

I'm working with Birt reports and, when i want to generate a pdf file, it never ends. The problem is in the line.
IRunAndRenderTask.run. I have no exception when I create the IBirtEngine.
Here is the code to create the BirtEngine and the reports designs.
private static IReportEngine birtEngine = null;
private static IReportRunnable examenAuditifReportDesign = null;
private static IReportRunnable bilanCollectifReportDesign = null;
private static Properties configProps = new Properties();
static{
loadEngineProps();//Read the birt configuration properties
EngineConfig config = new EngineConfig();
if( configProps != null){
config.setLogConfig(configProps.getProperty("logDirectory"), Level.INFO);
config.setBIRTHome(configProps.getProperty("birtHome"));
config.setResourcePath(configProps.getProperty("ressourcePath"));
config.setEngineHome(configProps.getProperty("birtHome"));
config.setProperty("birtReportsHome", configProps.getProperty("birtReportsHome"));
}
try {
RegistryProviderFactory.releaseDefault();
Platform.startup( config );
} catch ( BirtException e ) {
e.printStackTrace( );
}
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
birtEngine = factory.createReportEngine( config );
try {
examenAuditifReportDesign = birtEngine.openReportDesign(
new FileInputStream(birtEngine.getConfig().getProperty("birtReportsHome") + "/examenAuditif.rptdesign"));
bilanCollectifReportDesign = birtEngine.openReportDesign(
new FileInputStream(birtEngine.getConfig().getProperty("birtReportsHome") + "/bilanCollectif.rptdesign"));
} catch (EngineException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
And here's the code to execute the reports.
IRunAndRenderTask task = birtEngine.createRunAndRenderTask(examenAuditifReportDesign);
task.setParameterValue("RPT_ID_Travailleur", t.getId());
task.setParameterValue("RPT_LATEST_HA", params.getId_latest_ha());
task.setParameterValue("RPT_LATEST_EXAMN", params.getId_latest_examen());
task.setParameterValue("RPT_PREVIOUS_HA", params.getId_previous_ha());
task.setParameterValue("RPT_PREVIOUS_EXAMN", params.getId_previous_examen());
PDFRenderOption options = new PDFRenderOption();
options.setOutputStream(outputStream);
options.setOutputFormat("pdf");
task.setRenderOption(options);
task.run();
task.close();
and is in the task.run(); line that it takes forever, and i tried for about 1 hour or 1 hour and a half and it does not end.
If anyone can help it will be really apreciated.
Bye and thank you.
If this report works in a birt Eclipse designer then it should work with a birt runtime API, the issue is in your code.
You need to close yourself the outputStream sent to the PDFRenderOption object, when the task has terminated
Add this line to your code:
options.setSupportedImageFormats("PNG;JPG;BMP");
I found the problem and it wasn't neither of the two API's.
We were trying to generate a pdf file for worker, and we were zipping all the pdf file of all the workers, and this zip was saved in a blob in the database. That was the problem.
If the zip is saved in the File System it works ok.
thank you all.

Resources