Example usage for java.nio.channels Channels newChannel

List of usage examples for java.nio.channels Channels newChannel

Introduction

In this page you can find the example usage for java.nio.channels Channels newChannel.

Prototype

public static WritableByteChannel newChannel(OutputStream out) 

Source Link

Document

Constructs a channel that writes bytes to the given stream.

Usage

From source file:org.geowebcache.layer.wms.WMSHttpHelper.java

/**
 * Executes the actual HTTP request, checks the response headers (status and MIME) and
 * //  w w  w  .  j av a2  s.  c  om
 * @param tileRespRecv
 * @param wmsBackendUrl
 * @param data
 * @param wmsparams
 * @return
 * @throws GeoWebCacheException
 */
private void connectAndCheckHeaders(TileResponseReceiver tileRespRecv, URL wmsBackendUrl,
        Map<String, String> wmsParams, String requestMime, Integer backendTimeout, Resource target)
        throws GeoWebCacheException {

    GetMethod getMethod = null;
    final int responseCode;
    final int responseLength;

    try { // finally
        try {
            getMethod = executeRequest(wmsBackendUrl, wmsParams, backendTimeout);
            responseCode = getMethod.getStatusCode();
            responseLength = (int) getMethod.getResponseContentLength();

            // Do not set error at this stage
        } catch (IOException ce) {
            if (log.isDebugEnabled()) {
                String message = "Error forwarding request " + wmsBackendUrl.toString();
                log.debug(message, ce);
            }
            throw new GeoWebCacheException(ce);
        }
        // Check that the response code is okay
        tileRespRecv.setStatus(responseCode);
        if (responseCode != 200 && responseCode != 204) {
            tileRespRecv.setError();
            throw new ServiceException("Unexpected response code from backend: " + responseCode + " for "
                    + wmsBackendUrl.toString());
        }

        // Check that we're not getting an error MIME back.
        String responseMime = getMethod.getResponseHeader("Content-Type").getValue();

        if (responseCode != 204 && responseMime != null && !mimeStringCheck(requestMime, responseMime)) {
            String message = null;
            if (responseMime.equalsIgnoreCase(ErrorMime.vnd_ogc_se_inimage.getFormat())) {
                // TODO: revisit: I don't understand why it's trying to create a String message
                // out of an ogc_se_inimage response?
                InputStream stream = null;
                try {
                    stream = getMethod.getResponseBodyAsStream();
                    byte[] error = IOUtils.toByteArray(stream);
                    message = new String(error);
                } catch (IOException ioe) {
                    // Do nothing
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            } else if (responseMime != null
                    && responseMime.toLowerCase().startsWith("application/vnd.ogc.se_xml")) {
                InputStream stream = null;
                try {
                    stream = getMethod.getResponseBodyAsStream();
                    message = IOUtils.toString(stream);
                } catch (IOException e) {
                    //
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
            String msg = "MimeType mismatch, expected " + requestMime + " but got " + responseMime + " from "
                    + wmsBackendUrl.toString() + (message == null ? "" : (":\n" + message));
            tileRespRecv.setError();
            tileRespRecv.setErrorMessage(msg);
            log.warn(msg);
        }

        // Everything looks okay, try to save expiration
        if (tileRespRecv.getExpiresHeader() == GWCVars.CACHE_USE_WMS_BACKEND_VALUE) {
            String expireValue = getMethod.getResponseHeader("Expires").getValue();
            long expire = ServletUtils.parseExpiresHeader(expireValue);
            if (expire != -1) {
                tileRespRecv.setExpiresHeader(expire / 1000);
            }
        }

        // Read the actual data
        if (responseCode != 204) {
            try {
                InputStream inStream = getMethod.getResponseBodyAsStream();
                if (inStream == null) {
                    String uri = getMethod.getURI().getURI();
                    log.error("No response for " + getMethod.getName() + " " + uri);
                } else {
                    ReadableByteChannel channel = Channels.newChannel(inStream);
                    try {
                        target.transferFrom(channel);
                    } finally {
                        channel.close();
                    }
                }
                if (responseLength > 0) {
                    int readAccu = (int) target.getSize();
                    if (readAccu != responseLength) {
                        tileRespRecv.setError();
                        throw new GeoWebCacheException(
                                "Responseheader advertised " + responseLength + " bytes, but only received "
                                        + readAccu + " from " + wmsBackendUrl.toString());
                    }
                }
            } catch (IOException ioe) {
                tileRespRecv.setError();
                log.error("Caught IO exception, " + wmsBackendUrl.toString() + " " + ioe.getMessage());
            }
        }

    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}

From source file:org.dawnsci.dde.templates.AbstractTemplateTestBase.java

private static boolean isEqual(InputStream i1, InputStream i2) throws IOException {

    ReadableByteChannel ch1 = Channels.newChannel(i1);
    ReadableByteChannel ch2 = Channels.newChannel(i2);

    ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
    ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);

    try {/*from  ww w  . java 2  s.  c o  m*/
        while (true) {

            int n1 = ch1.read(buf1);
            int n2 = ch2.read(buf2);

            if (n1 == -1 || n2 == -1)
                return n1 == n2;

            buf1.flip();
            buf2.flip();

            for (int i = 0; i < Math.min(n1, n2); i++)
                if (buf1.get() != buf2.get())
                    return false;

            buf1.compact();
            buf2.compact();
        }

    } finally {
        if (i1 != null)
            i1.close();
        if (i2 != null)
            i2.close();
    }
}

From source file:org.geowebcache.util.ResponseUtils.java

/**
 * Helper method that writes an HTTP response setting the provided HTTP code. Using the provided
 * content length./*from  ww w.j a v a  2s  . co m*/
 *
 * @param response HTTP response
 * @param httpCode HTTP status code
 * @param contentType HTTP response content type
 * @param resource HTTP response resource
 * @param cacheRes provides information about the tile retrieving
 * @param contentLength HTTP response content length
 * @param runtimeStats runtime statistics
 */
public static void writeFixedResponse(HttpServletResponse response, int httpCode, String contentType,
        Resource resource, CacheResult cacheRes, int contentLength, RuntimeStats runtimeStats) {

    response.setStatus(httpCode);
    response.setContentType(contentType);

    response.setContentLength((int) contentLength);
    if (resource != null) {
        try {
            OutputStream os = response.getOutputStream();
            resource.transferTo(Channels.newChannel(os));

            runtimeStats.log(contentLength, cacheRes);

        } catch (IOException ioe) {
            log.debug("Caught IOException: " + ioe.getMessage() + "\n\n" + ioe.toString());
        }
    }
}

From source file:org.basinmc.maven.plugins.bsdiff.DiffMojo.java

/**
 * Retrieves a remote artifact and stores it in a pre-defined cache directory.
 *//*  w w w  .j av  a2  s  .  c o  m*/
@Nonnull
private Path retrieveSourceFile() throws MojoFailureException {
    HttpClient client = HttpClients.createMinimal();
    String fileName;

    {
        String path = this.sourceURL.getPath();

        int i = path.lastIndexOf('/');
        fileName = path.substring(i + 1);
    }

    try {
        this.getLog().info("Downloading source artifact from " + this.sourceURL.toExternalForm());

        HttpGet request = new HttpGet(this.sourceURL.toURI());
        HttpResponse response = client.execute(request);

        if (response.containsHeader("Content-Disposition")) {
            String disposition = response.getLastHeader("Content-Disposition").getValue();
            Matcher matcher = DISPOSITION_PATTERN.matcher(disposition);

            if (matcher.matches()) {
                fileName = URLDecoder.decode(matcher.group(1), "UTF-8");
            }
        }

        this.getLog().info("Storing " + fileName + " in cache directory");
        Path outputPath = this.cacheDirectory.toPath().resolve(fileName);

        if (!Files.isDirectory(outputPath.getParent())) {
            Files.createDirectories(outputPath.getParent());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                    outputChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }

        return outputPath;
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to read/write source artifact: " + ex.getMessage(), ex);
    } catch (URISyntaxException ex) {
        throw new MojoFailureException("Invalid source URI: " + ex.getMessage(), ex);
    }
}

From source file:edu.northwestern.jcr.adapter.fedora.persistence.FedoraConnectorREST.java

/**
 * Wrapper of getDatastreamDissemination in REST.
 *
 * @param pid pid of the object//from ww w .ja v  a  2  s .c o m
 * @param dsID id of the datastream
 * @return byte content of the data stream
 */
public byte[] getDataStream(String pid, String dsID) {
    HttpInputStream inputStream;
    ReadableByteChannel channel;
    ByteBuffer buf;
    byte[] bytes;
    int numRead = 0;
    int length = 0;

    try {
        inputStream = fc.get(
                String.format("/objects/%s/datastreams/%s/content", URLEncoder.encode(pid, "UTF-8"), dsID),
                true, false);
    } catch (Exception e) {
        return null;
    }

    channel = Channels.newChannel(inputStream);
    // Create a direct ByteBuffer
    buf = ByteBuffer.allocateDirect(10 * 1024 * 1024);

    while (numRead >= 0) {
        // Read bytes from the channel
        try {
            numRead = channel.read(buf);
        } catch (Exception e) {
            return null;
        }

        if (numRead > 0) {
            length += numRead;
        }
    }

    bytes = new byte[length];
    // reset the position of the buffer to zero
    buf.rewind();
    buf.get(bytes);

    return bytes;
}

From source file:org.alfresco.contentstore.ChecksumTest.java

protected int applyPatch(ReadableByteChannel inChannel, WritableByteChannel outChannel,
        PatchDocument patchDocument) throws IOException {
    InChannel c = new InChannel(inChannel, patchDocument.getMatchedBlocks(), patchDocument.getBlockSize());

    int totalWritten = 0;

    int blockIndex = c.nextBlock();
    if (blockIndex > -1) {
        for (Patch patch : patchDocument.getPatches()) {
            int lastMatchingBlockIndex = patch.getLastMatchIndex();

            while (blockIndex != -1 && blockIndex <= lastMatchingBlockIndex) {
                int bytesWritten = outChannel.write(c.currentBlock);
                totalWritten += bytesWritten;
                if (bytesWritten != c.blockSize) {
                    throw new RuntimeException("Wrote too few bytes, " + c.blockSize + ", " + bytesWritten);
                }/*from  w  w w .j a v  a2s.c om*/

                blockIndex = c.nextBlock();
                if (blockIndex == -1) {
                    break;
                }
            }

            // apply patch
            int patchSize = patch.getSize();
            ReadableByteChannel patchChannel = Channels.newChannel(patch.getStream());
            ByteBuffer patchBB = ByteBuffer.allocate(patchSize);
            int bytesRead = patchChannel.read(patchBB);
            patchBB.flip();
            int bytesWritten = outChannel.write(patchBB);
            totalWritten += bytesWritten;
            if (bytesWritten != bytesRead) {
                throw new RuntimeException(
                        "Wrote too few bytes, expected " + bytesRead + ", got " + bytesWritten);
            }
        }

        // we're done with all the patches, add the remaining blocks
        while (blockIndex != -1) {
            int bytesWritten = outChannel.write(c.currentBlock);
            totalWritten += bytesWritten;
            if (bytesWritten != c.bytesRead) {
                throw new RuntimeException("Wrote too few bytes");
            }

            blockIndex = c.nextBlock();
        }
    }

    return totalWritten;
}

From source file:com.p2p.peercds.tracker.TrackerService.java

/**
 * Process the announce request./*  www .  ja  va  2s  .c om*/
 *
 * <p>
 * This method attemps to read and parse the incoming announce request into
 * an announce request message, then creates the appropriate announce
 * response message and sends it back to the client.
 * </p>
 *
 * @param request The incoming announce request.
 * @param response The response object.
 * @param body The validated response body output stream.
 */
private void process(Request request, Response response, OutputStream body) throws IOException {
    // Prepare the response headers.
    response.set("Content-Type", "text/plain");
    response.set("Server", this.version);
    response.setDate("Date", System.currentTimeMillis());

    /**
     * Parse the query parameters into an announce request message.
     *
     * We need to rely on our own query parsing function because
     * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which
     * doesn't work well for the byte-encoded strings we expect.
     */
    HTTPAnnounceRequestMessage announceRequest = null;
    try {
        announceRequest = this.parseQuery(request);
    } catch (MessageValidationException mve) {
        this.serveError(response, body, Status.BAD_REQUEST, mve.getMessage());
        return;
    }

    // first check for existing torrent, if not present add a new torrent

    TrackerTorrent torrent = this.torrents.get(announceRequest.getHexInfoHash());
    if (torrent == null) {
        logger.info("New Torrent announce request received. Veriyfing the event-type:");
        if ((announceRequest.getEvent() == null
                || !AnnounceRequestMessage.RequestEvent.STARTED.equals(announceRequest.getEvent()))) {
            logger.warn("New torrent must be registered with started event");
            this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT);
            return;
        } else {
            logger.info("Lock grabbed to register a new torrent");
            lock.lock();
            if (this.torrents.get(announceRequest.getHexInfoHash()) == null) {
                logger.info("Event type verified, registering newly announced torrent.");
                torrent = new UntrackedTorrent("NewTorrent", announceRequest.getHexInfoHash());
                torrents.put(announceRequest.getHexInfoHash(), torrent);
                logger.info("new torrent registration complete.");
            } else
                logger.info("Torrent already registered by someone. Skipping the registration.");
            lock.unlock();
            logger.info("torrent registration lock released");
        }
    }

    AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent();
    String peerId = announceRequest.getHexPeerId();

    // When no event is specified, it's a periodic update while the client
    // is operating. If we don't have a peer for this announce, it means
    // the tracker restarted while the client was running. Consider this
    // announce request as a 'started' event.
    if ((event == null || AnnounceRequestMessage.RequestEvent.NONE.equals(event))
            && torrent.getPeer(peerId) == null) {
        event = AnnounceRequestMessage.RequestEvent.STARTED;
    }

    // If an event other than 'started' is specified and we also haven't
    // seen the peer on this torrent before, something went wrong. A
    // previous 'started' announce request should have been made by the
    // client that would have had us register that peer on the torrent this
    // request refers to.
    if (event != null && torrent.getPeer(peerId) == null
            && !AnnounceRequestMessage.RequestEvent.STARTED.equals(event)) {
        this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT);
        return;
    }

    // Update the torrent according to the announce event
    TrackedPeer peer = null;
    try {
        peer = torrent.update(event, ByteBuffer.wrap(announceRequest.getPeerId()),
                announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(),
                announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft());
    } catch (IllegalArgumentException iae) {
        this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT);
        return;
    } catch (Exception e) {
        this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    // Craft and output the answer
    HTTPAnnounceResponseMessage announceResponse = null;
    try {
        announceResponse = HTTPAnnounceResponseMessage.craft(torrent.getAnnounceInterval(),
                TrackedTorrent.MIN_ANNOUNCE_INTERVAL_SECONDS, this.version, torrent.seeders(),
                torrent.leechers(), torrent.getSomePeers(peer));
        WritableByteChannel channel = Channels.newChannel(body);
        channel.write(announceResponse.getData());
    } catch (Exception e) {
        this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

protected CryptoInputStream getCryptoInputStream(ByteArrayInputStream bais, Cipher cipher, int bufferSize,
        byte[] iv, boolean withChannel) throws IOException {
    if (withChannel) {
        return new CryptoInputStream(Channels.newChannel(bais), cipher, bufferSize, key, iv);
    } else {// w  w  w . jav  a  2s  .c  o  m
        return new CryptoInputStream(bais, cipher, bufferSize, key, iv);
    }
}

From source file:uk.ac.tgac.rampart.util.DependencyDownloader.java

public void downloadFromUrl(URL url, File localFile) throws IOException {

    System.out.print("Downloading: " + url.toString() + " ... ");

    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream(localFile);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

    if (!localFile.exists()) {
        System.err.println("Could not download: " + url.toString() + "; URL may have changed.");
    }//from  w  ww  .  j  av a  2  s.  c o m

    System.out.println("done.");
}

From source file:org.alfresco.patch.PatchServiceImpl.java

@SuppressWarnings("resource")
@Override//from w ww.j av  a  2  s.co  m
public PatchDocument getPatch(MultiPart resource) throws IOException {
    Integer blockSize = null;
    Integer matchCount = null;

    List<Integer> matchedBlocks = null;
    List<Patch> patches = new LinkedList<>();

    // This will iterate the individual parts of the multipart response
    for (BodyPart bodyPart : resource.getBodyParts()) {
        if (bodyPart instanceof FormDataMultiPart) {
            System.out.printf("Multipart Body Part [Mime Type: %s]\n", bodyPart.getMediaType());

            InputStream is = null;
            Integer size = null;
            Integer lastMatchIndex = null;

            FormDataMultiPart mp = (FormDataMultiPart) bodyPart;
            for (BodyPart bodyPart1 : mp.getBodyParts()) {
                ContentDisposition contentDisposition = bodyPart1.getContentDisposition();
                if (contentDisposition instanceof FormDataContentDisposition) {
                    FormDataContentDisposition cd = (FormDataContentDisposition) contentDisposition;
                    String name = cd.getName();

                    if (name.equals("p_size")) {
                        size = Integer.parseInt((String) bodyPart1.getEntity());
                    } else if (name.equals("p_last_match_idx")) {
                        lastMatchIndex = Integer.parseInt((String) bodyPart1.getEntity());
                    } else if (name.equals("p_stream")) {
                        is = (InputStream) bodyPart1.getEntity();
                    }
                }
            }

            ByteBuffer bb = ByteBuffer.allocate(1024 * 20); // TODO
            ReadableByteChannel channel = Channels.newChannel(is);
            channel.read(bb);
            bb.flip();
            byte[] buffer = new byte[bb.limit()];
            bb.get(buffer);
            Patch patch = new Patch(lastMatchIndex, size, buffer);
            patches.add(patch);
        } else {
            System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", bodyPart.getMediaType(),
                    bodyPart.getContentDisposition().getSize());

            ContentDisposition contentDisposition = bodyPart.getContentDisposition();
            if (contentDisposition instanceof FormDataContentDisposition) {
                FormDataContentDisposition cd = (FormDataContentDisposition) contentDisposition;
                String name = cd.getName();

                if (name.equals("p_block_size")) {
                    blockSize = Integer.parseInt((String) bodyPart.getEntity());
                } else if (name.equals("p_match_count")) {
                    matchCount = Integer.parseInt((String) bodyPart.getEntity());
                } else if (name.equals("p_matched_blocks")) {
                    String matchedBlocksStr = (String) bodyPart.getEntity();
                    List<String> l = Arrays.asList(matchedBlocksStr.split(","));
                    matchedBlocks = l.stream().filter(s -> s != null && !s.equals(""))
                            .map(s -> Integer.parseInt(s)).collect(Collectors.toList());
                }
            }
        }
    }

    PatchDocument patchDocument = new PatchDocument(blockSize, matchedBlocks, patches);
    return patchDocument;
}