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:opennlp.tools.doc_classifier.DocClassifierTrainingSetMultilingualExtender.java

private void copyURLToFile(URL url, File file) {
    ReadableByteChannel rbc = null;
    try {/*  w  w w .ja  v  a 2 s  .  c  o m*/
        rbc = Channels.newChannel(url.openStream());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file.getAbsolutePath());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.jeny.atmosphere.integration.websocket.RawWebSocketProtocol.java

private static ReadableByteChannel newChannel(final String s, final String charset)
        throws UnsupportedEncodingException {
    return Channels.newChannel(new ByteArrayInputStream(s.getBytes(charset)));
}

From source file:com.intel.chimera.CryptoCodecTest.java

private void cryptoCodecTestForReadableByteChannel(int count, String encCodecClass, String decCodecClass,
        byte[] iv) throws IOException {
    CryptoCodec encCodec = null;/*  ww  w.j  a  va  2s  . c  o m*/
    try {
        encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass),
                props);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto codec!");
    }
    LOG.info("Created a Codec object of type: " + encCodecClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);
    LOG.info("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = new CryptoOutputStream(Channels.newChannel(encryptedData), encCodec, bufferSize,
            key, iv);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.info("Finished encrypting data");

    CryptoCodec decCodec = null;
    try {
        decCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCodecClass),
                props);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto codec!");
    }
    LOG.info("Created a Codec object of type: " + decCodecClass);

    // Decrypt data
    CryptoInputStream in = new CryptoInputStream(
            Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())), decCodec, bufferSize,
            key, iv);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    // Decrypt data byte-at-a-time
    in = new CryptoInputStream(Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())),
            decCodec, bufferSize, key, iv);

    // Check
    DataInputStream originalIn = new DataInputStream(
            new BufferedInputStream(new ByteArrayInputStream(originalData)));
    int expected;
    do {
        expected = originalIn.read();
        Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read());
    } while (expected != -1);

    LOG.info("SUCCESS! Completed checking " + count + " records");
}

From source file:org.geotools.gce.imagepyramid.ImagePyramidReader.java

/**
 * Constructor for an {@link ImagePyramidReader}.
 * /*from w ww .  j  a v  a  2  s  .co m*/
 * @param source
 *            The source object.
 * @param uHints
 *            {@link Hints} to control the behaviour of this reader.
 * @throws IOException
 * @throws UnsupportedEncodingException
 * 
 */
public ImagePyramidReader(Object source, Hints uHints) throws IOException {
    // //
    //
    // managing hints
    //
    // //
    if (this.hints == null)
        this.hints = new Hints();
    if (uHints != null) {
        this.hints.add(uHints);
    }
    this.coverageFactory = CoverageFactoryFinder.getGridCoverageFactory(this.hints);

    // //
    //
    // Check source
    //
    // //
    if (source == null) {

        throw new DataSourceException("ImagePyramidReader:null source set to read this coverage.");
    }
    this.source = source;
    this.sourceURL = Utils.checkSource(source, uHints);
    if (sourceURL == null) {
        throw new IllegalArgumentException("This plugin accepts only File, URL and String pointing to a file");
    }

    // //
    // //
    //
    // get the crs if able to
    //
    // //      
    final URL prjURL = DataUtilities.changeUrlExt(sourceURL, "prj");
    PrjFileReader crsReader = null;
    try {
        crsReader = new PrjFileReader(Channels.newChannel(prjURL.openStream()));
    } catch (FactoryException e) {
        throw new DataSourceException(e);
    } finally {
        try {
            crsReader.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
        }
    }
    final Object tempCRS = hints.get(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM);
    if (tempCRS != null) {
        this.crs = (CoordinateReferenceSystem) tempCRS;
        LOGGER.log(Level.WARNING, "Using forced coordinate reference system " + crs.toWKT());
    } else {
        final CoordinateReferenceSystem tempcrs = crsReader.getCoordinateReferenceSystem();
        if (tempcrs == null) {
            // use the default crs
            crs = AbstractGridFormat.getDefaultCRS();
            LOGGER.log(Level.WARNING,
                    "Unable to find a CRS for this coverage, using a default one: " + crs.toWKT());
        } else
            crs = tempcrs;
    }

    //
    // Load properties file with information about levels and envelope
    //
    parseMainFile(sourceURL);
}

From source file:org.wso2.carbon.identity.common.testng.MockInitialContextFactory.java

/**
 * Copies a resource inside a jar to external file within a directory.
 * Then returns the created file./*  w ww  .j ava  2  s.com*/
 *
 * @param relativeFilePath
 * @param clazz
 * @return
 * @throws TestCreationException
 */
private static File copyTempFile(String relativeFilePath, Class clazz) throws TestCreationException {

    URL url = clazz.getClassLoader().getResource(relativeFilePath);
    if (url == null) {
        throw new TestCreationException("Could not find a resource on the classpath : " + relativeFilePath);
    }
    InputStream inputStream;
    try {
        inputStream = url.openStream();
        ReadableByteChannel inputChannel = Channels.newChannel(inputStream);
        File tempFile = File.createTempFile("tmp_", "_registry.sql");
        FileOutputStream fos = new FileOutputStream(tempFile);
        WritableByteChannel targetChannel = fos.getChannel();
        //Transfer data from input channel to output channel
        ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE);
        inputStream.close();
        targetChannel.close();
        fos.close();
        return tempFile;
    } catch (IOException e) {
        throw new TestCreationException(
                "Could not copy the file content to temp file from : " + relativeFilePath);
    }
}

