Finally & IOException

Hi everybody,
I'm using InputStream for reading file. I know it's a good programming practice to close every InputStream when done with reading, to prevent any resource leaks. So i would use something like this:
InputStream is = null;
try {
      is = new FileInputStream(someFile);
} catch(IOException ioe) {
      // do something with exception...
} finally {
     // closing InputStream to prevent resource leaks
      if(is != null) {
                  is.close();
}My question is: What happens if an I/O error occurs while closeing InputStream i.e. close() method throws IOException? How could i get notified that an I/O error occurred? Should i also surround this method with a try-catch block e.g. something like this:
} finally {
     // closing InputStream to prevent resource leaks
      if(is != null) {
             try {
                  is.close();
             } catch (IOException e) {
                                System.out.println("Error", e);
}it looks like a solution to me, but now finally block looks a bit fuzzy.
Can anyone please help me about this topic...
Kind regards!
Igor

your said
The finally block contains the cleanup code to runafter the actual work code
here the creation of InputStream is part of actual
work code, but it's not inside the try-block.If that fails, there's nothing to clean up, since that's the very first step.
Nonetheless, I would tend to do it this way, because I consider it simpler and more consistent, even thoug it adds a couple steps that are not strictly necessary:
InputStream is = null;
try {
  is = new ... ;
  use is
finally {
  if (is != null) {
    try {
      is.close();
    catch (...) {
      log it
}And again, I'd put the entire body of the try block into a utilty method to keep things tidier.
I've tried and constructor does need the throws
clause, but my final question is:
Is it a good programming practice to put a method
with throws clause (without the surrounding try-catch
block) inside the construstor, 'casuse i've never
seen constructors with throws clause ?If you're considering a throws clause, that means it must be possible for some step in your c'tor to fail. So, given that, the question is, what do you do if that step fails? If that step is critical to putting the new object into a valid state, then you can't just let the c'tor complete normally without handling the exception. (Note that logging the exception does not count as handling it.) You need to either provide some other, failsafe, default initialization, or declare the exception.
There's nothing wrong with throwing an exception from the c'tor--it's the right thing to do if the c'tor can't complete its job properly.
Of course, you can take a step back and ask whether the stuff you're doing in the c'tor actually belongs there. A c'tor's job is to put the object into a valid working state. It should do that as completely as possible, but it shouldn't do anything more than that. So you have to decide, based on your object's job, whether it's necessary to process that file to get the object into a valid initial state.

Similar Messages

  • SocketChannelImpl write data corruption issue

    Hi,
    I am new in working with the SocketChannelImpl class.. In fact java is not my forte.. I come from the C++ world. Recently we ported a socket based communication library originally written in C++ (this lib allows various processes in our App to communicate via sockets) to java to allow integration with an existing java application. We chose to use the same communication library in java to allow seamless application level integration.
    Things works fine mostly except few quirky-ness with data payload integraity when passed between the java based process to C++ based process. This app is running on solaris 10 with mostly latest patchset.
    Here is the typical action doen while communicating:
    - An object at the java process end is encoded in to an ASCII (UTF8/ISO-8859-1) char stream with delimeters like "\t", 0x07, etc. This results in a contiguous char stream.
    - The data is then pushed over the socket to the peer process.
    - The C++ process end then receives the payload and decode the data to recontruct the object with known delimeter, data markers, etc.
    We have not seen any issues with communication between C++ processes, however we have seen that between the java process and any other C++ processes, the payload contents changes for certain locations in the char stream. I have debugged from both the java end and c++ end simulataneously and see that when the char stream raw data (byteBuffer) is pushed out from java side in SocketChannelImpl.write() method, the char stream buffer looks perfectly OK in the byteBuffer, however when the read is done in the C++ process side and when I look at the raw data received, I see that some char sequences have changed!! This obviously causes problems in the C++ side decoding of the raw data.
    Here is the java code that sends the encoded dat (The method receives the raw char stream in the byte array buffer )
    final byte[] tmpBuffer = new byte[size];
    System.arraycopy(buffer, 0, tmpBuffer, 0, size);
    final ByteBuffer socketBufferWrite = ByteBuffer.wrap(tmpBuffer);
    int ErrorLoop = 0;
    final int MAX_LOOP = 100;
    int TotalWritten = 0;
    do {
    result = -1;
    try {
    result = socketCh.write(socketBufferWrite);
    } catch (final IOException ex) {
    trcStalker.logException(ex);
    if (result != -1) {
    TotalWritten += result;
    if (TotalWritten < size) {
    result = -1;
    if (result == -1) {
    ErrorLoop++;
    try {
    Thread.sleep(100 * ((ErrorLoop / (MAX_LOOP)) + 1)); //
    m to catch up
    } catch (final InterruptedException ex) {
    trcStalker.logException(ex);
    } // Wait a bit for the system to catch up
    } while ((result == -1) && (ErrorLoop < MAX_LOOP));
    My question to you would be what can cause the payload to get corrupted on the wire in socketchannelImpl.write() method invocation? I have tried using directAllocated Vs allocated Vs wrapped byteBuffers.. but the result has been same.
    I have not been able to find any pattern of corruption either, i.e. not seeing that the corrupted charactes are increased or decreased by certain number in the charset. However I have seen that certain locations in the buffer always gets changed.
    Any idea in debugging/fixing this issue? This thing is driving me nuts!
    thansk in advance.

    final byte[] tmpBuffer = new byte[size];
    System.arraycopy(buffer, 0, tmpBuffer, 0, size);
    final ByteBuffer socketBufferWrite = ByteBuffer.wrap(tmpBuffer);You can collapse all that to:
    final ByteBuffer socketBufferWrite = ByteBuffer.wrap(buffer, 0, size);
    result = socketCh.write(socketBufferWrite);
    } catch (final IOException ex) {
    trcStalker.logException(ex);
    if (result != -1) {SocketChannel.write() never returns -1. It can return zero if you are in non-blocking mode. Are you? Otherwise it can only return a positive integer. If you get any kind of IOException while writing to the socket the connection has been dropped and you should close the socket and start all over again. Retrying a write after an IOException is just a waste of time.
    if (TotalWritten < size) {
    result = -1;TotalWritten can be anything between 0 or 1 depending on your blocking mode, and 'size'. This is not an error.
    Thread.sleep(100 * ((ErrorLoop / (MAX_LOOP)) + 1));    //What is the purpose of this sleep?
    My question to you would be what can cause the payload to get corrupted on the wire in socketchannelImpl.write() method invocation?Nothing except bad coding at one end or the other.
    I have tried using directAllocated Vs allocated Vs wrapped byteBuffers.. but the result has been same.Have you tried using java.net.Socket? Much simpler.
    I have not been able to find any pattern of corruption either, i.e. not seeing that the corrupted charactes are increased or decreased by certain number in the charset. However I have seen that certain locations in the buffer always gets changed.It could be a disagreement about charsets between the sender and the receiver.

  • Error 403.7 - Forbidden: SSL client certificate is required

    Hi people!
    I�m developing a java client to a WebService (developed in .NET). The communication protocol is HTTPS to the URL where the Web Service is located (something like https://10.200.140.117/dirNotes/serviceName.asmx.). I�ve been reading many posts but I could'nt find the solution to the problem wich has the following message: Error 403.7 - Forbidden: SSL client certificate is required".
    I�m using JDK 1.5 and developing and testing on Windows Plataform. I'm able to access the URL specified above directly from the browser, I installed the client certificate (the same that �ve put into the ,jks keystore. I�ve also imported the whole certificate chain of the server to the cacerts.
    I�ll paste the code and the console trace below. I�d be very grateful if you can help me. Thanks a lot.
    _THE CODE_
    package principal;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.net.URL;
    import java.net.UnknownHostException;
    import java.security.KeyStore;
    import java.security.Security;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManagerFactory;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import entidade.Certificado;
    public class SSLClient {
    private static final int PORT_NUMBER = 443;
    private static final String HTTPS_ADDRESS = "10.200.140.117";
    private static String strCabecalhoMsg = "";
    private static String strDadosMsg = "";
    public static void main(String[] args) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", Certificado.getStrNomeArquivoJKSServidor());
    System.setProperty("javax.net.ssl.keyStorePassword", "senha");
    System.setProperty("javax.net.ssl.trustStore", "Certificados/cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.keyStoreType", "JKS");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    System.setProperty("javax.net.debug","ssl,handshake,record");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(Certificado.getStrNomeArquivoJKSServidor()),
    Certificado.getArranjoCharSenhaCertificadoServidor());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, Certificado.getArranjoCharSenhaCertificadoServidor());
    KeyStore ksT = KeyStore.getInstance(KeyStore.getDefaultType());
    ksT.load(new FileInputStream("C:/Arquivos de programas/Java/jre1.5.0_05/lib/security/cacerts"), "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ksT);
    SSLContext sc = SSLContext.getInstance("SSLv3");
    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
    SSLSocketFactory factory = sc.getSocketFactory();
    try{
    // method to load the values of the strings strCabecalhoMsg and strDadosMsg
    carregarXMLCabecalhoDados();
    SSLSocket socket =(SSLSocket)factory.createSocket(HTTPS_ADDRESS, PORT_NUMBER);
    socket.startHandshake();
    String [] arr = socket.getEnabledProtocols();
    URL url = new URL("https://10.200.140.117/dirNotes");
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
    HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
    urlc.setDoInput(true);
    urlc.setUseCaches(false);
    Object[] params = {strCabecalhoMsg, strDadosMsg};
    Service service = new Service();
    Call call = (Call) service.createCall();
    call.setTargetEndpointAddress(url);
    call.setOperationName("serviceName");
    String ret = (String) call.invoke(params);
    System.out.println("Result: " + ret);
    catch (UnknownHostException uhe) {
    uhe.printStackTrace();
    System.err.println(uhe);
    catch (Exception uhe) {
    uhe.printStackTrace();
    System.err.println(uhe);
    private static void carregarXMLCabecalhoDados()
    try
    BufferedReader input = new BufferedReader( new FileReader("notas/cabecalho.xml"));
    String str;
    while((str=input.readLine()) != null)
    strCabecalhoMsg += str ;
    System.out.println("Cabe�a: " + strCabecalhoMsg);
    input = new BufferedReader( new FileReader("notas/nota.xml"));
    while((str=input.readLine()) != null)
    strDadosMsg += str ;
    System.out.println("Nota: " + strDadosMsg);
    catch (FileNotFoundException e)
    // TODO Auto-generated catch block
    e.printStackTrace();
    catch (IOException e)
    // TODO Auto-generated catch block
    e.printStackTrace();
    _THE TRACE_
    adding as trusted cert:
    Subject: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 2 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network
    Issuer: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 2 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network
    Algorithm: RSA; Serial number: 0x1
    Valid from Fri Jun 25 21:19:54 BRT 1999 until Tue Jun 25 21:19:54 BRT 2019
    *others trusted certs*
    trigger seeding of SecureRandom
    done seeding SecureRandom
    export control - checking the cipher suites
    export control - no cached value available...
    export control - storing legal entry into cache...
    %% No cached client session
    *** ClientHello, TLSv1
    RandomCookie: GMT: 1198158630 bytes = { 48, 135, 53, 24, 112, 72, 104, 220, 27, 114, 37, 42, 25, 77, 224, 32, 12, 58, 90, 217, 232, 3, 104, 251, 93, 82, 40, 91 }
    Session ID: {}
    Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA]
    Compression Methods: { 0 }
    main, WRITE: TLSv1 Handshake, length = 73
    main, WRITE: SSLv2 client hello message, length = 98
    main, READ: TLSv1 Handshake, length = 3953
    *** ServerHello, TLSv1
    RandomCookie: GMT: 1198158523 bytes = { 56, 166, 181, 215, 86, 245, 8, 55, 214, 108, 128, 50, 8, 11, 0, 209, 38, 62, 187, 185, 240, 231, 56, 161, 212, 111, 194, 79 }
    Session ID: {222, 2, 0, 0, 147, 179, 182, 212, 18, 34, 199, 100, 168, 167, 48, 116, 140, 186, 151, 153, 226, 168, 163, 174, 24, 83, 208, 73, 179, 57, 86, 137}
    Cipher Suite: SSL_RSA_WITH_RC4_128_MD5
    Compression Method: 0
    %% Created: [Session-1, SSL_RSA_WITH_RC4_128_MD5]
    ** SSL_RSA_WITH_RC4_128_MD5
    *** Certificate chain
    chain [0] = [
    Version: V3
    *many chains and related data*
    Found trusted certificate:
    Version: V3
    Subject:
    *many trusted certificates and related data*
    *** ServerHelloDone
    *** ClientKeyExchange, RSA PreMasterSecret, TLSv1
    Random Secret: { 3, 1, 117, 112, 233, 166, 240, 9, 226, 67, 53, 111, 194, 84, 124, 103, 197, 28, 17, 36, 32, 48, 145, 166, 161, 61, 30, 63, 153, 214, 137, 113, 222, 204, 138, 77, 212, 75, 65, 192, 159, 215, 69, 156, 47, 188, 179, 219 }
    main, WRITE: TLSv1 Handshake, length = 134
    SESSION KEYGEN:
    PreMaster Secret:
    0000: 03 01 75 70 E9 A6 F0 09 E2 43 35 6F C2 54 7C 67 ..up.....C5o.T.g
    0010: C5 1C 11 24 20 30 91 A6 A1 3D 1E 3F 99 D6 89 71 ...$ 0...=.?...q
    0020: DE CC 8A 4D D4 4B 41 C0 9F D7 45 9C 2F BC B3 DB ...M.KA...E./...
    CONNECTION KEYGEN:
    Client Nonce:
    0000: 47 6A 73 26 30 87 35 18 70 48 68 DC 1B 72 25 2A Gjs&0.5.pHh..r%*
    0010: 19 4D E0 20 0C 3A 5A D9 E8 03 68 FB 5D 52 28 5B .M. .:Z...h.]R([
    Server Nonce:
    0000: 47 6A 73 BB 38 A6 B5 D7 56 F5 08 37 D6 6C 80 32 Gjs.8...V..7.l.2
    0010: 08 0B 00 D1 26 3E BB B9 F0 E7 38 A1 D4 6F C2 4F ....&>....8..o.O
    Master Secret:
    0000: 0B 3A 71 F8 BB 79 5E 07 78 C2 5F 13 4F 92 9D 87 .:q..y^.x._.O...
    0010: CF 69 0D 07 78 D2 59 46 1E C3 C1 5B A2 DB 04 B9 .i..x.YF...[....
    0020: 42 60 92 48 59 8E FD FD C3 5B BD 00 9C 54 7A 7E B`.HY....[...Tz.
    Client MAC write Secret:
    0000: 33 7C 19 C4 75 D2 CE 82 39 98 37 E5 7D 20 CB B1 3...u...9.7.. ..
    Server MAC write Secret:
    0000: 1E 1E 48 C7 D4 77 23 E4 22 26 8B 98 2E 92 5C 95 ..H..w#."&....\.
    Client write key:
    0000: EE 05 39 76 B2 85 63 6C F7 70 30 CB 6D 08 07 54 ..9v..cl.p0.m..T
    Server write key:
    0000: 5C 2E 3B 5E DC D9 EC C5 04 C4 D5 B5 12 11 B9 08 \.;^............
    ... no IV for cipher
    main, WRITE: TLSv1 Change Cipher Spec, length = 1
    *** Finished
    verify_data: { 143, 115, 243, 131, 242, 244, 12, 44, 191, 172, 205, 122 }
    main, WRITE: TLSv1 Handshake, length = 32
    main, READ: TLSv1 Change Cipher Spec, length = 1
    main, READ: TLSv1 Handshake, length = 32
    *** Finished
    verify_data: { 231, 215, 37, 250, 177, 121, 111, 192, 11, 41, 1, 165 }
    %% Cached client session: [Session-1, SSL_RSA_WITH_RC4_128_MD5]
    setting up default SSLSocketFactory
    use default SunJSSE impl class: com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl
    class com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl is loaded
    keyStore is : Certificados/certificadoSondaMonitor.jks
    keyStore type is : JKS
    keyStore provider is :
    init keystore
    init keymanager of type SunX509
    trustStore is: Certificados\cacerts
    trustStore type is : jks
    trustStore provider is :
    init truststore
    adding as trusted cert:
    Subject: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 2 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network
    Issuer: [email protected], CN=http://www.valicert.com/, OU=ValiCert Class 2 Policy Validation Authority, O="ValiCert, Inc.", L=ValiCert Validation Network
    Algorithm: RSA; Serial number: 0x1
    Valid from Fri Jun 25 21:19:54 BRT 1999 until Tue Jun 25 21:19:54 BRT 2019
    adding as trusted cert:
    * many certificates*
    init context
    trigger seeding of SecureRandom
    done seeding SecureRandom
    instantiated an instance of class com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl
    export control - checking the cipher suites
    export control - found legal entry in cache...
    %% No cached client session
    *** ClientHello, TLSv1
    RandomCookie: GMT: 1198158632 bytes = { 93, 1, 41, 236, 165, 146, 251, 117, 129, 195, 129, 72, 245, 181, 43, 48, 80, 251, 244, 198, 223, 85, 82, 101, 20, 159, 17, 26 }
    Session ID: {}
    Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA]
    Compression Methods: { 0 }
    main, WRITE: TLSv1 Handshake, length = 73
    main, WRITE: SSLv2 client hello message, length = 98
    main, READ: TLSv1 Handshake, length = 3953
    *** ServerHello, TLSv1
    RandomCookie: GMT: 1198158525 bytes = { 109, 114, 234, 1, 130, 97, 251, 9, 61, 105, 56, 246, 239, 222, 97, 143, 22, 254, 65, 213, 10, 204, 153, 67, 237, 133, 223, 48 }
    Session ID: {23, 30, 0, 0, 26, 129, 168, 21, 252, 107, 124, 183, 171, 228, 138, 227, 94, 17, 195, 213, 216, 233, 205, 2, 117, 16, 21, 65, 123, 119, 171, 109}
    Cipher Suite: SSL_RSA_WITH_RC4_128_MD5
    Compression Method: 0
    %% Created: [Session-2, SSL_RSA_WITH_RC4_128_MD5]
    ** SSL_RSA_WITH_RC4_128_MD5
    *** Certificate chain
    chain [0] = [
    many chains again
    *** ServerHelloDone
    *** ClientKeyExchange, RSA PreMasterSecret, TLSv1
    Random Secret: { 3, 1, 116, 247, 155, 227, 25, 25, 231, 129, 199, 76, 134, 222, 98, 69, 149, 224, 75, 6, 60, 121, 115, 216, 244, 246, 102, 92, 188, 64, 113, 56, 190, 43, 32, 51, 90, 254, 141, 184, 71, 48, 41, 29, 173, 180, 46, 116 }
    main, WRITE: TLSv1 Handshake, length = 134
    SESSION KEYGEN:
    PreMaster Secret:
    0000: 03 01 74 F7 9B E3 19 19 E7 81 C7 4C 86 DE 62 45 ..t........L..bE
    0010: 95 E0 4B 06 3C 79 73 D8 F4 F6 66 5C BC 40 71 38 ..K.<ys...f\.@q8
    0020: BE 2B 20 33 5A FE 8D B8 47 30 29 1D AD B4 2E 74 .+ 3Z...G0)....t
    CONNECTION KEYGEN:
    Client Nonce:
    0000: 47 6A 73 28 5D 01 29 EC A5 92 FB 75 81 C3 81 48 Gjs(].)....u...H
    0010: F5 B5 2B 30 50 FB F4 C6 DF 55 52 65 14 9F 11 1A ..+0P....URe....
    Server Nonce:
    0000: 47 6A 73 BD 6D 72 EA 01 82 61 FB 09 3D 69 38 F6 Gjs.mr...a..=i8.
    0010: EF DE 61 8F 16 FE 41 D5 0A CC 99 43 ED 85 DF 30 ..a...A....C...0
    Master Secret:
    0000: FC C9 75 A4 2B F1 8A D8 AD 16 27 70 B7 E4 64 6C ..u.+.....'p..dl
    0010: 05 D7 33 4A 53 91 2F 51 1E 32 D3 3B 2E 18 2E BC ..3JS./Q.2.;....
    0020: E4 16 EE 2F 01 A1 08 48 19 09 32 68 CE 69 8F B1 .../...H..2h.i..
    Client MAC write Secret:
    0000: F1 95 3B CE 06 5B 8A 9B EC DE 1C 8F B4 AB D9 36 ..;..[.........6
    Server MAC write Secret:
    0000: BF 52 36 48 63 24 FE 74 22 BE 00 99 BE F0 6E E5 .R6Hc$.t".....n.
    Client write key:
    0000: 9F 08 0A 6E 8F 54 A3 66 1C BC C7 6B AE 88 67 E0 ...n.T.f...k..g.
    Server write key:
    0000: 06 A1 0B 4F 69 DE 5F AF 0E 6B B5 04 ED E8 EA F5 ...Oi._..k......
    ... no IV for cipher
    main, WRITE: TLSv1 Change Cipher Spec, length = 1
    *** Finished
    verify_data: { 148, 93, 105, 42, 110, 212, 55, 2, 150, 191, 13, 111 }
    main, WRITE: TLSv1 Handshake, length = 32
    main, READ: TLSv1 Change Cipher Spec, length = 1
    main, READ: TLSv1 Handshake, length = 32
    *** Finished
    verify_data: { 171, 150, 45, 10, 99, 35, 67, 174, 35, 52, 23, 192 }
    %% Cached client session: [Session-2, SSL_RSA_WITH_RC4_128_MD5]
    main, setSoTimeout(600000) called
    main, WRITE: TLSv1 Application Data, length = 282
    main, WRITE: TLSv1 Application Data, length = 8208
    main, WRITE: TLSv1 Application Data, length = 1102
    main, READ: TLSv1 Application Data, length = 1830
    main, received EOFException: ignored
    main, called closeInternal(false)
    main, SEND TLSv1 ALERT: warning, description = close_notify
    main, WRITE: TLSv1 Alert, length = 18
    main, called close()
    main, called closeInternal(true)
    AxisFault
    faultCode: {http://xml.apache.org/axis/}HTTP
    faultSubcode:
    faultString: (404)Not Found
    faultActor:
    faultNode:
    faultDetail:
         {}:return code: 404
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <HTML><HEAD><TITLE>The page cannot be found</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
    <STYLE type="text/css">
    BODY { font: 8pt/12pt verdana }
    H1 { font: 13pt/15pt verdana }
    H2 { font: 8pt/12pt verdana }
    A:link { color: red }
    A:visited { color: maroon }
    </STYLE>
    </HEAD><BODY><TABLE width=500 border=0 cellspacing=10><TR><TD>
    <h1>The page cannot be found</h1>
    The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.
    <hr>
    <p>Please try the following:</p>
    <ul>
    <li>Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.</li>
    <li>If you reached this page by clicking a link, contact
    the Web site administrator to alert them that the link is incorrectly formatted.
    </li>
    <li>Click the <a href="javascript:history.back(1)">Back</a> button to try another link.</li>
    </ul>
    <h2>HTTP Error 404 - File or directory not found.<br>Internet Information Services (IIS)</h2>
    <hr>
    <p>Technical Information (for support personnel)</p>
    <ul>
    <li>Go to <a href="http://go.microsoft.com/fwlink/?linkid=8180">Microsoft Product Support Services</a> and perform a title search for the words <b>HTTP</b> and <b>404</b>.</li>
    <li>Open <b>IIS Help</b>, which is accessible in IIS Manager (inetmgr),
    and search for topics titled <b>Web Site Setup</b>, <b>Common Administrative Tasks</b>, and <b>About Custom Error Messages</b>.</li>
    </ul>
    </TD></TR></TABLE></BODY></HTML>
         {http://xml.apache.org/axis/}HttpErrorCode:404
    (404)Not Found
         at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:744)
         at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
         at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
         at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
         at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
         at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
         at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
         at org.apache.axis.client.Call.invoke(Call.java:2767)
         at org.apache.axis.client.Call.invoke(Call.java:2443)
         at org.apache.axis.client.Call.invoke(Call.java:2366)
         at org.apache.axis.client.Call.invoke(Call.java:1812)
         at principal.SSLClient.main(SSLClient.java:86)
    (404)Not Found
    -----

    I'm having the same problem with the same URL. I try many configuration and nothing works. My code is:
    public class NFeClient {
         static{
              Security.addProvider(new BouncyCastleProvider());
         public static void main(final String[] args) throws Exception {
              final String path = "https://homologacao.nfe.sefaz.rs.gov.br/ws/nfeconsulta/nfeconsulta.asmx";
              final String keyStoreProvider = "BC";
              final String keyStoreType = "PKCS12";
              final String keyStore = "/home/mendes/certificados/cert.p12";
              final String keyStorePassword = "xxxx";
              System.setProperty("javax.net.ssl.keyStoreProvider",keyStoreProvider);
              System.setProperty("javax.net.ssl.keyStoreType",keyStoreType);
              System.setProperty("javax.net.ssl.keyStore",keyStore);
              System.setProperty("javax.net.ssl.keyStorePassword",keyStorePassword);
              System.setProperty("javax.net.ssl.trustStore","/home/mendes/workspace/NFE/jssecacerts");
              final SSLContext context =  SSLContext.getInstance("TLS");
              final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
              final KeyStore ks = KeyStore.getInstance(keyStoreType);
              ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
              kmf.init(ks, keyStorePassword.toCharArray());
              context.init(kmf.getKeyManagers(), null, null);
              final URL url = new URL(path);
              final HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
              httpsConnection.setDoInput(true);
              httpsConnection.setRequestMethod("GET");
              httpsConnection.setRequestProperty("Host", "iis-server");
              httpsConnection.setRequestProperty("UserAgent", "Mozilla/4.0");
              httpsConnection.setSSLSocketFactory(context.getSocketFactory());
              try{
                   final InputStream is = httpsConnection.getInputStream();
                   final byte[] buff = new byte[1024];
                   int readed;
                   while((readed = is.read(buff)) > 0)
                        System.out.write(buff,0,readed);
              }catch(final IOException ioe){
                   ioe.printStackTrace();
    }and the response of the server is always the same:
    java.io.IOException: Server returned HTTP response code: 403 for URL: https://homologacao.nfe.sefaz.rs.gov.br/ws/nfeconsulta/nfeconsulta.asmx
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1241)
         at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
         at br.com.esales.nfe.signer.client.NFeClient.main(NFeClient.java:60)Edited by: mendes on Apr 25, 2008 9:56 AM

  • Path and file name problem when I want to download files from html

    Hi all,
    I want to write a small program to allow users download files from jsp file
    but the following files don't work .
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    try
    String SContent = request.getParameter("click");
    String SDocName = "temp.doc"; //  out put file File Name
    ServletOutputStream stream= response.getOutputStream(); // Getting ServletOutputStream
    response.setContentType("application/msword"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename=\"" +SDocName+"\""); // To pop dialog box
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(SContent));
    int c;
    while ((c = in.read()) != -1){
               stream.write(c);
    in.close();
    stream.flush();
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    %>I am so confuse, what is the path and file name I sould give ? for example my click should equal to http://******/Test/display.jsp?click=00-1

    Hi all,
    I got error at
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         org.apache.coyote.tomcat5.CoyoteResponse.getWriter(CoyoteResponse.java:599)
    if I want ot download file from html file.
    String SContent = request.getParameter("click");
    if I hard code like follow it work fine.
    String SContent ="C:/Project Coding.doc";
    what mistake I make.
    Thank you!

  • Should I use a temp buffer to gunzip bytes to bytes?

    Folks,
    I need a method to gunzip (uncompress) a zipped-byte-array into a plain-byte-array ... The below method (based on that used for file-i/o-streams) works, but I can't figure out if using the buf  "interveening temporary buffer" is good, bad, or indifferent.
    As I understand things... There's really no memory saving in reading/writing-by-the-temporary-buffer because the input gzippedByteArray is allready wholey in memory, and we (by definition) need the whole output plain-byte-array in memory concurrently... so it'd probably be more memory efficient to NOT use temporary-buffer and just zip the WHOLE input straight into the ByteArrayOutputStream with one call to output.write
    BUT I'm not really sure of myself here... so please can anyone offer an informed opinion?
    Memory efficiency is important (I think) because we're handling XML responses, and "the odd one" might be upto maybe 200 Mb (unzipped), though "the norm" is under a meg, and 99% are under 5 meg... So I guess I need to engineer this instead of just slapping it in and seeing if it pops.
          * Returns the g-unzipped (uncompressed) version of the given
          * gzippedByteArray.
          * @param gzippedByteArray byte[] - the bytes to uncompress
          * @return byte[] - the uncompressed bytes
          * @throws IOException
         public static byte[] getUnzippedBytes(byte[] gzippedByteArray)
              throws IOException
              ByteArrayInputStream input = null;
              GZIPInputStream unzipper = null;
              ByteArrayOutputStream output = null;
              byte[] bytes = null;
              try {
                   input = new ByteArrayInputStream(gzippedByteArray);
                   unzipper = new GZIPInputStream(input);
                   output = new ByteArrayOutputStream();
                   // unzip bytes onto the output stream
                   int len;
                   byte[] buf = new byte[BUFFER_SIZE];
                   while ( (len=unzipper.read(buf)) > 0 ) {
                        output.write(buf, 0, len);
                   // return the contents
                   bytes = output.toByteArray();
              } finally {
                   IOException x = null;
                   if(unzipper!=null) try{unzipper.close();}catch(IOException e){x = e;}
                   if(output!=null) try{output.close();}catch(IOException e){x = e;}
                   if(x!=null) throw x;
              return bytes;
         }Thanking you all. Keith.

    OutputStreams aren't 'exposed by routers... Our bluddy router "encapsulates" the servlet request. It exposes a swag of setters, one of which is setExtractXml(byte[])... the upside is that you don't have to worry about content types, and request headers and all that carp... the downside is the loss of flexibility.
    What I meant was that I'll need to customise the session model (which lives in our funky router) to expose the servlet-output-stream to the action class... Then we're laughing.
    Or not... My mad tech manager reckons "it's been working that way for years"... he didn't like it when I reminded him of our "odd "unexplained" out of memory" incidents... Nope... His code... His way... Gotta luv the managment, and why do I care anyway... Do I care? Naaah. I just work here.

  • Why is file size increasing while copiying contents of the file.

    Hi,
    Iam copying the contents of a file to another file using streams.But while doing this the size of the destination file is greater than the source file.For example, if iam copying the contents of file A whose size is 78 KB into file B then the size of B is 80 KB. Any body please explain the reason for this.The code i used for copying is given below.
    Thanks in advance.
    public static boolean copyFile(File srcFile,File destFile){
              FileInputStream fis = null;
              FileOutputStream fos = null;
              boolean isCopySucess = false;
              //============================================
              int ReadBytes = 0;
              int BUFSIZ = 4096;
              long fileSize ;
              long copiedBytes=0;
              try
                        fis = new FileInputStream(srcFile);
                        fos = new FileOutputStream(destFile);
                        fileSize = srcFile.length();
                        byte Buf[] = new byte[BUFSIZ];
                        while(copiedBytes < fileSize)
                             ReadBytes = fis.read(Buf, 0, BUFSIZ);
                             fos.write(Buf);
                             copiedBytes +=ReadBytes;
                        isCopySucess = true;
              }catch(Exception ex)
                   isCopySucess = false;
                   ex.printStackTrace();
              //============================================
              finally{
                   try {
                        if(fis != null)
                             fis.close();
                        if(fos != null)
                             fos.close();
                   } catch (final IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   return isCopySucess;
         }

    ReadBytes = fis.read(Buf, 0, BUFSIZ);
    fos.write(Buf, 0, ReadBytes);

  • How to display file content in browser using servlet..? urgent!!!

    hello,
    i am building a application for which when a user logs in he will we redirected to page where he will have one link ,with this link a file is associated.
    when user press that link he should be able to see that particular file in internet browser....
    now can anybody give me a code sample of how to display a file in browser....
    please reply me as soon as possible...

    thanks for your reply....
    but i don't want this....
    i want to read a file from disk into stream or buffer and from that again reading and printing in browser.....
    a servlet should be built for this....
    i wrote this but its not working
    ========================================================
    public class FilePrinting extends HttpServlet
         public void doPost(HttpServletRequest req,HttpServletResponse res)
              throws IOException,ServletException
              ServletOutputStream out=res.getOutputStream();
              res.setContentType("text/html");
              String fileURL="/mydomainWebApp/Test.htm";
              res.setHeader("Content-disposition","attachment; filename=" +="Test.htm" );
              BufferedInputStream bis=null;
              BufferedOutputStream bos=null;
              try
                   URL url = new URL( fileURL );
                   bis=new BufferedInputStream(url.openStream());
                   bos = new BufferedOutputStream(out);
                   byte[] buff = new byte[2048];
                   int bytesRead;
                   // Simple read/write loop.
                   while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                   bos.write(buff, 0, bytesRead);
              }catch(final MalformedURLException e)
                   System.out.println ( "MalformedURLException." );
                   throw e;
              }catch(final IOException e)
                   System.out.println ( "IOException." );
                   throw e;
              }finally
                   if (bis != null)
                        bis.close();
                   if (bos != null)
                        bos.close();
    =======================================================================
    please send me sample code if anyone have../...

  • How to open a ".doc" file with ms word directly with this servlet?

    Here is a servlet for opening a word or a excel or a powerpoint or a pdf file,but I don't want the "file download" dialog appear,eg:when i using this servlet to open a word file,i want open the ".doc" file with ms word directly,not in IE or save.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class OpenWord extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
    String strFileName = req.getParameter("filename");
    int len = 0;
    String strFileType1 = "application/msword";
    String strFileType2 = "application/vnd.ms-excel";
    String strFileType3 = "application/vnd.ms-powerpoint";
    String strFileType4 = "application/pdf";
    String strFileType = "";
    if(strFileName != null) {
         len = strFileName.length();
         if(strFileName.substring(len-3,len).equalsIgnoreCase("doc")) {
              strFileType = strFileType1;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("xls")) {
              strFileType = strFileType2;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("ppt")) {
              strFileType = strFileType3;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("pdf")) {
              strFileType = strFileType4;
         } else {
              strFileType = strFileType1;
    if(strFileName != null) {
         ServletOutputStream out = res.getOutputStream();
         res.setContentType(strFileType); // MIME type for word doc
    //if uncomment below sentence,the "file download" dialog will appear twice.
         //res.setHeader("Content-disposition","attachment;filename="+strFileName);
         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         String path = "d:\\"; //put a word or a excel file here,eg a.doc
         try {
         File f = new File(path.concat(strFileName));
         FileInputStream fis = new FileInputStream(f);
         bis = new BufferedInputStream(fis);
         bos = new BufferedOutputStream(out);
         byte[] buff = new byte[2048];
         int bytesRead;
         while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
         bos.write(buff, 0, bytesRead);
         } catch(NullPointerException e) {
         System.out.println ( "NullPointerException." );
         throw e;
         } catch(FileNotFoundException e) {
         System.out.println ( "FileNotFoundException." );
         throw e;
         } catch(final IOException e) {
         System.out.println ( "IOException." );
         throw e;
         } finally {
         if (bis != null)
         bis.close();
         if (bos != null)
         bos.close();

    Hello!
    Does some one of you had open a MS word file (.doc) in Java search for a token like [aToken] replace it with another text and then feed it to a stream of save it?
    I want to build a servlet to open a well formatted and rich on media (images) ms word document search for tokens and replace them with information form a web form.
    Any Ideas?
    Thank you in advanced.

  • HttpConnection.getResponseCode() return -1

    Hi guy's
    I am developing a midp application which is communicate with server and display the result on the client using HttpConnection.Basically i am from bangalore,India and using Airtel,Vodafone connections for GPRS. My jar file is properly working in the Sony Ericsson models(k800i,k310i) with airtel and vodafone connections. But the same jar file is failed to communicate with server in Nokia models. HttpConnection.getResponseCode() return -1 in Nokia 6020,6070,6300 devices. Even N6030 is also return same value with vodafone. But same time application working fine in another 6030 model with airtel. Please look at my source code below.
    private static String requestToServer(final String url, final String data)throws IOException {
    HttpConnection httpCon = null;
    InputStream inputStream = null;
    String result = null;
    try {
    while (true) {
    httpCon = (HttpConnection) Connector.open(connectionUrl,Connector.READ_WRITE);
    httpCon.setRequestMethod(HttpConnection.POST);
    final String conf = System.getProperty("microedition.configuration");
    final String prof = System.getProperty("microedition.profiles");
    httpCon.setRequestProperty("User-Agent","Profile/" + prof + " Configuration/" + conf);
    writeDataToConnection(httpCon, data);
    if (!isRedirectResponse(httpCon)) {
    break;
    connectionUrl = httpCon.getHeaderField("Location");
    httpCon.close();
    inputStream = httpCon.openInputStream();
    result = readStreamData(inputStream);
    } catch (final ClassCastException e) {
    throw new IllegalArgumentException("Not an HTTP URL"); }
    catch (final IOException e) { throw e; }
    catch (final Exception e) { throw e; }
    finally {
    if (inputStream != null) { inputStream.close(); }
    if (httpCon != null) { httpCon.close(); }
    return result;
    private static void writeDataToConnection(final HttpConnection c, final String data) throws IOException {
    final OutputStream os = c.openOutputStream();
    try {
    final DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(data);
    dos.flush();
    catch(IOException e) { throw e; }
    finally { os.close(); }
    private static boolean requestToServer(final HttpConnection httpCon)throws IOException {
    boolean result = false;
    final int conResponseCode = httpCon.getResponseCode();
    switch (conResponseCode) {
    case HttpConnection.HTTP_OK:
    result = false;
    break;
    case HttpConnection.HTTP_MOVED_TEMP:
    if (DEBUG_REDIRECT) {
    System.out.println("Request is redirected"); }
    result = true;
    break;
    default:
    throw new IOException("HTTP response code: " + conResponseCode);
    return result;
    In the Nokia models, the httpCon.getResponseCode() return -1. Can anybody tell me, whats the problem and what the solution for this please.
    Regards,
    Jobin

    use this ---> return new int[]{1,3};

  • Rather Specific JList Conundrum

    Hi Guys,
    I've come to a bit of a brick wall on the project I'm working on, but as my problem is so specific no amount of Googling is helping me.
    Essentially my coursework is to make a twitter client using the Twitter4JAPI, the part I'm stuggling with is showing the home feed. I want it to show the Icon, with the User and Status next to it which I'm doing using my own custom cell renderer. Now it works fine, but the program takes ages to load as it pulls all the avatars off the web, swapping to and from that tab takes ages (for the same reason), and scrolling the list is so mind blowingly slow, as every tick it refreshes all the images (from the web).
    Any suggestions how to stop this?
    Here is my custom cell renderer code:
    public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus) {
              input = value.toString();
              final String splitArray[] = input.split("`");
              Image avatar = null;
              try {
                   final URL avatarURL = new URL(splitArray[0]);
                   avatar = ImageIO.read(avatarURL);
              } catch (final IOException e) {
                   JOptionPane.showMessageDialog(null,
                             "Error retriving some users avatars",
                             "Image download error", JOptionPane.ERROR_MESSAGE);
              usersAvatar.setIcon(new ImageIcon(avatar));
              tweet.setText(splitArray[2]);
              userName.setText(" " + splitArray[1] + "    ");
              return mainPanel;
         }I cut out all the layout junk.
    And the input for the list is in the form avatarurl`username`tweet, which is then split and stored in the split array.
    I've had a bash at threading it based on [Improve Application Performance With SwingWorker in Java SE 6|http://java.sun.com/developer/technicalArticles/javase/swingworker/] but it meant that the avatars were all identical.
    Do I need to thread the entire list creation section instead of just the image retrival.
    All help greatly appreciated.
    For your reference --->

    I can safely say you answered my question.
    The 2 classes I added were:
    User Class import javax.swing.ImageIcon;
    public class UserClass {
         String userName;
         ImageIcon userAvatar;
         public UserClass(String user, ImageIcon avatar) {
              userName = user;
              userAvatar = avatar;
         public String getUserName() {
              return userName;
         public ImageIcon getUserAvatar() {
              return userAvatar;
    }and UserDB
    import java.awt.Image;
    import java.io.IOException;
    import java.net.URL;
    import java.util.ArrayList;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    public class UserDB {
         private ArrayList<UserClass> users;
         public UserDB(){
              users = new ArrayList<UserClass>();
         public ImageIcon getAvatar(String username){
              ImageIcon avatar = null;
              for (int i = 0; i < users.size(); i++) {
                   String beingChecked = users.get(i).getUserName();
                   if (username.equals(beingChecked)) {
                        avatar = users.get(i).getUserAvatar();
              return avatar;
         public String getUserName(int index){
              return users.get(index).getUserName();
         public int getTotalUsers() {
              return users.size();
         public void addUser(String userName, URL profileImageURL){
              Image avatar = null;
              try {
                   final URL avatarURL = profileImageURL;
                   avatar = ImageIO.read(avatarURL);
              } catch (final IOException e) {
              ImageIcon avatarIcon = new ImageIcon(avatar);
              UserClass tooAdd = new UserClass(userName, avatarIcon);
              users.add(tooAdd);
         public boolean isEmpty(){
              return users.isEmpty();
    }So now the first time it encounters a unique user for the first time it add's it too the database.
    Honestly that's an approach i would never have thought of in a million years!
    Thanks a bunch

  • Won't display Images

    Hey,
    I am making a application to pin point a particular point on a map (as in 1 specific pixel)
    but the problem i have is,before scanning in 6 dozen maps for my uni mate (shes doing geography im doing software enginerring) i am using a plain bmp (its just purple) mad eusing MSPaint (im not running unix.liunix)
    and it wont display the image, but it will display a scanned image and image sobtained off the net,
    why is this??
    this isnt exactly specific to the application i am creating now as it will used scanned images (which work) but for future reference,if you could tell me why, and how to get around it.......
    Drogo

    "catch whatever it is"That code will not compile.
    Please post extracts of the of what you are using, or a Short, Self Contained, Correct (Compilable), Example. I'm fairly sure you will need a JPEG or GIF file, as getImage I'm sure does not support .BMP.
    What did the code I posted above return? (the file exists stuff?) However, I'm sure it is down to the use of a BMP.
    Unless you are targeting an old platform, consider using ImageIO, it supports more formats, and is just spanker than Toolkit.
    Image image;
    try {
        image = ImageIO.read( new File( filename ) );
    } catch( final IOException ioe ) {
       System.err.println( "Failed to load image" );
       ioe.printStackTrace();
    if( image == null ) {
       System.out.println( "Check the file exists, and is the format you think it is" );
    }

  • WAS 6.0 - Response already committed / OutputStream already obtained

    Hello, we have struts code that is working fine in websphere 5, but not 6. I've seen this same kind of thing being post around, but haven't found one that closely resembles our simple setup. Below I've copied what our code looks like. Please help me to understand what the least-intrusive way would be to fix something simple like this, and let me know if more info is needed. FYI, we have tried returning null from the class, but this doens't seem to work. Also, some additional info is that we need this to work in WAS 5 and 6, because we have two different apps containing the same code, one of which is deployed (via EAR file) on 5 and the other 6. Thanks!
    struts-config entry:     
    <action path="/streamFile" type="MyClass" scope="request" validate="false">
                  <forward name="success" path=""/>
    </action>     
    web.xml entry:
         <servlet-mapping>
              <servlet-name>opsconsoleServlet</servlet-name>
              <url-pattern>streamFile</url-pattern>
         </servlet-mapping>
    Snippet of Class file:
    public class MyClass extends Action {
         public ActionForward execute(ActionMapping mapping,
                         ActionForm form,
                        HttpServletRequest request,
                        HttpServletResponse response)
              throws Exception {    
         ServletOutputStream out = response.getOutputStream();
         BufferedOutputStream bos = null;
         try {
                   bos = new BufferedOutputStream(out);
                    bos.write(<bytes, etc>);
         } catch(final MalformedURLException e) {
         throw e;
         } catch(final IOException e) {
         throw e;
         } finally {
         if (bos != null)
              bos.close();
         if (out != null)
              out.close();
         return mapping.findForward("success");
    error from log:
    [11/5/07 12:50:11:737 EST] 00000036 ServletWrappe E   SRVE0014E: Uncaught service() exception root cause FilterProxyServlet: Cannot forward. Response already committed.
    [11/5/07 12:50:12:001 EST] 00000036 ServletWrappe E   SRVE0068E: Could not invoke the service() method on servlet opsconsoleServlet. Exception thrown : javax.servlet.ServletException: Cannot forward. Response already committed.
            at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:157)
            at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:82)
    error later in log:
    [11/5/07 12:50:12:621 EST] 00000036 SRTServletRes W   WARNING: Cannot set status. Response already committed.
    [11/5/07 12:50:12:627 EST] 00000036 SRTServletRes W   WARNING: Cannot set header. Response already committed.
    [11/5/07 12:50:14:191 EST] 00000036 ServletWrappe A   SRVE0242I: [Communication] [/OpsConsole] [/WEB-INF/jsp/error/internalError.jsp]: Initialization successful.
    [11/5/07 12:50:14:201 EST] 00000036 ServletWrappe E   SRVE0068E: Could not invoke the service() method on servlet /WEB-INF/jsp/error/internalError.jsp. Exception thrown : java.lang.IllegalStateException: SRVE0199E: OutputStream already obtained
            at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:490)
            at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:170)
            at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:163)
            at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:227)

    svguerin3 :
    So this is something that worked in websphere 5 but not 6.. Are you sure this same code working on WAS5? This shouldn't. I guess you are trying to display the contents of the stream in a JSP page.If that's correct don't use
    ServletOutputStream out = response.getOutputStream();
         BufferedOutputStream bos = null;
         try {
                   bos = new BufferedOutputStream(out);
                    bos.write(<bytes, etc>);
         }instead read the bytes in to an in memory object, add this in memory object to request param and then call findForward(). In the JSP page get this request attribute and do whatever you want.
    Note: You can either use servletoutstream.write or RequestDispactcher.forward/redirect/response.sendRedirect.

  • Where does the word document store?

    Hi Expert,
    Using webdynpro java to upload the file, where does the file actually store?
    I refer to below tutorial but have no ideal where the file is store. Please help.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/00062266-3aa9-2910-d485-f1088c3a4d71
    Thank you.
    Regards,
    Henry

    Hi Henry,
      Once you reach the Action handler of the FileUpload UI Element your file has already been uploaded and is available in your context attribute. Now depending on the requirement you need to store the file.
    If you need to store the file in a shared location then you need to write the file to that location using normal java I/O.
    IWDResource resource = element.getMyResAttr();
    InputStream is = resource.read(true);
    try
    /* read bytes from stream and write it to file */
    finally
      try { is.close(); } catch (final IOException ex) {}
    If you need to store the file on the R/3 system then you need to call the function module/BAPI capable of doing so and pass the resource file to the function module. Some times you might need to convert the IWDResource file to a byte array. The code given above can be modified to do that. If there are no function modules or BAPI's capable of storing the Word Document available you will have to write one.
    Let me know if this helps.
    Regards,
    Sanyev

  • Download file problem

    Hi all,
    I write jsp to allow user download file from server, but I only download the path C:/Project Coding.doc into my file not the file itself.
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    OutputStream outStream = null;
    try
    String SContent ="C:/Project Coding.doc";
    String SDocName = "temp.xls"; // File Name
    outStream = response.getOutputStream(); // Getting ServletOutputStream
    response.setContentType("application/vnd.ms-excel"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename="+SDocName); // To pop dialog box
    byte[] buff = SContent.getBytes(); // Converting file content to byte array
    outStream.write(buff,0,buff.length); // Write to the OutputStream
    outStream.flush(); // Forcing buffered bytes to be written out.
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    finally
    if (outStream != null)
    outStream.close();
    %>

    Hi all,
    Thank you fro the reply,
    the following hard code woke
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    try
    //String SContent ="C:/Other Sources Viruses 2004.xls";
    String SContent ="C:/Project Coding.doc";
    //String SDocName = "temp.xls"; // File Name
    String SDocName = "temp.doc"; //  out put file File Name
    ServletOutputStream stream= response.getOutputStream(); // Getting ServletOutputStream
    //response.setContentType("application/vnd.ms-excel"); // Setting content type
    response.setContentType("application/msword"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename="+SDocName); // To pop dialog box
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(SContent));
    int c;
    while ((c = in.read()) != -1){
               stream.write(c);
    in.close();
    stream.flush();
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    %>but if I change the SContent from a html file
    String SContent = request.getParameter("click");
    I got the following error
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         org.apache.coyote.tomcat5.CoyoteResponse.getWriter(CoyoteResponse.java:599)
    any advice?
    Thank you !

  • How to debug a custom doclet

    Hi,
    Can an incorrect taglet name cause javadoc generation to crash/ hang?
    We have a custon taglet with the name of @abc.comment
    However, someone added a period at the end of the name by mistake: @abc.comment.
    This caused the cruise control build to crash...
    Any clues on why this would have happened would be helpful. Also, how do you debug a custom doclet?
    Thanks in advance.
    BB

    Also, how do you debug a custom doclet?Well, the usual way: you use a debugger ;-)
    Since Javadoc features a programmatic interface, it's easy to write a simple main class.
    Here is my test entry class, just replace "your.doclet.name.here" with the actual name of your custom doclet.
    TestRun requires a filename as sole argument/cmd option, this filename should point to a standard Javadoc options file. To successfully use TestRun, the classes that make up your custom doclet and the JDK tools.jar should (probably) be in the classpath.
    * @(#) TestRun.java 1.00
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.StringTokenizer;
    * <code>TestRun</code>
    * @author Thomas Behr 27.11.2003
    public class TestRun
        public static void main( final String[] args )
            if ( args.length != 1 || !(new java.io.File( args[0] )).isFile() )
                System.err.println( "usage: java TestRun <filename>" );
                return;
            com.sun.tools.javadoc.Main.execute( "javadoc",
                                                "your.doclet.name.here",
                                                processOptionsFile( args[0] ) );
        private static String[] processOptionsFile( final String filename )
            final String options = readOptionsFile( filename );
            final StringTokenizer tokens = new StringTokenizer( options );
            final String[] jargs = new String[tokens.countTokens()];
            for ( int i = 0; i < jargs.length; ++i )
                jargs[i] = tokens.nextToken();
            return jargs;
        private static String readOptionsFile( final String filename )
            final StringBuffer buffer = new StringBuffer();
            BufferedReader br = null;
            try
                br = new BufferedReader( new FileReader( filename ) );
                String line;
                while ( (line = br.readLine()) != null )
                    buffer.append( line ).append( "\n" );
            catch ( final IOException ioe )
                ioe.printStackTrace();
                buffer.setLength( 0 );
            finally
                if ( br != null )
                    try
                        br.close();
                    catch ( IOException ioe )
                        ioe.printStackTrace();
            return buffer.toString();
    }

Maybe you are looking for

  • Delivery Costs into SO

    Hi all, I have below scenario. Let's say i have a material X, this material X which will be procured through Purchase Order (PO). The delivery costs for this material until our warehouse will be issued with another PO. So, in short, we will use 2 POs

  • Issue when calling Stored procedure from application

    Dear all,   Oracle DB version: 11.2.0.3    OS : RHEL 5.9 64-bit version   We are trying to execute one of the stored procedure (belonging to oracle DB schema) from our Dotnet application(recites in application server) but it takes more than 30 second

  • Why can't I see presenter information

    In edit presenter information I can do just that : [IMG]http://i6.tinypic.com/2u6feps.png[/IMG] However when the slide show runs all I see is the slides themselves no presenter into. Problem? or am I doing something wrong? [IMG]http://i6.tinypic.com/

  • Free web hosting?

    Hi everyone - I have read several of the help pages and searched all over for information on free space with BT and can't find a thing to help me. Some of you say it is free but I don't know how to access it. I have followed links and have been told

  • Issue with pretest into video back button in Adobe Captivate 6

    Hello, I have a pretest that goes into a video. When I hit the back button on the video screen it goes to the pretest screen but when I hit back again it jumps forward to the video and gets stuck on the same two screens. Can you please help smart Cap