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:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/files/upload.json", method = RequestMethod.POST)
@ResponseBody/*from www  .java2s .c  om*/
public List<Attachment> uploadFiles(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "fileId", defaultValue = "0", required = false) Long fileId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    Iterator<String> names = request.getFileNames();
    List<Attachment> list = new ArrayList<Attachment>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("fileId: " + fileId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Attachment attachment;
        if (fileId > 0) {
            attachment = attachmentManager.getAttachment(fileId);
            attachment.setName(mpf.getOriginalFilename());
            ((AttachmentImpl) attachment).setInputStream(is);
            ((AttachmentImpl) attachment).setSize((int) mpf.getSize());
        } else {
            attachment = attachmentManager.createAttachment(objectType, user.getUserId(),
                    mpf.getOriginalFilename(), mpf.getContentType(), is, (int) mpf.getSize());
        }

        attachmentManager.saveAttachment(attachment);
        list.add(attachment);
    }
    return list;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@Secured({ "ROLE_USER" })
@RequestMapping(value = "/me/photo/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody/*from w  w  w .j  ava  2 s . c om*/
public List<Image> uploadMyImageWithMedia(
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();

    if (user.isAnonymous())
        throw new UnAuthorizedException();

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());
        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);

            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(2, user.getUserId(), mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody/*from w  ww.  j  av a 2  s .co  m*/
public List<Image> uploadImageWithMedia(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    if (objectType == 1) {
        objectId = user.getCompanyId();
    } else if (objectType == 2) {
        objectId = user.getUserId();
    } else if (objectType == 30) {
        objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
    }

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);
            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(objectType, objectId, mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:architecture.ee.web.spring.controller.SecureWebMgmtDataController.java

@RequestMapping(value = "/mgmt/logo/upload.json", method = RequestMethod.POST)
@ResponseBody//w  w w  .  j  a  va 2s  .co m
public Result uploadLogoImage(
        @RequestParam(value = "objectType", defaultValue = "1", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {

    User user = SecurityHelper.getUser();
    if (objectId == 0) {
        if (objectType == 1) {
            objectId = user.getCompanyId();
        } else if (objectType == 30) {
            objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
        }
    }
    Iterator<String> names = request.getFileNames();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        LogoImage logo = logoManager.createLogoImage();
        logo.setFilename(mpf.getName());
        logo.setImageContentType(mpf.getContentType());
        logo.setImageSize((int) mpf.getSize());
        logo.setObjectType(objectType);
        logo.setObjectId(objectId);
        logo.setPrimary(true);

        logoManager.addLogoImage(logo, mpf.getInputStream());
    }
    return Result.newResult();
}

From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStream.java

/**
 * Reads the HMAC from the end of the underlying stream and returns it as
 * a byte array.//from  w ww . j  av  a 2  s.  c  o  m
 *
 * @return HMAC as byte array
 * @throws MantaIOException thrown when stream is unavailable or invalid
 */
private byte[] readHmacFromEndOfStream() throws MantaIOException {
    final InputStream stream = super.getBackingStream();
    final int hmacSize = this.hmac.getMacSize();
    final byte[] hmacBytes = new byte[hmacSize];

    int totalBytesRead = 0;
    int bytesRead;

    while (totalBytesRead < hmacSize) {
        final int lengthToRead = hmacSize - totalBytesRead;

        try {
            bytesRead = stream.read(hmacBytes, totalBytesRead, lengthToRead);
        } catch (IOException e) {
            String msg = "Unable to read HMAC from the end of stream";
            MantaIOException mioe = new MantaIOException(msg);
            annotateException(mioe);
            mioe.setContextValue("backingStreamClass", stream.getClass());
            mioe.setContextValue("hmacBytesReadTotal", totalBytesRead);
            mioe.setContextValue("hmacBytesExpected", hmacSize);

            throw mioe;
        }

        if (totalBytesRead < hmacSize && bytesRead == EOF) {
            String msg = "No HMAC was stored at the end of the stream";
            MantaIOException e = new MantaIOException(msg);
            annotateException(e);
            throw e;
        }

        totalBytesRead += bytesRead;
    }

    return hmacBytes;
}

From source file:com.bt.aloha.testing.JdbcHelper.java

private String readContent(String filename) {
    Reader r = null;/*  ww w .java 2  s  .c o m*/
    BufferedReader br = null;
    InputStream is = null;
    try {
        is = JdbcHelper.class.getClassLoader().getResourceAsStream(filename);
        r = new InputStreamReader(is);
        br = new BufferedReader(r);
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            if (line.indexOf(SERIAL) != -1)
                sb.append(line.replaceAll(SERIAL, INT_IDENTITY));
            else
                sb.append(line);
        }
        String content = sb.toString();
        return content;
    } catch (Throwable e) {
        throw new IllegalArgumentException(String.format("Couldn't read content of create script %s", filename),
                e);
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, br.getClass().getSimpleName()), e);
        }
        try {
            if (r != null)
                r.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, r.getClass().getSimpleName()), e);
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, is.getClass().getSimpleName()), e);
        }
    }
}