From source file:com.thinkberg.vfs.s3.jets3t.Jets3tFileObject.java

protected InputStream doGetInputStream() throws Exception {
    if (!contentCached) {
        object = service.getObject(bucket, getS3Key());
        LOG.debug(String.format("caching content of '%s'", object.getKey()));

        InputStream objectInputStream = object.getDataInputStream();
        if (object.getContentLength() > 0) {
            ReadableByteChannel rbc = Channels.newChannel(objectInputStream);
            FileChannel cacheFc = getCacheFile().getChannel();
            cacheFc.transferFrom(rbc, 0, object.getContentLength());
            cacheFc.close();//from  ww  w  . ja v a2s  .c  o  m
            rbc.close();
        } else {
            objectInputStream.close();
        }
        contentCached = true;
    }

    return Channels.newInputStream(getCacheFile().getChannel());
}

From source file:com.titankingdoms.nodinchan.mobjockeys.MobJockeys.java

/**
 * Checks for update of the library//w  ww  . j  a  v  a  2s.  c  o m
 */
private void updateLib() {
    PluginManager pm = getServer().getPluginManager();

    NCBL libPlugin = (NCBL) pm.getPlugin("NC-BukkitLib");

    File destination = new File(getDataFolder().getParentFile().getParentFile(), "lib");
    destination.mkdirs();

    File lib = new File(destination, "NC-BukkitLib.jar");
    File pluginLib = new File(getDataFolder().getParentFile(), "NC-BukkitLib.jar");

    boolean inPlugins = false;
    boolean download = false;

    try {
        URL url = new URL("http://bukget.org/api/plugin/nc-bukkitlib");

        JSONObject jsonPlugin = (JSONObject) new JSONParser().parse(new InputStreamReader(url.openStream()));
        JSONArray versions = (JSONArray) jsonPlugin.get("versions");

        if (libPlugin == null) {
            getLogger().log(Level.INFO, "Missing NC-Bukkit lib");
            inPlugins = true;
            download = true;

        } else {
            double currentVer = Double.parseDouble(libPlugin.getDescription().getVersion());
            double newVer = currentVer;

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    newVer = Double
                            .parseDouble(((String) version.get("name")).split(" ")[1].trim().substring(1));
                    break;
                }
            }

            if (newVer > currentVer) {
                getLogger().log(Level.INFO, "NC-Bukkit lib outdated");
                download = true;
            }
        }

        if (download) {
            System.out.println("Downloading NC-Bukkit lib...");

            String dl_link = "";

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    dl_link = (String) version.get("dl_link");
                    break;
                }
            }

            if (dl_link == null)
                throw new Exception();

            URL link = new URL(dl_link);
            ReadableByteChannel rbc = Channels.newChannel(link.openStream());

            if (inPlugins) {
                FileOutputStream output = new FileOutputStream(pluginLib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
                pm.loadPlugin(pluginLib);

            } else {
                FileOutputStream output = new FileOutputStream(lib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
            }

            getLogger().log(Level.INFO, "Downloaded NC-Bukkit lib");
        }

    } catch (Exception e) {
        System.out.println("Failed to check for library update");
    }
}

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

private void assertFileEquals(InputStream expected, InputStream actual, State state) throws IOException {
    ByteBuffer bb1 = ByteBuffer.allocate(1024);
    ByteBuffer bb2 = ByteBuffer.allocate(1024);
    int count1 = 0;
    int count2 = 0;

    try (ReadableByteChannel channel = Channels.newChannel(expected);
            ReadableByteChannel channel1 = Channels.newChannel(actual)) {
        int i1 = channel.read(bb1);
        bb1.flip();/*from   ww  w .  j a v  a 2s . c  om*/

        int i2 = channel1.read(bb2);
        bb2.flip();

        if (i1 == i2) {
            count1 += i1;
            count2 += i2;
            assertTrue("Not equal at " + state, bb1.equals(bb2));
        } else {
            fail("Not equal at " + state);
        }
    }
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static IOStaging createStagingAndCopyFromInputstream(InputStream is, long length,
        IOStagingFactory factory) throws NetIOException {
    IOStaging staging = factory.newInstance();
    ReadableByteChannel channel = Channels.newChannel(is);

    staging.transferFrom(channel, 0, length);
    staging.reset();/*from   w w w . j a v  a2  s  .co m*/

    return staging;
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Sends a file to a URL/*from w  w w  . jav a 2s . co m*/
 * @param url URL to send to
 * @param file File to send
 * @return If successful
 */
@Action(aliases = { "sendFile", "fileSend" })
public boolean sendFile(final String url, final String file) {
    FileOutputStream fileOutputStream = null;
    ReadableByteChannel readableByteChannel = null;
    try {
        File file_ = new File(file);
        if (file_.exists())
            if (!deleteFile(file_.getPath()))
                return false;
        URL url_ = new URL(url);
        readableByteChannel = Channels.newChannel(url_.openStream());
        fileOutputStream = new FileOutputStream(file_);
        fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, 1 << 24);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null)
                fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (readableByteChannel != null)
                readableByteChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}