Example usage for java.io InputStream skip

List of usage examples for java.io InputStream skip

Introduction

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

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips over and discards n bytes of data from this input stream.

Usage

From source file:org.rhq.core.util.stream.StreamUtil.java

/**
 * Copies data from the input stream to the output stream. The caller has the responsibility to close them. This
 * method allows you to copy a byte range from the input stream. The start byte is the index (where the first byte
 * of the stream is index #0) that starts to be copied. <code>length</code> indicates how many bytes to copy, a
 * negative length indicates copy everything up to the EOF of the input stream.
 *
 * <p>Because this method must leave the given input stream intact in case the caller wants to continue reading from
 * the input stream (that is, in case the caller wants to read the next byte after the final byte read by this
 * method), this method will not wrap the input stream with a buffered input stream. Because of this, this method is
 * less efficient than {@link #copy(InputStream, OutputStream, boolean)}. If you do not care to continue reading
 * from the input stream after this method completes, it is recommended you wrap your input stream in a
 * {@link BufferedInputStream} and pass that buffered stream to this method.</p>
 *
 * @param  input     the originating stream that contains the data to be copied
 * @param  output    the destination stream where the data should be copied to
 * @param  startByte the first byte to copy from the input stream (byte indexes start at #0)
 * @param  length    the number of bytes to copy - if -1, then copy all until EOF
 *
 * @return the number of bytes copied from the input to the output stream (usually length, but if length was larger
 *         than the number of bytes in <code>input</code> after the start byte, this return value will be less than
 *         <code>length</code>.
 *
 * @throws RuntimeException if failed to read or write the data
 *///from   w  w w. java2 s  .c o m
public static long copy(InputStream input, OutputStream output, long startByte, long length)
        throws RuntimeException {
    if (length == 0) {
        return 0;
    }

    if (startByte < 0) {
        throw new IllegalArgumentException("startByte=" + startByte);
    }

    long numBytesCopied = 0;
    int bufferSize = 32768;

    try {
        byte[] buffer = new byte[bufferSize];

        if (startByte > 0) {
            input.skip(startByte); // skips so the next read will read byte #startByte
        }

        // ok to cast to int, if length is less then bufferSize it must be able to fit into int
        int bytesRead = input.read(buffer, 0,
                ((length < 0) || (length >= bufferSize)) ? bufferSize : (int) length);

        while (bytesRead > 0) {
            output.write(buffer, 0, bytesRead);
            numBytesCopied += bytesRead;
            length -= bytesRead;
            bytesRead = input.read(buffer, 0,
                    ((length < 0) || (length >= bufferSize)) ? bufferSize : (int) length);
        }

        output.flush();
    } catch (IOException ioe) {
        throw new RuntimeException("Stream data cannot be copied", ioe);
    }

    return numBytesCopied;
}

From source file:tokyo.northside.io.IOUtils2.java

/**
 * Compare the contents of two Streams to determine if they are equal or not.
 *
 * @param first  first input stream./*from  w  ww .jav a2  s  .c o  m*/
 * @param second  second input stream.
 * @param off     compare from offset
 * @param len     comparison length
 * @return boolean true if content of input streams are equal, true if streams are equal,
 *     otherwise false.
 * @throws IOException when I/O error occurred.
 */
