javax.imageio.ImageIO.read(new ByteArrayInputStream(data)) throws instantiation exception while reading byte array image data - spring-boot

public static void createImage2() {
try {
BufferedImage bImage = ImageIO.read(new File("input.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("image created");
}
The method ImageIO.read(bis) throws this exception:
Exception in thread "main" java.util.ServiceConfigurationError: javax.imageio.spi.ImageReaderSpi: Provider com.aware.j2k.imageio.J2KImageReaderSpi could not be instantiated

If you application throw exception with message of SPI - java.util.ServiceLoader don't find library, for add library you must just choose and add dependency f.e. group: com.twelvemonkeys.imageio or another implementation
For reading image to BufferedImage i recommend use
ImageIO.read(new MemoryCacheImageInputStream(new ByteArrayInputStream(file.getBytes())))
if you need create new image i recommend use
ImageTypeSpecifier.createFromRenderedImage(source).createBufferedImage(width, height)
ATTENTION
a lot of function for working with image use disk storage for cache or tmp by default

Related

Spring Boot using Apache POI streaming workbook - How do I release the memory taken up

I am writing a simple Spring boot app that reads from the DB and writes it out to an excel file using Apache POI. The generated file can contain upto 100K rows, and is around 8-10 MB in size.
My controller class:
public ResponseEntity<Resource> getExcelData(
#RequestBody ExcelRequest request) {
InputStreamResource file = new InputStreamResource(downloadService.startExcelDownload(request));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=myFile.xlsx")
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(file);
}
Service class:
public ByteArrayInputStream startExcelDownload(ExcelRequest request) {
/** Apache POI code using SXSSFWorkbook **/
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Excel generation logic here
...
workbook.write(out);
return new ByteArrayInputStream(out.toByteArray());
}
catch (IOException | ParseException e) {
throw new RuntimeException("fail to import data to Excel file: " + e.getMessage());
}
finally {
try {
out.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Here is what I see in VisualVM
And in the heap dump:
byte[] 151,521,152 B (41.2%) 3,100,020 (30.7%)
Is there something I have missed? Should the byte[] continue to take up memory after the response has been returned? The memory goes down once I manually run the GC.

read json file from resources

I'm trying to read json file that located in documents folder into resources file in quarkus.
here is my code:
try(InputStream inputStream = classLoader.getResourceAsStream("documents/helloWorldDocument.json")) {
// Retrieve the JSON document and put into a string/object map
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> documentMapType =
new TypeReference<HashMap<String, Object>>() {};
//
Map<String, Object> document = mapper.readValue(
new File(inputStream.toString()),
documentMapType);
// Use builder methods in the SDK to create the directive.
RenderDocumentDirective renderDocumentDirective = RenderDocumentDirective.builder()
.withToken("helloWorldToken")
.withDocument(document)
.build();
// Add the directive to a responseBuilder.
responseBuilder.addDirective(renderDocumentDirective);
// Tailor the speech for a device with a screen.
speechText.append(" You should now also see my greeting on the screen.");
} catch (IOException e) {
throw new AskSdkException("Unable to read or deserialize the hello world document", e);
}
but getting exception. really appreciate if anyone could help.
(I'm implementing APL for an alexa skill)
After searching a lot, I solve this:
try {
File file = new File(
Objects.requireNonNull(this.getClass().getClassLoader().getResource("helloWorldDocument.json")).getFile()
);
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> documentMapType =
new TypeReference<HashMap<String, Object>>() {
};
Map<String, Object> document = mapper.readValue(
new File(file.toString()),
documentMapType);
RenderDocumentDirective renderDocumentDirective = RenderDocumentDirective.builder()
.withToken("helloWorldToken")
.withDocument(document)
.build();
responseBuilder.addDirective(renderDocumentDirective);
speechText.append(" You should now also see my greeting on the screen.");
} catch (IOException e) {
throw new AskSdkException("Unable to read or deserialize the hello world document", e);
}

Generated PDF not send in the browser

I build a PDF document with iText library, and i want to get this document by clicking a link in the webapp.
But, it happens... nothing. No error message, no exception, really nothing.
I really don't master IO Streaming, so I think I made a mistake on this point, but after few hours of research, I don't know and I need a bit of help.
I have two methods. The first is the one to create pdf doc.
public void exporterPDF(SomeObjectIWillUse o) {
Document documentPDF = new Document(PageSize.A4);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(documentPDF, baos);
documentPDF.open();
documentPDF.addTitle("Test ! ");
Paragraph par = new Paragraph("Liste des participants");
documentPDF.add(par)
documentPDF.close();
telechargerPdfViaVue(FacesContext.getCurrentInstance(), baos, "filename.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
JsfUtils.addMessageByCode(FacesMessage.SEVERITY_FATAL, "drc.export.generation.pdf.erreur");
}
}
And the second is use to send the document.
public static final void telechargerPdfViaVue(FacesContext context, ByteArrayOutputStream baos, String fileName) throws IOException, DocumentException {
ExternalContext externalContext = context.getExternalContext();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName);
externalContext.setResponseContentLength(baos.size());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
context.responseComplete();
}
and it's called on my web page by a simple commandeLink
<p:commandLink id="exportPdf" action="#{myBean.exporterPDF(o)}">
Literally, in debug mode, all is done, but nothing happen...
Thank you for your help!
More informations, I use :
- JSF 2.2.7
- Spring 4.0.6

How to download data from url?

I can download data via HttpUrlConnection and InputStream but I need to download raw-data. So, i want to create a DownloadManager via raw-data, then using raw-data I convert this data to binary or image format. According to my research, I see "download file from url" but I can't download file in mac? Always, I get FileNotFoundException. Please help me. How I can download data from url?
public class DownloadData extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
downloadData("https://blablalabla/get");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void downloadData(String myurl) throws IOException {
URL u = new URL(myurl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
OutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/Users/ilknurpc/Desktop/text.docx"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
}
}
If you want to construct a workable download manager, I would suggest that you take a look at the
Tomcat Default Servlet Implementation
.
There a few number of HTTP headers that you need to understand such as E-Tags and Http Range Headers for a proper implementation.
Thankfully the Tomcat Default Servlet handles the prerequisites for you.
You can adapt this servlet in your code with minor changes (package declaration etc).

Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage name

I'm developing an app that processes files in ODS format.The code snippet is as follows:
public static void main(String[] args) throws IOException {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
display();
//print();
}
private static void display() throws IOException {
// Load the spreadsheet.
final OpenDocument doc = new OpenDocument();
doc.loadFrom("temperature3.ods");
String styleName = "Calibri";
StyleHeader header = new StyleHeader();
header.setStyleDisplay("Testing");
StyleMasterPage page = new StyleMasterPage();
page.setStyleHeader(header);
page.setStyleName(styleName);
OfficeMasterStyles off = new OfficeMasterStyles();
off.addMasterPage(off.getMasterPageFromStyleName(styleName));
doc.setMasterStyles(off);
// Show time !
final JFrame mainFrame = new JFrame("Viewer");
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
ODSViewerPanel viewerPanel = new ODSViewerPanel(doc, true);
mainFrame.setContentPane(viewerPanel);
mainFrame.pack();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocation(10, 10);
mainFrame.setVisible(true);
}
I intend loading the file into a jcomponent for easy manipulation but I'm having this error message in the netbeans console:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage named:Calibri
at org.jopendocument.model.office.OfficeMasterStyles.getMasterPageFromStyleName(Unknown Source)
at starzsmarine1.PrintSpreadSheet.display(PrintSpreadSheet.java:60)
at starzsmarine1.PrintSpreadSheet.main(PrintSpreadSheet.java:45)
Is there an alternative API for this purpose?

Resources