From source file:com.joyent.manta.client.MantaClient.java

/**
 * Puts an object into Manta.// w  w w.j a v  a 2  s .co m
 *
 * @param rawPath The path to the Manta object.
 * @param source {@link InputStream} to copy object data from
 * @param contentLength the total length of the stream (-1 if unknown)
 * @param headers optional HTTP headers to include when copying the object
 * @param metadata optional user-supplied metadata for object
 * @return Manta response object
 * @throws IOException If an IO exception has occurred.
 * @throws MantaClientHttpResponseException If a http status code {@literal > 300} is returned.
 */
public MantaObjectResponse put(final String rawPath, final InputStream source, final long contentLength,
        final MantaHttpHeaders headers, final MantaMetadata metadata) throws IOException {
    Validate.notBlank(rawPath, "rawPath must not be blank");
    Validate.notNull(source, "Input stream must not be null");
    final String path = formatPath(rawPath);

    final ContentType contentType = ContentTypeLookup.findOrDefaultContentType(headers,
            ContentType.APPLICATION_OCTET_STREAM);

    final int preLoadSize = config.getUploadBufferSize();
    final HttpEntity entity;

    /* We don't know how big the stream is, so we read N bytes from it and
     * see if it ends. If it ended, then we just convert that buffer into
     * an entity and pass it. If it didn't end, then we create new stream
     * that concatenates the bytes read with the source stream.
     * Unfortunately, this will put us in a chunked transfer encoding and
     * it will affect performance. */
    if (contentLength < 0) {
        // If our stream is a FileInputStream, then we can pull the size off of it
        if (source.getClass().equals(FileInputStream.class)) {
            FileInputStream fsin = (FileInputStream) source;
            entity = new InputStreamEntity(fsin, fsin.getChannel().size(), contentType);
        } else {
            byte[] preLoad = new byte[preLoadSize];
            int read = IOUtils.read(source, preLoad);

            // The total amount of bytes read was less than the preload size,
            // so we can just return a in-memory non-streaming entity
            if (read < preLoadSize) {
                entity = new ExposedByteArrayEntity(preLoad, 0, read, contentType);
            } else {
                ByteArrayInputStream bin = new ByteArrayInputStream(preLoad);
                SequenceInputStream sin = new SequenceInputStream(bin, source);

                entity = new InputStreamEntity(sin, contentType);
            }

        }
        /* We know how big the stream is, so we can decide if it is within our
         * preload threshold and load it into memory or if it isn't within the
         * threshold, we can pass it on as a streamed entity in non-chunked mode. */
    } else {
        if (contentLength <= preLoadSize && contentLength <= Integer.MAX_VALUE) {
            byte[] preLoad = new byte[(int) contentLength];
            IOUtils.read(source, preLoad);
            entity = new ExposedByteArrayEntity(preLoad, contentType);
        } else {
            entity = new InputStreamEntity(source, contentLength, contentType);
        }
    }

    return httpHelper.httpPut(path, headers, entity, metadata);
}

From source file:homenetapp.HomeNetApp.java

/**
 * Call openStream() without automatic gzip decompression.
 *//*from ww  w  . j a  v a  2 s.  c  o  m*/