public static boolean contentEquals(final InputStream first, final InputStream second, final long off,
        final long len) throws IOException {
    boolean result;

    if (len < 1) {
        throw new IllegalArgumentException();
    }
    if (off < 0) {
        throw new IllegalArgumentException();
    }
    if (first.equals(second)) {
        return false;
    }

    try {
        byte[] firstBytes = new byte[BUF_LEN];
        byte[] secondBytes = new byte[BUF_LEN];

        if (off > 0) {
            long totalSkipped = 0;
            while (totalSkipped < off) {
                long skipped = first.skip(off - totalSkipped);
                if (skipped == 0) {
                    throw new IOException("Cannot seek offset bytes.");
                }
                totalSkipped += skipped;
            }
            totalSkipped = 0;
            while (totalSkipped < off) {
                long skipped = second.skip(off - totalSkipped);
                if (skipped == 0) {
                    throw new IOException("Cannot seek offset bytes.");
                }
                totalSkipped += skipped;
            }
        }

        long readLengthTotal = 0;
        result = true;
        while (readLengthTotal < len) {
            int readLength = BUF_LEN;
            if (len - readLengthTotal < (long) BUF_LEN) {
                readLength = (int) (len - readLengthTotal);
            }
            int lenFirst = first.read(firstBytes, 0, readLength);
            int lenSecond = second.read(secondBytes, 0, readLength);
            if (lenFirst != lenSecond) {
                result = false;
                break;
            }
            if ((lenFirst < 0) && (lenSecond < 0)) {
                result = true;
                break;
            }
            readLengthTotal += lenFirst;
            if (lenFirst < firstBytes.length) {
                byte[] a = Arrays.copyOfRange(firstBytes, 0, lenFirst);
                byte[] b = Arrays.copyOfRange(secondBytes, 0, lenSecond);
                if (!Arrays.equals(a, b)) {
                    result = false;
                    break;
                }
            } else if (!Arrays.equals(firstBytes, secondBytes)) {
                result = false;
                break;
            }
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (IOException ioe) {
        throw ioe;
    }
    return result;
}

From source file:net.dorokhov.pony.web.server.common.StreamingViewRenderer.java

/**
 * Copy the given byte range of the given input to the given output.
 * @param input The input to copy the given range to the given output for.
 * @param output The output to copy the given range from the given input for.
 * @param start Start of the byte range.
 * @param length Length of the byte range.
 * @throws IOException If something fails at I/O level.
 *//*from w w w  .  j  a v a2 s  .  c  om*/
private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length)
        throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;

    if (inputSize == length) {
        // Write full range.
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
            output.flush();
        }
    } else {
        //noinspection ResultOfMethodCallIgnored
        input.skip(start);
        long toRead = length;

        while ((read = input.read(buffer)) > 0) {
            if ((toRead -= read) > 0) {
                output.write(buffer, 0, read);
                output.flush();
            } else {
                output.write(buffer, 0, (int) toRead + read);
                output.flush();
                break;
            }
        }
    }
}

From source file:tv.phantombot.httpserver.HTTPServerCommon.java

public static void handleYTP(HttpExchange exchange) throws IOException {
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }// w w  w.java 2  s  . c  o  m
    inputStream.close();

    if (requestMethod.equals("GET")) {
        if (uriPath.equals("/ytplayer")) {
            handleFile("/web/ytplayer/index.html", exchange, false, false);
        } else {
            handleFile("/web/" + uriPath, exchange, false, false);
        }
    }
}

From source file:tv.phantombot.httpserver.HTTPServerCommon.java

public static void handlePanel(HttpExchange exchange) throws IOException {
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }/*from   w w w .j  ava 2 s  .c  o m*/
    inputStream.close();

    if (requestMethod.equals("GET")) {
        if (uriPath.equals("/panel")) {
            HTTPServerCommon.handleFile("/web/panel/index.html", exchange, false, false);
        } else {
            HTTPServerCommon.handleFile("/web/" + uriPath, exchange, false, false);
        }
    }
}

From source file:tv.phantombot.httpserver.HTTPServerCommon.java

public static void handleBetaPanel(HttpExchange exchange) throws IOException {
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }/*from ww w.j ava 2 s . c om*/
    inputStream.close();

    if (requestMethod.equals("GET")) {
        if (uriPath.equals("/beta-panel")) {
            HTTPServerCommon.handleFile("/web/beta-panel/index.html", exchange, false, false);
        } else {
            HTTPServerCommon.handleFile("/web/" + uriPath, exchange, false, false);
        }
    }
}

From source file:org.jcodec.samples.mux.AVCMP4Mux.java

