Example usage for com.google.common.io InputSupplier InputSupplier

List of usage examples for com.google.common.io InputSupplier InputSupplier

Introduction

In this page you can find the example usage for com.google.common.io InputSupplier InputSupplier.

Prototype

InputSupplier

Source Link

Usage

From source file:com.jeffplaisance.util.fingertree.bytestring.FingerTreeByteString.java

@Override
public InputStream newInput() {
    try {//from w  ww. j av  a 2  s  .c  o  m
        return ByteStreams
                .join(Iterables.transform(bytes, new Function<ByteStringLiteral, InputSupplier<InputStream>>() {
                    @Override
                    public InputSupplier<InputStream> apply(final ByteStringLiteral literal) {
                        return new InputSupplier<InputStream>() {
                            @Override
                            public InputStream getInput() throws IOException {
                                return literal.newInput();
                            }
                        };
                    }
                })).getInput();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.seedboxer.seedboxer.ws.controller.DownloadsController.java

/**
 * Save torrent file to watch-dog directory of downloader application (rTorrent or uTorrent) and
 * add the same torrent to the user queue.
 *
 * @param fileName//from w  w  w  .j  av  a2s. c o m
 * @param torrentFileInStream
 * @throws Exception
 */
public void addTorrent(String username, String fileName, final InputStream torrentFileInStream)
        throws Exception {
    User user = getUser(username);

    File torrent = new File(watchDownloaderPath + File.separator + fileName);
    Files.copy(new InputSupplier<InputStream>() {
        @Override
        public InputStream getInput() throws IOException {
            return torrentFileInStream;
        }
    }, torrent);
    torrent.setReadable(true, false);
    torrent.setWritable(true, false);
    String name = TorrentUtils.getName(torrent);
    putToDownload(user, Collections.singletonList(name), false);
}

From source file:org.dishevelled.variation.vcf.VcfReader.java

/**
 * Read zero or more VCF samples from the specified input stream.
 *
 * @param inputStream input stream to read from, must not be null
 * @return zero or more VCF samples read from the specified input stream
 * @throws IOException if an I/O error occurs
 *//* w  w  w. ja va  2  s  .c  o  m*/
static Iterable<VcfSample> samples(final InputStream inputStream) throws IOException {
    checkNotNull(inputStream);
    return samples(new InputSupplier<InputStreamReader>() {
        @Override
        public InputStreamReader getInput() throws IOException {
            return new InputStreamReader(inputStream);
        }
    });
}

From source file:com.mycelium.wallet.bitid.BitIdAsyncTask.java

@Override
protected BitIDResponse doInBackground(Void... params) {
    final BitIDResponse response = new BitIDResponse();
    try {//from ww w .ja v a2s.co m

        SignedMessage signature = privateKey.signMessage(request.getFullUri(), new AndroidRandomSource());

        final HttpURLConnection conn = (HttpURLConnection) new URL(request.getCallbackUri()).openConnection();
        //todo evaluate enforceSslCorrectness to disable verification stuff if false (and remove setting it to true)
        enforceSslCorrectness = true;
        conn.setReadTimeout(MyceliumWalletApi.SHORT_TIMEOUT_MS);
        conn.setConnectTimeout(MyceliumWalletApi.SHORT_TIMEOUT_MS);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(request.getCallbackJson(address, signature).toString());
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        try {
            response.code = conn.getResponseCode();
        } catch (IOException ioe) {
            //yes, this seems weird, but there might be a IOException in case of a 401 response, and afterwards the object is in a stable state again
            response.code = conn.getResponseCode();
        }
        response.message = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                if (response.code >= 200 && response.code < 300) {
                    return conn.getInputStream();
                }
                return conn.getErrorStream();
            }
        }, Charsets.UTF_8));

        if (response.code >= 200 && response.code < 300) {
            response.status = BitIDResponse.ResponseStatus.SUCCESS;
        } else {
            response.status = BitIDResponse.ResponseStatus.ERROR;
        }

    } catch (SocketTimeoutException e) {
        //connection timed out
        response.status = BitIDResponse.ResponseStatus.TIMEOUT;
    } catch (UnknownHostException e) {
        //host not known, most probably the device has no internet connection
        response.status = BitIDResponse.ResponseStatus.NOCONNECTION;
    } catch (SSLException e) {
        Preconditions.checkState(enforceSslCorrectness);
        //ask user whether he wants to proceed although there is a problem with the certificate
        response.message = e.getLocalizedMessage();
        response.status = BitIDResponse.ResponseStatus.SSLPROBLEM;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return response;
}

From source file:org.jetbrains.kotlin.maven.K2JSCompilerMojo.java

