Problems with java.util.zip
I've got a odd problem here. I'm not sure if this is the appropriate forum but I couldn't find anyplace more appropriate.
So the problem is...
I create my ZIP file and if I open it in WinZip, no problem. But if I open the ZIP file using the 'Compressed Folders' feature of Windows Explorer I don't see any of the files. As far as I can tell, if the files I ZIP up do not contain any path information then they open fine via 'Compressed Folders'.
Is this a bug in java.util.zip? Or is the 'Compressed Folders' feature in Windows Explorer half-baked?
And finally is there any way for me to not include the path information of the files added to ZIP?
Thanks.
Looce:
I'm more than willing to modify things.
But I'm still curious why WinZip and Windows are treating the ZIP files differently.
Also, the only way I can figure to get the files into the ZIP without the path information being stored in the ZIP file is by copying the files to the directory containing my application jar file and then passing in the file name without the path being specified. That is the only way FileInputStream would be able to find the files without including path information. This seems like a lot of unnecessary overhead.
Another oddity is that if I create the ZIP archive using the file path for the FileInputStream and view the ZIP file using a HEX editor the entire path is being stored including the drive letter. But if you view the file using WinZip the path field seems to be removing the drive letter and only displaying the path. On top of that, even though the drive letter is contained in the archive if you unzip the file using WinZip it ignores the drive letter and unzips the file to whatever drive the archive is located on. In the grand scheme of things it makes sense for WinZip to ignore the drive letter.
Thanks for you help anyways.
Similar Messages
-
How do I compress a string with java.util.zip - not a file ?
How do I compress a string with java.util.zip?
Is possible to compress something else except a file?Of course, compression works on bytes, not some higher level constructs like Strings or files.
You can use the ZipOutputStream or DeflaterOutputStream for compression.
And the javadoc for Deflater even has a code example of compressing a String.
Edited by: Kayaman on May 22, 2011 5:04 PM -
Cannot extract Zip file with Winzip after zipping with java.util.zip
Hi all,
I write a class for zip and unzip the text files together which can be zip and unzip successfully with Java platform. However, I cannot extract the zip file with Winzip or even WinRAR after zipping with Java platform.
Please help to comment, thanks~
Below is the code:
=====================================================================
package myapp.util;
import java.io.* ;
import java.util.TreeMap ;
import java.util.zip.* ;
import myapp.exception.UserException ;
public class CompressionUtil {
public CompressionUtil() {
super() ;
public void createZip(String zipName, String fileName)
throws ZipException, FileNotFoundException, IOException, UserException {
FileOutputStream fos = null ;
BufferedOutputStream bos = null ;
ZipOutputStream zos = null ;
File file = null ;
try {
file = new File(zipName) ; //new zip file
if (file.isDirectory()) //check if it is a directory
throw new UserException("Invalid zip file ["+zipName+"]") ;
if (file.exists() && !file.canWrite()) //check if it is readonly
throw new UserException("Zip file is ReadOnly ["+zipName+"]") ;
if (file.exists()) //overwrite the existing file
file.delete();
file.createNewFile();
//instantiate the ZipOutputStream
fos = new FileOutputStream(file) ;
bos = new BufferedOutputStream(fos) ;
zos = new ZipOutputStream(bos) ;
this.writeZipFileEntry(zos, fileName); //call to write the file into the zip
zos.finish() ;
catch (ZipException ze) {
throw ze ;
catch (FileNotFoundException fnfe) {
throw fnfe ;
catch (IOException ioe) {
throw ioe ;
catch (UserException ue) {
throw ue ;
finally {
//close all the stream and file
if (fos != null)
fos.close() ;
if (bos != null)
bos.close();
if (zos != null)
zos.close();
if (file != null)
file = null ;
}//end of try-catch-finally
private void writeZipFileEntry(ZipOutputStream zos, String fileName)
throws ZipException, FileNotFoundException, IOException, UserException {
BufferedInputStream bis = null ;
File file = null ;
ZipEntry zentry = null ;
byte[] bArray = null ;
try {
file = new File(fileName) ; //instantiate the file
if (!file.exists()) //check if the file is not exist
throw new UserException("No such file ["+fileName+"]") ;
if (file.isDirectory()) //check if the file is a directory
throw new UserException("Invalid file ["+fileName+"]") ;
//instantiate the BufferedInputStream
bis = new BufferedInputStream(new FileInputStream(file)) ;
//Get the content of the file and put into the byte[]
int size = (int) file.length();
if (size == -1)
throw new UserException("Cannot determine the file size [" +fileName + "]");
bArray = new byte[(int) size];
int rb = 0;
int chunk = 0;
while (((int) size - rb) > 0) {
chunk = bis.read(bArray, rb, (int) size - rb);
if (chunk == -1)
break;
rb += chunk;
}//end of while (((int)size - rb) > 0)
//instantiate the CRC32
CRC32 crc = new CRC32() ;
crc.update(bArray, 0, size);
//instantiate the ZipEntry
zentry = new ZipEntry(fileName) ;
zentry.setMethod(ZipEntry.STORED) ;
zentry.setSize(size);
zentry.setCrc(crc.getValue());
//write all the info to the ZipOutputStream
zos.putNextEntry(zentry);
zos.write(bArray, 0, size);
zos.closeEntry();
catch (ZipException ze) {
throw ze ;
catch (FileNotFoundException fnfe) {
throw fnfe ;
catch (IOException ioe) {
throw ioe ;
catch (UserException ue) {
throw ue ;
finally {
//close all the stream and file
if (bis != null)
bis.close();
if (file != null)
file = null ;
}//end of try-catch-finally
}Tried~
The problem is still here~ >___<
Anyway, thanks for information sharing~
The message is:
Cannot open file: it does not appear to be a valid archive.
If you downloaded this file, try downloading the file again.
The problem may be here:
if (fos != null)
fos.close() ;
if (bos != null)
bos.close();
if (zos != null)
zos.close();
if (file != null)
file = null ;
The fos is closed before bos so the last buffer is not
saved.
zos.close() is enough. -
Problem with Java and Zip Files
Hello there everyone. I have a problem with trying to zip up directories with empty folders in them. They zip fine with my code, but according to winzip, the number of files in the archive is incorrect. It's supposed to have a total of 288 files in it, but when it's zipped up, it only says 284. I mention specifically the "empty directories" note because the zipping works fine without empty folders.
Below is the code for the zip method:
public static void zip(File[] list, File zipfile, File zipRoot)
throws IOException {
if (!zipfile.exists()) {
zipfile.createNewFile();
else if (!zipfile.isFile()) {
throw new IOException("The zip file, " + zipfile.getAbsolutePath()
+ " is not a file.");
if (list.length == 0) {
LOG.error("The list of files to zip up is empty.");
for (int i = 0; i < list.length; i++) {
if (!list.exists()) {
throw new IOException("The file or directory, " + list[i].getAbsolutePath()
+ " does not exist.");
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i = 0; i < list.length; i++) {
if (LOG.isDebugEnabled())
LOG.debug(i + ": " + list[i].getName());
String entryName = getRelativeName(list[i], zipRoot);
if (list[i].isDirectory()){
if (list[i].listFiles().length == 0){
ZipEntry entry = new ZipEntry(entryName + "/");
zos.putNextEntry(entry);
else {
ZipEntry ze = new ZipEntry(entryName);
zos.putNextEntry(ze);
byte[] buffer = new byte[8096];
FileInputStream fis = new FileInputStream(list[i]);
int read = 0;
read = fis.read(buffer);
if (LOG.isDebugEnabled())
LOG.debug("\tFound " + read + " bytes.");
if (read == -1){
//empty file, but add it for preservation.
//zos.write(buffer,0,0);
while (read != -1) {
zos.write(buffer, 0, read);
read = fis.read(buffer);
fis.close();
zos.closeEntry();
zos.close();
The files look like they're there, but I need the system to be able to determine the number correctly.
Here's the interesting thing: It zips the files, and then when I use the size() method for zip files in java, it says 284 files. But when I unzip, it says 288 again. It's like there's files missing when compressed, but when decompressed, they return. Note that the files are actually there. If I open the archive in a third party app such as Winzip AND Winrar AND IZarc, they all show 288 files. Any idea what would make the number of files appear incorrectly in a zip file when zipped by java with the code above? Thanks in advance.
- ChrisI figured out the problem. When zipping files in windows using winzip, it doesn't explicitly count folders as a "file/folder" as a file in itself. It will create the folders for files to go in, but the folder itself will not be 'counted' when you query the info of the file itself. You have more control of the zip file in java, and can count the folder as a file or not.
-
Extracting file from a TAR file with java.util.zip.* classes
Is there a way to extract files from a .TAR file using the java.util.zip.* classes?
I tried in some ways but I get the following error:
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.<init>(ZipFile.java127)
at java.util.zip.ZipFile.<init>(ZipFile.java92)
Thank you
Giuseppedownload the tar.jar from the above link and use the sample program below
import com.ice.tar.*;
import java.util.zip.GZIPInputStream;
import java.io.*;
public class untarFiles
public static void main(String args[]){
try{
untar("c:/split/20040826172459.tar.gz",new File("c:/split/"));
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
private static void untar(String tarFileName, File dest)throws IOException{
//assuming the file you pass in is not a dir
dest.mkdir();
//create tar input stream from a .tar.gz file
TarInputStream tin = new TarInputStream( new GZIPInputStream( new FileInputStream(new File(tarFileName))));
//get the first entry in the archive
TarEntry tarEntry = tin.getNextEntry();
while (tarEntry != null){//create a file with the same name as the tarEntry
File destPath = new File(
dest.toString() + File.separatorChar + tarEntry.getName());
if(tarEntry.isDirectory()){
destPath.mkdir();
}else {
FileOutputStream fout = new FileOutputStream(destPath);
tin.copyEntryContents(fout);
fout.close();
tarEntry = tin.getNextEntry();
tin.close();
} -
How to zip one file i have on disk with java.util.zip
I don't know how to zip a file. I managed to do new html file, but i don't know how to zip it.
This is my code:
PrintWriter pw = new PrintWriter (new FileWriter(export), true);
Thanks!heres a zipper class i wrote which i have butchered a bit to make more generic (its basic and at present only takes one zipentry etc, but very simple and should be easy to extend etc) Just pass it your file in its constructor and then call its zipme method. PS if it can be made better let me know so i can update my class, cheers.
import java.io.*;
import java.util.zip.*;
import java.awt.*;
class zipper
public File file;
public zipper(File f)
file = new File(f);
public void zipme()
try
FileInputStream fin = new FileInputStream(file);
int a = (int)file.length();
byte b[] = new byte[a];
fin.read(b);
ZipEntry k = new ZipEntry(fin.getName());//represents a single file in a zip archive!
File newFile = new File("D:\\AZipFile.zip");
ZipOutputStream zi = new ZipOutputStream(new FileOutputStream(newFile));
zi.putNextEntry(k);
zi.write(b,0,a);
zi.close();
fin.close();
catch(FileNotFoundException e)
//System.out.println("ERROR File not found");
catch(IOException ee)
//System.out.println("ERROR IO exception in Zipping file");
} -
Problem with java.util while migrating an app. from Apache to OC4J
Hello.
I have a application which runs fine under APache/Jserv . This
application contains bunch of jsp's. In the jsp's even though
there are no directives for import of java.util.* packages it
still works fine. But under oc4j the same application does not
work unless I modify the jsp to include java.util.* in the
import directive. What am I missing here?.
Thanks in advance.
PrakashHi,
I think that Apache/Jserv does the inlcude of java.util.*
automatically which OC4J dosen't.
Thanks,
Andy
Hello.
I have a application which runs fine under APache/Jserv . This
application contains bunch of jsp's. In the jsp's even though
there are no directives for import of java.util.* packages it
still works fine. But under oc4j the same application does not
work unless I modify the jsp to include java.util.* in the
import directive. What am I missing here?.
Thanks in advance.
Prakash -
Type Mapping Problem with java.util.Vector in Axis
Hi,buddies,I want to use the Vector class as the return type of my service, but it seems that there isn't a built-in Ser/Deser factory for Vector, is it?So i think we need to provide our own Ser/Derser. and this is a very common problem,and i wonder how to write my own Ser/Derser, please give me some suggestion,thx!
Best Regards:)Hi,I checked out the src of Axis 1.2, I found there is a org.apache.axis.encoding.ser.VectorSerializerFactory class and an according org.apache.axis.encoding.ser.VectorDeserializerFactory class.so in the deploy.wsdd i use them as the ser/deser factories in the TypeMapping part inside the service tag.everything goes well and i got no problem deploying the service to axis.But the problem is that when i try to invoke the service and get a vector as return(Suppose the components in the vector is instances of Movie class), the following error occured:
org.xml.sax.SAXException: No deserializer for {urn:movies}Movie
But it is a little bit confusing,for I declared the ser/deser factories for the bean class Movie(with built-in ser/deser factories of axis),and everything was going fine when i deployed the service to axis.So should i still use the TypeMappingRegistry or there are something i just missed.Please give me some suggestion,thx :)
Best Regards:) -
Problem with java.util.logging - write to multiple log files
Hi guys,
I'm having trouble with logging to multiple files - i am using the constructor for creating multiple files with size limitation - FileHandler(String pattern, int limit, int count, boolean append).
The problem i encounter is that it writes to the next log file before exceeding the limit, can it be because of file lock or something? what can i do in order to fill log files in a given limit and then write to the next?I thought it is synchronized by definition - i'm just creating loggers that write to
the same file(s). When i used 1 file instead of using the limit and several
files - all went well.Just a small question: all these loggers do use the same FileHandler don't they?
I bet they do, just asking ...
The problem started when i wanted each file to reach a limit before start writing
to a new file. Should i synchronize the log somehow? That's what I suggested in my previous reply, but IMHO it shouldn't be necessary
given what I read from the sources ...
What could be the reason for not reaching the limit before opening a new file?Sorry I don't have an answer (yet), still thinking though ... it's a strange problem.
kind regards,
Jos (hrrmph ... stoopid problem ;-) -
Hi,
I have a wierd issue with java.util.zip.ZipFile
Code as simple as
ZipFile file = new ZipFile("my.zip") ;
System.out.println(file.size());
For this particular zip file, it says 99 files found but the zip contains more than 60,000 files. I tried the zip with unzip and zip utilities and the zip file checks out fine. I even tried to unzip the contents, and zip 'em up all over again, just to eliminate the chances of corruption while the zip was being transferred over the network.
The same program works fine with another zip containing more or less the same number of files and prints 63730.
Any idea? This can not possibly be related to the type of files the zips contain? right? In any case, the contents of both zips are text/xml files.
Any help would be greatly appreciated.
Regards,
ZiroFrequencyI know its a problem with this particular zip. But whats interesting is that "unzip" can easily open / verify the zip and claims that it is a valid zip.
As I wrote earlier, I unzipped the file and zipped up the contents again in a new zip but java can't still count the contents correctly.
So I am thinking there is something to do with the "contents" of the xmls inside the zip? (characterset issues?)
There are no exceptions thrown and no error anywhere :(
I basically need to pinpoint the issue so that I can have it corrected upstream as this zip file processing is an ongoing process and I need to resolve it not just once but for the periodic executions.
Hope this helps explain the issue. -
Zip created through java.util.zip but problem in windows XP compress folder
Hi friends,
I am a software developer ,working on java/j2ee.currently i am working in a document management software related to logistics.Here i am facing a problem at the time of open the zip file through windows XP's in built software called "Folder compress".It's creared through java.util.zip.zipoutputstream.but at time of open through xp compress folder software ,it's showing error that "you can't open this file , this file are protected for your computer security" , but when i trying to open it through winzip or winrar, it's not giving any problem.My also specefing the code snippet below :-
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
//required for XP compress
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.DEFAULT_COMPRESSION); //use default level
}catch (Exception ex){
ex.printStackTrace();
System.exit(0);
addFolderToZip("", srcFolder, zip);
try
zip.flush();
zip.close();
zip=null;
fileWriter.close();
fileWriter = null;
}catch (Exception ex)
//ex.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Zip folder processing");
}I desperately looking for a help regarding this issue , if any body have any solution the please send at this forum.
Thanks,
Chiranjitthis file working file for winzip or winrar there is no problem.i am also sending the whole code of that java file that can help you better.
Program Name: EdocRetrieveServiceSLBean.java
Description: EdocRetrieveService CMP Bean Class
Classes: EdocRetrieveServiceSLBean
Package: net.mlog.edoc.ejb.entity
Modification History
<CR No> <Date> <Modified By> <Comments>
Version 1.0 2005.12.01 Sutapa Ray Create
/** The sequence of methods to be called.
===============================================================================================================================
1. mlogOriginDocumentAudit(String argActionDetails,int argDocumentId,int argActionId,String argActionByUserId)
2. mlogDestinationBatchDownload(Vector TREEDATA,String SessionIDVal,String argUserId)
a) Start DIR --
private String DoFolder(String folderNname)
b) Create the folder
private String CreateFolder(String FolderName,String newFolderPath)
c) Zip the folder
private void zipFolder(String srcFolder, String destZipFile)
d) Add folders to zip file
private void addToZip(String path, String srcFile, ZipOutputStream zip)
e) Add the srcFolder to the zip stream.
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
f) Delete Directory from server
public boolean deleteDir(File dir) {
3. mpsDocumentView(String argUserId,Integer[] argSfxFileId)
4. mlogOriginDocumentView(int argDocumentId,String argUserId)
5. findDocTypeForDocId(Integer argDocId) throws RemoteException;
package net.mlog.edoc.ejb.session;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.FinderException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.rmi.PortableRemoteObject;
import java.rmi.RemoteException;
//import lib for all entity beans
import net.mlog.edoc.ejb.entity.IDocumentCMP;
import net.mlog.edoc.ejb.entity.IDocumentCMPHome;
import net.mlog.edoc.ejb.entity.IDocumentTypeCMP;
import net.mlog.edoc.ejb.entity.IDocumentTypeCMPHome;
import net.mlog.edoc.ejb.entity.IDocumentAuditCMP;
import net.mlog.edoc.ejb.entity.IDocumentAuditCMPHome;
//import lib for reader class of properties file
import net.mlog.edoc.ejb.session.PropertiesFileReader;
//import lib for user Define File class
import net.mlog.edoc.ejb.Session.EFile;
//import lib for SFXWebClient
import net.mlog.edoc.webservice.sfxWeb.ISFXWebClientSLHome;
import net.mlog.edoc.webservice.sfxWeb.ISFXWebClientSL;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.Deflater;
import java.util.Vector;
import java.util.Iterator;
import java.util.Collection;
import java.util.StringTokenizer;
import java.util.Enumeration;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//import lib for NGP Mail
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueConnection;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.JMSException;
import weblogic.jms.extensions.WLQueueSession;
import weblogic.jms.extensions.XMLMessage;
//import javax.mail.*;
//import javax.mail.internet.*;
//import lib for USI
import com.msl.security.USIException;
import com.msl.security.USIServerAPI;
import com.msl.security.UserPolicyData;
import net.msl.util.logging.MLogger;
public class EdocRetrieveServiceSLBean implements SessionBean {
private static final boolean VERBOSE = true;
private SessionContext ctx;
public void ejbActivate() {
public void ejbRemove() {
public void ejbPassivate() {
public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
public void ejbCreate () throws CreateException {
private static final MLogger logger;
static
logger = MLogger.getLogger(net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.class.getName(), "net/mlog/edoc/ejb/session/eDocRetrieveServiceMessagesXML");
//*********************KEEPING AUDITS OF DOCUMENTS BY MLOG ORIGIN PEOPLE*******************************
* <b>
* Used for Auditing the user action.
* </b>
* This function is called from various functions of eDocController
* <p>
* @param argActionDetails Gives the details of Action in document audit.
* @param argDocumentId gives the Document Id in Document Audit.
* @param argActionId Action Id in Document Audit.
* @param argActionByUserId User Id of the Docment Audit action.
* @return Returns a boolean value. 1 for success, 0 for Failure.
public boolean mlogOriginDocumentAudit(String argActionDetails,int argDocumentId,int argActionId,String argActionByUserId) throws RemoteException
//NGP/JDK Logging
boolean flag=false;
try{
//getting context of the server
InitialContext documentAuditCMPInitialContext=getInitialContext();
Object objDocumentAuditCMPRef=null;
try{
objDocumentAuditCMPRef=documentAuditCMPInitialContext.lookup("DocumentAuditCMPBeanJNDI");
catch(Exception e)
//NGP/JDK Logging if JNDI Not found
//logger.log(Level.SEVERE, "{0} : JNDI not found : {1}",new Object[] {"MSG002","DocumentAuditCMPBeanJNDI"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","DocumentAuditCMPBeanJNDI not found");
//find the maximum audit id in the Document_Audit table
//Home interface reference of DocumentAuditCMP EJB
//IDocumentAuditCMPHome iDocumentAuditCMPHomeRef=(IDocumentAuditCMPHome)PortableRemoteObject.narrow(objDocumentAuditCMPRef,IDocumentAuditCMPHome.class);
IDocumentAuditCMPHome iDocumentAuditCMPHomeRef=(IDocumentAuditCMPHome)objDocumentAuditCMPRef;
//Remote interface reference of DocumentAuditCMP EJB
IDocumentAuditCMP iDocumentAuditCMPCreateRef=iDocumentAuditCMPHomeRef.create(new Timestamp(System.currentTimeMillis()),argActionDetails,argActionByUserId,new Integer(argActionId),new Integer(argDocumentId));
//set flag to true if Document is audited
flag=true;
}//end of try
catch(Exception expt)
//logger.finer(expt);
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.CreateException","Exception in creating Document Audit record");
return flag;
//*********************BATCH DOWNLOAD OF DOCUMENTS BY MLOG ORIGIN PEOPLE*******************************
* <b>
* Used for Validating the documents.
* </b>
* This function is called from Struts
* <p>
* @param TREEDATA Treeset obtained after search.
* @param SessionIDVal gives the Session Value Id.
* @return Returns a boolean value. 1 for success, 0 for Failure.
public byte[] mlogDestinationBatchDownload(Vector TREEDATA,String SessionIDVal,String argUserId) throws RemoteException
//NGP/JDK Logging
/*FileHandler handler = null;
Logger logger=null;
try
PropertiesFileReader propertiesFileReaderRef=new PropertiesFileReader();
String logFile=propertiesFileReaderRef.getProperties("/edoc.properties","EDOC_LOG");
handler = new FileHandler("eDoc.log",0,1, true);
logger = Logger.getLogger("ErrorMsg");
logger.addHandler(handler);
logger.setLevel(Level.ALL);
}catch(Exception excp)
NGP/JDK Logging warning
logger.log(Level.WARNING, "{0} : Unable to find Resource Bundle File : {1}",new Object[] {"MSG001","ErrorMsg"});
//Remote interface reference of SFXWebClientSL
ISFXWebClientSL iSFXWebClientSLRef=null;
//Home interface reference of SFXWebClientSL
ISFXWebClientSLHome iSFXWebClientSLHomeRef=null;
Vector filePath=new Vector();
byte[] fileContent=null;
String eDocRoot="";
String eDocPathMain="";
String eDocPath="";
File tempRootFileforDelete = null;
if (TREEDATA.capacity() != 0 )
String BLNODirPath="";
String PONODirPath="";
String SONODirPath="";
// added for doc type level--2005.11.27--samar
String docTypeDirPath="";
String filepath="";
try
PropertiesFileReader propertiesFileReaderRef=new PropertiesFileReader();
filepath=propertiesFileReaderRef.getProperties("/edoc.properties","TEMP_FILE_DIR");
logger.finer("File Path:" +filepath);
}catch(Exception excp)
excp.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.IOException","TEMP_FILE_DIR property (edoc.properties) not found");
eDocRoot=CreateFolder("eDocTemp",filepath+File.separator);
// added for top level--2005.12.02--samar
//eDocRoot=CreateFolder("eDocTemp",System.getProperty("user.home")+File.separator);
//eDocPath=CreateFolder(SessionIDVal,eDocRoot+File.separator);
Enumeration TREEDATAEn = TREEDATA.elements(); //Setting The Tree Folder
String BLNO="";
String PONO="";
String SONO="";
String DNO ="";
while(TREEDATAEn.hasMoreElements())
StringTokenizer st = new StringTokenizer((TREEDATAEn.nextElement()).toString(),"_");
while (st.hasMoreTokens()) // Extract All the Fields Of Every Vector Element
BLNO = st.nextToken(); // CSBWNO
PONO = st.nextToken(); // PONO
SONO = st.nextToken(); // SONO
DNO = st.nextToken(); // DNO
eDocPathMain=CreateFolder(SessionIDVal,eDocRoot+File.separator);
eDocPath=CreateFolder("eDoc",eDocPathMain+File.separator);
BLNODirPath = CreateFolder(BLNO,eDocPath+File.separator);
PONODirPath = CreateFolder(PONO,BLNODirPath+File.separator);
SONODirPath = CreateFolder(SONO,PONODirPath+File.separator);
// added for doc type level--2005.11.27--samar
docTypeDirPath=CreateFolder(findDocTypeForDocId(new Integer(DNO)),SONODirPath+File.separator);
File tempRootFile=new File(eDocRoot);
tempRootFile.canWrite();
filePath.add(tempRootFile.getParent());
tempRootFileforDelete = tempRootFile;
//File tempeDocPathMainFile=new File(eDocPathMain);
//filePath.add(tempeDocPathMainFile.getParent());
//2005-12-01::code change for top level directory deletion
//File tempFile=new File(eDocPath);//BLNODirPath);
//filePath.add(tempFile.getParent());
filePath.add(eDocPathMain);
filePath.add(eDocPath);
filePath.add(BLNODirPath);
filePath.add(PONODirPath);
filePath.add(SONODirPath);
// added for doc type level--2005.11.27--samar
filePath.add(docTypeDirPath);
/* Access The Data from DataBase Temp Storage with Document Id And Store In This SO Folder */
/*Long Raw*/
try
InitialContext initialContext=new InitialContext();
int sfxid=0;
/*DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
OraclePooledConnection pc = new OraclePooledConnection("jdbc:oracle:thin:hr/hr@essoraclesvr:1521:essorcl","edoc","edoc");
Connection con=new DBCon().Connect();//pc.getConnection();
PreparedStatement pstm=con.prepareStatement("select SFX_FILE_ID from DOCUMENT where DOCUMENT_ID=?");
//getting context of the server
InitialContext documentCMPInitialContext=getInitialContext();
Object objDocumentCMPRef=null;
try{
objDocumentCMPRef=documentCMPInitialContext.lookup("DocumentCMPBeanJNDI");
catch(Exception e)
//logger.log(Level.SEVERE, "{0} : JNDI not found : {1}",new Object[] {"MSG002","DocumentCMPBeanJNDI"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","DocumentCMPBeanJNDI not found");
//Home interface reference of DocumentCMP EJB
//IDocumentCMPHome iDocumentCMPHomeRef=(IDocumentCMPHome)PortableRemoteObject.narrow(objDocumentCMPRef,IDocumentCMPHome.class);
IDocumentCMPHome iDocumentCMPHomeRef=(IDocumentCMPHome)objDocumentCMPRef;
IDocumentCMP documentCMPRef=null;
//Remote interface reference of DocumentCMP EJB
try{
documentCMPRef=iDocumentCMPHomeRef.findByPrimaryKey(new Integer(DNO));
catch(Exception e)
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ObjectNotFound","Document Id not found");
/*pstm.setInt(1,Integer.parseInt(DNO));
ResultSet rs1=pstm.executeQuery();
if(rs1.next()){
sfxid=rs1.getInt(1);
sfxid=documentCMPRef.getSfxFileId().intValue();
logger.finer("sfxid==="+sfxid);
String strFile=documentCMPRef.getDocumentName().toString();
//SFX lookup
//InitialContext initialContext=new InitialContext();
Object sfxWebClient=null;
try{
sfxWebClient=initialContext.lookup("SFXWebClientJNDI");
catch(Exception e)
//NGP/JDK logging if JNDI not found
//logger.log(Level.SEVERE, "{0} : JNDI not found : {1}",new Object[] {"MSG002","SFXWebClientJNDI"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","SFXWebClientJNDI not found");
iSFXWebClientSLHomeRef=(ISFXWebClientSLHome)PortableRemoteObject.narrow(sfxWebClient,ISFXWebClientSLHome.class);
iSFXWebClientSLRef=iSFXWebClientSLHomeRef.create();//SFXWebClient reference creation
if(iSFXWebClientSLRef!=null)
//logger.finer("ffffffff---");
int arrSFXFileId[]=new int[1];
arrSFXFileId[0]=sfxid;
Object objEFile[]=iSFXWebClientSLRef.retrieveDocument(argUserId,arrSFXFileId);
if(objEFile.length>0)
byte b[]=(byte[])objEFile[1];
String f=strFile.substring(strFile.lastIndexOf(File.separator)+1,strFile.length());
// changed(instead of SONODirPath now docTypeDirPath) for doc type level--2005.11.27--samar
FileOutputStream fout=new FileOutputStream(docTypeDirPath+File.separator + f);
//logger.finer("SONODirPath+File.separator + f---"+SONODirPath+File.separator + f);
filePath.add(docTypeDirPath+File.separator + f);
int j;
for(j=0;j<b.length;j++)
fout.write(b[j]);
fout.close();
//for auditing the document
//logger.finer("Document download audited");
boolean flagAudit=mlogOriginDocumentAudit("Document has been downloaded",Integer.parseInt(DNO),5,argUserId);
//logger.finer("Audit complete"+flagAudit);
if(logger.isFinerLoggable()) {
logger.finer("Audit complete"+flagAudit);
//Delete after finish
tempRootFile.delete();
}catch(Exception e)
//e.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Folder creation processing");
/* End Long Raw */
}// end of while hasMoreTokens
}// end of while hasMoreElements
}else{ }
/* Zip */
try
zipFolder(eDocPath+File.separator,eDocPath+".zip");
}catch(Exception excp)
////logger.finer(excp.toString());
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Zip processing");
// send the byte array for the file
String fileName=eDocPath+".zip";
try{
File file=new File(fileName);
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.It needs to be an int type.
// Before converting to an int type,check to ensure that file is not larger than Integer.MAX_VALUE.
//Kept for future requirement if any
if (length > Integer.MAX_VALUE) {
// File is too large
// Create the byte array to hold the data
fileContent = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < fileContent.length
&& (numRead=is.read(fileContent, offset, fileContent.length-offset)) >= 0) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < fileContent.length) {
throw new IOException("Could not completely read file "+file.getName());
// Close the input stream and return bytes
is.close();
}catch(Exception e){
deleteDir(tempRootFileforDelete);
//trying for deleting folder and zip file
File file=new File(fileName);
if(file.exists())
file.delete();
//logger.finer("File Deleted successfully");
if(file.exists()){
//logger.finer("File Not Deleted ");
/* File FileToDelete = new File(eDocPath+".zip");
boolean DelStatus1 = deleteDir(FileToDelete);
//logger.finer("Deletion 1:"+DelStatus1 );
File FolderToDelete = new File(eDocPath);
boolean DelStatus2 = deleteDir(FolderToDelete);
//logger.finer("Deletion 2:"+DelStatus2);
for(int index=filePath.size()-1;index>=0;index--)
File delFile=new File(filePath.elementAt(index).toString());
//logger.finer(delFile.getAbsolutePath());
if(delFile.exists())
//logger.finer("Before delete---123");
//logger.finer("File Deleted========>"+delFile.delete());
//logger.finer("After delete---123");
//logger.finer(delFile.getAbsolutePath()+"-----------"+delFile.exists());
return fileContent;
/* ***************************Start DIR *********************/
private String DoFolder(String folderNname)
File f;
f = new File(folderNname);
f.mkdir(); // Create The Folder
//f.deleteOnExit(); //R n D to Delete The zip folders only */
return(folderNname+File.separator);
//to create the folder
private String CreateFolder(String FolderName,String newFolderPath)
String NewDir ="";
NewDir=newFolderPath + FolderName;
newFolderPath=DoFolder(NewDir);
return(NewDir);
//To zip the folder
private void zipFolder(String srcFolder, String destZipFile)
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
//required for XP compress
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.DEFAULT_COMPRESSION); //use default level
}catch (Exception ex){
ex.printStackTrace();
System.exit(0);
addFolderToZip("", srcFolder, zip);
try
zip.flush();
zip.close();
zip=null;
fileWriter.close();
fileWriter = null;
}catch (Exception ex)
//ex.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Zip folder processing");
// File f2= new File(destZipFile);
* Write the content of srcFile in a new ZipEntry, named path+srcFile,of the zip stream
* The result is that the srcFile will be in the path folder in the generated archive.
* @param path String, the relative path with the root archive.
* @param srcFile String, the absolute path of the file to add
* @param zip ZipOutputStram, the stream to use to write the given file.
//the folders are added to zip file
private void addToZip(String path, String srcFile, ZipOutputStream zip)
File folder = new File(srcFile);
//folder.deleteOnExit();
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
else {
//Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
FileInputStream in = null;
try {
in = new FileInputStream(srcFile);
// void putNextEntry(ZipEntry e) Begins writing a new ZIP file entry
// and positions the stream to the start of the entry data.
zip.putNextEntry(new ZipEntry(path +File.separator+ folder.getName()));
while ((len = in.read(buf)) > 0)
zip.write(buf, 0, len);
}catch (Exception ex){
ex.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Adding to Zip Folder");
}finally{
try
//2005-12-01::file pointer close
in.close();
}catch(Exception e){
e.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Adding to Zip Folder");
folder.delete(); //we addedd for DELETE
* add the srcFolder to the zip stream.
* @param path String, the relatif path with the root archive.
* @param srcFile String, the absolute path of the file to add
* @param zip ZipOutputStram, the stream to use to write the given file.
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
File folder = new File(srcFolder);
folder.canWrite();
//folder.deleteOnExit();
String fileListe[] = folder.list();
try
int i = 0;
while (true)
addToZip(path+File.separator+ folder.getName(), srcFolder+File.separator+fileListe, zip);
i++;
}catch (Exception ex)
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in Naming after adding to Zip Folder");
/* $$$$$$$$$$$$$$$$$ End Zipping $$$$$$$$$$$$$$$ */
/****************Start Of Deleting Directory from server***********/
public boolean deleteDir(File dir) {
// to see if this directory is actually a symbolic link to a directory,
// we want to get its canonical path
//- that is, we follow the link to the file it's actually linked to
File candir;
try {
candir = dir.getCanonicalFile();
} catch (IOException e) {
return false;
// a symbolic link has a different canonical path than its actual path,
// unless it's a link to itself
if (!candir.equals(dir.getAbsoluteFile())) {
//this file is a symbolic link, and there's no reason for us to follow it,
//because then we might be deleting something outside of the directory we were told to delete
return false;
// now we go through all of the files and subdirectories in the directory and delete them one by one
File[] files = candir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
//file read only set false
//in case this directory is actually a symbolic link, or it's empty,
//we want to try to delete the link before we try anything
boolean deleted = file.delete();
if (!deleted) {
// deleting the file failed, so maybe it's a non-empty directory
if (file.isDirectory()) deleteDir(file);
// otherwise, there's nothing else we can do
// now that we tried to clear the directory out, we can try to delete it again
return dir.delete();
/************End Of Deleting Directory *********************/
private InitialContext getInitialContext() throws NamingException {
try {
return new InitialContext();
} catch (NamingException ne) {
//logger.finer("Please make sure that the server is running.");
throw ne;
//*****************************WEB SERVICE FILE RETRIEVE IMPLEMENTATION FOR MPS PEOPLE*************************************************
* <b>
* Used for Retrieval of a document.
* </b>
* This function is called from retrieveDocument function of MPStoEdocWebServiceSLBean.
* <p>
* @param argUserId User Id of the user who wants to retrieve the document
* @param argSfxFileId[] Sfx File Id which gives the reference number of the document(s) in the SFX database.
* @return Returns a one dimentional Object array containing a series of file name and file content of the retrieved documents.
public Object[] mpsDocumentView(String argUserId,Integer[] argSfxFileId) throws RemoteException
//NGP/JDK logging
logger.finer("mpsDocumentView called--");
try{
argUserId=argUserId.toUpperCase();
catch(Exception e)
e.printStackTrace();
logger.finer("mpsDocumentView argSfxFileId[0]--"+argSfxFileId[0]);
Object[] searchResult=null;
/*FileHandler handler = null;
Logger logger=null;
int finalIndex=0;
try
//PropertiesFileReader propertiesFileReaderRef=new PropertiesFileReader();
//String logFile=propertiesFileReaderRef.getProperties("/edoc.properties","EDOC_LOG");
//handler = new FileHandler("eDoc.log",0,1, true);
//logger = Logger.getLogger("ErrorMsg");
//logger.addHandler(handler);
//logger.setLevel(Level.ALL);
}catch(Exception excp)
//NGP/JDK Logging warning
//logger.log(Level.WARNING, "{0} : Unable to find Resource Bundle File : {1}",new Object[] {"MSG001","ErrorMsg"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","PurchaseOrderCMPBeanJNDI not found");
Object objDocumentFile[]=null;
ISFXWebClientSLHome iSFXWebClientSLHomeRef=null;
ISFXWebClientSL iSFXWebClientSLRef=null;
try{
//Locating SFX WEB CLIENT SESSION BEAN
InitialContext initialContext=new InitialContext();
Object sfxWebClient=null;
try{
sfxWebClient=initialContext.lookup("SFXWebClientJNDI");
catch(Exception e)
//NGP/JDK Logging if JNDI not found
//logger.log(Level.SEVERE, "{0} : JNDI not found : {1}",new Object[] {"MSG002","SFXWebClientJNDI"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","SFXWebClientJNDI not found");
iSFXWebClientSLHomeRef=(ISFXWebClientSLHome)PortableRemoteObject.narrow(sfxWebClient,ISFXWebClientSLHome.class);
//creation of SFX we client
iSFXWebClientSLRef=iSFXWebClientSLHomeRef.create();
int arrSFXFileId[]=new int[argSfxFileId.length];
logger.finer("SFXWebClient created----");
//holds the sequence of SFX file id in the array
//EFile file=new EFile();
//getting context of the server
InitialContext documentCMPInitialContext=getInitialContext();
Object objDocumentCMPRef=null;
int docId=0;
try{
objDocumentCMPRef=documentCMPInitialContext.lookup("DocumentCMPBeanJNDI");
catch(Exception e)
//NGP/JDK Logging if JNDI not found
//logger.log(Level.SEVERE, "{0} : JNDI not found : {1}",new Object[] {"MSG002","DocumentCMPBeanJNDI"});
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.JNDINotFound","DocumentCMPBeanJNDI not found");
//Home interface reference of DocumentCMP EJB
//IDocumentCMPHome iDocumentCMPHomeRef=(IDocumentCMPHome)PortableRemoteObject.narrow(objDocumentCMPRef,IDocumentCMPHome.class);
IDocumentCMPHome iDocumentCMPHomeRef=(IDocumentCMPHome)objDocumentCMPRef;
//find the document id in the Document table from the SFx File Id
for(int index=0;index<argSfxFileId.length;index++)
arrSFXFileId[index]=argSfxFileId[index].intValue();
logger.finer("mpsDocumentView arrSFXFileId[index]--"+arrSFXFileId[index]);
logger.finer("For Document auditing----");
//Remote interface reference of DocumentCMP EJB
IDocumentCMP iDocumentCMPRef=iDocumentCMPHomeRef.findDocIdBySfxId(new Integer(arrSFXFileId[index]));
docId=iDocumentCMPRef.getDocumentId().intValue();
//for document audit
try{
boolean flagAudit=mlogOriginDocumentAudit("Document is Viewed",docId,5,argUserId);
catch(Exception e)
//logger.finer("Document cannot be audited----");
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in audit processing");
//call the retrieveDocument method for the above array of elements
//Object[] tempObjDocumentFile=iSFXWebClientSLRef.retrieveDocument(argUserId,arrSFXFileId);
//EFile file=new EFile();
//for(int index=0;index<tempObjDocumentFile.length;index++){
// file= (EFile) tempObjDocumentFile[index];
// objDocumentFile[finalIndex++]=file.getDocFileName();
// objDocumentFile[finalIndex++]=file.getDocFileContent();
objDocumentFile=iSFXWebClientSLRef.retrieveDocument(argUserId,arrSFXFileId);
//EFile[] efileArray = (EFile[]) = objDocumentFile;
searchResult = new Object[efileArray.length*2];
for (int i=0;i<efileArray.length;i=i+2)
EFile currentFile = efileArray[i];
searchResult[i] = currentFile.getDocFileName();
searchResult[i+1] = currentFile.getDocFileContent();
searchResult=iSFXWebClientSLRef.retrieveDocument(argUserId,arrSFXFileId);
}//end of try
catch(Exception expt)
//logger.finer(expt);
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in retrieve from SFX");
//if exception occurs returns null as per initilisation above
//logger.finer("mpsDocumentView size--"+objDocumentFile.length);
return searchResult;
//**************************** FILE RETRIEVE IMPLEMENTATION FOR MLOG PEOPLE*******************************
* <b>
* Used for Retrieval of a document.
* </b>
* This function is called from struts.
* <p>
* @param argDocumentId Documnet Id which gives the ID of the document in the eDoc database..
* @param argUserId User Id of the user who wants to retrieve the document
* @return Returns a one dimentional Object array containing a series of file name and file content of the retrieved documents.
public Object[] mlogOriginDocumentView(int argDocumentId,String argUserId) throws RemoteException
//NGP/JDK Logging
logger.finer("mlogOriginDocumentView called--");
try{
argUserId=argUserId.toUpperCase();
catch(Exception e)
//e.printStackTrace();
logger.log("net.mlog.edoc.ejb.session.EdocRetrieveServiceSLBean.ProcessException","Exception in uppercase");
//logger.finer("mlogOriginDocumentView-- argDocumentId---"+argDocumentId);
/*FileHandler handler = null;
Logger logger=null;
try
//PropertiesFileReader propertiesFileReaderRef=new PropertiesFileReader();
//String logFile=propertiesFileReaderRef.getProperties("/edoc.properties","EDOC_LOG");
//handler = new FileHandler("eDoc.log",0,1, tr -
Hi All,
We are using WLS 5.1 clustering. 2 WLS are running in 2 different unix box in same subnet. But we are getting the following exception ( Though all the Beans have been deployed successfully).
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.open(Compiled Code)
at java.util.zip.ZipFile.<init>(Compiled Code)
at java.util.zip.ZipFile.<init>(Compiled Code)
at weblogic.boot.ServerClassLoader.deploy(ServerClassLoader.java:132)
at weblogic.cluster.AnnotatedServiceOffer.expandClassPath(Compiled Code)
at weblogic.cluster.AnnotatedServiceOffer.readObject(Compiled Code)
at weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(Compiled Code)
Fri Jan 25 16:57:22 MST 2002:<E> <MulticastSocket> Multicast socket receive error: java.lang.RuntimeException: I/O error opening JAR file from file:/opt/wlogic/weblogic/obscluster/server113/tmp_deployments/ejbjar-4247.jar
(cluster name we have changed to obscluster )
This Exception is coming in both the servers The difference is that the server whose ip ends with 112 is trying to open the file from server113 dir and the server whose ip ends with 113 is trying to open the file from server112 dir.
In web I have found that if the directory structure of 2 servers doesn't match then this porblem can arise. But for both of my servers the directory structure is same , at least until /opt/wlogic/weblogic/obscluster/ and then the directory server113 or server112 is created by Weblogic automatically when I have started the Server.
Any help regarding this will be very helpful.
Thanks & Regards
Srijeeb.Hi everyone,
I think I have got the solution. Using sp11. added sp11 related jar in PRE_CLASSPATH . Problem Solved....
Thanks
Srijeeb -
Problems with java logging utility
Hi,
I am having a few problems with java's logging framework.
When I create a logger using
Logger log = Logger.getLogger("my.com");
and log my messages using this "log" object, the messages are logged to System.err which is my console. But when I add a Filehandler to this Logger object, I get log messages both in the file and the standard error.
The problem is that I want to supress logging to the standard error but do not know how to do this. I tried a few things:
1) If I close the standard error (System.err.close() ), things work fine but I can't afford doing this since other parts of my application might use System.err for some purpose.
2) I thought that , by default, a ConsoleHandler object is added to the Logger object. So I thought I might get around the problem if I close() this ConsoleHandler object. But, to my surprise, log.getHandlers() returns an empty array by default. So there is no ConsoleHandler attached to it.
Any info. regarding it will be very much appreciated.
Thanks,
Arch.Logger.setUseParentHandlers(false)
-
I want to unzip OpenOffice 1.0 files inside the OJVM but it fails into the native method java.util.zip.CRC32.updateBytes(CRC32.java).
The first execution of the code runs OK, but the second not.
After a long wait it shutdown the connection and the oracle trace file shows an stack trace like this:
*** 2003-04-18 11:31:31.926
*** SESSION ID:(17.97) 2003-04-18 11:31:31.926
java.lang.IllegalArgumentException
at java.util.zip.CRC32.updateBytes(CRC32.java)
at java.util.zip.CRC32.update(CRC32.java)
at java.util.zip.ZipInputStream.read(ZipInputStream.java)
at oracle.xml.parser.v2.XMLByteReader.fillByteBuffer(XMLByteReader.java:354)
at oracle.xml.parser.v2.XMLUTF8Reader.fillBuffer(XMLUTF8Reader.java:142)
at oracle.xml.parser.v2.XMLByteReader.saveBuffer(XMLByteReader.java:448)
at oracle.xml.parser.v2.XMLReader.fillBuffer(XMLReader.java:2012)
at oracle.xml.parser.v2.XMLReader.skipWhiteSpace(XMLReader.java:1800)
at oracle.xml.parser.v2.NonValidatingParser.parseMisc(NonValidatingParser.java:305)
at oracle.xml.parser.v2.NonValidatingParser.parseProlog(NonValidatingParser.java:274)
at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:254)
at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:225)
at com.prism.cms.frontend.EditPropertiesActions.processUpload(EditPropertiesActions.java:1901)
Exception signal: 11 (SIGSEGV), code: 1 (Address not mapped to object), addr: 0x6d3a74a0, PC: [0x40263600, eomake_reference_to_eobjec
t()+80]
Registers:
%eax: 0x54a54000 %ebx: 0x40429c20 %ecx: 0x54a546bf
%edx: 0x6d3a7478 %edi: 0x402b27d0 %esi: 0x45c718ac
%esp: 0xbfffbf20 %ebp: 0xbfffbf48 %eip: 0x40263600
%efl: 0x00010206
The code of the java method is:
public static void processUpload(String id_page, String longname,
String filename, String filetype,
String s00)
throws SQLException {
Integer p_id = new Integer(id_page);
String toSource;
XMLDocument doc = null;
DOMParser theParser = null;
InputStream XSLStream = null;
BufferedWriter out = null;
#sql { select path||name||'.html' into :toSource from pages where id_page=:p_id };
if ("Cancel".equalsIgnoreCase(s00)) {
Jxtp.redirecUrl("/dbprism/ldoc/live/edit.html?p_source="+toSource);
return;
if ("no-file".equals(filename) && "no-contenttpye".equals(filetype)) {
Jxtp.redirecUrl("/dbprism/ldoc/live/edit.html?p_source="+toSource);
return;
if ("xml".equalsIgnoreCase(filetype))
#sql { call CMSj.moveFromUpload(:filename,:p_id) };
else if ("sxw".equalsIgnoreCase(filetype)) {
XSLProcessor processor = new XSLProcessor();
XSLStylesheet theXSLStylesheet = null;
BLOB locator = null;
// open sxw file, it will be in zip format with a file named content.xml
// then convert content.xml to document-v10.dtd with an stylesheet
#sql { select blob_content into :locator from wpg_document where name = :filename for update };
ZipInputStream zin = new ZipInputStream(locator.binaryStreamValue());
ZipEntry entry;
try {
while((entry=zin.getNextEntry())!=null)
if ("content.xml".equalsIgnoreCase(entry.getName())) {
Integer newVersion;
CLOB dstDoc;
CMSDocURLStreamHandlerFactory.enableCMSDocURLs();
try {
URL inUrl = new URL("cms:/stylesheets/sxw2document-v10.xsl");
XSLStream = inUrl.openStream();
// Create the Stylesheet from the stream
theXSLStylesheet = processor.newXSLStylesheet(XSLStream);
// Stores the document processing it with the given stylesheet
theParser = new DOMParser();
theParser.setValidationMode(theParser.NONVALIDATING);
theParser.setBaseURL(new URL("cms:/dtd/"));
theParser.parse(zin);
doc = theParser.getDocument();
#sql { SELECT NVL(MAX(version),0)+1 INTO :newVersion FROM content
WHERE cn_id_page = :p_id };
#sql { INSERT INTO content( cn_id_page, version, owner, status, source_file,
file_size, content, created, modified, created_by,
modified_by)
VALUES ( :p_id, :newVersion, sys_context('cms_context','user_id'),
'Uploaded', :filename, 0 , EMPTY_CLOB(), SYSDATE, SYSDATE,
sys_context('cms_context','user_id'),
sys_context('cms_context','user_id')) };
#sql { SELECT content INTO :dstDoc FROM content
WHERE cn_id_page = :p_id AND version = :newVersion for update };
#sql { call DBMS_LOB.trim(:inout dstDoc,0) };
out = new BufferedWriter(dstDoc.getCharacterOutputStream(),dstDoc.getChunkSize());
processor.processXSL(theXSLStylesheet, doc, new PrintWriter(out));
#sql { delete from wpg_document where name=:filename };
} catch (SAXParseException spe) {
throw new SQLException("processUpload SAXParseException: "+xmlError(spe));
} catch (SAXException se) {
throw new SQLException("processUpload SAXException: "+se.getLocalizedMessage());
} catch (XSLException xsle) {
throw new SQLException("processUpload XSLException: "+xsle.getLocalizedMessage());
} finally {
if (XSLStream!=null)
XSLStream.close();
if (theParser!=null)
theParser = null;
if (out!=null) {
out.flush();
out.close();
zin.close();
} catch (IOException ioe) {
throw new SQLException("processUpload IOException: "+ioe.getLocalizedMessage());
} finally {
if (XSLStream!=null)
XSLStream = null;
if (out!=null)
out = null;
if (zin!=null)
zin = null;
Jxtp.redirecUrl("/dbprism/ldoc/live/edit.html?p_source="+toSource);
Basically it takes the content from a BLOB column of the wpg_document table, unzip it using java.util.zip package, look for the file content.xml and parse it using Oracle XML toolkit.
Using an open source utility which replace java.util.package (http://jazzlib.sourceforge.net/) it works perfect because is a pure java application.
Best regards, Marcelo.
PD: I am using Oracle 9.2.0.2 on Linux.The cause of errors was a dying Westen Digital drive, specially the 48G partition reserved only for $ORACLE_BASE (/dev/sdb3 mounted on /opt/oracle).
A simple quick scan of unmounted partition (badblocks -v /dev/sdb3) reported more than thousand new bad blocks (compared to the last scan six months ago). Although I strongly believe, specially in the case of WDC drives, that the best utility to "repair" bad blocks is the one that opens a window and prints the message: "Go to the nearest shop and buy a new drive", I was very curious to prove my suspicion just on this drive. After zero-filling the partition with dd, then formatting it (mke2fs -cc) and mounting again, the 11g installation and database creation (on the same partition) successfully completed, performing fast and smoothly. To make sure it was not a casual event, I repeated the installation once again with full success. The database itself is working fine (by now). Well, the whole procedure took me more than four hours, but I'm pretty satisfied. I learned once again - stay away from Western Digital. As Oracle cannot rely on dying drive, my friend is going tomorrow to spend a 150+ euro on two 250G Seagate Barracudas and replace both WDC drives, even though the first drive seems to be healthy.
In general there is no difference between loading correct data from good disk into bad memory and loading the incorrect data from dying disk into good memory. In both cases the pattern is damaged. For everyone who runs into the problem similar to this, and the cause cannot be easily determined, the rule of thumb must be:
1. test memory and, if it shows any error, check sockets and test memory modules individually
2. check disks for bad blocks regardless of the result of memory testing
Therefore I consider your answer being generally correct.
Regards
NJ -
Java.util.zip.ZipException: invalid entry size error -- help required
Hi all
I am sure this error would have been posted many number of times, but I would really appreciate if someone could help me with my problem. I am working on reading data from a .zip file, which in it has ~5GB data. All I am performing is a read operation through the piece of code specified below. This code worked well for .zip files handling till ~2.5GB
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis);
StreamTokenizer tok = new StreamTokenizer( zis );
ZipEntry entry;
while((entry = zis.getNextEntry()) != null)
\\read from the zip file through the streamTokenizer
I just print what I read through the program, on the console.
But the error I get is
java.util.zip.ZipException: invalid entry size (expected 4294967295 but got 2117536490 bytes)
at java.util.zip.ZipInputStream.readEnd(Unknown Source)
at java.util.zip.ZipInputStream.read(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.io.StreamTokenizer.read(Unknown Source)
at java.io.StreamTokenizer.nextToken(Unknown Source)
at ZipFileStreams.getMessages(ZipFileStreams.java:677)
at ZipFileStreams.main(ZipFileStreams.java:814)
Could anybody give me hints as to what am I missing and where am i going wrong. Any help would be appreciated.
ThanksHi,
I get the same exception while reading a ZIP file. The size if the ZIP file is just 82KB but I am reading it over FTP not sure if it makes any difference. I am using JDK 1.4.2_05. Here is the code I am trying to execute.
public class TestFTP {
public static void main( String[] argv ) throws Exception {
String inboundPath = "/transfer/inbound/";
FTPClient ftp = new FTPClient();
ftp.connect("123");
ftp.login( "123", "123" );
ftp.changeWorkingDirectory(inboundPath);
FTPFile[] zipFiles = ftp.listFiles("*.zip");
TelnetClient telnetClient;
for(int i=0;i<zipFiles.length;i++){
System.out.println(zipFiles.getName());
ZipInputStream zis = new ZipInputStream(ftp.retrieveFileStream(zipFiles[i].getName()));
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()){
System.out.println(entry.getName());
The error message is
java.util.zip.ZipException: invalid entry size (expected 10291 but got 10233 bytes)
at java.util.zip.ZipInputStream.readEnd(ZipInputStream.java:367)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:141)
at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:91)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:69)
at test.TestFTP.main(TestFTP.java:41)
Exception in thread "main"
Please let me know if you were able to fix the problem.
Thanks
Maybe you are looking for
-
Everytime i plug my phone into itunes it says it cant connect because the phone is locked well i restored my phone twice and set a new passcode the last time and it still wont work . I even deleted itunes and reinstalled it , it dosent work . HELP PL
-
Miro's power button stopped working
Suddenly my phone's power button stopped working. I can't lock/unlock the phone nor turn it off :/ Tried to take a screen shot, to restart the device but nothing happened. I dropped the phone only once or twice before months, it hasn't been in touch
-
Why does the app store freeze on ipad2?
While surfing the app store, my ipad2 locks up and the touchpad won't respond so I have to do a complete reboot. Anyone else have this problem?
-
Does a Macbook Pro running OS X 10.9 have number lock?
I am trying to find number lock on my Macbook but don't see any options. Is there some combination of keys I should know to activate it?
-
Hi We had a problem with the discoverer viewer, where the sessions wouldnt stop and reach the max level, so we used a patch 6155500 to kill the idle sessions, it was working fine for a couple of days but not its not working ..........................