private static void mux(CompressedTrack track, File f, List<SeqParameterSet> spsList,
        List<PictureParameterSet> ppsList) throws IOException {
    InputStream is = null;/*from   w  ww.j av  a2s.  co m*/
    try {
        is = new BufferedInputStream(new FileInputStream(f));
        NALUnitReader in = new NALUnitReader(is);
        InputStream nextNALUnit = null;
        int i = 0;
        do {
            nextNALUnit = in.nextNALUnit();
            if (nextNALUnit == null)
                continue;
            NALUnit nu = NALUnit.read(nextNALUnit);
            if (nu.type == NALUnitType.IDR_SLICE || nu.type == NALUnitType.NON_IDR_SLICE) {

                track.addFrame(new MP4Packet(formPacket(nu, nextNALUnit), i, 25, 1, i,
                        nu.type == NALUnitType.IDR_SLICE, null, i, 0));
                i++;
            } else if (nu.type == NALUnitType.SPS) {
                spsList.add(SeqParameterSet.read(nextNALUnit));
            } else if (nu.type == NALUnitType.PPS) {
                ppsList.add(PictureParameterSet.read(nextNALUnit));
            } else {
                nextNALUnit.skip(Integer.MAX_VALUE);
            }
        } while (nextNALUnit != null);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.opendatakit.briefcase.util.AggregateUtils.java

/**
 * Send a HEAD request to the server to confirm the validity of the URL and
 * credentials./* w w  w  . ja v a  2  s  . c om*/
 * 
 * @param serverInfo
 * @param actionAddr
 * @return the confirmed URI of this action.
 * @throws TransmissionException
 */
public static final URI testServerConnectionWithHeadRequest(ServerConnectionInfo serverInfo, String actionAddr)
        throws TransmissionException {

    String urlString = serverInfo.getUrl();
    if (urlString.endsWith("/")) {
        urlString = urlString + actionAddr;
    } else {
        urlString = urlString + "/" + actionAddr;
    }

    URI u;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (MalformedURLException e) {
        String msg = "Invalid url: " + urlString + " for " + actionAddr + ".\nFailed with error: "
                + e.getMessage();
        if (!urlString.toLowerCase().startsWith("http://") && !urlString.toLowerCase().startsWith("https://")) {
            msg += "\nDid you forget to prefix the address with 'http://' or 'https://' ?";
        }
        log.warn(msg, e);
        throw new TransmissionException(msg);
    } catch (URISyntaxException e) {
        String msg = "Invalid uri: " + urlString + " for " + actionAddr + ".\nFailed with error: "
                + e.getMessage();
        log.warn(msg, e);
        throw new TransmissionException(msg);
    }

    HttpClient httpClient = WebUtils.createHttpClient();

    // get shared HttpContext so that authentication and cookies are retained.
    HttpClientContext localContext = WebUtils.getHttpContext();

    WebUtils.setCredentials(localContext, serverInfo, u);

    {
        // we need to issue a head request
        HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

        // prepare response
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpHead, localContext);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 204) {
                Header[] openRosaVersions = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
                if (openRosaVersions == null || openRosaVersions.length == 0) {
                    String msg = "Url: " + u.toString() + ", header missing: "
                            + WebUtils.OPEN_ROSA_VERSION_HEADER;
                    log.warn(msg);
                    throw new TransmissionException(msg);
                }
                Header[] locations = response.getHeaders("Location");
                if (locations != null && locations.length == 1) {
                    try {
                        URL url = new URL(locations[0].getValue());
                        URI uNew = url.toURI();
                        if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                            // trust the server to tell us a new location
                            // ... and possibly to use https instead.
                            u = uNew;
                            // At this point, we may have updated the uri to use https.
                            // This occurs only if the Location header keeps the host name
                            // the same. If it specifies a different host name, we error
                            // out.
                            return u;
                        } else {
                            // Don't follow a redirection attempt to a different host.
                            // We can't tell if this is a spoof or not.
                            String msg = "Starting url: " + u.toString()
                                    + " unexpected redirection attempt to a different host: " + uNew.toString();
                            log.warn(msg);
                            throw new TransmissionException(msg);
                        }
                    } catch (Exception e) {
                        String msg = "Starting url: " + u + " unexpected exception: " + e.getLocalizedMessage();
                        log.warn(msg, e);
                        throw new TransmissionException(msg);
                    }
                } else {
                    String msg = "The url: " + u.toString()
                            + " is not ODK Aggregate - status code on Head request: " + statusCode;
                    log.warn(msg);
                    throw new TransmissionException(msg);
                }
            } else {
                // may be a server that does not handle HEAD requests
                if (response.getEntity() != null) {
                    try {
                        // don't really care about the stream...
                        InputStream is = response.getEntity().getContent();
                        // read to end of stream...
                        final long count = 1024L;
                        while (is.skip(count) == count)
                            ;
                        is.close();
                    } catch (Exception e) {
                        log.error("failed to process http stream", e);
                    }
                }
                String msg = "The username or password may be incorrect or the url: " + u.toString()
                        + " is not ODK Aggregate - status code on Head request: " + statusCode;
                log.warn(msg);
                throw new TransmissionException(msg);
            }
        } catch (Exception e) {
            String msg = "Starting url: " + u.toString() + " unexpected exception: " + e.getLocalizedMessage();
            log.warn(msg, e);
            throw new TransmissionException(msg);
        }
    }
}

From source file:tv.phantombot.httpserver.HTTPServerCommon.java

