Search in sources :

Example 51 with BufferedInputStream

use of java.io.BufferedInputStream in project hibernate-orm by hibernate.

the class JarFileBasedArchiveDescriptor method visitArchive.

@Override
public void visitArchive(ArchiveContext context) {
    final JarFile jarFile = resolveJarFileReference();
    if (jarFile == null) {
        return;
    }
    final Enumeration<? extends ZipEntry> zipEntries = jarFile.entries();
    while (zipEntries.hasMoreElements()) {
        final ZipEntry zipEntry = zipEntries.nextElement();
        final String entryName = extractName(zipEntry);
        if (getEntryBasePrefix() != null && !entryName.startsWith(getEntryBasePrefix())) {
            continue;
        }
        if (zipEntry.isDirectory()) {
            continue;
        }
        if (entryName.equals(getEntryBasePrefix())) {
            // just any random entry
            try (InputStream is = new BufferedInputStream(jarFile.getInputStream(zipEntry))) {
                final JarInputStream jarInputStream = new JarInputStream(is);
                ZipEntry subZipEntry = jarInputStream.getNextEntry();
                while (subZipEntry != null) {
                    if (!subZipEntry.isDirectory()) {
                        final String name = extractName(subZipEntry);
                        final String relativeName = extractRelativeName(subZipEntry);
                        final InputStreamAccess inputStreamAccess = buildByteBasedInputStreamAccess(name, jarInputStream);
                        final ArchiveEntry entry = new ArchiveEntry() {

                            @Override
                            public String getName() {
                                return name;
                            }

                            @Override
                            public String getNameWithinArchive() {
                                return relativeName;
                            }

                            @Override
                            public InputStreamAccess getStreamAccess() {
                                return inputStreamAccess;
                            }
                        };
                        final ArchiveEntryHandler entryHandler = context.obtainArchiveEntryHandler(entry);
                        entryHandler.handleEntry(entry, context);
                    }
                    subZipEntry = jarInputStream.getNextEntry();
                }
            } catch (Exception e) {
                throw new ArchiveException("Error accessing JarFile entry [" + zipEntry.getName() + "]", e);
            }
        } else {
            final String name = extractName(zipEntry);
            final String relativeName = extractRelativeName(zipEntry);
            final InputStreamAccess inputStreamAccess;
            try (InputStream is = jarFile.getInputStream(zipEntry)) {
                inputStreamAccess = buildByteBasedInputStreamAccess(name, is);
            } catch (IOException e) {
                throw new ArchiveException(String.format("Unable to access stream from jar file [%s] for entry [%s]", jarFile.getName(), zipEntry.getName()));
            }
            final ArchiveEntry entry = new ArchiveEntry() {

                @Override
                public String getName() {
                    return name;
                }

                @Override
                public String getNameWithinArchive() {
                    return relativeName;
                }

                @Override
                public InputStreamAccess getStreamAccess() {
                    return inputStreamAccess;
                }
            };
            final ArchiveEntryHandler entryHandler = context.obtainArchiveEntryHandler(entry);
            entryHandler.handleEntry(entry, context);
        }
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) InputStreamAccess(org.hibernate.boot.archive.spi.InputStreamAccess) BufferedInputStream(java.io.BufferedInputStream) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) ArchiveEntry(org.hibernate.boot.archive.spi.ArchiveEntry) ArchiveEntryHandler(org.hibernate.boot.archive.spi.ArchiveEntryHandler) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) ArchiveException(org.hibernate.boot.archive.spi.ArchiveException) ArchiveException(org.hibernate.boot.archive.spi.ArchiveException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) BufferedInputStream(java.io.BufferedInputStream)

Example 52 with BufferedInputStream

use of java.io.BufferedInputStream in project j2objc by google.

the class MockWebServer method serveConnection.

