Example usage for java.io InputStream reset

List of usage examples for java.io InputStream reset

Introduction

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

Prototype

public synchronized void reset() throws IOException 

Source Link

Document

Repositions this stream to the position at the time the mark method was last called on this input stream.

Usage

From source file:com.alibaba.simpleimage.ScaleSpeedTest.java

public void doScale(File rootDir, String imgName, Scaler scaler, int times, float scale) throws Exception {
    FileInputStream inputStream = new FileInputStream(new File(rootDir, imgName));

    ByteArrayOutputStream temp = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, temp);//from  w w w. j  a  v a  2  s. c o  m
    IOUtils.closeQuietly(inputStream);

    InputStream img = temp.toInputStream();
    temp = null;

    System.out.println("***********Scale Performance Test**************");
    long start = 0L, end = 0L, total = 0L;

    img.reset();

    ReadRender rr = new ReadRender(img, false);
    ImageWrapper wi = rr.render();
    BufferedImage bi = wi.getAsBufferedImage();

    for (int i = 0; i < times; i++) {
        start = System.currentTimeMillis();
        PlanarImage zoomOp = scaler.doScale(PlanarImage.wrapRenderedImage(bi), scale);
        zoomOp.getAsBufferedImage();
        end = System.currentTimeMillis();
        total += (end - start);
    }

    System.out.printf("Scale alg : %s \n", scaler.getName());
    System.out.println("Image : " + imgName);
    System.out.printf("Times : %d\n", times);
    System.out.printf("Total time : %d ms\n", total);
    System.out.printf("Average time : %.2f ms\n", ((double) total / times));
}

From source file:org.jbpm.bpel.xml.ProcessWsdlLocator.java

private void upgradeWsdlDocumentIfNeeded(InputSource source) {
    // get the thread-local document parser
    DocumentBuilder documentParser = XmlUtil.getDocumentBuilder();

    // install our problem handler as document parser's error handler
    documentParser.setErrorHandler(problemHandler.asSaxErrorHandler());

    // parse content
    Document document;//w w  w .  j  av a 2 s. c o m
    try {
        document = documentParser.parse(source);
        // halt on parse errors
        if (problemHandler.getProblemCount() > 0)
            return;
    } catch (IOException e) {
        Problem problem = new Problem(Problem.LEVEL_ERROR, "document is not readable", e);
        problem.setResource(latestImportURI);
        problemHandler.add(problem);
        return;
    } catch (SAXException e) {
        Problem problem = new Problem(Problem.LEVEL_ERROR, "document contains invalid xml", e);
        problem.setResource(latestImportURI);
        problemHandler.add(problem);
        return;
    } finally {
        // reset error handling behavior
        documentParser.setErrorHandler(null);
    }

    // check whether the wsdl document requires upgrading
    if (hasUpgradableElements(document)) {
        try {
            // create wsdl upgrader
            Transformer wsdlUpgrader = getWsdlUpgradeTemplates().newTransformer();

            // install our problem handler as transformer's error listener
            wsdlUpgrader.setErrorListener(problemHandler.asTraxErrorListener());

            // upgrade into memory stream
            ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
            wsdlUpgrader.transform(new DOMSource(document), new StreamResult(resultStream));

            // replace existing source with upgraded document
            source.setByteStream(new ByteArrayInputStream(resultStream.toByteArray()));

            log.debug("upgraded wsdl document: " + latestImportURI);
        } catch (TransformerException e) {
            Problem problem = new Problem(Problem.LEVEL_ERROR, "wsdl upgrade failed", e);
            problem.setResource(latestImportURI);
            problemHandler.add(problem);
        }
    } else {
        // if the source is a stream, reset it
        InputStream sourceStream = source.getByteStream();
        if (sourceStream != null) {
            try {
                sourceStream.reset();
            } catch (IOException e) {
                log.error("could not reset source stream: " + latestImportURI, e);
            }
        }
    }
}

From source file:cn.vlabs.clb.server.ui.frameservice.image.ImageUtil.java