public static void handle(HttpExchange exchange, String serverPassword, String serverWebAuth)
        throws IOException {
    Boolean hasPassword = false;/*from   w  w w .ja  v a  2  s .c  o m*/
    Boolean doRefresh = false;
    Boolean doMarquee = false;
    String myPassword = "";
    String myHdrUser = "";
    String myHdrMessage = "";
    String[] uriQueryList = null;
    int marqueeWidth = 420;
    int msgLength = 40;

    // Get the path and query string from the URI
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();
    String uriQuery = uriData.getQuery();

    if (uriQuery != null) {
        uriQueryList = uriQuery.split("&");
    }

    // Get the headers
    Headers headers = exchange.getRequestHeaders();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }
    inputStream.close();

    if (headers.containsKey("password")) {
        myPassword = headers.getFirst("password");
        if (myPassword.equals(serverPassword) || myPassword.equals("oauth:" + serverPassword)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("webauth")) {
        myPassword = headers.getFirst("webauth");
        if (myPassword.equals(serverWebAuth)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("user")) {
        myHdrUser = headers.getFirst("user");
    }
    if (headers.containsKey("message")) {
        myHdrMessage = headers.getFirst("message");
        byte[] myHdrMessageBytes = myHdrMessage.getBytes(StandardCharsets.ISO_8859_1);
        myHdrMessage = new String(myHdrMessageBytes, StandardCharsets.UTF_8);
    }

    // Check the uriQueryList for the webauth
    if (uriQuery != null) {
        for (String query : uriQueryList) {
            if (query.startsWith("webauth=")) {
                String[] webAuthData = query.split("=");
                myPassword = webAuthData[1];
                if (myPassword.equals(serverWebAuth)) {
                    hasPassword = true;
                }
            } else if (query.startsWith("refresh")) {
                doRefresh = true;
            } else if (query.startsWith("marquee")) {
                doMarquee = true;
            } else if (query.startsWith("width")) {
                String[] splitData = query.split("=");
                try {
                    marqueeWidth = Integer.parseInt(splitData[1]);
                } catch (NumberFormatException ex) {
                    marqueeWidth = 420;
                }
            } else if (query.startsWith("cutoff")) {
                String[] splitData = query.split("=");
                try {
                    msgLength = Integer.parseInt(splitData[1]);
                } catch (NumberFormatException ex) {
                    msgLength = 40;
                }
            }
        }
    }

    if (requestMethod.equals("GET")) {
        if (uriPath.contains("..")) {
            sendHTMLError(403, "Invalid URL", exchange);
        } else if (uriPath.startsWith("/inistore")) {
            handleIniStore(uriPath, exchange, hasPassword);
        } else if (uriPath.startsWith("/dbquery")) {
            handleDBQuery(uriPath, uriQueryList, exchange, hasPassword);
        } else if (uriPath.startsWith("/addons") && !doRefresh && !doMarquee) {
            handleFile(uriPath, exchange, hasPassword, true);
        } else if (uriPath.startsWith("/addons") && doMarquee) {
            handleRefresh(uriPath, exchange, true, hasPassword, true, marqueeWidth, msgLength);
        } else if (uriPath.startsWith("/addons") && doRefresh) {
            handleRefresh(uriPath, exchange, false, hasPassword, true, 0, 0);
        } else if (uriPath.startsWith("/logs")) {
            handleFile(uriPath, exchange, hasPassword, true);
        } else if (uriPath.equals("/playlist")) {
            handleFile("/web/playlist/index.html", exchange, hasPassword, false);
        } else if (uriPath.equals("/")) {
            handleFile("/web/index.html", exchange, hasPassword, false);
        } else if (uriPath.equals("/alerts")) {
            handleFile("/web/alerts/index.html", exchange, hasPassword, false);
        } else if (uriPath.startsWith("/config/audio-hooks")) {
            handleFile(uriPath, exchange, hasPassword, false);
        } else if (uriPath.startsWith("/config/gif-alerts")) {
            handleFile(uriPath, exchange, hasPassword, false);
        } else if (uriPath.startsWith("/get-lang")) {
            handleLangFiles("", exchange, hasPassword, true);
        } else if (uriPath.startsWith("/lang")) {
            handleLangFiles(headers.getFirst("lang-path"), exchange, hasPassword, true);
        } else if (uriPath.startsWith("/games")) {
            handleGamesList(exchange, hasPassword, true);
        } else {
            handleFile("/web" + uriPath, exchange, hasPassword, false);
        }
    }

    if (requestMethod.equals("PUT")) {
        if (myHdrUser.isEmpty() && headers.containsKey("lang-path")) {
            handlePutRequestLang(headers.getFirst("lang-path"), headers.getFirst("lang-data"), exchange,
                    hasPassword);
        } else {
            handlePutRequest(myHdrUser, myHdrMessage, exchange, hasPassword);
        }
    }
}

From source file:net.sergetk.mobile.lcdui.BitmapFont.java

private static Image getColorizedFontImage(String path, short skip, int color) {
    InputStream inputStream = BitmapFont.class.getResourceAsStream(path);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buff = new byte[2048];
    int bytesRead = 0;
    try {// w  ww  .  ja v a 2 s. com
        inputStream.skip(skip);
        while ((bytesRead = inputStream.read(buff)) != -1) {
            bos.write(buff, 0, bytesRead);
        }
        return getColorizedImage(bos.toByteArray(), color);
    } catch (IOException ioe) {
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ignoreCloseFailure) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ignoreCloseFailure) {
            }
        }
    }
    return null;
}