inputStream = new FileInputStream(path) not working - java

This is the code in Java Class.
redflaglight.png image is present in the Images folder
file not found Null pointer exception is at
inputStream = new FileInputStream(path);
Struts2.3.5 Java7
public String createRootPath() throws UnsupportedEncodingException {
String rootPath = "";
String path = ExportExcelBusiness.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
File f = new File(path);
String ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
String decodedPath = URLDecoder.decode(ff, "UTF-8");
rootPath = decodedPath.replace('\\', '/');
rootPath += "/WebContent/pages/appsresponse/images";
return rootPath;
}
path = createRootPath()+ "/up_arrow_export.png";
InputStream inputStream = null;
int pictureIdx = 0;
byte[] bytes;
try {
inputStream = new FileInputStream(path);
bytes = IOUtils
.toByteArray(inputStream);
pictureIdx = wb.addPicture(bytes,
Workbook.PICTURE_TYPE_PNG);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
Though File is present in the path, unable to fetch that file. This started after upgrading from Struts2.2.1 to struts2.3.5

If you are running this code on server and using relative path then, your file should be inside server directory. like:-
your_server_path/pages/appsresponse/images
Problem is you are keeping your images in workspace, you need to keep that in server directory.
EDIT
Verify your path
File file=new File(path);
System.out.print(file.getAbsolutePath()); //check whether file is present at this path or not

Related

How to open pdf file in browser

I'm trying to open a pdf file in which has been exported from a repository. Here is the code that I'm using:
ConnectionManager con = new ConnectionManager();
String id = request.getParameter("uname");
String objname = request.getParameter("pass");
Properties prop = new Properties();
//ResourceBundle resource = ResourceBundle.getBundle("query");
//prop.load(getClass().getResourceAsStream("query.properties"));
String uname = "DmAdmin";
String pass = "<pass>";
String docbase = "QDocs";
String ext = new String();
IDfSession ssn = con.getSession(uname, pass, docbase);
sysObj = (IDfSysObject)ssn.getObject((IDfId)new DfId(id));
//ByteArrayInputStream buf = sysObj.getContent();
//sysObj.getFile("C:\\Users\\rsaha04\\Downloads\\"+objname+".pdf");
String path = "C:\\Users\\rsaha04\\Downloads\\";
String filename = path + sysObj.getObjectName().toString();
IDfCollection coll = sysObj.getRenditions(null);
if (coll != null)
{
while (coll.next())
{
String format = coll.getString("full_format");
{
if (format.equalsIgnoreCase("pdf"))
{
ext = "pdf";
System.out.println("extension set: "+ext);
}
}
}
filename = filename+"."+ext;
sysObj.getFileEx(filename, ext, 0, false);
}
con.closeConnection(ssn);
//Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+filename);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='"+filename+"'");
I'm able to open the pdf file in adobe acrobat reader but it is failing for browser with this error.
Please help me understand where I'm going wrong here.
You need your server to respond with a pdf file. You set the response headers, but your code never writes the pdf data into the response.
Do that using
response.write(bytesFromPdfFile)

How to replace DataXML from Slide Diagram in Powerpoint using Apache POI

i want to replace the one data.xml file of power point presentation in java using apache API with other file data.xml
For the reference i want to replace the following file with another power point file.
Following is the code i have tried but xml isnt replacing. I have different XML for both files every time i run after replacing using this code
public static void main(String[] args) {
// TODO Auto-generated method stub
final String filename = "C:/Users/skhan/Desktop/game.pptx";
final String filename1 = "C:/Users/skhan/Desktop/globe.pptx";
try {
XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(filename));
OPCPackage pkg = ppt.getPackage();
PackagePart data = pkg.getPart(
PackagingURIHelper.createPartName("/ppt/diagrams/data1.xml"));
InputStream data1Inp = data.getInputStream();
XMLSlideShow ppt1 = new XMLSlideShow(new FileInputStream(filename1));
OPCPackage pkg1 = ppt1.getPackage();
PackagePart data11 = pkg1.getPart(
PackagingURIHelper.createPartName("/ppt/diagrams/data1.xml"));
InputStream data1Inp1 = data11.getInputStream();
String data1String = GetData(data1Inp);
String data2String = GetData(data1Inp1);
//i want to replace here
PrintStream pr = new PrintStream(data.getOutputStream());
pr.print(data2String);
pr.close();
System.out.println("Completed");
} catch (Exception e) {
e.printStackTrace();
}
}
public static String GetData(InputStream input) throws Exception
{
StringBuilder builder = new StringBuilder();
int ch;
while((ch = input.read()) != -1){
builder.append((char)ch);
}
String theString = builder.toString();
return theString;
}
I added the few line after changing in order to save the file.
The XMLSlideShow must write to some file after changing or adding.
File file =new File(filename);
FileOutputStream out = new FileOutputStream(file);
ppt.write(out);
out.close();

creating a gz file and adding the tar file into it

