Example usage for java.io InputStream getClass

List of usage examples for java.io InputStream getClass

Introduction

In this page you can find the example usage for java.io InputStream getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.norconex.commons.lang.io.IOUtil.java

/**
 * Wraps the input stream in a {@link BufferedInputStream} if not a subclass
 * already.// ww  w  .  j av a 2s  . co m
 * @param in the input stream to wrap if needed
 * @return buffered input stream
 * @since 1.6.0
 */
public static BufferedInputStream toBufferedInputStream(InputStream in) {
    if (in == null) {
        throw new IllegalArgumentException("InputStream cannot be null");
    }
    if (BufferedInputStream.class.isAssignableFrom(in.getClass())) {
        return (BufferedInputStream) in;
    }
    return new BufferedInputStream(in);
}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

private static int readUByte(InputStream in) throws IOException {
    int b = in.read();
    if (b == -1) {
        throw new EOFException();
    }/*from  w ww.  java2  s.com*/
    if (b < -1 || b > 255) {
        // Report on this.in, not argument in; see read{Header, Trailer}.
        throw new IOException(in.getClass().getName() + ".read() returned value out of range -1..255: " + b);
    }
    return b;
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Convenient way of sending data from an input stream to an output stream
 * in the most efficient way possible/*  w w  w.j  a v a2s .  com*/
 * If the bCloseOutput flag is false, then the output stream remains open
 * so that further writes can be made to the stream
 *
 * @param in           Input stream to read from
 * @param out          Output stream to write to
 * @param closeOutput  True if the output stream should be closed on exit
 * @param ignoreErrors True if this method must not throw any socket errors
 *
 * @throws IOException if an error occurs
 */
public static void pipeInputToOutputStream(InputStream in, OutputStream out, boolean closeOutput,
        boolean ignoreErrors) throws IOException {

    OutputStream bufferedOut = out;
    InputStream bufferedIn = in;

    if (in != null && out != null) {
        try {
            // Buffer the streams if they aren't already

            if (!bufferedOut.getClass().equals(BufferedOutputStream.class)) {
                bufferedOut = new BufferedOutputStream(bufferedOut, DEFAULT_BUFFER_SIZE);
            }
            if (!bufferedIn.getClass().equals(BufferedInputStream.class)) {
                bufferedIn = new BufferedInputStream(bufferedIn, DEFAULT_BUFFER_SIZE);
            }

            // Push the data

            int iTmp;
            while ((iTmp = bufferedIn.read()) != -1) {
                bufferedOut.write((byte) iTmp);
            }
            bufferedOut.flush();
            out.flush();
        } catch (IOException e) {
            if (!ignoreErrors && !(e instanceof java.net.SocketException)) {
                logger.error(e.getMessage());
                throw e;
            } else {
                logger.debug(e.getMessage());
            }
        } finally {
            bufferedIn.close();
            if (closeOutput) {
                bufferedOut.close();
            }
        }
    }
}

From source file:com.trailmagic.image.ui.ImageManifestationController.java

@RequestMapping("/mf/by-id/{imageId}")
public ModelAndView imageById(HttpServletResponse res, @PathVariable("imageId") Long imageId) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    HeavyImageManifestation mf = imageManifestationRepository.getHeavyById(imageId);

    java.io.InputStream dataStream = mf.getData().getBinaryStream();
    res.setContentLength((int) mf.getData().length());

    log.debug("Passing manifestation data stream to view (type: " + dataStream.getClass() + ")");
    model.put(InputStreamView.STREAM_KEY, dataStream);
    model.put(InputStreamView.CONTENT_TYPE_KEY, mf.getFormat());
    if (mf.getName() != null) {
        model.put(InputStreamView.CONTENT_DISPOSITION_KEY, "inline; filename=" + mf.getName() + ";");
    }//from   w  w  w. j  ava  2  s.c o  m
    return new ModelAndView(new InputStreamView(), model);
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

@Override
public PART uploadPart(final UPLOAD upload, final int partNumber, final InputStream inputStream)
        throws IOException {
    Validate.notNull(inputStream, "InputStream must not be null");

    if (inputStream.getClass().equals(FileInputStream.class)) {
        final FileInputStream fin = (FileInputStream) inputStream;
        final long contentLength = fin.getChannel().size();
        return uploadPart(upload, partNumber, contentLength, inputStream);
    }//from   ww w .  jav  a2 s  . co  m

    HttpEntity entity = new MantaInputStreamEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM);

    return uploadPart(upload, partNumber, entity, null);
}

From source file:org.springmodules.cache.impl.Element.java

private void close(InputStream closeable) {
    if (closeable == null) {
        return;//from   w  ww .  j  a  va 2  s .  c o  m
    }

    try {
        closeable.close();
    } catch (Exception exception) {
        String clazz = closeable.getClass().getName();
        logger.error("Unable to close " + clazz, exception);
    }
}

From source file:com.fseport.sftp.SftpUtil.java

public void setErrorOccurredOnInputStream(InputStream inputStream) {

    // If an exception occurs and the keepFileOnError property is
    // true, keep the file on the originating endpoint
    // Note: this is only supported when using the sftp transport on
    // both inbound & outbound
    if (inputStream != null) {
        if (inputStream instanceof ErrorOccurredDecorator) {
            // Ensure that the SftpInputStream or
            // SftpFileArchiveInputStream knows about the error and
            // dont delete the file
            ((ErrorOccurredDecorator) inputStream).setErrorOccurred();

        } else {// w  w w . j ava 2 s.c  o  m
            logger.warn("Class " + inputStream.getClass().getName()
                    + " did not implement the 'ErrorOccurred' decorator, errorOccured=true could not be set.");
        }
    }
}