private void serveConnection(final Socket raw) {
    String name = "MockWebServer-" + raw.getRemoteSocketAddress();
    requestExecutor.execute(namedRunnable(name, new Runnable() {

        int sequenceNumber = 0;

        public void run() {
            try {
                processConnection();
            } catch (Exception e) {
                logger.log(Level.WARNING, "MockWebServer connection failed", e);
            }
        }

        public void processConnection() throws Exception {
            Socket socket;
            if (sslSocketFactory != null) {
                if (tunnelProxy) {
                    createTunnel();
                }
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (socketPolicy == FAIL_HANDSHAKE) {
                    dispatchBookkeepingRequest(sequenceNumber, raw);
                    processHandshakeFailure(raw);
                    return;
                }
                socket = sslSocketFactory.createSocket(raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
                SSLSocket sslSocket = (SSLSocket) socket;
                sslSocket.setUseClientMode(false);
                openClientSockets.put(socket, true);
                sslSocket.startHandshake();
                openClientSockets.remove(raw);
            } else {
                socket = raw;
            }
            InputStream in = new BufferedInputStream(socket.getInputStream());
            OutputStream out = new BufferedOutputStream(socket.getOutputStream());
            while (processOneRequest(socket, in, out)) {
            }
            if (sequenceNumber == 0) {
                logger.warning("MockWebServer connection didn't make a request");
            }
            in.close();
            out.close();
            socket.close();
            openClientSockets.remove(socket);
        }

        /**
             * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response
             * is dispatched.
             */
        private void createTunnel() throws IOException, InterruptedException {
            while (true) {
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) {
                    throw new IllegalStateException("Tunnel without any CONNECT!");
                }
                if (socketPolicy == SocketPolicy.UPGRADE_TO_SSL_AT_END)
                    return;
            }
        }

        /**
             * Reads a request and writes its response. Returns true if a request
             * was processed.
             */
        private boolean processOneRequest(Socket socket, InputStream in, OutputStream out) throws IOException, InterruptedException {
            RecordedRequest request = readRequest(socket, in, out, sequenceNumber);
            if (request == null) {
                return false;
            }
            requestCount.incrementAndGet();
            requestQueue.add(request);
            MockResponse response = dispatcher.dispatch(request);
            if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AFTER_READING_REQUEST) {
                logger.info("Received request: " + request + " and disconnected without responding");
                return false;
            }
            writeResponse(out, response);
            if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) {
                in.close();
                out.close();
            } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) {
                socket.shutdownInput();
            } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) {
                socket.shutdownOutput();
            }
            logger.info("Received request: " + request + " and responded: " + response);
            sequenceNumber++;
            return true;
        }
    }));
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) BufferedInputStream(java.io.BufferedInputStream) BufferedOutputStream(java.io.BufferedOutputStream) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket)

Example 53 with BufferedInputStream

use of java.io.BufferedInputStream in project j2objc by google.

the class OutputPropertiesFactory method loadPropertiesFile.

/**
     * Load the properties file from a resource stream.  If a
     * key name such as "org.apache.xslt.xxx", fix up the start of
     * string to be a curly namespace.  If a key name starts with
     * "xslt.output.xxx", clip off "xslt.output.".  If a key name *or* a
     * key value is discovered, check for : in the text, and
     * fix it up to be ":", since earlier versions of the JDK do not
     * handle the escape sequence (at least in key names).
     *
     * @param resourceName non-null reference to resource name.
     * @param defaults Default properties, which may be null.
     */
