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:com.respam.comniq.models.OMDBParser.java

public void requestOMDB(String movie, String year) {
    String imageURL;/*from w w w  . ja va 2  s  .com*/

    // Location for downloading and storing thumbnails
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output"
            + File.separator + "thumbnails";
    File userOutDir = new File(path);

    // Create Thumbnails directory if not present
    if (userOutDir.mkdirs()) {
        System.out.println(userOutDir + " was created");
    }

    // Connect to OMDB API and fetch details
    try {
        // Proxy details
        HttpHost proxy = new HttpHost("web-proxy.in.hpecorp.net", 8080, "http");

        //            HttpClient client = HttpClientBuilder.create().build();

        // Start of proxy client
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build();
        // End of proxy client

        String uri = "http://www.omdbapi.com/?t=" + URLEncoder.encode(movie) + "&y=" + year;
        uri = uri.replace(" ", "%20");
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        String json = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(json);

        // Excluding Non Movies
        if (null != jsonObject.get("Title")) {
            movieInfo.add(jsonObject);

            // Download the thumbnails if Poster URL present
            if (null != jsonObject.get("Poster")) {
                imageURL = ((String) jsonObject.get("Poster"));
                System.out.println(imageURL);
                URL thumbnail = new URL(imageURL);
                ReadableByteChannel rbc = Channels.newChannel(thumbnail.openStream());
                FileOutputStream fos = new FileOutputStream(
                        path + File.separator + jsonObject.get("Title") + ".jpg");
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
        }

    } catch (ParseException | IOException | UnsupportedOperationException e) {
        e.printStackTrace();
    }
}

From source file:io.druid.segment.data.CompressedIntsIndexedWriterTest.java

private void checkSerializedSizeAndData(int chunkFactor) throws Exception {
    CompressedIntsIndexedWriter writer = new CompressedIntsIndexedWriter(ioPeon, "test", chunkFactor, byteOrder,
            compressionStrategy);/*from  www  .ja va2s  . c om*/
    CompressedIntsIndexedSupplier supplierFromList = CompressedIntsIndexedSupplier.fromList(Ints.asList(vals),
            chunkFactor, byteOrder, compressionStrategy);
    writer.open();
    for (int val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, supplierFromList.getSerializedSize());

    // read from ByteBuffer and check values
    CompressedIntsIndexedSupplier supplierFromByteBuffer = CompressedIntsIndexedSupplier
            .fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder);
    IndexedInts indexedInts = supplierFromByteBuffer.get();
    assertEquals(vals.length, indexedInts.size());
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], indexedInts.get(i));
    }
    CloseQuietly.close(indexedInts);
}

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

private void assertEqual(InputStream expected, InputStream actual) throws IOException {
    ByteBuffer bb1 = ByteBuffer.allocate(1024);
    ByteBuffer bb2 = ByteBuffer.allocate(1024);

    try (ReadableByteChannel expectedChannel = Channels.newChannel(expected);
            ReadableByteChannel actualChannel = Channels.newChannel(actual)) {
        State state = new State();
        for (;;) {
            int numRead1 = expectedChannel.read(bb1);
            bb1.flip();//from  w  ww. j  a  v  a2 s.c  o m

            int numRead2 = actualChannel.read(bb2);
            bb2.flip();

            assertEqual(bb1, bb2, state);

            if (numRead1 < 1) {
                break;
            }

            bb1.clear();
            bb2.clear();
        }
    }
}

From source file:org.carlspring.strongbox.storage.metadata.nuget.TempNupkgFile.java

/**
 * Creates a temporary file based on the stream.
 *
 * @param inputStream/*ww  w.  ja va2s .  com*/
 *            data stream
 * @param targetFile
 *            file to copy the package to
 * @return data file
 * @throws IOException
 *             read / write error
 * @throws NoSuchAlgorithmException
 *             the system does not have an algorithm for calculating the
 *             value of HASH
 */
private static String copyDataAndCalculateHash(InputStream inputStream, File targetFile)
        throws IOException, NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_512);
    DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);

    try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
            ReadableByteChannel src = Channels.newChannel(digestInputStream);
            FileChannel dest = fileOutputStream.getChannel();) {
        fastChannelCopy(src, dest);

        byte[] digest = digestInputStream.getMessageDigest().digest();

        return DatatypeConverter.printBase64Binary(digest);
    }
}