public InputStream createInputRaw(String filename) {
    InputStream stream = null;

    if (filename == null) {
        return null;
    }

    if (filename.length() == 0) {
        // an error will be called by the parent function
        //System.err.println("The filename passed to openStream() was empty.");
        return null;
    }

    // safe to check for this as a url first. this will prevent online
    // access logs from being spammed with GET /sketchfolder/http://blahblah
    //        if (filename.indexOf(":") != -1) {  // at least smells like URL
    //            try {
    //                URL url = new URL(filename);
    //                stream = url.openStream();
    //                return stream;
    //
    //            } catch (MalformedURLException mfue) {
    //                // not a url, that's fine
    //            } catch (FileNotFoundException fnfe) {
    //                // Java 1.5 likes to throw this when URL not available. (fix for 0119)
    //                // http://dev.processing.org/bugs/show_bug.cgi?id=403
    //            } catch (IOException e) {
    //                // changed for 0117, shouldn't be throwing exception
    //                e.printStackTrace();
    //                //System.err.println("Error downloading from URL " + filename);
    //                return null;
    //                //throw new RuntimeException("Error downloading from URL " + filename);
    //            }
    //        }
    //
    //        // Moved this earlier than the getResourceAsStream() checks, because
    //        // calling getResourceAsStream() on a directory lists its contents.
    //        // http://dev.processing.org/bugs/show_bug.cgi?id=716
    //        try {
    //            // First see if it's in a data folder. This may fail by throwing
    //            // a SecurityException. If so, this whole block will be skipped.
    //            System.err.println("Load file");
    //            File file = new File(getAppPath(filename));
    //
    //            if (file.isDirectory()) {
    //                return null;
    //            }
    //            if (file.exists()) {
    //                try {
    //                    // handle case sensitivity check
    //                    
    //                    String filePath = file.getCanonicalPath();
    //                    System.err.println("file path: Load file"+filePath);
    //
    //                    String filenameActual = new File(filePath).getName();
    //                    // make sure there isn't a subfolder prepended to the name
    //                    String filenameShort = new File(filename).getName();
    //                    // if the actual filename is the same, but capitalized
    //                    // differently, warn the user.
    //                    //if (filenameActual.equalsIgnoreCase(filenameShort) &&
    //                    //!filenameActual.equals(filenameShort)) {
    //                    if (!filenameActual.equals(filenameShort)) {
    //                        throw new RuntimeException("This file is named "
    //                                + filenameActual + " not "
    //                                + filename + ". Rename the file "
    //                                + "or change your code.");
    //                    }
    //                } catch (IOException e) {
    //                }
    //            }
    //
    //            // if this file is ok, may as well just load it
    //            stream = new FileInputStream(file);
    //            if (stream != null) {
    //                return stream;
    //            }
    //
    //            // have to break these out because a general Exception might
    //            // catch the RuntimeException being thrown above
    //        } catch (IOException ioe) {
    //            System.err.println("File IO Error");
    //            ioe.printStackTrace();
    //        } catch (SecurityException se) {
    //            System.err.println("File Security Error");
    //        }

    // Using getClassLoader() prevents java from converting dots
    // to slashes or requiring a slash at the beginning.
    // (a slash as a prefix means that it'll load from the root of
    // the jar, rather than trying to dig into the package location)
    ClassLoader cl = getClass().getClassLoader();
    //
    //        // by default, data files are exported to the root path of the jar.
    //        // (not the data folder) so check there first.
    //        stream = cl.getResourceAsStream(filename);
    //        if (stream != null) {
    //            String cn = stream.getClass().getName();
    //            // this is an irritation of sun's java plug-in, which will return
    //            // a non-null stream for an object that doesn't exist. like all good
    //            // things, this is probably introduced in java 1.5. awesome!
    //            // http://dev.processing.org/bugs/show_bug.cgi?id=359
    //            if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
    //                return stream;
    //            }
    //        }

    // When used with an online script, also need to check without the
    // data folder, in case it's not in a subfolder called 'data'.
    // http://dev.processing.org/bugs/show_bug.cgi?id=389
    stream = cl.getResourceAsStream(filename);
    if (stream != null) {
        String cn = stream.getClass().getName();
        if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
            return stream;
        }
    }

    try {
        // attempt to load from a local file, used when running as
        // an application, or as a signed applet
        try { // first try to catch any security exceptions
            try {
                stream = new FileInputStream(getAppPath(filename));
                if (stream != null) {
                    return stream;
                }
            } catch (IOException e2) {
            }

            try {
                stream = new FileInputStream(filename);
                if (stream != null) {
                    return stream;
                }
            } catch (IOException e1) {
            }

        } catch (SecurityException se) {
        } // online, whups

    } catch (Exception e) {
        //die(e.getMessage(), e);
        e.printStackTrace();
    }

    return null;
}

