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:rascal.storage.loose.LooseStorageNodeWritableChannel.java

private void initTempObjectFileChannel() throws IOException {
    Deflater deflater = new Deflater(storageConfiguration.getLooseCompressionLevel());
    DeflaterOutputStream output = new DeflaterOutputStream(new FileOutputStream(tempObjectFile), deflater);
    tempObjectFileChannel = Channels.newChannel(output);
}

From source file:updater.Updater.java

@SuppressWarnings("resource")
public Updater() {
    try {/*from   w  ww.  j  ava 2  s .com*/
        System.out.println("Checking for updates...");
        URL url1 = new URL(
                "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-version.txt");
        ReadableByteChannel obj1 = Channels.newChannel(url1.openStream());
        FileOutputStream outputstream1 = new FileOutputStream(".release-version.txt");
        outputstream1.getChannel().transferFrom(obj1, 0, Long.MAX_VALUE);
        FileReader file = new FileReader(".release-version.txt");
        BufferedReader reader = new BufferedReader(file);
        String DownloadedString = reader.readLine();
        File file2 = new File(".release-version.txt");
        if (file2.exists() && !file2.isDirectory()) {
            file2.delete();
        }
        double AvailableUpdate = Double.parseDouble(DownloadedString);
        InputStreamReader reader2 = new InputStreamReader(
                getClass().getResourceAsStream("/others/app-version.txt"));
        String tmp = IOUtils.toString(reader2);
        double ApplicationVersion = Double.parseDouble(tmp);
        if (AvailableUpdate > ApplicationVersion) {
            System.out.println("Your Droid PC Suite version: V" + ApplicationVersion);
            System.out.println(
                    "New update V" + AvailableUpdate + " is available! Please download latest version now!");
            URL url2 = new URL(
                    "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-changelog.txt");
            ReadableByteChannel obj2 = Channels.newChannel(url2.openStream());
            FileOutputStream outputstream2 = new FileOutputStream(".release-changelog.txt");
            outputstream2.getChannel().transferFrom(obj2, 0, Long.MAX_VALUE);
            UpdaterGUI obj = new UpdaterGUI();
            obj.setVisible(true);
        } else {
            System.out.println("You are running latest Droid PC Suite...");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Network.CReportHandler.java

@Override
public void update(Observable o, Object arg) {

    Socket objSocket = (Socket) arg;

    int intSeq = -1;

    try {//from w  w w . j av a  2 s  . c o  m

        System.out.println("dasdasdasdsa");

        /*            JSONParser jsonParser = new JSONParser();
                
                    JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream()));
                
                    System.out.println(objJSON.toJSONString());
                
                    int intTempSeq = Integer.parseInt(objJSON.get("id").toString());
                
                    CReport.genReport((JSONArray) objJSON.get("stats"));
                
                    intSeq = intTempSeq;*/

        //   } catch (IOException | ParseException | NumberFormatException | COSVisitorException ex) {
        //      System.out.println(ex);
    } finally {
        try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()),
                StandardCharsets.US_ASCII.name())) {

            objWriter.write(intSeq + "");
            objWriter.flush();

        } catch (IOException ex) {
            System.out.println(ex);
        }
    }

}

From source file:com.rogiel.httpchannel.service.channel.LinkedUploadChannelContentBody.java

@Override
public void writeTo(OutputStream out) throws IOException {
    final WritableByteChannel outputChannel = Channels.newChannel(out);
    channel.linkChannel(outputChannel);/*w  w  w . j av  a 2 s. c  o m*/
    while (channel.isOpen() && outputChannel.isOpen()) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
}

From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java

@SneakyThrows
public static void load(Plugin plugin) {
    try { // Check if it is already loaded
        Class.forName("org.yaml.snakeyaml.Yaml");
        return;//from  w  w w.  j a  v  a  2 s . c o  m
    } catch (ClassNotFoundException ignored) {
    }

    Path path = Paths.get("lib", SNAKE_YAML_JAR);

    if (Files.notExists(path)) {
        Files.createDirectories(path.getParent());

        plugin.getLogman().info("Downloading SnakeYAML...");

        URL url = new URL(SNAKE_YAML);
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");

        try (ReadableByteChannel source = Channels.newChannel(new DigestInputStream(url.openStream(), sha1));
                FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE)) {
            out.transferFrom(source, 0, Long.MAX_VALUE);
        }

        if (!new String(Hex.encodeHex(sha1.digest())).equals(EXPECTED_HASH)) {
            Files.delete(path);
            throw new IllegalStateException(
                    "Downloaded SnakeYAML, but checksum check failed. Please try again later.");
        }

        plugin.getLogman().info("Successfully downloaded!");
    }

    loadJAR(path);
}