From source file:com.streamsets.pipeline.lib.remote.TestChrootSFTPClient.java

@Test
public void testOpenForReading() throws Exception {
    File file = testFolder.newFile("file.txt");
    String text = "hello";
    Files.write(text.getBytes(Charset.forName("UTF-8")), file);
    Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));

    path = testFolder.getRoot().getAbsolutePath();
    setupSSHD(path);/*from   w  ww  .j  av  a  2  s  .  co m*/
    SSHClient sshClient = createSSHClient();

    for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) {
        // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be
        // equivalent
        for (String p : new String[] { file.getName(), "/" + file.getName(), }) {
            InputStream is = sftpClient.openForReading(p);
            Assert.assertThat(is, instanceOf(RemoteFile.ReadAheadRemoteFileInputStream.class));
            Assert.assertTrue(is.getClass().getName().startsWith(SFTPStreamFactory.class.getCanonicalName()));
            Assert.assertNotNull(is);
            Assert.assertEquals(text, IOUtils.toString(is, Charset.forName("UTF-8")));
            is.close();
        }
    }
}

From source file:com.streamsets.pipeline.lib.remote.TestChrootSFTPClient.java

@Test
public void testOpenForReadingReadAheadInputStreamDisabled() throws Exception {
    File file = testFolder.newFile("file.txt");
    String text = "hello";
    Files.write(text.getBytes(Charset.forName("UTF-8")), file);
    Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));

    path = testFolder.getRoot().getAbsolutePath();
    setupSSHD(path);//ww w .j  a v a  2 s . c  o m
    SSHClient sshClient = createSSHClient();
    final SFTPClient sftpClient = sshClient.newSFTPClient();
    final ChrootSFTPClient chrootSFTPClient = createChrootSFTPClient(sftpClient, path, false, null, false,
            true);
    final InputStream is = chrootSFTPClient.openForReading(file.getName());
    try {
        Assert.assertThat(is, instanceOf(RemoteFile.RemoteFileInputStream.class));
        Assert.assertTrue(is.getClass().getName().startsWith(SFTPStreamFactory.class.getCanonicalName()));
        Assert.assertNotNull(is);
        Assert.assertEquals(text, IOUtils.toString(is, Charset.forName("UTF-8")));
    } finally {
        is.close();
    }
}

From source file:de.zib.sfs.WrappedFSDataInputStream.java

/**
 * Gets the datanode that was last read from as a string. Should be called
 * after the first read operation has been performed.
 * //from   www.j a v  a  2 s  .  c  o  m
 * @return "->" + hostname of the datanode, or empty string if the
 *         information is not available
 */
private String getDatanodeHostNameString() {
    if (this.datanodeHostnameSupplier == null) {
        if (this.in instanceof HdfsDataInputStream) {
            // call Hadoop's method directly
            final HdfsDataInputStream hdfsIn = (HdfsDataInputStream) this.in;
            if (hdfsIn.getCurrentDatanode() != null) {
                this.datanodeHostnameSupplier = () -> hdfsIn.getCurrentDatanode().getHostName();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using datanodeHostNameSupplier from Hadoop.");
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("datanodeHostNameSupplier from Hadoop has no DataNode information.");
                }
                this.datanodeHostnameSupplier = () -> "";
            }
        } else {
            try {
                // Check if there's an appropriately named method available
                // that returns the hostname of the current node that is
                // being read from. Using the lambda factory provides almost
                // direct invocation performance.
                MethodHandles.Lookup methodHandlesLookup = MethodHandles.lookup();

                // try this stream or the one it wraps
                Method getCurrentDatanodeHostNameMethod = null;
                InputStream bindToStream = null;
                try {
                    getCurrentDatanodeHostNameMethod = this.in.getClass()
                            .getDeclaredMethod("getCurrentDatanodeHostName");
                    bindToStream = this.in;
                } catch (NoSuchMethodException e) {
                    getCurrentDatanodeHostNameMethod = this.in.getWrappedStream().getClass()
                            .getDeclaredMethod("getCurrentDatanodeHostName");
                    bindToStream = this.in.getWrappedStream();
                }

                MethodHandle datanodeHostNameSupplierTarget = LambdaMetafactory.metafactory(methodHandlesLookup,
                        "get", MethodType.methodType(Supplier.class, bindToStream.getClass()),
                        MethodType.methodType(Object.class),
                        methodHandlesLookup.unreflect(getCurrentDatanodeHostNameMethod),
                        MethodType.methodType(Object.class)).getTarget();
                this.datanodeHostnameSupplier = (Supplier<String>) datanodeHostNameSupplierTarget
                        .bindTo(bindToStream).invoke();

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using 'getCurrentDatanodeHostName' as datanodeHostNameSupplier.");
                }
            } catch (Throwable t) {
                this.datanodeHostnameSupplier = () -> "";
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No datanodeHostNameSupplier available.", t);
                }
            }
        }
    }

    // handle cases where we have to perform a reverse lookup if
    // hostname is an IP
    String dnHostname = this.datanodeHostnameSupplier.get();
    String cachedHostname = HOSTNAME_CACHE.get(dnHostname);
    if (cachedHostname == null) {
        try {
            // strip port if necessary
            int portIndex = dnHostname.indexOf(":");
            cachedHostname = InetAddress
                    .getByName(portIndex == -1 ? dnHostname : dnHostname.substring(0, portIndex)).getHostName();
        } catch (UnknownHostException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not determine hostname for " + dnHostname, e);
            }
            cachedHostname = "";
        }
        HOSTNAME_CACHE.put(dnHostname, cachedHostname);
    }
    return cachedHostname;
}