protected void copyJsLibraryFile(String jsLib) throws MojoExecutionException {
    // lets copy the kotlin library into the output directory
    try {/*from   ww w  . j  a va 2s  . c om*/
        outputKotlinJSDir.mkdirs();
        final InputStream inputStream = MetaInfServices.loadClasspathResource(jsLib);
        if (inputStream == null) {
            System.out.println("WARNING: Could not find " + jsLib + " on the classpath!");
        } else {
            InputSupplier<InputStream> inputSupplier = new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return inputStream;
                }
            };
            Files.copy(inputSupplier, new File(outputKotlinJSDir, jsLib));
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.fusesource.process.manager.support.ProcessManagerImpl.java

@Override
public Installation installJar(final JarInstallParameters parameters) throws Exception {
    InstallScript installScript = new InstallScript() {
        @Override//from   w  w  w . j  a v a2  s  . c om
        public void doInstall(ProcessConfig config, int id, File installDir) throws Exception {
            String name = parameters.getGroupId() + ":" + parameters.getArtifactId();
            String version = parameters.getVersion();
            if (!Strings.isNullOrEmpty(version)) {
                name += ":" + version;
            }
            config.setName(name);

            // lets untar the process launcher
            String resourceName = "process-launcher.tar.gz";
            final InputStream in = getClass().getClassLoader().getResourceAsStream(resourceName);
            Preconditions.checkNotNull(in, "Could not find " + resourceName + " on the file system");
            File tmpFile = File.createTempFile("process-launcher", ".tar.gz");
            Files.copy(new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return in;
                }
            }, tmpFile);
            FileUtils.extractTar(tmpFile, installDir, untarTimeout, executor);

            // lets generate the etc configs
            File etc = new File(installDir, "etc");
            etc.mkdirs();
            Files.write("", new File(etc, "config.properties"), Charsets.UTF_8);
            Files.write("", new File(etc, "jvm.config"), Charsets.UTF_8);

            JarInstaller installer = new JarInstaller(executor);
            installer.unpackJarProcess(config, id, installDir, parameters);
        }
    };
    return installViaScript(parameters.getControllerJson(), installScript);
}

From source file:com.notifier.desktop.transport.usb.impl.Adb.java

protected String runAdb(String... args) throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(Lists.asList(getAdbPath(), args));
    processBuilder.redirectErrorStream(true);
    final Process process = processBuilder.start();
    String output = CharStreams.toString(new InputSupplier<BufferedReader>() {
        @Override/*  w w w .  j a  va 2 s .c  o m*/
        public BufferedReader getInput() throws IOException {
            return new BufferedReader(new InputStreamReader(process.getInputStream()));
        }
    });
    logger.trace("adb output:\n{}", output);
    int exitCode = process.waitFor();
    if (exitCode != 0) {
        throw new IOException("adb returned error code: " + exitCode);
    }
    return output;
}

From source file:com.facebook.buck.java.AccumulateClassNamesStep.java

/**
 * @return an Optional that will be absent if there was an error.
 *///  w  ww.j  a va2  s. com
private Optional<ImmutableSortedMap<String, HashCode>> calculateClassHashes(ExecutionContext context,
        Path path) {
    final ImmutableSortedMap.Builder<String, HashCode> classNamesBuilder = ImmutableSortedMap.naturalOrder();
    ClasspathTraversal traversal = new ClasspathTraversal(Collections.singleton(path),
            context.getProjectFilesystem()) {
        @Override
        public void visit(final FileLike fileLike) throws IOException {
            // When traversing a JAR file, it may have resources or directory entries that do not
            // end in .class, which should be ignored.
            if (!FileLikes.isClassFile(fileLike)) {
                return;
            }

            String key = FileLikes.getFileNameWithoutClassSuffix(fileLike);
            InputSupplier<InputStream> input = new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return fileLike.getInput();
                }
            };
            HashCode value = ByteStreams.hash(input, Hashing.sha1());
            classNamesBuilder.put(key, value);
        }
    };

    try {
        new DefaultClasspathTraverser().traverse(traversal);
    } catch (IOException e) {
        context.logError(e, "Error accumulating class names for %s.", pathToJarOrClassesDirectory);
        return Optional.absent();
    }

    return Optional.of(classNamesBuilder.build());
}

From source file:com.notifier.desktop.os.OperatingSystems.java

private static File getWindowsStartupDirFromRegistry() {
    try {/*  w ww  .  jav  a  2 s. co  m*/
        ProcessBuilder builder = new ProcessBuilder("reg", "query",
                "\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"", "/v",
                "Startup");
        final Process process = builder.start();
        String result = CharStreams.toString(new InputSupplier<InputStreamReader>() {
            @Override
            public InputStreamReader getInput() throws IOException {
                return new InputStreamReader(process.getInputStream());
            }
        });
        String startupDirName = result.substring(result.indexOf("REG_SZ") + 6).trim();
        return new File(startupDirName);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.facebook.presto.util.InMemoryTpchBlocksProvider.java

private static InputSupplier<InputStreamReader> readResource(final String name) {
    return new InputSupplier<InputStreamReader>() {
        @Override//from  w  w w .  j ava 2 s .  c o m
        public InputStreamReader getInput() throws IOException {
            URL url = Resources.getResource(name);
            GZIPInputStream gzip = new GZIPInputStream(url.openStream());
            return new InputStreamReader(gzip, UTF_8);
        }
    };
}