Write inputstream to zipfile

Hi all,
Can someone show me how to read (text) data from a (Filter)InputStream and write those to a text file (as a ZipEntry)? It's getting 2 in the morning here and I'm too dizzy to figure this out...
Thanks in advance for your help.
Manos

Read the data from the input stream, then write it to an output stream that is then wrapped around the ZIP stream.
- K

Similar Messages

  • Write inputStream to file

    Hi,
    who could give me a short sample code how to write an inputStream or a Reader to a file.
    Thanks for your help
    Bye

    This will help u
    http://web2.java.sun.com/docs/books/tutorial/essential/io/filestreams.html

  • Write InputStream to Webserver's Filesystem

    I am obtaining a resource as an InputStream using the getResourceAsStream method. I would like to use it in the PageContext.include() method, but this takes a String as a path to a resource.
    Is there any way I can write this InputStream to the file system, and then pass a path to it?
    This would be when running a custom tag in a web server.

    I tried that, but the file that I am reading is in the WEB-INF, so on some app servers it doesnt allow you to pass it as a app resource.
    So:
    /WEB-INF/resources/include.jsp
    can't be passed in to the include method in some servers, but can in others...

  • Write File to disk

    hi everyone'
    i have an UploadFile instance and i'd like to write it to disk how can i do this?
    please help urgently.

    You could have googled it yourself ...
    http://www.google.de/search?q=write+inputstream+to+file&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:de:official&client=firefox-a
    one answer ...
    import java.io.*;
    public class InputStreamToFile
      public static void main(String args[])
        try
        File f=new File("outFile.java");
        InputStream inputStream= new FileInputStream
    ("InputStreamToFile.java");
        OutputStream out=new FileOutputStream(f);
        byte buf[]=new byte[1024];
        int len;
        while((len=inputStream.read(buf))>0)
        out.write(buf,0,len);
        out.close();
        inputStream.close();
        System.out.println("\nFile is created........
        catch (IOException e){}
      }

  • Why can't I read this ZipFile?

    hi, this code looks right to me, but it will not read anything. I have a zipfile, called 'cdtemp.001'
    which has only 1 zip entry, called 'cdtemp.x001', which i am trying to read some bytes from.
    Here is the code:
                   byte temp[] = new byte[50];
                   ZipInputStream ZIS;
              InputStream IS;
              ZipFile claimFileZipped = new ZipFile("cdtemp.001");
              ZipEntry Entry = claimFileZipped.getEntry("cdtemp.x001");
              IS = claimFileZipped.getInputStream(claimFileZipped.getEntry("cdtemp.x001"));
              ZIS = new ZipInputStream(IS);
              ZIS.read(temp,0,50);can anybody spot a problem? When i print out the contens of 'temp' after that read operation, i get null.
    Thanks for any input....

    so, i have this now:
                            byte temp[] = new byte[50];
                   ZipInputStream ZIS;
                   InputStream IS = getClass().getResourceAsStream("cdtemp.001");
                   ZIS = new ZipInputStream(IS);
                   ZIS.read(temp,0,50);
                   System.out.println("Read this:" + new String(temp));However, i'm still not getting anything at all. This is weird. i am sure it is a classpath like you said. I will look into that and report back on monday. I appreciate your help!

  • How to include custom application.xml in JDev9i project

    Can anybody explain to me how to include a custom application.xml file when deploying to an .ear file? I need to include application wide security roles, and I can't see where in Jev9i how to do this.
    After searching this forum, I see that jdev9i can't include the orion-application.xml, but I want to include just the standard J2EE application.xml. Is this possible?
    Thanks,
    matt

    The standard application.xml file unfortunately can't be customized in JDev 9.0.2. The reasons why this capability was left out of JDev 9.0.2 are same reasons why the other EAR-level XML files were excluded. The OTN thread
    Re: Regarding 11i and E-business suite
    has a summary of those reasons, which you've probably seen. We know this is an area in need of improvement and will be adding this functionality in the JDev 9.0.3 release. Until then, you'll have to go with a work-around like an Ant build file, batch file, Java application, or some other kind of script.
    Below is a sample Java application which can be used to insert <security-role> elements into an EAR file's application.xml. Modify the main() method to customize for your purposes, and put xmlparserv2.jar on the classpath (in a JDev project, add the "Oracle XML Parser v2" library):
    package mypackage4;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    public class PostProcessEAR
    public static void main( String[] args ) throws IOException
    final String earFile = "C:\\temp\\myapp.ear";
    final PostProcessEAR postProcess = new PostProcessEAR( earFile );
    postProcess.addSecurityRole( null, "first_role" );
    postProcess.addSecurityRole( "Description for the second role", "second_role" );
    postProcess.commit();
    System.out.println( "Done." );
    private final File _earFile;
    private final ArrayList _securityRoles = new ArrayList();
    public PostProcessEAR( String earFile )
    _earFile = new File( earFile );
    public void addSecurityRole( String description, String roleName )
    if ( roleName == null )
    throw new IllegalArgumentException();
    _securityRoles.add( description );
    _securityRoles.add( roleName );
    * Write out modified EAR file.
    public void commit() throws IOException
    if ( _securityRoles.size() == 0 )
    return;
    final ZipFile zipFile = new ZipFile( _earFile );
    final Enumeration entries = zipFile.entries();
    final File outFile = new File( _earFile.getAbsolutePath() + ".out" );
    final ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream( outFile ) ) );
    while ( entries.hasMoreElements() )
    final ZipEntry entry = (ZipEntry) entries.nextElement();
    final InputStream in = zipFile.getInputStream( entry );
    if ( "META-INF/application.xml".equals( entry.getName() ) )
    final XMLDocument modifiedApplicationXml = insertSecurityRoles( in );
    final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    modifiedApplicationXml.print( byteOutput );
    final int numBytes = byteOutput.size();
    entry.setSize( numBytes );
    if ( entry.getMethod() == ZipEntry.STORED )
    entry.setCompressedSize( numBytes );
    final CRC32 crc32 = new CRC32();
    crc32.update( byteOutput.toByteArray() );
    entry.setCrc( crc32.getValue() );
    out.putNextEntry( entry );
    byteOutput.writeTo( out );
    else
    // Copy all other zip entries as they are.
    out.putNextEntry( entry );
    copy( in, out );
    in.close();
    out.close();
    private XMLDocument insertSecurityRoles( InputStream in ) throws IOException
    final DOMParser domParser = new DOMParser();
    domParser.setAttribute( DOMParser.STANDALONE, Boolean.TRUE );
    try
    domParser.parse( in );
    final XMLDocument doc = domParser.getDocument();
    final Element docElem = doc.getDocumentElement();
    final Iterator iter = _securityRoles.iterator();
    while ( iter.hasNext() )
    final String desc = (String) iter.next(); // might be null
    final String roleName = iter.next().toString(); // must not be null
    final Element securityRoleElem = doc.createElement( "security-role" );
    if ( desc != null )
    securityRoleElem.appendChild( createPcdata( doc, "description", desc ) );
    securityRoleElem.appendChild( createPcdata( doc, "role-name", roleName ) );
    docElem.appendChild( securityRoleElem );
    return doc;
    catch ( SAXException e )
    e.printStackTrace();
    return null;
    private Element createPcdata( XMLDocument doc, String elemName, String pcdata )
    final Element elem = doc.createElement( elemName );
    elem.appendChild( doc.createTextNode( pcdata ) );
    return elem;
    private final byte[] buffer = new byte[4096];
    private void copy( InputStream in, OutputStream out ) throws IOException
    while ( true )
    final int bytesRead = in.read( buffer );
    if ( bytesRead < 0 )
    break;
    out.write( buffer, 0, bytesRead );

  • To alter content of the file

    Hi
    I can not get file.txt that this contained in the jar to alter. it is a file of properties in format text, I get to read the information inside of the file using the package java.util.zip.*! but I don't get to alter that file and to save inside of the jar! It is in time of execution.
    this get file:
    public void readProps()throws FileNotFoundException, IOException{
    java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile("celesc.jar");
    java.io.InputStream inputStream = zipFile.getInputStream(new java.util.zip.ZipEntry("files/SerCom.props"));
    properties.load(inputStream);
    inputStream.close();
    zipFile.close();
    this should save the file inside of the jar, but it doesn't work.
    public void saveProps() throws Exception{
    FileOutputStream dest = new FileOutputStream("celesc.jar");
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
    ZipEntry entry = new ZipEntry("files/SerCom.props");
    out.putNextEntry(entry);
    //out.write(data, 0, count);
    This code is part of an executable jar, celesc.jar

    but I don't get to alter that file and to save inside of the jar!No, you don't. You have to create a new jar file, then copy everything from the old jar file to the new file, writing the new version of your special file instead of the old version. However you may want to rethink the idea of keeping that file inside the jar, as recreating the entire jar file is an expensive operation.
    PC&#178;

  • File not Opening in KM

    Hi Experts,<br>
    Can helpme ASAP plz,<br>
    I'm Uploading file in to KM using FileUpload UI in WDJ, affter click on submit button (any of the file) is storing in KM, but My Problem is <br> when am opeing file @KM am not able to C the data on th file, file is blak and some time its diplaying PopUp box like ConvertFile.<br> so am not sure bout this what to do?
    Can u tell me Exactly where i have cahnge plz. am attaching my code on ActionImpl Button also .<br>
         IPrivateTendersUploadView.IFileElement fileelement = wdContext.currentFileElement();//createFileElement();<br>
         try<br>
         {<br>
          IWDAttributeInfo attributeInfo  = wdContext.nodeFile().getNodeInfo().getAttribute("Filedata") ;<br>
          IWDModifiableBinaryType binaryType = (IWDModifiableBinaryType) attributeInfo.getModifiableSimpleType();<br>      byte[] fileByteArray = wdContext.currentFileElement().getFiledata();<br>
          IWDClientUser wdClientUser = WDClientUser.getCurrentUser();<br>
          com.sap.security.api.IUser sapUser = wdClientUser.getSAPUser(); <br>
          IUser ep5User =WPUMFactory.getUserFactory().getEP5User(sapUser); <br>
          ResourceContext context = new ResourceContext(ep5User);<br>
          RID rid = RID.getRID("/documents/MCGM Department/City Eng/");<br>
          IResourceFactory factory = ResourceFactory.getInstance();<br>
          ICollection collection = (ICollection) factory.getResource(rid,context);<br>
          String fileName = wdContext.currentFileElement().getResource().getResourceName();<br>
          //String location = "D:
    Test
    ";<br>
          //ByteArrayInputStream inputStream = new ByteArrayInputStream(fileByteArray);<br>
          //wdComponentAPI.getMessageManager().reportSuccess("catch error = " + e);     <br>
          InputStream inputStream = wdContext.currentFileElement().getResource().read(false);<br>
          File destfile = new File(fileName);//fileName <br>
          FileOutputStream out = new FileOutputStream(destfile);<br>
          if (inputStream != null)<br>
          {<br>
          out.write(inputStream.read());      <br>
          }<br>
          out.close();<br>
          FileInputStream fin = new FileInputStream(fileName);//fileName<br>
          fin.read(); <br>
          BufferedInputStream bufInStream = new BufferedInputStream(new FileInputStream(destfile));<br>
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));<br>
                          Content content = new Content(inputStream,"application/octer-stream",-1L,"UTF-16");<br>
          IResource newResource = collection.createResource(fileName, null, content);//IResource newResource = collection.createResource("NDGD.pdf",null,content);<br>
          long contentLen = newResource.getContent().getContentLength();<br>
          if (contentLen < 0) <br>
          {<br>
          } <br>
                      else<br>
            {<br>
          IWDControllerInfo controllerInfo1 = wdControllerAPI.getViewInfo().getViewController();<br>
          String first1 = "File uploaded Successfully!!! ";<br>
          IWDConfirmationDialog dialog1 = wdComponentAPI.getWindowManager().createConfirmationWindow(first1, controllerInfo1.findInEventHandlers("Ok"),"Ok");<br>
          dialog1.open();<br>
          } //else<br>
         }<br>
                    catch (Exception e) <br>
                    {<br>
         //wdComponentAPI.getMessageManager().reportSuccess(" First Select a File From Your Loal System" + e);<br>
          IWDControllerInfo controllerInfo = wdControllerAPI.getViewInfo().getViewController();<br>
          String dialogText = "The given File Alreday Exists Please Change File Name OR Do you want to create New version of this file";<br>
          IWDConfirmationDialog dialog = wdComponentAPI.getWindowManager().createConfirmationWindow(dialogText,controllerInfo.findInEventHandlers("Yes"),"Yes");<br>
          dialog.addChoice(controllerInfo.findInEventHandlers("No"), "No");<br>
          dialog.open();<br>
          }<br>
    ThanQ
    Edited by: vRichard on Sep 24, 2009 9:14 AM

    Hi,
    Seems as a problem with the mimetype of the uploaded file - check this line:
    Content content = new Content(inputStream,"application/octer-stream",-1L,"UTF-16");
    should't be:
    Content content = new Content(inputStream,"application/octet-stream",-1L,"UTF-16");
    I think, the best would be to get the mimetype from the file element...
    Romano

  • Writing a Vector to a Output File Line by Line.

    Can anyone tell me how to write each element of the Vector on a New Line to the Output file? Right now the Output is in a String across 1 line.
    Now - � t Bowser 5 years 105 lbs.t Bowser 5 years 106 lbs.t Daisy 1 year 30 lbs.t Dog 1 yr 66 lbs.t King 6 years 77 lbs.t Nikki 5 years 68 lbs.
    Here is what I need -
    Bowser 5 years 106 lbs.
    Bowser 5 years 105 lbs.
    Rover 7 years 88 lbs.
    Dog 1 yr 66 lbs.
    King 6 years 77 lbs.
    Nikki 5 years 68 lbs.
    Daisy 1 year 30 lbs.
    Do a find on // Writes Vector Object to a file
    Thank You in advance.
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    public class VectorSort
    Vector v;
    private DataInputStream inputStream = null;
    private ObjectOutputStream outputStream = null; // <== this is for a Vector
    // private DataOutputStream outputStream = null; // <== This is for a Textfile
    (1) Read in Pet Records put them in a Vector, Sort them Print them.
    public static void main(String[] args) throws java.io.IOException
    VectorSort newVector = new VectorSort();
    newVector.connectToInputFile();
    newVector.connectToOutputFile();
    newVector.readInput();
    newVector.sortPrint();
    newVector.closeFiles();
    System.out.println(" ");
    System.out.println("Check A:/DataOut.txt Now");
    public void connectToInputFile()
    String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
    try
    inputStream = new DataInputStream(new FileInputStream(inputFileName));
    catch(FileNotFoundException e)
    System.out.println("File " + inputFileName + " not found.");
    System.exit(0);
    public void connectToOutputFile()
    String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
    try
    outputStream = new ObjectOutputStream( // <== this is for a Vector
    // outputStream = new DataOutputStream( // <== this is for a Textfile
    new FileOutputStream(outputFileName));
    catch(IOException e)
    System.out.println("Error opening output file "
    + outputFileName);
    System.out.println(e.getMessage());
    System.exit(0);
    private String getFileName(String prompt)
    String fileName = null;
    System.out.println(prompt);
    fileName = SavitchIn.readLineWord();
    return fileName;
    //===========================================================================
    public void readInput()
    v = new Vector ();
    try
    String result = "";
    boolean done = false;
    int ctr = 0;
    String next;
    next = inputStream.readLine();
    while ( next != null)
    v.addElement( next.trim() );
    next = inputStream.readLine();
    catch(EOFException e)
    //Do nothing. This just ends the loop.
    System.out.println("Do Nothing Here");
    catch(IOException e)
    System.out.println(
    "Error: reading or writing files.");
    System.out.println(e.getMessage());
    System.exit(0);
    public void sortPrint()
    Collections.sort(v);
    int vsize = v.size();
    for (int j = 0; j < vsize - 1 ; j++)
    try
    outputStream.writeObject(v.elementAt(j)); // Writes Vector Object to a file
    System.out.println(v.elementAt(j));
    catch(IOException e)
    System.out.println("Error Writing Output "
    + e.getMessage());
    System.exit(0);
    public void closeFiles()
    try
    outputStream.flush(); // <== force the buffer to write
    inputStream.close();
    outputStream.close();
    catch(IOException e)
    System.out.println("Error closing files "
    + e.getMessage());
    System.exit(0);

    // did you try with java.io.PrintWriter
    // here is simple method to write file from vector.
    // you need to change obtaining your string value at the vector loop
    private void writeDataLog(Vector vector, String filename)
    try
    PrintWriter pw = new PrintWriter(new FileWriter(filename, true));     
    if (vector.size()>0)
    for (int i=0; i<vector.size(); i++)
    { String str = ((your object)vector.get(i)).getYourString();
    pw.println( str );
    pw.close();
    catch(Exception e)
    { System.out.print(e.toString()); }
    }

  • Problem with Blob

    Hi to all
    My JDBC driver not supports getBlob();
    My code is
    //reading blob1
    mResultSet=mStatement.executeQuery("Select blob1 from table1");
    mResultSet.next();
    InputStream is = mResultSet.getBinaryStream("blob1");
    //writing blob2
    String mm="UPDATE table2 set blob2=?";
    PreparedStatement pp=connection.prepareStatement(mm);
    pp.setBinaryStream(1, is, is.available());
    pp.executeUpdate();
    Can somebody say why I can read blob1 (it is not null), but when I try read blob2 (after executing this code), i retrieve empty BinaryStream - null?
    Thanks

    Thanks very much Martin for reply,
    But I can't understand this:
    You wrote:
    InputStream is = new InputStream(mResultSet.getBinaryStream("blob1");I write
    InputStream is = mResultSet.getBinaryStream("blob1");
    Now I think I have Input Stream with data or I'm wrong?
    Maybe in this InputStream I have only Adress and no data?
    byte[] buf = new byte[MAX_LENGTH];
    is.read(buf, 0, buf.length);with these program reads data from InputStream to byte[].Why I must do it?
    //Following API:
    //setBinaryStream(int parameterIndex, InputStream x, int length)
    I must write:
    pp.setBinaryStream(1, is, is.available());
    //pp is Prepered Statement; is - InputStream.
    When I write
    byte[] buf = new byte[MAX_LENGTH];
    int IS_length=is.read(buf, 0, buf.length);
    I get IS_length=8 and is.available()=8
    Regards,
    Sigis

  • Java IRC bot.

    hi, recently I started making an irc bot in Java. I was testing it out on my friend's server and everything seemed to be working, it was reading from the server, and was responding to the one command. I wanted to show it to my other friend so I changed the variables to match his irc server, and the bot couldn't connect. I was wondering if the problem was in my friend's server or in my code. (I'll include what the server sends when I connect at the bottom)
    package ircbot;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    public class bot {
        public static String message;
        /* variables */
        Socket sock;
        OutputStream out;
        BufferedWriter writer;
        InputStream in;
        BufferedReader reader;
        static doaction action = new doaction();
        String nick = "Gary";
        String user = "account 8 * :oHai";
        public static String channel = "#malvager";
        String ip = "127.0.0.1"; // <-- not the actual ip...
        int port = 11235;
        /* end variable and object declarations */
        public static void main(String[] args) {
            bot superbot = new bot();
            superbot.connect();
        public void connect() {
            try {
            sock = new Socket(ip, port);
            out = sock.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(out));
            in = sock.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            join(nick, channel, user, writer, reader);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException i) {
                i.printStackTrace();
            }// end try/catch
        public static void join(String nick, String channel, String user, BufferedWriter writer, BufferedReader reader) {
            try {
                writer.write("NICK " + nick);
                System.out.println("set nick");
                writer.newLine();
                writer.flush();
                System.out.println(reader.readLine());
                writer.write("USER " + user);
                System.out.println("set user");
                writer.newLine();
                writer.flush();
                System.out.println(reader.readLine());
                writer.write("JOIN " + channel);
                System.out.println("joined channel");
                writer.newLine();
                writer.flush();
                System.out.println(reader.readLine());
                read(reader, writer);
            } catch (IOException e) {
                e.printStackTrace();
        public static void read(BufferedReader reader, BufferedWriter writer) {
            String said;
            while(1 == 1) {
                try {
                    said = reader.readLine();
                    System.out.println(said);
                    if (check(said) == true) {
                        print(writer);
                } catch (IOException f) {
                    f.printStackTrace();
        public static boolean check(String input) {
            message = action.setinput(input);
            if (message.equals("I'm awesome")) {
                return(true);
            } else {
                return(false);
        public static void print(BufferedWriter writer) {
            Scanner input = new Scanner(System.in);
           try {
               writer.write("PRIVMSG " + channel + " " + message);
               writer.newLine();
               writer.flush();
           } catch(IOException r) {
               r.printStackTrace();
    }// end class
    package ircbot;
    import java.lang.String;
    public class doaction {
        public String setinput(String input) {
            int length = input.length();
            int control;
            String message = input;
            control = length - 5;
            message = message.substring(control, length);
            if (message.equals("!Gary")) {
                message = "I'm awesome";
                return(message);
            } else {
                message = input;
                return("bad");
    }When I connect to my second friend's server (the one that doesn't work) I get:
    set nick
    :lolnepp.no-ip.biz NOTICE AUTH :*** Looking up your hostname...
    set user
    :lolnepp.no-ip.biz NOTICE AUTH :*** Found your hostname (cached)
    joined channel
    PING :51AA6A7F
    :lolnepp.no-ip.biz 451 JOIN :You have not registered
    When I connect to the friend's server that works I get:
    set nick
    :Malvager.hub NOTICE AUTH :*** Looking up your hostname...
    set user
    :Malvager.hub NOTICE AUTH :*** Found your hostname
    joined channel
    :Malvager.hub 001 Gary :Welcome to the Malvager-IRC-Network IRC Network [email protected]
    :Malvager.hub 002 Gary :Your host is Malvager.hub, running version Unreal3.2.7
    :Malvager.hub 003 Gary :This server was created Sun Oct 26 2008 at 00:01:26 PDT
    :Malvager.hub 004 Gary Malvager.hub Unreal3.2.7 iowghraAsORTVSxNCWqBzvdHtGp
    Okay yea, can anyoen tell me if the problem is in my code or the server? And if the problem is in the code could you please tell me what to change or point me in the right directin? thanks.

    kajbj wrote:
    youngdeveloper wrote:
    What do you mean it doesn't look like a java program..? Sorry, I was watching tv while I was typing. It should say "Java problem" and not "Java program" :)
    And yea, I realize it says that, but the steps to register are you enter the nick and the user which both come before that, so I was wondering if anyone with knowledge of how irc works could tell me if there's some other way of registering, or if the problem's in my code.Some IRC servers requires that an admin in the channel creates the user account.
    KajOkay, glad to know it was supposed to say program :).
    I'm pretty sure that it's not because the admin has to set up the acc. because this server was set up with the sole purpose of showing my friend my bot. However, it might be just that the server is retarded. I'm gonna try it on some other servers and see how it works there.

  • Validate xml with local dtd

    hello
    trying to write a unit test that validates some xml we are marshalling against a dtd. here is a snippet of code. The problem is how to specify the dtd against which the xml is to be validated. verification_transaction is our root xml element. when i run this code i get a
    malformedurlexception: no protocol: verification.dtd
    any ideas?
                    StringWriter writer = new StringWriter();
                   // write the doctype declaration
                    writer.write("<!DOCTYPE verification_transaction SYSTEM \"verification.dtd\">");
                    // now marshal to the writer
              marshaller.marshal(spec, requestType, componentNumber, writer);
              InputStream inputStream = new ByteArrayInputStream(writer.getBuffer().toString().getBytes());
              Reader reader = new InputStreamReader(inputStream);
                    // get a sax parser that is validating
              TestHandler handler = new TestHandler();
              SAXParserFactory factory = SAXParserFactory.newInstance();
              factory.setValidating(true);
              SAXParser saxParser = factory.newSAXParser();
              try {
                   saxParser.parse(new InputSource(reader), handler);
                   fail("Should have thrown exception.");
              } catch (RuntimeException e) {
                   // pass
              }Message was edited by:
    shrndegruv

    I needed to do a bunch of things.
    1.
                    URL url = getClass().getResource("/verification.dtd");
              StringWriter writer = new StringWriter();
              writer.write("<?xml version=\"1.0\"?><!DOCTYPE verification_transaction SYSTEM \"" + url + "\">");and then I had to use a handler which processed the errors (which I got from an online tutorial):
    private static class MyErrorHandler extends DefaultHandler {
              public void warning(SAXParseException e) throws SAXException {
                   System.out.println("Warning: ");
                   printInfo(e);
              public void error(SAXParseException e) throws SAXException {
                   System.out.println("Error: ");
                   printInfo(e);
                   throw new SAXException("DTD Validation Error: [" + e.getMessage() + "]");
              public void fatalError(SAXParseException e) throws SAXException {
                   System.out.println("Fatal error: ");
                   printInfo(e);
              private void printInfo(SAXParseException e) {
                   System.out.println("   Public ID: " + e.getPublicId());
                   System.out.println("   System ID: " + e.getSystemId());
                   System.out.println("   Line number: " + e.getLineNumber());
                   System.out.println("   Column number: " + e.getColumnNumber());
                   System.out.println("   Message: " + e.getMessage());
         }

  • Should I ask for a BufferedReader or just a Reader?

    Wrapping a BufferedReader in a BufferedReader is not a big deal, right?
    Please consider these two methods:
    public void exampleA(BufferedReader bufRdr) { ........ }
    public void exampleB(Reader rdr) { BufferedReader bufRdr = new BufferedReader(rdr); ... }In exampleA, users with a Reader, but not a BufferedReader, cannot use the method (but I can't think
    of any examples of when a user could not create the BufferedReader).
    In exampleB, if someone passes a BufferedReader then that creates a BufferedReader wrapped in another BufferedReader.
    While method overloading fixs this:
    public void example(BufferedReader bufRdr) { ........ }
    public void example(Reader rdr) { example(new BufferedReader(rdr));}If a BufferedReader wrapped in a BufferedReader is nothing of note cleary my best solution is exampleB.
    Method overloading perfectly fixs the problem, but it clutters the API so thats why I'd prefer exampleB.

    I would like to test my understanding of the before mentioned comments. Please consider:
    public void foo(Reader rdr) {
      BufferedReader bufRdr = new BufferedReader(rdr);
      ... // do whatever
    }After foo exits, there is still a reference to rdr.
    The bufRdr object dies when foo exits.
    bufRdr wraps rdr and provides a buffer where it temporarly holds data to allow for block reads.
    There is no way to guarantee the buffer will flush before bufRdr is gc.
    So, the above foo method is not safe.
    Methods should never wrap a Reader/Writer/InputStream/OutputStream ( that has a reference outside of its scope ) with a local object that has a buffer.
    For performance upside, I buffered anything I could get a reference to.
    Now, I think this attitude is completely wrong.

  • Response.setContentLength() always necessary when writing to OuputStream?

    Hi All -
    I have a situation where I have a proxy servlet between my Portal and various back end systems. Different sub-classes of this Servlet work to proxy different back end systems. The main task is brute-force URL rewriting.
    I'm working in a Portal 9.2.2 environment.
    Basic flow: Read InputStream from back end system via HttpURLConnection, write InputStream to StringBuffer, replace URLs as necessary in the String, get ServletOutputStream via response.getOutputStream(), write modified String to OutputStream, call flush on OutputStream.
    The odd issue I'm seeing is:
    Use Case 1:
    After doing my URL rewriting - the length of the output is shorter than before.
    If I call response.setContentLength(lengthOfOutput) my proxied page does not render - although no error is thrown.
    If I do not call response.setContentLength(lengthOfOutput) everything renders just fine.
    Use Case 2:
    After doing my URL rewriting - the length of the output is longer than before.
    If I call response.setContentLength(lengthOfOutput) everything outputs just fine.
    If I do not call response.setContentLength(lengthOfOutput) my page does not render - an exception is thrown that the output exceeded the stated length. (this makes sense)
    It seems to me that I should be able to call setContentLength every time - but that's not working out...if anyone has any ideas I'd love to hear them.
    Thanks in advance!

    hi
    when we had to do a similar task, we had suppresed Content Length.
    However unless you are streaming the output , you seem to have all the data in memory in order to rewrite the URL's in which case there is no reason why you cant output the correct content length (dont rely on the content-length the backend server is sending, you have to set the content length after your manipulations and take care of the encoding your using).
    Browser's generally work OK with no content length but give you problems with incorrect length , and the BEA code also throws up exceptions. Either suppress this value or output the correct one.

  • PLEASE HELP! how to get certificat form a JarFile (NOT JarInputStream) ?

    Hi,
    I have a signed JAR-file.
    If I try to verify this file with "jarsigner -verify", I get OK.
    But if I want to get the certificat-chain from this JAR-file with
    "JarFile" and then "JarEntry", I receive only "null".
    For example I try it with this code:
    JarEntry entry;
    java.security.cert.Certificate[] dmCertChain;
    for (Enumeration enumJar2 = zipFile.entries();enumJar2.hasMoreElements() ;) {
    entry = zipFile.getJarEntry((enumJar2.nextElement()).toString());
    dmCertChain = ((JarEntry)entry).getCertificates();
    if(dmCertChain == null) {
              System.out.println("The entry has no certificate.");
    else {
              System.out.println(dmCertChain.length);
              for (int i = 0; i < dmCertChain.length; i++)
              System.out.println(dmCertChain<i>.toString());
    But my JAR-file is ok, because when I try it with "JarInputStream" and
    then "JarFile", I receive the correct certificate-chain.
    (I try it with getNextJarEntry())
    How can I read the certfication-chain from the JarFile?
    I searched the web for a solution, but i don't find an answer!
    So please HELP!

    I found the solution :-)
    I found in Java-api-doc the following sentence:
    "This method can only be called once the JarEntry has been completely verified by reading from the entry input stream until the end of the stream has been reached. Otherwise, this method will return null."
    So I added this lines to my code:
    // JarEntry must be completely verified by reading from the entry
    // input stream until the end of the stream has been reached.
    InputStream is = zipFile.getInputStream(entry);
    int c;
    while ((c = is.read()) != -1) {
    //do nothing here, just to make sure the whole stream is read
    bye

Maybe you are looking for