My task is to tar list of files and this tar should be kept in .gz file. I have succeeded in creating .tar file, but the next step like when creating .gz file I got an issue. After creating .gz file with a tar inside is converted into File format without any extension.
java code to generate .tar file
FileSystem fs = FileSystems.getDefault();
OutputStream tar_output = new FileOutputStream(fs.getPath(hardLink.toString(), tarFileName + ".tar")
.toFile());
ArchiveOutputStream my_tar_ball = new ArchiveStreamFactory().createArchiveOutputStream(
ArchiveStreamFactory.TAR, tar_output);
Path p = null;
TarArchiveEntry tar_file = null;
for (String list : certFileList) {
p = fs.getPath(hardLink.toString(), list);
tar_file = new TarArchiveEntry(p.getFileName().toString());
tar_file.setSize(p.toFile().length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(p.toFile()), my_tar_ball);
my_tar_ball.closeArchiveEntry();
}
call gzipIt function
gzipIt(hardLink.toString() + "/" + tarFileName + ".gz", hardLink.toString() + "/" + tarFileName + ".tar");
Java code to generate .gz file
public static void gzipIt(String outputDir, String sourceFile) {
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream(new File(outputDir));
GZIPOutputStream gzos = new GZIPOutputStream(fos);
FileInputStream in = new FileInputStream(sourceFile);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Could anyone help me in resolving the issue.
Regards
Sai

How to extract Lotus Notes database icon?

I have tried to extract Lotus Notes database icon by using DXL Exporter but it is not success. Result file is corrupt and can not be opened by image viewer.
How can I extract Lotus Notes database icon by using java?
private String extractDatabaseIcon() {
String tag = "";
String idfile = "";
String password = "";
String dbfile = "";
NotesThread.sinitThread();
Session s = NotesFactory.createSessionWithFullAccess();
s.createRegistration().switchToID(idfile, password);
Database d = s.getDatabase("", dbfile);
NoteCollection nc = d.createNoteCollection(false);
nc.setSelectIcon(true);
nc.buildCollection();
String noteId = nc.getFirstNoteID();
int counter = 0;
while (noteId != null) {
counter++;
try {
Document doc = d.getDocumentByID(noteId);
DxlExporter dxl = s.createDxlExporter();
String xml = dxl.exportDxl(doc);
xml = xml.substring(xml.indexOf("<note "));
org.jsoup.nodes.Document jdoc = Jsoup.parse(xml);
Element ele = jdoc.select("rawitemdata").first();
String raw = ele.text().trim();
String temp = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "\\";
File file = new File(temp);
file.mkdir();
String filename = temp + UUID.randomUUID().toString().replaceAll("-", "") + ".gif";
byte[] buffer = decode(raw.getBytes());
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
tag = filename;
} catch (Exception e) {
logger.error("", e);
}
if (counter >= nc.getCount()) {
noteId = null;
} else {
noteId = nc.getNextNoteID(noteId);
}
}
return tag;
}
private byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
It is not even a bitmap, it is an icon. The format you can find here:
http://www.daubnet.com/formats/ICO.html
I managed to do this, a long time ago, in LotusScript. My code was based on an earlier version of this page:
http://www2.tcl.tk/11202
For the icon itself, you only have to open one document:
NotesDocument doc = db.getDocumentByID("FFFF8010")
exporter = session.createDXLExporter
exporter.setConvertNotesBitmapsToGIF(false)
outputXML = exporter.export(doc)
and then parse the XML to find the rawitemdata from the IconBitmap item, as you did in your original code.
I'm not sure what the format is. As far as I know' it's a 16 color bitmap, but not in standard BMP file format. And it's definitely not GIF format, but you can tell the DXLExporter to convert it. The default is to leave it native, so you need to add this to your code before you export:
dxl.setConvertNotesBitmapsToGIF(true);

Java- Copy file to either new file or existing file

I would like to write a function copy(File f1, File f2)
f1 is always a file.
f2 is either a file or a directory.
If f2 is a directory I would like to copy f1 to this directory (the file name should stay the same).
If f2 is a file I would like to copy the contents of f1 to the end of the file f2.
So for example if F2 has the contents:
2222222222222
And F1 has the contents
1111111111111
And I do copy(f1,f2) then f2 should become
2222222222222
1111111111111
Thanks!
Apache Commons IO to the rescue!
Expanding on Allain's post:
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true); // appending output stream
try {
IOUtils.copy(in, out);
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
Using Commons IO can simplify a lot of the stream grunt work.
Using the code from the answer by Allain Lolande and extending it, this should address both parts of your question:
File f1 = new File(srFile);
File f2 = new File(dtFile);
// Determine if a new file should be created in the target directory,
// or if this is an existing file that should be appended to.
boolean append;
if (f2.isDirectory()) {
f2 = new File(f2, f1.getName());
// Do not append to the file. Create it in the directory,
// or overwrite if it exists in that directory.
// Change this logic to suite your requirements.
append = false;
} else {
// The target is (likely) a file. Attempt to append to it.
append = true;
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(f1);
out = new FileOutputStream(f2, append);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
FileOutputStream has a constructor that allows you to specify append as opposed to overwrite.
You can use this to copy the contents of f1 to the end of f2 as below:
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Check out the link below. it is a source file that copies a file to another using NIO.
http://www.java2s.com/Code/Java/File-Input-Output/CopyafileusingNIO.htm

Categories