From source file:com.recomdata.transmart.data.export.util.ExportImageProcessor.java

public void run() {
    URL imageURL = null;/*from w  w w . j  a  v  a2s .co  m*/
    File imageFile = new File(imagesTempDir + File.separator + filename);
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {
        if (StringUtils.isEmpty(imageURI))
            return;

        imageURL = new URL(imageURI);
        rbc = Channels.newChannel(imageURL.openStream());
        fos = new FileOutputStream(imageFile);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (null != fos)
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

From source file:org.geoserver.gwc.wms.CachingWebMapService.java

/**
 * Wraps {@link WebMapService#getMap(GetMapRequest)}, called by the {@link Dispatcher}
 * //from  ww  w  . j  a  v a  2 s .c o  m
 * @see WebMapService#getMap(GetMapRequest)
 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
 */
public WebMap invoke(MethodInvocation invocation) throws Throwable {
    GWCConfig config = gwc.getConfig();
    if (!config.isDirectWMSIntegrationEnabled()) {
        return (WebMap) invocation.proceed();
    }

    final GetMapRequest request = getRequest(invocation);
    boolean tiled = request.isTiled();
    if (!tiled) {
        return (WebMap) invocation.proceed();
    }

    final StringBuilder requestMistmatchTarget = new StringBuilder();
    ConveyorTile cachedTile = gwc.dispatch(request, requestMistmatchTarget);

    if (cachedTile == null) {
        WebMap dynamicResult = (WebMap) invocation.proceed();
        dynamicResult.setResponseHeader("geowebcache-cache-result", MISS.toString());
        dynamicResult.setResponseHeader("geowebcache-miss-reason", requestMistmatchTarget.toString());
        return dynamicResult;
    }
    checkState(cachedTile.getTileLayer() != null);
    final TileLayer layer = cachedTile.getTileLayer();

    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest("GetMap request intercepted, serving cached content: " + request);
    }

    final byte[] tileBytes;
    {
        final Resource mapContents = cachedTile.getBlob();
        if (mapContents instanceof ByteArrayResource) {
            tileBytes = ((ByteArrayResource) mapContents).getContents();
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            mapContents.transferTo(Channels.newChannel(out));
            tileBytes = out.toByteArray();
        }
    }

    // Handle Etags
    final String ifNoneMatch = request.getHttpRequestHeader("If-None-Match");
    final byte[] hash = MessageDigest.getInstance("MD5").digest(tileBytes);
    final String etag = toHexString(hash);
    if (etag.equals(ifNoneMatch)) {
        // Client already has the current version
        LOGGER.finer("ETag matches, returning 304");
        throw new HttpErrorCodeException(HttpServletResponse.SC_NOT_MODIFIED);
    }

    LOGGER.finer("No matching ETag, returning cached tile");
    final String mimeType = cachedTile.getMimeType().getMimeType();

    RawMap map = new RawMap(null, tileBytes, mimeType);

    map.setContentDispositionHeader(null, "." + cachedTile.getMimeType().getFileExtension(), false);

    Integer cacheAgeMax = getCacheAge(layer);
    LOGGER.log(Level.FINE, "Using cacheAgeMax {0}", cacheAgeMax);
    if (cacheAgeMax != null) {
        map.setResponseHeader("Cache-Control", "max-age=" + cacheAgeMax);
    } else {
        map.setResponseHeader("Cache-Control", "no-cache");
    }

    setConditionalGetHeaders(map, cachedTile, request, etag);
    setCacheMetadataHeaders(map, cachedTile, layer);

    return map;

}

From source file:info.fetter.rrdclient.GraphCommand.java

@Override
public void execute(OutputStream out) {
    String command = "graph";
    for (String arg : args) {
        command += " " + arg;
    }//from  w ww.j a  v  a  2  s.c o  m
    try {
        ByteBuffer response = sendCommandToServer(command);
        WritableByteChannel channel = Channels.newChannel(out);
        channel.write(response);
        isOutputParsed = false;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.codelabor.system.file.util.UploadUtils.java

/**
 * ?? .</br> ?  ?? FILE_SYSTEM? , ??  DATABASE?  byte[]
 *  DTO? ./*from www . j av a 2  s.  c  o m*/
 * 
 * @param repositoryType
 *            ?  ?
 * @param inputStream
 *             
 * @param fileDTO
 *            ? DTO
 * @throws Exception
 *             
 */
static public void processFile(RepositoryType repositoryType, InputStream inputStream, FileDTO fileDTO)
        throws Exception {
    // prepare io
    OutputStream outputStream = null;
    ReadableByteChannel inputChannel = null;
    WritableByteChannel outputChannel = null;

    int fileSize = 0;

    switch (repositoryType) {
    case FILE_SYSTEM:
        // prepare repository
        File repository = new File(fileDTO.getRepositoryPath());
        String repositoryPath = fileDTO.getRepositoryPath();
        StringBuilder sb = new StringBuilder();
        if (logger.isDebugEnabled()) {
            sb.append("repositoryPath: ").append(repositoryPath);
            sb.append(", repositoryType: ").append(repositoryType);
            sb.append(", repository.exists(): ").append(repository.exists());
            sb.append(", repository.isDirectory(): ").append(repository.isDirectory());
            logger.debug(sb.toString());
        }

        // prepare directory
        File file = new File(repositoryPath);
        if (!file.exists()) {
            try {
                FileUtils.forceMkdir(file);
            } catch (IOException e) {
                StringBuilder sb = new StringBuilder();
                sb.append("Cannot make directory: ");
                sb.append(file.toString());
                logger.error(sb.toString());
                throw new ServletException(sb.toString());
            }
        }

        // prepare stream
        sb.setLength(0);
        sb.append(fileDTO.getRepositoryPath());
        if (!fileDTO.getRepositoryPath().endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(fileDTO.getUniqueFilename());
        String filename = sb.toString();
        outputStream = new FileOutputStream(filename);
        logger.debug("filename: {}", filename);

        // copy channel
        inputChannel = Channels.newChannel(inputStream);
        outputChannel = Channels.newChannel(outputStream);
        fileSize = ChannelUtils.copy(inputChannel, outputChannel);

        // set vo
        if (StringUtils.isEmpty(fileDTO.getContentType())) {
            fileDTO.setContentType(TikaMimeDetectUtils.getMimeType(filename));
        }
        break;
    case DATABASE:
        // prepare steam
        outputStream = new ByteArrayOutputStream();

        // copy channel
        inputChannel = Channels.newChannel(inputStream);
        outputChannel = Channels.newChannel(outputStream);
        fileSize = ChannelUtils.copy(inputChannel, outputChannel);

        // set vo
        byte[] bytes = ((ByteArrayOutputStream) outputStream).toByteArray();
        fileDTO.setBytes(bytes);
        fileDTO.setRepositoryPath(null);
        if (StringUtils.isEmpty(fileDTO.getContentType())) {
            fileDTO.setContentType(TikaMimeDetectUtils.getMimeType(bytes));
        }
        break;
    }
    fileDTO.setFileSize(fileSize);

    // close io
    inputChannel.close();
    outputChannel.close();
    inputStream.close();
    outputStream.close();
}

From source file:com.radiohitwave.ftpsync.API.java

public String DownloadApplicationFile() throws IOException {
    try {//from  w w w  . j a  v  a  2 s  . c  o  m
        URL website = new URL(this.apiDomain + this.updateRemoteFile + "?" + System.nanoTime());
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        File downloadFolder = new File(this.tempFilePath);
        downloadFolder.mkdirs();
        FileOutputStream fos = new FileOutputStream(this.tempFilePath + "/" + this.updateLocalFile);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        return this.tempFilePath;
    } catch (FileNotFoundException ex) {
        Log.error(ex.toString());
        Log.remoteError(ex);
    }
    return null;
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public long createFileAtomic(String fileName, InputStream inputStream) throws IOException {
    long fileSize;
    Path filePath = this.directory.resolve(fileName);
    Path fileTempPath = this.directory.resolve(fileName + ".part");

    try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            FileChannel fc = FileChannel.open(fileTempPath, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) {
        fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }//www  .j a v a2 s  . c  om

    Files.move(fileTempPath, filePath);

    return fileSize;
}