private boolean processScaleCommand(InputStream ins, OutputStream ous, SizePair dstPair, String type,
        boolean isMultiple) {
    try {/*from w ww  . java  2  s. co  m*/
        ins.reset();
    } catch (IOException e1) {
        LOG.error(e1.getMessage(), e1);
    }
    ConvertCmd convert = new ConvertCmd(true);
    try {
        Pipe pipeIn = new Pipe(ins, null);
        Pipe pipeOut = new Pipe(null, ous);
        convert.setInputProvider(pipeIn);
        convert.setOutputConsumer(pipeOut);
        IMOperation op = null;
        if (isMultiple) {
            op = resizeDynamicGifOperation(type, dstPair);
        } else {
            op = resizeStaticImageOperation(type, dstPair);
        }
        convert.run(op);
    } catch (IOException | InterruptedException | IM4JavaException e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:com.epam.wilma.browsermob.transformer.helper.InputStreamConverter.java

/**
 * Converts an inputStream to a String with Apache Commons' IOUtils.
 * @param inputStream InputStream to convert
 * @return converted stream//from   w ww  .j a  va 2s .co m
 * @throws ApplicationException when IOUtils or mark/reset fails
 */
public String getStringFromStream(final InputStream inputStream) throws ApplicationException {
    String result = "";
    if (inputStream != null) {
        try {
            int extendedReadLimit = inputStream.available() + BUFFER_SIZE;
            inputStream.mark(extendedReadLimit);
            result = IOUtils.toString(inputStream);
            inputStream.reset();
        } catch (IOException e) {
            throw new ApplicationException("Could not transform request input stream into string!", e);
        }
    }
    return result;
}

From source file:com.haulmont.cuba.web.gui.components.WebEmbedded.java

@Override
public void setSource(String fileName, final InputStream src) {
    if (src != null) {
        resource = new StreamResource((StreamResource.StreamSource) () -> {
            try {
                src.reset();
            } catch (IOException e) {
                Logger log = LoggerFactory.getLogger(WebEmbedded.this.getClass());
                log.debug("Ignored IOException on stream reset", e);
            }/* w w  w. j  a  v  a  2 s  .  co  m*/
            return src;
        }, fileName);
        component.setSource(resource);
    } else {
        resetSource();
    }
}

From source file:TypeUtil.java

public static byte[] readLine(InputStream in) throws IOException {
    byte[] buf = new byte[256];

    int i = 0;/*from w  w  w.  ja v  a 2  s . c  om*/
    int loops = 0;
    int ch = 0;

    while (true) {
        ch = in.read();
        if (ch < 0)
            break;
        loops++;

        // skip a leading LF's
        if (loops == 1 && ch == LF)
            continue;

        if (ch == CR || ch == LF)
            break;

        if (i >= buf.length) {
            byte[] old_buf = buf;
            buf = new byte[old_buf.length + 256];
            System.arraycopy(old_buf, 0, buf, 0, old_buf.length);
        }
        buf[i++] = (byte) ch;
    }

    if (ch == -1 && i == 0)
        return null;

    // skip a trailing LF if it exists
    if (ch == CR && in.available() >= 1 && in.markSupported()) {
        in.mark(1);
        ch = in.read();
        if (ch != LF)
            in.reset();
    }

    byte[] old_buf = buf;
    buf = new byte[i];
    System.arraycopy(old_buf, 0, buf, 0, i);

    return buf;
}

From source file:com.intuit.karate.http.jersey.LoggingInterceptor.java

@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatus()).append('\n');
    logHeaders(sb, id, '<', response.getHeaders());
    if (response.hasEntity() && isPrintable(response.getMediaType())) {
        InputStream is = response.getEntityStream();
        if (!is.markSupported()) {
            is = new BufferedInputStream(is);
        }// w  ww  .ja  v  a 2 s  .  c o m
        is.mark(Integer.MAX_VALUE);
        String buffer = IOUtils.toString(is, UTF8);
        sb.append(buffer).append('\n');
        is.reset();
        response.setEntityStream(is); // in case it was swapped
    }
    logger.debug(sb.toString());
}

From source file:org.xwiki.filter.xar.internal.input.XARInputFilterStream.java

private Boolean isZip(InputStream stream) throws IOException {
    if (!stream.markSupported()) {
        // ZIP by default
        return null;
    }/*from w w w  .j  a  va  2  s.c om*/

    final byte[] signature = new byte[12];
    stream.mark(signature.length);
    int signatureLength = stream.read(signature);
    stream.reset();

    return ZipArchiveInputStream.matches(signature, signatureLength);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.BodyPartAttachment.java

public String getUrl() {
    if (tempFile == null) {
        String contentType = getContentType();
        int ix = contentType.lastIndexOf('/');
        int iy = -1;
        if (ix != -1)
            iy = contentType.indexOf(';', ix);

        try {/*from  w  ww. j  a va  2s. co  m*/
            tempFile = File.createTempFile("response-attachment", (ix == -1 ? ".dat"
                    : "." + (iy == -1 ? contentType.substring(ix + 1) : contentType.substring(ix + 1, iy))));

            OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
            InputStream inputStream = getInputStream();
            out.write(Tools.readAll(inputStream, 0).toByteArray());
            out.flush();
            out.close();

            inputStream.reset();
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    try {
        return tempFile.toURI().toURL().toString();
    } catch (MalformedURLException e) {
        SoapUI.logError(e);
        return null;
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageWritable.java

/**
 * Copy all of input to output.//from w w  w  .  j  a v a2 s .  co m
 * @param in The input stream to writeInputStreamToResponse from
 * @param out The output to write to
 * @throws IOException When an error occurs writing to the response Writer
 */
protected void writeInputStreamToResponse(InputStream in, Writer out) throws IOException {
    try {
        in.reset();
        Reader reader = new InputStreamReader(in, "UTF-8");
        char[] buf = new char[8192];

        for (;;) {
            int read = reader.read(buf);
            if (read <= 0)
                break;
            out.write(buf, 0, read);
        }
    } finally {
        out.close();
        in.close();
    }
}