From source file:org.neo4j.server.webdriver.WebdriverChromeDriver.java

private static ZipFile downloadFile(String fromUrl) {
    System.out.println("Downloading binary from " + fromUrl);
    try {/*  w  w w .ja va2  s . c o  m*/
        URL zipUrl = new URL(fromUrl);
        ReadableByteChannel rbc = Channels.newChannel(zipUrl.openStream());
        File localPath = new File(System.getProperty("java.io.tmpdir"), "chromedriver.zip");
        FileOutputStream zipOutputStream = new FileOutputStream(localPath);
        zipOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
        return new ZipFile(localPath);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.msr.dnsdemo.network.DownloadFile.java

public DownloadFile(final Context ctxt, String url, FileOutputStream out)
        throws IOException, NullPointerException {
    String version = "0.3.x";
    try {//from   w w w . j  a  va 2 s  .c  o  m
        version = ctxt.getPackageManager().getPackageInfo("com.msr.dnsdemo", 0).versionName;
    } catch (NameNotFoundException e) {
    }

    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter("http.useragent", USERAGENT + version);
    InputStream in = openURL(url);
    if (in == null) {
        Log.e(TAG, "Unable to download: " + url);
        return;
    }

    final ReadableByteChannel inputChannel = Channels.newChannel(in);
    final WritableByteChannel outputChannel = Channels.newChannel(out);

    try {
        Log.i(TAG, "Downloading " + url);
        fastChannelCopy(inputChannel, outputChannel);
    } finally {
        try {
            if (inputChannel != null) {
                inputChannel.close();
            }
            if (outputChannel != null) {
                outputChannel.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            if (e != null && e.getMessage() != null) {
                Log.e(TAG, e.getMessage());
            } else {
                Log.e(TAG, "fastChannelCopy() unknown error");
            }
        }
    }
}

From source file:com.destroystokyo.paperclip.Paperclip.java

static void run(final String[] args) {
    try {/*from w  w  w.  j a  v  a  2s  . c o  m*/
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Could not create hashing instance");
        e.printStackTrace();
        System.exit(1);
    }

    final PatchData patchInfo;
    try (final InputStream is = getConfig()) {
        patchInfo = PatchData.parse(is);
    } catch (final IllegalArgumentException e) {
        System.err.println("Invalid patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    } catch (final IOException e) {
        System.err.println("Error reading patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    final File vanillaJar = new File(cache, "mojang_" + patchInfo.getVersion() + ".jar");
    paperJar = new File(cache, "patched_" + patchInfo.getVersion() + ".jar");

    final boolean vanillaValid;
    final boolean paperValid;
    try {
        vanillaValid = checkJar(vanillaJar, patchInfo.getOriginalHash());
        paperValid = checkJar(paperJar, patchInfo.getPatchedHash());
    } catch (final IOException e) {
        System.err.println("Error reading jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    if (!paperValid) {
        if (!vanillaValid) {
            System.out.println("Downloading original jar...");
            //noinspection ResultOfMethodCallIgnored
            cache.mkdirs();
            //noinspection ResultOfMethodCallIgnored
            vanillaJar.delete();

            try (final InputStream stream = patchInfo.getOriginalUrl().openStream()) {
                final ReadableByteChannel rbc = Channels.newChannel(stream);
                try (final FileOutputStream fos = new FileOutputStream(vanillaJar)) {
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                }
            } catch (final IOException e) {
                System.err.println("Error downloading original jar");
                e.printStackTrace();
                System.exit(1);
            }

            // Only continue from here if the downloaded jar is correct
            try {
                if (!checkJar(vanillaJar, patchInfo.getOriginalHash())) {
                    System.err.println("Invalid original jar, quitting.");
                    System.exit(1);
                }
            } catch (final IOException e) {
                System.err.println("Error reading jar");
                e.printStackTrace();
                System.exit(1);
            }
        }

        if (paperJar.exists()) {
            if (!paperJar.delete()) {
                System.err.println("Error deleting invalid jar");
                System.exit(1);
            }
        }

        System.out.println("Patching original jar...");
        final byte[] vanillaJarBytes;
        final byte[] patch;
        try {
            vanillaJarBytes = getBytes(vanillaJar);
            patch = Utils.readFully(patchInfo.getPatchFile().openStream());
        } catch (final IOException e) {
            System.err.println("Error patching original jar");
            e.printStackTrace();
            System.exit(1);
            return;
        }

        // Patch the jar to create the final jar to run
        try (final FileOutputStream jarOutput = new FileOutputStream(paperJar)) {
            Patch.patch(vanillaJarBytes, patch, jarOutput);
        } catch (final CompressorException | InvalidHeaderException | IOException e) {
            System.err.println("Error patching origin jar");
            e.printStackTrace();
            System.exit(1);
        }
    }

    // Exit if user has set `paperclip.patchonly` system property to `true`
    if (Boolean.getBoolean("paperclip.patchonly")) {
        System.exit(0);
    }

    // Get main class info from jar
    final String main;
    try (final FileInputStream fs = new FileInputStream(paperJar);
            final JarInputStream js = new JarInputStream(fs)) {
        main = js.getManifest().getMainAttributes().getValue("Main-Class");
    } catch (final IOException e) {
        System.err.println("Error reading from patched jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    // Run the jar
    Utils.invoke(main, args);
}

From source file:info.lamatricexiste.network.Network.DownloadFile.java

public DownloadFile(final Context ctxt, String url, FileOutputStream out)
        throws IOException, NullPointerException {
    String version = "0.3.x";
    try {/*from  ww  w .  java  2s. com*/
        version = ctxt.getPackageManager().getPackageInfo(ActivityMain.TAG, 0).versionName;
    } catch (NameNotFoundException e) {
    }

    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter("http.useragent", USERAGENT + version);
    InputStream in = openURL(url);
    if (in == null) {
        Log.e(TAG, "Unable to download: " + url);
        return;
    }

    final ReadableByteChannel inputChannel = Channels.newChannel(in);
    final WritableByteChannel outputChannel = Channels.newChannel(out);

    try {
        Log.i(TAG, "Downloading " + url);
        fastChannelCopy(inputChannel, outputChannel);
    } finally {
        try {
            if (inputChannel != null) {
                inputChannel.close();
            }
            if (outputChannel != null) {
                outputChannel.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            if (e != null && e.getMessage() != null) {
                Log.e(TAG, e.getMessage());
            } else {
                Log.e(TAG, "fastChannelCopy() unknown error");
            }
        }
    }
}

From source file:org.kurento.test.utils.Ffmpeg.java

public static float getPesqMos(String audio, int sampleRate) {
    float pesqmos = 0;

    try {//  w  w w . ja v  a 2  s . co  m
        String pesq = KurentoTest.getTestFilesDiskPath() + "/bin/pesq/PESQ";
        String origWav = "";
        if (audio.startsWith(HTTP_TEST_FILES)) {
            origWav = KurentoTest.getTestFilesDiskPath() + audio.replace(HTTP_TEST_FILES, "");
        } else {
            // Download URL
            origWav = KurentoTest.getDefaultOutputFile("downloaded.wav");
            URL url = new URL(audio);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            FileOutputStream fos = new FileOutputStream(origWav);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
        }

        Shell.runAndWait(pesq, "+" + sampleRate, origWav, RECORDED_WAV);
        List<String> lines = FileUtils.readLines(new File(PESQ_RESULTS), "utf-8");
        pesqmos = Float.parseFloat(lines.get(1).split("\t")[2].trim());
        log.debug("PESQMOS " + pesqmos);

        Shell.runAndWait("rm", PESQ_RESULTS);

    } catch (IOException e) {
        log.error("Exception recording local audio", e);
    }

    return pesqmos;
}