Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:EditorDropTarget4.java

protected boolean dropContent(Transferable transferable, DropTargetDropEvent dtde) {
    if (!pane.isEditable()) {
        // Can't drop content on a read-only text control
        return false;
    }/*from   w  w  w .j  a v a 2s .c  om*/

    try {
        // Check for a match with the current content type
        DataFlavor[] flavors = dtde.getCurrentDataFlavors();

        DataFlavor selectedFlavor = null;

        // Look for either plain text or a String.
        for (int i = 0; i < flavors.length; i++) {
            DataFlavor flavor = flavors[i];
            DnDUtils.debugPrintln("Drop MIME type " + flavor.getMimeType() + " is available");
            if (flavor.equals(DataFlavor.plainTextFlavor) || flavor.equals(DataFlavor.stringFlavor)) {
                selectedFlavor = flavor;
                break;
            }
        }

        if (selectedFlavor == null) {
            // No compatible flavor - should never happen
            return false;
        }

        DnDUtils.debugPrintln("Selected flavor is " + selectedFlavor.getHumanPresentableName());

        // Get the transferable and then obtain the data
        Object data = transferable.getTransferData(selectedFlavor);

        DnDUtils.debugPrintln("Transfer data type is " + data.getClass().getName());

        String insertData = null;
        if (data instanceof InputStream) {
            // Plain text flavor
            String charSet = selectedFlavor.getParameter("charset");
            InputStream is = (InputStream) data;
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            try {
                insertData = new String(bytes, charSet);
            } catch (UnsupportedEncodingException e) {
                // Use the platform default encoding
                insertData = new String(bytes);
            }
        } else if (data instanceof String) {
            // String flavor
            insertData = (String) data;
        }

        if (insertData != null) {
            int selectionStart = pane.getCaretPosition();
            pane.replaceSelection(insertData);
            pane.select(selectionStart, selectionStart + insertData.length());
            return true;
        }
        return false;
    } catch (Exception e) {
        return false;
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.license.impl.PersonalLicenseServiceImpl.java

@Override
@Transactional//from  ww  w.ja  va 2 s. c om
public void update(PersonalLicense transientObject) {

    try {
        // XXX WORKAROUND for Hibernate pre 4.0, update entity with blob this way.
        PersonalLicense merged = personalLicenseDao.merge(transientObject);
        InputStream fileContentStream = transientObject.getFileContentStream();
        if (fileContentStream != null) {
            Blob createBlob;
            createBlob = personalLicenseDao.getSessionFactory().getCurrentSession().getLobHelper()
                    .createBlob(fileContentStream, fileContentStream.available());
            merged.setAttachmentContent(createBlob);
            personalLicenseDao.update(merged);
        }
    } catch (HibernateException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:de.decidr.model.XmlToolsTest.java

/**
 * Uses the thread context classloader to load the specified resource into a
 * byte array. Returns <code>null</code> if the resource isn't found.
 *//*w w w .  j  a  va2 s.c  om*/
private byte[] getResourceAsByteArray(String name) {
    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
    try {
        try {
            if (stream == null) {
                return null;
            }
            ByteArrayOutputStream result = new ByteArrayOutputStream(stream.available());
            IOUtils.copy(stream, result);
            return result.toByteArray();
        } finally {
            if (stream instanceof InputStream) {
                stream.close();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.gwt.dev.shell.CompilingClassLoader.java

private static byte[] getClassBytesFromStream(InputStream is) throws IOException {
    try {/*  w  w w .ja v a2  s . c  om*/
        byte classBytes[] = new byte[is.available()];
        int read = 0;
        while (read < classBytes.length) {
            read += is.read(classBytes, read, classBytes.length - read);
        }
        return classBytes;
    } finally {
        Utility.close(is);
    }
}

From source file:com.armorize.hackalert.extractor.msword.MSExtractor.java

/**
 * Extracts properties and text from an MS Document input stream
 *//*from   w w  w .  j a  va  2 s. c  om*/
protected void extract(InputStream input) throws Exception {
    // First, extract properties
    this.reader = new POIFSReader();
    this.properties = new PropertiesBroker();
    this.reader.registerListener(new PropertiesReaderListener(this.properties),
            SummaryInformation.DEFAULT_STREAM_NAME);
    input.reset();
    if (input.available() > 0) {
        reader.read(input);
    }
    // Then, extract text
    input.reset();
    this.text = extractText(input);
}

From source file:com.breel.wearables.shadowclock.graphics.ShapeShadow.java

private String loadJSONFromAsset(String file) {
    String json = null;/*  w  w w . j a v  a2 s.  co  m*/
    try {
        InputStream is = this.context.getAssets().open("json_lowpoly/" + file);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

From source file:org.openrepose.filters.translation.TranslationFilter.java

public void handleResponse(HttpServletRequestWrapper request, HttpServletResponseWrapper response) {
    MediaType contentType = HttpServletWrappersHelper.getContentType(response);
    List<MediaType> acceptValues = HttpServletWrappersHelper.getAcceptValues(request);
    List<XmlChainPool> pools = getHandlerChainPool("", contentType, acceptValues,
            String.valueOf(response.getStatus()), new ArrayList<>(responseProcessorPools));

    if (!pools.isEmpty()) {
        try {//from   w ww .  j  av  a2s .c  om
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            TranslationResult result = null;
            for (XmlChainPool pool : pools) {
                final InputStream in = response.getOutputStreamAsInputStream();
                if (in != null && in.available() > 0) {
                    result = pool.executePool(
                            new TranslationPreProcessor(in, contentType, true).getBodyStream(), baos,
                            getInputParameters(request, response, result));

                    if (result.isSuccess()) {
                        result.applyResults(request, response);
                        if (StringUtilities.isNotBlank(pool.getResultContentType())) {
                            contentType = HttpServletWrappersHelper.getContentType(pool.getResultContentType());
                            response.replaceHeader(CONTENT_TYPE, contentType.getValue());
                        }
                        response.setOutput(new ByteArrayInputStream(baos.toByteArray()));
                    } else {
                        response.setStatus(SC_INTERNAL_SERVER_ERROR);
                        break;
                    }
                }
            }
        } catch (IOException ex) {
            LOG.error("Error executing response transformer chain", ex);
            response.setStatus(SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:eu.eidas.auth.engine.core.impl.SignP12.java

/**
 * Initialize the file configuration./*from   w w  w . j a  va  2  s. com*/
 * 
 * @param fileConf name of the file configuration
 * 
 * @throws SAMLEngineException error at the load from  file configuration
 */
public void init(final String fileConf) throws SAMLEngineException {
    InputStream fileProperties = null;
    setProperties(new Properties());
    try {
        fileProperties = loadFileProperties(fileConf);
        LOG.trace("Loaded " + fileProperties.available() + " bytes");
        getProperties().loadFromXML(fileProperties);

    } catch (InvalidPropertiesFormatException e) {
        LOG.info("Exception: invalid properties format.", e);
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOG.info("Exception: invalid file: " + fileConf, e);
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(fileProperties);
    }
}

From source file:calliope.handler.post.AeseImportHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from w w w . j a  v  a2s . co m*/
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docID = new DocID(contents);
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.XSLT))
                        xslt = getConfig(Config.xslt, contents);
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
    //        System.out.println("Import params received:");
    //        System.out.println("docID="+docID.get());
    //        System.out.println("style="+style);
    //        System.out.println("filterName="+filterName);
    //        System.out.println("database="+database);
    //        System.out.println("splitterName="+splitterName);
    //        System.out.println("stripperName="+stripperName);
    //        System.out.println("encoding="+encoding);
    //        System.out.println("hhExceptions="+hhExceptions);
    //        System.out.println("similarityTest="+similarityTest);
    //        System.out.println("dict="+dict);
    //        System.out.println("xslt="+xslt);
    //        System.out.println("demo="+demo);
    //        System.out.println("textName="+textName);
}

From source file:ch.cyberduck.core.socket.HttpProxyAwareSocket.java

@Override
public void connect(final SocketAddress endpoint, final int timeout) throws IOException {
    if (proxy.type() == Proxy.Type.HTTP) {
        super.connect(proxy.address(), timeout);
        final InetSocketAddress address = (InetSocketAddress) endpoint;
        final OutputStream out = this.getOutputStream();
        IOUtils.write(String.format("CONNECT %s:%d HTTP/1.0\n\n", address.getHostName(), address.getPort()),
                out, Charset.defaultCharset());
        final InputStream in = this.getInputStream();
        final String response = new LineNumberReader(new InputStreamReader(in)).readLine();
        if (null == response) {
            throw new SocketException(String.format("Empty response from HTTP proxy %s",
                    ((InetSocketAddress) proxy.address()).getHostName()));
        }//from w w w  .  j a  v  a  2  s.  c om
        if (response.contains("200")) {
            in.skip(in.available());
        } else {
            throw new SocketException(String.format("Invalid response %s from HTTP proxy %s", response,
                    ((InetSocketAddress) proxy.address()).getHostName()));
        }
    } else {
        super.connect(endpoint, timeout);
    }
}