private static Properties loadPropertiesFile(final String resourceName, Properties defaults) throws IOException {
    // This static method should eventually be moved to a thread-specific class
    // so that we can cache the ContextClassLoader and bottleneck all properties file
    // loading throughout Xalan.
    Properties props = new Properties(defaults);
    InputStream is = null;
    BufferedInputStream bis = null;
    try {
        if (ACCESS_CONTROLLER_CLASS != null) {
            is = (InputStream) AccessController.doPrivileged(new PrivilegedAction() {

                public Object run() {
                    return OutputPropertiesFactory.class.getResourceAsStream(resourceName);
                }
            });
        } else {
            // User may be using older JDK ( JDK < 1.2 )
            is = OutputPropertiesFactory.class.getResourceAsStream(resourceName);
        }
        bis = new BufferedInputStream(is);
        props.load(bis);
    } catch (IOException ioe) {
        if (defaults == null) {
            throw ioe;
        } else {
            throw new WrappedRuntimeException(Utils.messages.createMessage(MsgKey.ER_COULD_NOT_LOAD_RESOURCE, new Object[] { resourceName }), ioe);
        //"Could not load '"+resourceName+"' (check CLASSPATH), now using just the defaults ", ioe);
        }
    } catch (SecurityException se) {
        // Repeat IOException handling for sandbox/applet case -sc
        if (defaults == null) {
            throw se;
        } else {
            throw new WrappedRuntimeException(Utils.messages.createMessage(MsgKey.ER_COULD_NOT_LOAD_RESOURCE, new Object[] { resourceName }), se);
        //"Could not load '"+resourceName+"' (check CLASSPATH, applet security), now using just the defaults ", se);
        }
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (is != null) {
            is.close();
        }
    }
    // Note that we're working at the HashTable level here,
    // and not at the Properties level!  This is important
    // because we don't want to modify the default properties.
    // NB: If fixupPropertyString ends up changing the property
    // name or value, we need to remove the old key and re-add
    // with the new key and value.  However, then our Enumeration
    // could lose its place in the HashTable.  So, we first
    // clone the HashTable and enumerate over that since the
    // clone will not change.  When we migrate to Collections,
    // this code should be revisited and cleaned up to use
    // an Iterator which may (or may not) alleviate the need for
    // the clone.  Many thanks to Padraig O'hIceadha
    // <padraig@gradient.ie> for finding this problem.  Bugzilla 2000.
    Enumeration keys = ((Properties) props.clone()).keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        // Now check if the given key was specified as a
        // System property. If so, the system property
        // overides the default value in the propery file.
        String value = null;
        try {
            value = System.getProperty(key);
        } catch (SecurityException se) {
        // No-op for sandbox/applet case, leave null -sc
        }
        if (value == null)
            value = (String) props.get(key);
        String newKey = fixupPropertyString(key, true);
        String newValue = null;
        try {
            newValue = System.getProperty(newKey);
        } catch (SecurityException se) {
        // No-op for sandbox/applet case, leave null -sc
        }
        if (newValue == null)
            newValue = fixupPropertyString(value, false);
        else
            newValue = fixupPropertyString(newValue, false);
        if (key != newKey || value != newValue) {
            props.remove(key);
            props.put(newKey, newValue);
        }
    }
    return props;
}
Also used : Enumeration(java.util.Enumeration) BufferedInputStream(java.io.BufferedInputStream) PrivilegedAction(java.security.PrivilegedAction) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Properties(java.util.Properties) WrappedRuntimeException(org.apache.xml.serializer.utils.WrappedRuntimeException)

Example 54 with BufferedInputStream

use of java.io.BufferedInputStream in project j2objc by google.

the class FileURLConnection method connect.

/**
     * This methods will attempt to obtain the input stream of the file pointed
     * by this <code>URL</code>. If the file is a directory, it will return
     * that directory listing as an input stream.
     *
     * @throws IOException
     *             if an IO error occurs while connecting
     */
@Override
public void connect() throws IOException {
    File f = new File(filename);
    if (f.isDirectory()) {
        isDir = true;
        is = getDirectoryListing(f);
    // use -1 for the contentLength
    } else {
        is = new BufferedInputStream(new FileInputStream(f));
        length = f.length();
    }
    connected = true;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 55 with BufferedInputStream

use of java.io.BufferedInputStream in project j2objc by google.

the class OldBufferedInputStreamTest method test_read.

public void test_read() throws IOException {
    int c = is.read();
    assertTrue("Test 1: Incorrect character read.", c == fileString.charAt(0));
    byte[] bytes = new byte[256];
    for (int i = 0; i < 256; i++) {
        bytes[i] = (byte) i;
    }
    BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(bytes), 5);
    // Read more bytes than are buffered.
    for (int i = 0; i < 10; i++) {
        assertEquals("Test 2: Incorrect byte read;", bytes[i], in.read());
    }
    in.close();
    try {
        in.read();
        fail("Test 3: IOException expected.");
    } catch (IOException e) {
    // Expected.
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException)

Aggregations

BufferedInputStream (java.io.BufferedInputStream)1700 FileInputStream (java.io.FileInputStream)854 IOException (java.io.IOException)836 InputStream (java.io.InputStream)707 File (java.io.File)449 BufferedOutputStream (java.io.BufferedOutputStream)228 FileOutputStream (java.io.FileOutputStream)218 DataInputStream (java.io.DataInputStream)168 ByteArrayInputStream (java.io.ByteArrayInputStream)159 FileNotFoundException (java.io.FileNotFoundException)147 URL (java.net.URL)147 ZipEntry (java.util.zip.ZipEntry)123 ByteArrayOutputStream (java.io.ByteArrayOutputStream)112 OutputStream (java.io.OutputStream)100 ZipInputStream (java.util.zip.ZipInputStream)72 GZIPInputStream (java.util.zip.GZIPInputStream)68 ArrayList (java.util.ArrayList)62 HashMap (java.util.HashMap)62 HttpURLConnection (java.net.HttpURLConnection)61 ObjectInputStream (java.io.ObjectInputStream)56