I made a HTTP server out of boredom and made it single file program.
The problem is, when serving a large file, for example 1.2GB, the CPU ramps up all the way up to 100% and my Lenovo X220 jumps immediately to 80C.
The catch is that the Netbeans profile nor Task Manager report it using that much CPU. Let's take a look:
Here it is serving the large file, this is task manager sorted by CPU and showing all processes:
Nothing suspicious, but in the Performance tab all hell is breaking loose:
All four cores locked to almost 99% with my i5 2520m at full turbo (3.2GHz)
Here is the server itself, just copy it into a file named JavaApplication1.java
What is going on here?
package javaapplication1;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class JavaApplication1 {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(80);
ServiceManager manager = ServiceManager.getManager();
while (true) {
Socket sock = server.accept();
HttpResponse response = new HttpResponse(sock);
manager.submit(response);
}
}
}
class ServiceManager {
private static ServiceManager instance;
private static ExecutorService executor;
private static ArrayList<Future<?>> taskPool;
private static final int MAX_WORKERS = 150;
private ServiceManager() {
executor = Executors.newFixedThreadPool(MAX_WORKERS);
taskPool = new ArrayList<>();
}
public static ServiceManager getManager() {
if (instance == null) {
instance = new ServiceManager();
}
return instance;
}
public void registerService(Runnable runnable) {
taskPool.add(executor.submit(runnable));
}
void submit(HttpResponse response) {
executor.submit(response);
}
}
class HttpAccept {
private final ByteArrayOutputStream baos;
private final InputStream in;
private final Callback<HttpAccept> back;
public HttpAccept(InputStream in, Callback<HttpAccept> back) {
baos = new ByteArrayOutputStream(512);
this.in = in;
this.back = back;
}
public void readAndRespond() {
byte[] buf = new byte[512];
int b;
try {
while ((b = in.read(buf)) > 0) {
baos.write(buf, 0, b);
if (HttpTools.endsWithCrlfCrlf(baos.toByteArray())) {
back.callback(this);
return;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
public void call(Callback<HttpAccept> back) {
back.callback(this);
}
public String getHttpHeader() {
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
}
interface Callback<E> {
void callback(E a);
}
class HttpHeader {
private final ByteArrayOutputStream baos;
private final String raw;
public HttpHeader(String raw) {
baos = new ByteArrayOutputStream(512);
this.raw = raw;
}
public String getRequestPath() {
char[] workset = raw.toCharArray();
for (char c : workset) {
baos.write((byte) c);
if (HttpTools.endsWithCrlf(baos.toByteArray())) {
String response[] = baos.toString().split(" ");
if (response.length == 0) return "./error.html";
if (response[1].equals("/")) return "./index.html";
return ".".concat(response[1]);
}
}
return "./";
}
}
abstract class HttpTools {
private static final byte[] CRLFCRLF = {13, 10, 13, 10};
private static final byte[] CRLF = {13, 10};
public static boolean endsWithCrlfCrlf(byte[] arr) {
if (arr.length < 4) {
return false;
}
int len = arr.length - 1;
return (arr[len] == CRLFCRLF[3]
&& arr[len - 1] == CRLFCRLF[2]
&& arr[len - 2] == CRLFCRLF[1]
&& arr[len - 3] == CRLFCRLF[0]);
}
public static boolean endsWithCrlf(byte[] arr) {
if (arr.length < 2) {
return false;
}
int len = arr.length - 1;
return (arr[len] == CRLF[1]
&& arr[len - 1] == CRLF[0]);
}
}
class HttpResponse implements Runnable {
private final Socket conn;
public HttpResponse(Socket conn) {
this.conn = conn;
}
public void respond() throws IOException {
HttpAccept accept = new HttpAccept(conn.getInputStream(), (httpAcc) -> {
try (OutputStream out = conn.getOutputStream()) {
HttpHeader header = new HttpHeader(httpAcc.getHttpHeader());
String path = header.getRequestPath();
File file = new File(path);
if (file.exists()) {
writeResponse(out, 200);
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[4096];
int b;
while ((b = in.read(buf)) > 0) {
out.write(buf, 0, b);
}
} else {
writeResponse(out, 404);
}
writeEnd(out);
} catch (IOException e) {
System.err.println(e);
}
});
accept.readAndRespond();
}
#Override
public void run() {
try {
respond();
} catch (IOException ex) {
System.err.println(ex);
}
}
private void writeResponse(OutputStream out, int i) throws IOException {
char[] resp = String.format("HTTP/1.1 %s OK\r\n\r\n", i).toCharArray();
for (char c : resp) {
out.write((int) c);
}
if (i == 404) {
char[] four0four = "<b>404 - Not found</b>".toCharArray();
for (char c : four0four) {
out.write((int) c);
}
}
}
private void writeEnd(OutputStream out) throws IOException {
char[] resp = "\r\n\r\n".toCharArray();
for (char c : resp) {
out.write((int) c);
}
}
}
I have made a java basic program written below, which is making 3 kind of files (ppt,doc,txt) embedded in Excel sheet using Apache POI. Now this file I want to Export with its original format. How to do this?
Reference link is Embed files into Excel using Apache POI.
I have made program from this link.
In short I want export functionality on Embedded file.
I have tried above problem using give below code but it not working for exporting embedded file in excel sheet:
Here this is the code which is tried to solve:
public static void main(String[] args) throws IOException {
String fileName = "ole_ppt_in_xls.xls";
ReadExcel(fileName);
}
public static void ReadExcel(String fileName) throws IOException {
FileInputStream inputFileStream = new FileInputStream(fileName);
POIFSFileSystem fs = new POIFSFileSystem(inputFileStream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
// the OLE2 Class Name of the object
String oleName = obj.getOLE2ClassName();
System.out.println(oleName);
if (oleName.equals("Worksheet")) {
System.out.println("Worksheet");
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false);
} else if (oleName.equals("Document")) {
System.out.println("Document");
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
HWPFDocument embeddedWordDocument = new HWPFDocument(dn, fs);
} else if (oleName.equals("Presentation")) {
System.out.println("Presentation");
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
SlideShow embeddedPowerPointDocument = new SlideShow(
new HSLFSlideShow(dn, fs));
} else if (oleName.equals("Presentation")) {
System.out.println("Presentation");
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
SlideShow embeddedPowerPointDocument = new SlideShow(
new HSLFSlideShow(dn, fs));
}else {
System.out.println("Else part ");
if (obj.hasDirectoryEntry()) {
System.out.println("obj.hasDirectoryEntry()"+obj.hasDirectoryEntry());
// The DirectoryEntry is a DocumentNode. Examine its entries
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
for (Iterator entries = dn.getEntries(); entries.hasNext();) {
Entry entry = (Entry) entries.next();
System.out.println(oleName + "." + entry.getName());
}
} else {
System.out.println("Else part 22");
byte[] objectData = obj.getObjectData();
}
}
}
}
Output screen of above program:
So ,how to exporting functionality implement?
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Demonstrates how you can extract embedded data from a .xlsx file
*/
public class GetEmbedded {
public static void main(String[] args) throws Exception {
String path = "SomeExcelFile.xlsx"
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
if (contentType.equals("application/vnd.ms-excel")) { //This is to read xls workbook embedded to xlsx file
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
int countOfSheetXls=embeddedWorkbook.getNumberOfSheets();
}
else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { //This is to read xlsx workbook embedded to xlsx file
if(pPart.getPartName().getName().equals("/xl/embeddings/Microsoft_Excel_Worksheet12.xlsx")){
//"/xl/embeddings/Microsoft_Excel_Worksheet12.xlsx" - Can read an Excel from a particular sheet
// This is the worksheet from the Parent Excel-sheet-12
XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
int countOfSheetXlsx=embeddedWorkbook.getNumberOfSheets();
ArrayList<String> sheetNames= new ArrayList<String>();
for(int i=0;i<countOfSheetXlsx;i++){
String name=workbook.getSheetName(i);
sheetNames.add(name);
}
}
}
}
}
}
This is partly a duplicate of How to get pictures with names from an xls file using Apache POI, for which I've written the original paste.
As per request, I've added also an example of how to add and embedding with the help of a OLE 1.0 packager - in the meantime I've added the code to POI, so this easier now. For the OOXML based files have a look into this answer.
So the code iterates through all shapes of the DrawingPatriarch and extracts the pictures and embedded files.
I've added the full code - instead of a snippet - to this answer, as I expect the next "why can't I export this kind of embedding" to come up soon ...
package poijartest;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.apache.poi.ddf.EscherComplexProperty;
import org.apache.poi.ddf.EscherOptRecord;
import org.apache.poi.ddf.EscherProperty;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFObjectData;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.Ole10Native;
import org.apache.poi.poifs.filesystem.Ole10NativeException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.sl.usermodel.AutoShape;
import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture;
/**
* Tested with POI 3.16-beta1
*
* 17.12.2014: original version for
* http://apache-poi.1045710.n5.nabble.com/How-to-get-the-full-file-name-of-a-picture-in-xls-file-td5717205.html
*
* 17.12.2016: added sample/dummy data for
* https://stackoverflow.com/questions/41101012/how-to-export-embeded-file-which-from-excel-using-poi
*/
public class EmbeddedReader {
private File excel_file;
private ImageReader image_reader;
public static void main(String[] args) throws Exception {
File sample = new File("bla.xls");
getSampleEmbedded(sample);
ImageReader ir = new ImageReader(sample);
for (EmbeddedData ed : ir.embeddings) {
System.out.println(ed.filename);
FileOutputStream fos = new FileOutputStream(ed.filename);
IOUtils.copy(ed.is, fos);
fos.close();
}
ir.close();
}
static void getSampleEmbedded(File sample) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
int storageId = wb.addOlePackage(getSamplePPT(), "dummy.ppt", "dummy.ppt", "dummy.ppt");
int picId = wb.addPicture(getSamplePng(), HSSFPicture.PICTURE_TYPE_PNG);
HSSFSheet sheet = wb.createSheet();
HSSFPatriarch pat = sheet.createDrawingPatriarch();
HSSFClientAnchor anc = pat.createAnchor(0, 0, 0, 0, 1, 1, 3, 6);
HSSFObjectData od = pat.createObjectData(anc, storageId, picId);
od.setNoFill(true);
wb.write(sample);
wb.close();
}
static byte[] getSamplePng() throws IOException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL imgUrl = cl.getResource("javax/swing/plaf/metal/icons/ocean/directory.gif");
BufferedImage img = ImageIO.read(imgUrl);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "PNG", bos);
return bos.toByteArray();
}
static byte[] getSamplePPT() throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow();
Slide<?,?> slide = ppt.createSlide();
AutoShape<?,?> sh1 = slide.createAutoShape();
sh1.setShapeType(ShapeType.STAR_32);
sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200));
sh1.setFillColor(Color.red);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ppt.write(bos);
ppt.close();
POIFSFileSystem poifs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
poifs.getRoot().setStorageClsid(ClassID.PPT_SHOW);
bos.reset();
poifs.writeFilesystem(bos);
poifs.close();
return bos.toByteArray();
}
public EmbeddedReader(String excel_path) throws IOException {
excel_file = new File(excel_path);
image_reader = new ImageReader(excel_file);
}
public String[] get_file_names() {
ArrayList<String> file_names = new ArrayList<String>();
for (EmbeddedData ed : image_reader.embeddings) {
file_names.add(ed.filename);
}
return file_names.toArray(new String[file_names.size()]);
}
public InputStream get_stream(String file_name) {
InputStream input_stream = null;
for (EmbeddedData ed : image_reader.embeddings) {
if(file_name.equals(ed.filename)) {
input_stream = ed.is;
break;
}
}
return input_stream;
}
static class ImageReader implements Closeable {
EmbeddedExtractor extractors[] = {
new Ole10Extractor(), new PdfExtractor(), new WordExtractor(), new ExcelExtractor(), new FsExtractor()
};
List<EmbeddedData> embeddings = new ArrayList<EmbeddedData>();
Workbook wb;
public ImageReader(File excelfile) throws IOException {
try {
wb = WorkbookFactory.create(excelfile);
Sheet receiptImages = wb.getSheet("Receipt images");
if (wb instanceof XSSFWorkbook) {
addSheetPicsAndEmbedds((XSSFSheet)receiptImages);
} else {
addAllEmbedds((HSSFWorkbook)wb);
addSheetPics((HSSFSheet)receiptImages);
}
} catch (Exception e) {
// todo: error handling
}
}
protected void addSheetPicsAndEmbedds(XSSFSheet sheet) throws IOException {
if (sheet == null) return;
XSSFDrawing draw = sheet.createDrawingPatriarch();
for (XSSFShape shape : draw.getShapes()) {
if (!(shape instanceof XSSFPicture)) continue;
XSSFPicture picture = (XSSFPicture)shape;
XSSFPictureData pd = picture.getPictureData();
PackagePart pp = pd.getPackagePart();
CTPicture ctPic = picture.getCTPicture();
String filename = null;
try {
filename = ctPic.getNvPicPr().getCNvPr().getName();
} catch (Exception e) {}
if (filename == null || "".equals(filename)) {
filename = new File(pp.getPartName().toString()).getName();
}
EmbeddedData ed = new EmbeddedData();
ed.filename = fileNameWithoutPath(filename);
ed.is = pp.getInputStream();
embeddings.add(ed);
}
}
protected void addAllEmbedds(HSSFWorkbook hwb) throws IOException {
for (HSSFObjectData od : hwb.getAllEmbeddedObjects()) {
String alternativeName = getAlternativeName(od);
if (od.hasDirectoryEntry()) {
DirectoryNode src = (DirectoryNode)od.getDirectory();
for (EmbeddedExtractor ee : extractors) {
if (ee.canExtract(src)) {
EmbeddedData ed = ee.extract(src);
if (ed.filename == null || ed.filename.startsWith("MBD") || alternativeName != null) {
ed.filename = alternativeName;
}
ed.filename = fileNameWithoutPath(ed.filename);
ed.source = "object";
embeddings.add(ed);
break;
}
}
}
}
}
protected String getAlternativeName(HSSFShape shape) {
EscherOptRecord eor = reflectEscherOptRecord(shape);
if (eor == null) return null;
for (EscherProperty ep : eor.getEscherProperties()) {
if ("groupshape.shapename".equals(ep.getName()) && ep.isComplex()) {
return new String(((EscherComplexProperty)ep).getComplexData(),
Charset.forName("UTF-16LE"));
}
}
return null;
}
protected void addSheetPics(HSSFSheet sheet) {
if (sheet == null) return;
int picIdx=0;
int emfIdx = 0;
HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
if (patriarch == null) return;
// Loop through the objects
for (HSSFShape shape : patriarch.getChildren()) {
if (!(shape instanceof HSSFPicture)) {
continue;
}
HSSFPicture picture = (HSSFPicture) shape;
if (picture.getShapeType() != HSSFSimpleShape.OBJECT_TYPE_PICTURE) continue;
HSSFPictureData pd = picture.getPictureData();
byte pictureBytes[] = pd.getData();
int pictureBytesOffset = 0;
int pictureBytesLen = pictureBytes.length;
String filename = picture.getFileName();
// try to find an alternative name
if (filename == null || "".equals(filename)) {
filename = getAlternativeName(picture);
}
// default to dummy name
if (filename == null || "".equals(filename)) {
filename = "picture"+(picIdx++);
}
filename = filename.trim();
// check for emf+ embedded pdf (poor mans style :( )
// Mac Excel 2011 embeds pdf files with this method.
boolean validFile = true;
if (pd.getFormat() == Workbook.PICTURE_TYPE_EMF) {
validFile = false;
int idxStart = indexOf(pictureBytes, 0, "%PDF-".getBytes());
if (idxStart != -1) {
int idxEnd = indexOf(pictureBytes, idxStart, "%%EOF".getBytes());
if (idxEnd != -1) {
pictureBytesOffset = idxStart;
pictureBytesLen = idxEnd-idxStart+6;
validFile = true;
}
} else {
// This shape was not a Mac Excel 2011 embedded pdf file.
// So this is a shape related to a regular embedded object
// Lets update the object filename with the shapes filename
// if the object filename is of format ARGF1234.pdf
EmbeddedData ed_obj = embeddings.get(emfIdx);
Pattern pattern = Pattern.compile("^[A-Z0-9]{8}\\.[pdfPDF]{3}$");
Matcher matcher = pattern.matcher(ed_obj.filename);
if(matcher.matches()) {
ed_obj.filename = filename;
}
emfIdx += 1;
}
}
EmbeddedData ed = new EmbeddedData();
ed.filename = fileNameWithoutPath(filename);
ed.is = new ByteArrayInputStream(pictureBytes, pictureBytesOffset, pictureBytesLen);
if(fileNotInEmbeddings(ed.filename) && validFile) {
embeddings.add(ed);
}
}
}
private static EscherOptRecord reflectEscherOptRecord(HSSFShape shape) {
try {
Method m = HSSFShape.class.getDeclaredMethod("getOptRecord");
m.setAccessible(true);
return (EscherOptRecord)m.invoke(shape);
} catch (Exception e) {
// todo: log ... well actually "should not happen" ;)
return null;
}
}
private String fileNameWithoutPath(String filename) {
int last_index = filename.lastIndexOf("\\");
return filename.substring(last_index + 1);
}
private boolean fileNotInEmbeddings(String filename) {
boolean exists = true;
for(EmbeddedData ed : embeddings) {
if(ed.filename.equals(filename)) {
exists = false;
}
}
return exists;
}
public void close() throws IOException {
Iterator<EmbeddedData> ed = embeddings.iterator();
while (ed.hasNext()) {
ed.next().is.close();
}
wb.close();
}
}
static class EmbeddedData {
String filename;
InputStream is;
String source;
}
static abstract class EmbeddedExtractor {
abstract boolean canExtract(DirectoryNode dn);
abstract EmbeddedData extract(DirectoryNode dn) throws IOException;
protected EmbeddedData extractFS(DirectoryNode dn, String filename) throws IOException {
assert(canExtract(dn));
POIFSFileSystem dest = new POIFSFileSystem();
copyNodes(dn, dest.getRoot());
EmbeddedData ed = new EmbeddedData();
ed.filename = filename;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
dest.writeFilesystem(bos);
dest.close();
ed.is = new ByteArrayInputStream(bos.toByteArray());
return ed;
}
}
static class Ole10Extractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return ClassID.OLE10_PACKAGE.equals(clsId);
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
try {
Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(dn);
EmbeddedData ed = new EmbeddedData();
ed.filename = new File(ole10.getFileName()).getName();
ed.is = new ByteArrayInputStream(ole10.getDataBuffer());
return ed;
} catch (Ole10NativeException e) {
throw new IOException(e);
}
}
}
static class PdfExtractor extends EmbeddedExtractor {
static ClassID PdfClassID = new ClassID("{B801CA65-A1FC-11D0-85AD-444553540000}");
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (PdfClassID.equals(clsId)
|| dn.hasEntry("CONTENTS"));
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
EmbeddedData ed = new EmbeddedData();
ed.is = dn.createDocumentInputStream("CONTENTS");
ed.filename = dn.getName()+".pdf";
return ed;
}
}
static class WordExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (ClassID.WORD95.equals(clsId)
|| ClassID.WORD97.equals(clsId)
|| dn.hasEntry("WordDocument"));
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName()+".doc");
}
}
static class ExcelExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (ClassID.EXCEL95.equals(clsId)
|| ClassID.EXCEL97.equals(clsId)
|| dn.hasEntry("Workbook") /*...*/);
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName()+".xls");
}
}
static class FsExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
return true;
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName()+".dat");
}
}
private static void copyNodes(DirectoryNode src, DirectoryNode dest) throws IOException {
for (Entry e : src) {
if (e instanceof DirectoryNode) {
DirectoryNode srcDir = (DirectoryNode)e;
DirectoryNode destDir = (DirectoryNode)dest.createDirectory(srcDir.getName());
destDir.setStorageClsid(srcDir.getStorageClsid());
copyNodes(srcDir, destDir);
} else {
InputStream is = src.createDocumentInputStream(e);
dest.createDocument(e.getName(), is);
is.close();
}
}
}
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching
* Finds the first occurrence of the pattern in the text.
*/
private static int indexOf(byte[] data, int offset, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0) return -1;
for (int i = offset; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) { j++; }
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private static int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
Required jar File List:
commons-codec-1.10.jar
dom4j.jar
poi-3.16-beta1.jar
poi-ooxml-3.8.jar
poi-ooxml-schemas-3.9.jar
poi-scratchpad-3.9.jar
xmlbeans-2.3.0.jar
This is my Whole code implementation:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.apache.poi.ddf.EscherComplexProperty;
import org.apache.poi.ddf.EscherOptRecord;
import org.apache.poi.ddf.EscherProperty;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFObjectData;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.Ole10Native;
import org.apache.poi.poifs.filesystem.Ole10NativeException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.sl.usermodel.AutoShape;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture;
public class EmbeddedReader {
public static final OleType OLE10_PACKAGE = new OleType("{0003000C-0000-0000-C000-000000000046}");
public static final OleType PPT_SHOW = new OleType("{64818D10-4F9B-11CF-86EA-00AA00B929E8}");
public static final OleType XLS_WORKBOOK = new OleType("{00020841-0000-0000-C000-000000000046}");
public static final OleType TXT_ONLY = new OleType("{5e941d80-bf96-11cd-b579-08002b30bfeb}");
public static final OleType EXCEL97 = new OleType("{00020820-0000-0000-C000-000000000046}");
public static final OleType EXCEL95 = new OleType("{00020810-0000-0000-C000-000000000046}");
public static final OleType WORD97 = new OleType("{00020906-0000-0000-C000-000000000046}");
public static final OleType WORD95 = new OleType("{00020900-0000-0000-C000-000000000046}");
public static final OleType POWERPOINT97 = new OleType("{64818D10-4F9B-11CF-86EA-00AA00B929E8}");
public static final OleType POWERPOINT95 = new OleType("{EA7BAE70-FB3B-11CD-A903-00AA00510EA3}");
public static final OleType EQUATION30 = new OleType("{0002CE02-0000-0000-C000-000000000046}");
public static final OleType PdfClassID = new OleType("{B801CA65-A1FC-11D0-85AD-444553540000}");
private File excel_file;
private ImageReader image_reader;
static class OleType {
final String classId;
OleType(String classId) {
this.classId = classId;
}
ClassID getClassID() {
ClassID cls = new ClassID();
byte clsBytes[] = cls.getBytes();
String clsStr = classId.replaceAll("[{}-]", "");
for (int i = 0; i < clsStr.length(); i += 2) {
clsBytes[i / 2] = (byte) Integer.parseInt(
clsStr.substring(i, i + 2), 16);
}
return cls;
}
}
public static void main(String[] args) throws Exception {
File sample = new File("D:\\ole_ppt_in_xls.xls");
ImageReader ir = new ImageReader(sample);
for (EmbeddedData ed : ir.embeddings) {
FileOutputStream fos = new FileOutputStream(System.getProperty("user.home") + "/Desktop" + "/sumit/"+ ed.filename);
IOUtils.copy(ed.is, fos);
fos.close();
}
ir.close();
}
static byte[] getSamplePng() throws IOException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL imgUrl = cl.getResource("javax/swing/plaf/metal/icons/ocean/directory.gif");
BufferedImage img = ImageIO.read(imgUrl);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "PNG", bos);
return bos.toByteArray();
}
public EmbeddedReader(String excel_path) throws IOException {
excel_file = new File(excel_path);
image_reader = new ImageReader(excel_file);
}
public String[] get_file_names() {
ArrayList<String> file_names = new ArrayList<String>();
for (EmbeddedData ed : image_reader.embeddings) {
file_names.add(ed.filename);
}
return file_names.toArray(new String[file_names.size()]);
}
public InputStream get_stream(String file_name) {
InputStream input_stream = null;
for (EmbeddedData ed : image_reader.embeddings) {
if (file_name.equals(ed.filename)) {
input_stream = ed.is;
break;
}
}
return input_stream;
}
static class ImageReader implements Closeable {
EmbeddedExtractor extractors[] = { new Ole10Extractor(),new PdfExtractor(), new WordExtractor(), new ExcelExtractor(),new FsExtractor() };
List<EmbeddedData> embeddings = new ArrayList<EmbeddedData>();
Workbook wb;
public ImageReader(File excelfile) throws IOException {
try {
wb = WorkbookFactory.create(excelfile);
Sheet receiptImages = wb.getSheet("Receipt images");
if (wb instanceof XSSFWorkbook) {
addSheetPicsAndEmbedds((XSSFSheet) receiptImages);
} else {
addAllEmbedds((HSSFWorkbook) wb);
addSheetPics((HSSFSheet) receiptImages);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void addSheetPicsAndEmbedds(XSSFSheet sheet)throws IOException {
if (sheet == null)
return;
XSSFDrawing draw = sheet.createDrawingPatriarch();
for (XSSFShape shape : draw.getShapes()) {
if (!(shape instanceof XSSFPicture))
continue;
XSSFPicture picture = (XSSFPicture) shape;
XSSFPictureData pd = picture.getPictureData();
PackagePart pp = pd.getPackagePart();
CTPicture ctPic = picture.getCTPicture();
String filename = null;
try {
filename = ctPic.getNvPicPr().getCNvPr().getName();
} catch (Exception e) {
}
if (filename == null || "".equals(filename)) {
filename = new File(pp.getPartName().toString()).getName();
}
EmbeddedData ed = new EmbeddedData();
ed.filename = fileNameWithoutPath(filename);
ed.is = pp.getInputStream();
embeddings.add(ed);
}
}
protected void addAllEmbedds(HSSFWorkbook hwb) throws IOException {
for (HSSFObjectData od : hwb.getAllEmbeddedObjects()) {
String alternativeName = getAlternativeName(od);
if (od.hasDirectoryEntry()) {
DirectoryNode src = (DirectoryNode) od.getDirectory();
for (EmbeddedExtractor ee : extractors) {
if (ee.canExtract(src)) {
EmbeddedData ed = ee.extract(src);
if (ed.filename == null || ed.filename.startsWith("MBD")|| alternativeName != null) {
if (alternativeName != null) {
ed.filename = alternativeName;
}
}
ed.filename = fileNameWithoutPath(ed.filename);
ed.source = "object";
embeddings.add(ed);
break;
}
}
}
}
}
protected String getAlternativeName(HSSFShape shape) {
EscherOptRecord eor = reflectEscherOptRecord(shape);
if (eor == null) {
return null;
}
for (EscherProperty ep : eor.getEscherProperties()) {
if ("groupshape.shapename".equals(ep.getName())
&& ep.isComplex()) {
return new String(
((EscherComplexProperty) ep).getComplexData(),
Charset.forName("UTF-16LE"));
}
}
return null;
}
protected void addSheetPics(HSSFSheet sheet) {
if (sheet == null)
return;
int picIdx = 0;
int emfIdx = 0;
HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
if (patriarch == null)
return;
// Loop through the objects
for (HSSFShape shape : patriarch.getChildren()) {
if (!(shape instanceof HSSFPicture)) {
continue;
}
HSSFPicture picture = (HSSFPicture) shape;
if (picture.getShapeType() != HSSFSimpleShape.OBJECT_TYPE_PICTURE)
continue;
HSSFPictureData pd = picture.getPictureData();
byte pictureBytes[] = pd.getData();
int pictureBytesOffset = 0;
int pictureBytesLen = pictureBytes.length;
String filename = picture.getFileName();
// try to find an alternative name
if (filename == null || "".equals(filename)) {
filename = getAlternativeName(picture);
}
// default to dummy name
if (filename == null || "".equals(filename)) {
filename = "picture" + (picIdx++);
}
filename = filename.trim();
// check for emf+ embedded pdf (poor mans style :( )
// Mac Excel 2011 embeds pdf files with this method.
boolean validFile = true;
if (pd.getFormat() == Workbook.PICTURE_TYPE_EMF) {
validFile = false;
int idxStart = indexOf(pictureBytes, 0, "%PDF-".getBytes());
if (idxStart != -1) {
int idxEnd = indexOf(pictureBytes, idxStart,"%%EOF".getBytes());
if (idxEnd != -1) {
pictureBytesOffset = idxStart;
pictureBytesLen = idxEnd - idxStart + 6;
validFile = true;
}
} else {
// This shape was not a Mac Excel 2011 embedded pdf file.
// So this is a shape related to a regular embedded object
// Lets update the object filename with the shapes filename
// if the object filename is of format ARGF1234.pdf
EmbeddedData ed_obj = embeddings.get(emfIdx);
Pattern pattern = Pattern
.compile("^[A-Z0-9]{8}\\.[pdfPDF]{3}$");
Matcher matcher = pattern.matcher(ed_obj.filename);
if (matcher.matches()) {
ed_obj.filename = filename;
}
emfIdx += 1;
}
}
EmbeddedData ed = new EmbeddedData();
ed.filename = fileNameWithoutPath(filename);
ed.is = new ByteArrayInputStream(pictureBytes,
pictureBytesOffset, pictureBytesLen);
if (fileNotInEmbeddings(ed.filename) && validFile) {
embeddings.add(ed);
}
}
}
private static EscherOptRecord reflectEscherOptRecord(HSSFShape shape) {
try {
Method m = HSSFShape.class.getDeclaredMethod("getOptRecord");
m.setAccessible(true);
return (EscherOptRecord) m.invoke(shape);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String fileNameWithoutPath(String filename) {
int last_index = filename.lastIndexOf("\\");
return filename.substring(last_index + 1);
}
private boolean fileNotInEmbeddings(String filename) {
boolean exists = true;
for (EmbeddedData ed : embeddings) {
if (ed.filename.equals(filename)) {
exists = false;
}
}
return exists;
}
public void close() throws IOException {
Iterator<EmbeddedData> ed = embeddings.iterator();
while (ed.hasNext()) {
ed.next().is.close();
}
wb.close();
}
}
static class EmbeddedData {
String filename;
InputStream is;
String source;
}
static abstract class EmbeddedExtractor {
abstract boolean canExtract(DirectoryNode dn);
abstract EmbeddedData extract(DirectoryNode dn) throws IOException;
protected EmbeddedData extractFS(DirectoryNode dn, String filename)
throws IOException {
assert (canExtract(dn));
POIFSFileSystem dest = new POIFSFileSystem();
copyNodes(dn, dest.getRoot());
EmbeddedData ed = new EmbeddedData();
ed.filename = filename;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
dest.writeFilesystem(bos);
bos.close();
ed.is = new ByteArrayInputStream(bos.toByteArray());
return ed;
}
}
static class Ole10Extractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return OLE10_PACKAGE.equals(clsId);
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
try {
Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(dn);
EmbeddedData ed = new EmbeddedData();
ed.filename = new File(ole10.getFileName()).getName();
ed.is = new ByteArrayInputStream(ole10.getDataBuffer());
return ed;
} catch (Ole10NativeException e) {
e.printStackTrace();
throw new IOException(e);
}
}
}
static class PdfExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (PdfClassID.equals(clsId) || dn.hasEntry("CONTENTS"));
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
EmbeddedData ed = new EmbeddedData();
ed.is = dn.createDocumentInputStream("CONTENTS");
ed.filename = dn.getName() + ".pdf";
return ed;
}
}
static class WordExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (WORD95.equals(clsId) || WORD97.equals(clsId) || dn.hasEntry("WordDocument"));
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName() + ".doc");
}
}
static class ExcelExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (EXCEL95.equals(clsId) || EXCEL97.equals(clsId) || dn
.hasEntry("Workbook") /* ... */);
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName() + ".xls");
}
}
static class FsExtractor extends EmbeddedExtractor {
public boolean canExtract(DirectoryNode dn) {
return true;
}
public EmbeddedData extract(DirectoryNode dn) throws IOException {
return extractFS(dn, dn.getName() + ".dat");
}
}
private static void copyNodes(DirectoryNode src, DirectoryNode dest)
throws IOException {
for (Entry e : src) {
if (e instanceof DirectoryNode) {
DirectoryNode srcDir = (DirectoryNode) e;
DirectoryNode destDir = (DirectoryNode) dest
.createDirectory(srcDir.getName());
destDir.setStorageClsid(srcDir.getStorageClsid());
copyNodes(srcDir, destDir);
} else {
InputStream is = src.createDocumentInputStream(e);
dest.createDocument(e.getName(), is);
is.close();
}
}
}
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching Finds the first
* occurrence of the pattern in the text.
*/
private static int indexOf(byte[] data, int offset, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0)
return -1;
for (int i = offset; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) {
j++;
}
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process, where the
* pattern is matched against itself.
*/
private static int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
To simplify the processing of embedded data, I've added an extractor class to POI, which will be available in POI 3.16-beta2 or a nightly until then.
The following will extract the objects of .xls/x files - all which is left, is to write the embedded bytes somewhere. It's possible to extend the extractor classes by simply extending EmbeddedExtractor and provide your own iterator() method.
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.ss.extractor.EmbeddedData;
import org.apache.poi.ss.extractor.EmbeddedExtractor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class BlaExtract {
public static void main(String[] args) throws Exception {
InputStream fis = new FileInputStream("bla.xlsx");
Workbook wb = WorkbookFactory.create(fis);
fis.close();
EmbeddedExtractor ee = new EmbeddedExtractor();
for (Sheet s : wb) {
for (EmbeddedData ed : ee.extractAll(s)) {
System.out.println(ed.getFilename()+" ("+ed.getContentType()+") - "+ed.getEmbeddedData().length+" bytes");
}
}
wb.close();
}
}
How we can convert a dicom file(.dcm) to a jpeg image using java?
Here is my code:
import java.io.File;
import java.io.IOException;
import org.dcm4che2.tool.dcm2jpg.Dcm2Jpg;
public class MainClass {
public static void main(String[] args) throws IOException{
Dcm2Jpg conv = new Dcm2Jpg();
conv.convert(new File("C:\\Users\\lijo.joseph\\Desktop\\Dicom\\IM-0001-0001.dcm"), new File("C:\\Users\\lijo.joseph\\Desktop\\Dicom\\IM-0001-0001.jpg"));
}
}
and i am getting the following error while running the project
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException
at MainClass.main(MainClass.java:7)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.cli.ParseException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
please help and thanks in advance
Here is the link Converting DICOM to JPEG using dcm4che 2
Following is my code which works perfectly.I have placed it with imports so it might be use-full.
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Examplke1 {
static BufferedImage myJpegImage=null;
public static void main(String[] args) {
File file = new File("test5/12840.dcm");
Iterator<ImageReader> iterator =ImageIO.getImageReadersByFormatName("DICOM");
while (iterator.hasNext()) {
ImageReader imageReader = (ImageReader) iterator.next();
DicomImageReadParam dicomImageReadParam = (DicomImageReadParam) imageReader.getDefaultReadParam();
try {
ImageInputStream iis = ImageIO.createImageInputStream(file);
imageReader.setInput(iis,false);
myJpegImage = imageReader.read(0, dicomImageReadParam);
iis.close();
if(myJpegImage == null){
System.out.println("Could not read image!!");
}
} catch (IOException e) {
e.printStackTrace();
}
File file2 = new File("/test.jpg");
try {
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file2));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
encoder.encode(myJpegImage);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Completed");
}
}
}
Jars Used to Run it
dcm4che-imageio-2.0.28.jar
dcm4che-image-2.0.28.jar
jai_imageio-1.1.jar
dcm4che-core-2.0.28.jar
slf4j-api-1.7.7.jar
slf4j-log4j12-1.7.7.jar
apache-logging-log4j.jar
Hope it helps.
This Code is used for Converting Dicom Image to JPG Image
import java.io.File;
import java.io.IOException;
public class Dcm2JpgTest {
public static void main(String[] args) throws IOException {
try{
File src = new File("d:\\Test.dcm");
File dest = new File("d:\\Test.jpg");
Dcm2Jpeg dcm2jpg= new Dcm2Jpeg();
dcm2jpg.convert(src, dest);
System.out.println("Completed");
} catch(IOException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
}
Dcm2Jpeg.java File
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import org.dcm4che2.io.DicomInputStream;
import org.dcm4che2.util.CloseUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Dcm2Jpeg {
private static final String USAGE =
"dcm2jpg [Options] <dcmfile> <jpegfile>\n" +
"or dcm2jpg [Options] <dcmfile>... <outdir>\n" +
"or dcm2jpg [Options] <indir>... <outdir>";
private static final String DESCRIPTION =
"Convert DICOM image(s) to JPEG(s)\nOptions:";
private static final String EXAMPLE = null;
private int frame = 1;
private float center;
private float width;
private String vlutFct;
private boolean autoWindowing;
private DicomObject prState;
private short[] pval2gray;
private String fileExt = ".jpg";
private void setFrameNumber(int frame) {
this.frame = frame;
}
private void setWindowCenter(float center) {
this.center = center;
}
private void setWindowWidth(float width) {
this.width = width;
}
public final void setVoiLutFunction(String vlutFct) {
this.vlutFct = vlutFct;
}
private final void setAutoWindowing(boolean autoWindowing) {
this.autoWindowing = autoWindowing;
}
private final void setPresentationState(DicomObject prState) {
this.prState = prState;
}
private final void setPValue2Gray(short[] pval2gray) {
this.pval2gray = pval2gray;
}
public final void setFileExt(String fileExt) {
this.fileExt = fileExt;
}
public void convert(File src, File dest) throws IOException {
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = iter.next();
DicomImageReadParam param =
(DicomImageReadParam) reader.getDefaultReadParam();
param.setWindowCenter(center);
param.setWindowWidth(width);
param.setVoiLutFunction(vlutFct);
param.setPresentationState(prState);
param.setPValue2Gray(pval2gray);
param.setAutoWindowing(autoWindowing);
ImageInputStream iis = ImageIO.createImageInputStream(src);
BufferedImage bi;
OutputStream out = null;
try {
reader.setInput(iis, false);
bi = reader.read(frame - 1, param);
if (bi == null) {
System.out.println("\nError: " + src + " - couldn't read!");
return;
}
out = new BufferedOutputStream(new FileOutputStream(dest));
JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
enc.encode(bi);
} finally {
CloseUtils.safeClose(iis);
CloseUtils.safeClose(out);
}
//System.out.print('.');
}
public int mconvert(List<String> args, int optind, File destDir)
throws IOException {
int count = 0;
for (int i = optind, n = args.size() - 1; i < n; ++i) {
File src = new File(args.get(i));
count += mconvert(src, new File(destDir, src2dest(src)));
}
return count;
}
private String src2dest(File src) {
String srcname = src.getName();
return src.isFile() ? srcname + this.fileExt : srcname;
}
public int mconvert(File src, File dest) throws IOException {
if (!src.exists()) {
System.err.println("WARNING: No such file or directory: " + src
+ " - skipped.");
return 0;
}
if (src.isFile()) {
try {
convert(src, dest);
} catch (Exception e) {
System.err.println("WARNING: Failed to convert " + src + ":");
e.printStackTrace(System.err);
System.out.print('F');
return 0;
}
System.out.print('.');
return 1;
}
File[] files = src.listFiles();
if (files.length > 0 && !dest.exists()) {
dest.mkdirs();
}
int count = 0;
for (int i = 0; i < files.length; ++i) {
count += mconvert(files[i], new File(dest, src2dest(files[i])));
}
return count;
}
#SuppressWarnings("unchecked")
public static void main(String args[]) throws Exception {
CommandLine cl = parse(args);
Dcm2Jpeg dcm2jpg = new Dcm2Jpeg();
if (cl.hasOption("f")) {
dcm2jpg.setFrameNumber(
parseInt(cl.getOptionValue("f"),
"illegal argument of option -f",
1, Integer.MAX_VALUE));
}
if (cl.hasOption("p")) {
dcm2jpg.setPresentationState(loadDicomObject(
new File(cl.getOptionValue("p"))));
}
if (cl.hasOption("pv2gray")) {
dcm2jpg.setPValue2Gray(loadPVal2Gray(
new File(cl.getOptionValue("pv2gray"))));
}
if (cl.hasOption("c")) {
dcm2jpg.setWindowCenter(
parseFloat(cl.getOptionValue("c"),
"illegal argument of option -c"));
}
if (cl.hasOption("w")) {
dcm2jpg.setWindowWidth(
parseFloat(cl.getOptionValue("w"),
"illegal argument of option -w"));
}
if (cl.hasOption("sigmoid")) {
dcm2jpg.setVoiLutFunction(DicomImageReadParam.SIGMOID);
}
dcm2jpg.setAutoWindowing(!cl.hasOption("noauto"));
if (cl.hasOption("jpgext")) {
dcm2jpg.setFileExt(cl.getOptionValue("jpgext"));
}
final List<String> argList = cl.getArgList();
int argc = argList.size();
File dest = new File(argList.get(argc-1));
long t1 = System.currentTimeMillis();
int count = 1;
if (dest.isDirectory()) {
count = dcm2jpg.mconvert(argList, 0, dest);
} else {
File src = new File(argList.get(0));
if (argc > 2 || src.isDirectory()) {
exit("dcm2jpg: when converting several files, "
+ "last argument must be a directory\n");
}
dcm2jpg.convert(src, dest);
}
long t2 = System.currentTimeMillis();
System.out.println("\nconverted " + count + " files in " + (t2 - t1)
/ 1000f + " s.");
}
private static DicomObject loadDicomObject(File file) {
DicomInputStream in = null;
try {
in = new DicomInputStream(file);
return in.readDicomObject();
} catch (IOException e) {
exit(e.getMessage());
throw new RuntimeException();
} finally {
CloseUtils.safeClose(in);
}
}
private static short[] loadPVal2Gray(File file) {
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(
file)));
short[] pval2gray = new short[256];
int n = 0;
String line;
while ((line = r.readLine()) != null) {
try {
int val = Integer.parseInt(line.trim());
if (n == pval2gray.length) {
if (n == 0x10000) {
exit("Number of entries in " + file + " > 2^16");
}
short[] tmp = pval2gray;
pval2gray = new short[n << 1];
System.arraycopy(tmp, 0, pval2gray, 0, n);
}
pval2gray[n++] = (short) val;
} catch (NumberFormatException nfe) {
// ignore lines where Integer.parseInt fails
}
}
if (n != pval2gray.length) {
exit("Number of entries in " + file + ": " + n
+ " != 2^[8..16]");
}
return pval2gray;
} catch (IOException e) {
exit(e.getMessage());
throw new RuntimeException();
} finally {
CloseUtils.safeClose(r);
}
}
private static CommandLine parse(String[] args) {
Options opts = new Options();
OptionBuilder.withArgName("frame");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"frame to convert, 1 (= first frame) by default");
opts.addOption(OptionBuilder.create("f"));
OptionBuilder.withArgName("prfile");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path of presentation state to apply");
opts.addOption(OptionBuilder.create("p"));
OptionBuilder.withArgName("center");
OptionBuilder.hasArg();
OptionBuilder.withDescription("Window Center");
opts.addOption(OptionBuilder.create("c"));
OptionBuilder.withArgName("width");
OptionBuilder.hasArg();
OptionBuilder.withDescription("Window Width");
opts.addOption(OptionBuilder.create("w"));
opts.addOption("sigmoid", false,
"apply sigmoid VOI LUT function with given Window Center/Width");
opts.addOption("noauto", false,
"disable auto-windowing for images w/o VOI attributes");
OptionBuilder.withArgName("file");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path of P-Value to gray value map");
opts.addOption(OptionBuilder.create("pv2gray"));
OptionBuilder.withArgName(".xxx");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"jpeg file extension used with destination directory argument,"
+ " default: '.jpg'.");
opts.addOption(OptionBuilder.create("jpgext"));
opts.addOption("h", "help", false, "print this message");
opts.addOption("V", "version", false,
"print the version information and exit");
CommandLine cl = null;
try {
cl = new GnuParser().parse(opts, args);
} catch (ParseException e) {
exit("dcm2jpg: " + e.getMessage());
throw new RuntimeException("unreachable");
}
if (cl.hasOption('V')) {
Package p = Dcm2Jpeg.class.getPackage();
System.out.println("dcm2jpg v" + p.getImplementationVersion());
System.exit(0);
}
if (cl.hasOption('h') || cl.getArgList().size() < 2) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
System.exit(0);
}
return cl;
}
private static int parseInt(String s, String errPrompt, int min, int max) {
try {
int i = Integer.parseInt(s);
if (i >= min && i <= max)
return i;
} catch (NumberFormatException e) {
// parameter is not a valid integer; fall through to exit
}
exit(errPrompt);
throw new RuntimeException();
}
private static float parseFloat(String s, String errPrompt) {
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
exit(errPrompt);
throw new RuntimeException();
}
}
private static void exit(String msg) {
System.err.println(msg);
System.err.println("Try 'dcm2jpg -h' for more information.");
System.exit(1);
}
}
Jars Files Used to Run this code
dcm4che-core-2.0.23.jar
dcm4che-image-2.0.23.jar
dcm4che-imageio-2.0.23.jar
dcm4che-imageio-rle-2.0.23.jar
slf4j-log4j12-1.5.0.jar
slf4j-api-1.5.0.jar
log4j-1.2.13.jar
commons-cli-1.2.jar
If you don't want to use direct Dcm2Jpg.java file then you can include below jar file.
dcm4che-tool-dcm2jpg-2.0.23.jar
In this jar you can import org.dcm4che2.tool.dcm2jpg.Dcm2Jpg this java file
I'm trying to load a csv file into an arrayList to later break it up and store it. Between my methods the arrayList is being reset to null. I'm confused as to the cause and would be grateful for any advice
package TestInput;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class Bean {
private String fileContent;
private String fileContent2;
private ArrayList<String> fileContentArray;
private int counter = 0;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public ArrayList<String> getFileContentArray() {
return fileContentArray;
}
public void setFileContentArray(ArrayList<String> fileContentArray) {
this.fileContentArray = fileContentArray;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
public String getFileContent2() {
return fileContent2;
}
public void setFileContent2(String fileContent2) {
this.fileContent2 = fileContent2;
}
public void upload() {
File file = new File("/Users/t_sedgman/Desktop/FinalProject/test_output_data.rtf");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
ArrayList<String> tempArray = new ArrayList<>();
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
tempArray.add(dis.readLine());
}
setFileContentArray(tempArray);
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
fileContent = fileContentArray.get((fileContentArray.size() - 2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void next() {
ArrayList<String> tempArray = getFileContentArray();
int size = fileContentArray.size();
if (counter <= size) {
counter++;
fileContent2 = tempArray.get(counter);
} else {
counter = 0;
}
}
}
Many Thanks
Tom
You can try By marking your bean with #ViewScoped/#SessionScoped
this code couldn't find the files that the buffered reader is supposed to read from it and i have the files in the src folder in eclipse project and it still doesn't read from file so does anybody have any idea about what the problem is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.*;
import java.util.ArrayList;
public class Encrypt {
public static ArrayList<String> data = new ArrayList<String>();
public static BigInteger [] keys = new BigInteger[3];
public static BigInteger n;
public static double e;
public static BigInteger d;
public static String line;
public static String result;
public static String [] temp;
public static BigInteger tempVar;
public static BigInteger tempResult;
public static int tempVar2;
public static void encryption(ArrayList<String> data) throws IOException{
for (int i = 0; i<data.size(); i++){
if(data.get(i)!= null){
temp = new String[data.get(i).split(" ").length];
temp = data.get(i).split(" ");
for(int j = 0; j<temp.length;j++){
for (int k = 0; k< temp[j].length(); k++){
tempVar2 = (int)temp[j].charAt(k);
tempVar=BigInteger.valueOf((long)Math.pow(tempVar2,e));
tempResult = (tempVar.remainder(n));
result =""+ tempResult;
LogEncrypt(result);
}
}
}
}
}
public static void read() throws IOException{
try {
BufferedReader br = new BufferedReader(new FileReader("plainText.txt"));
System.out.println(br.ready());
while ((line = br.readLine()) != null) {
data.add(br.readLine());
}
System.out.println("done with text");
} catch (FileNotFoundException e) {
System.out.println("please add the text file");
e.printStackTrace();
}
try {
BufferedReader ba = new BufferedReader(new FileReader("Key.txt"));
System.out.println(ba.ready());
int i =0;
while ((line = ba.readLine()) != null) {
keys[i] = new BigInteger(ba.readLine());
i++;
}
n = keys[0];
e = keys[1].doubleValue();
d = keys[2];
System.out.println("done with key");
} catch (FileNotFoundException e) {
System.out.println("please add the key file");
e.printStackTrace();
}
}
public static void LogEncrypt(String result) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
try {
out.write(result);
out.newLine();
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
}
}
public static void main(String[]args) throws IOException{
read();
encryption(data);
}
}
Put the file outside of the src, or at least add "src/" to the file location