From source file:org.apache.airavata.gfac.core.GFacUtils.java

/**
 * Read data from inputStream and convert it to String.
 *
 * @param in/*from  w  ww  .  j  a  va2s  .  c o m*/
 * @return String read from inputStream
 * @throws java.io.IOException
 */
public static String readFromStream(InputStream in) throws IOException {
    try {
        StringBuffer wsdlStr = new StringBuffer();

        int read;

        byte[] buf = new byte[1024];
        while ((read = in.read(buf)) > 0) {
            wsdlStr.append(new String(buf, 0, read));
        }
        return wsdlStr.toString();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.warn("Cannot close InputStream: " + in.getClass().getName(), e);
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.io.FSDataInputStreamWrapper.java

/**
 * This will free sockets and file descriptors held by the stream only when the stream implements
 * org.apache.hadoop.fs.CanUnbuffer. NOT THREAD SAFE. Must be called only when all the clients
 * using this stream to read the blocks have finished reading. If by chance the stream is
 * unbuffered and there are clients still holding this stream for read then on next client read
 * request a new socket will be opened by Datanode without client knowing about it and will serve
 * its read request. Note: If this socket is idle for some time then the DataNode will close the
 * socket and the socket will move into CLOSE_WAIT state and on the next client request on this
 * stream, the current socket will be closed and a new socket will be opened to serve the
 * requests.//from ww  w  .ja v a  2  s  .  c o m
 */
@SuppressWarnings({ "rawtypes" })
public void unbuffer() {
    FSDataInputStream stream = this.getStream(this.shouldUseHBaseChecksum());
    if (stream != null) {
        InputStream wrappedStream = stream.getWrappedStream();
        // CanUnbuffer interface was added as part of HDFS-7694 and the fix is available in Hadoop
        // 2.6.4+ and 2.7.1+ versions only so check whether the stream object implements the
        // CanUnbuffer interface or not and based on that call the unbuffer api.
        final Class<? extends InputStream> streamClass = wrappedStream.getClass();
        if (this.instanceOfCanUnbuffer == null) {
            // To ensure we compute whether the stream is instance of CanUnbuffer only once.
            this.instanceOfCanUnbuffer = false;
            Class<?>[] streamInterfaces = streamClass.getInterfaces();
            for (Class c : streamInterfaces) {
                if (c.getCanonicalName().toString().equals("org.apache.hadoop.fs.CanUnbuffer")) {
                    try {
                        this.unbuffer = streamClass.getDeclaredMethod("unbuffer");
                    } catch (NoSuchMethodException | SecurityException e) {
                        if (isLogTraceEnabled) {
                            LOG.trace("Failed to find 'unbuffer' method in class " + streamClass
                                    + " . So there may be a TCP socket connection "
                                    + "left open in CLOSE_WAIT state.", e);
                        }
                        return;
                    }
                    this.instanceOfCanUnbuffer = true;
                    break;
                }
            }
        }
        if (this.instanceOfCanUnbuffer) {
            try {
                this.unbuffer.invoke(wrappedStream);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                if (isLogTraceEnabled) {
                    LOG.trace("Failed to invoke 'unbuffer' method in class " + streamClass
                            + " . So there may be a TCP socket connection left open in CLOSE_WAIT state.", e);
                }
            }
        } else {
            if (isLogTraceEnabled) {
                LOG.trace("Failed to find 'unbuffer' method in class " + streamClass
                        + " . So there may be a TCP socket connection "
                        + "left open in CLOSE_WAIT state. For more details check "
                        + "https://issues.apache.org/jira/browse/HBASE-9393");
            }
        }
    }
}