Example usage for com.google.common.io ByteStreams copy

List of usage examples for com.google.common.io ByteStreams copy

Introduction

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

Prototype

public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException 

Source Link

Document

Copies all bytes from the readable channel to the writable channel.

Usage

From source file:com.axelor.meta.loader.DataLoader.java

private void copy(InputStream in, File toDir, String name) throws IOException {
    File dst = FileUtils.getFile(toDir, name);
    Files.createParentDirs(dst);//  ww  w. j a  va2  s. com
    OutputStream out = new FileOutputStream(dst);
    try {
        ByteStreams.copy(in, out);
    } finally {
        out.close();
    }
}

From source file:com.facebook.buck.doctor.DefaultDefectReporter.java

private void addFilesToArchive(CustomZipOutputStream out, ImmutableSet<Path> paths) throws IOException {
    for (Path logFile : paths) {
        Path destPath = logFile;/*ww w.ja v a  2  s.com*/
        if (destPath.isAbsolute()) {
            // If it's an absolute path, make it relative instead
            destPath = destPath.subpath(0, logFile.getNameCount());
            Preconditions.checkArgument(!destPath.isAbsolute(), "Should be a relative path", destPath);
        }
        if (destPath.getFileName().toString().startsWith(".")) {
            // If the file is hidden(UNIX terms) save it as normal file.
            destPath = Optional.ofNullable(destPath.getParent()).orElse(Paths.get(""))
                    .resolve(destPath.getFileName().toString().replaceAll("^\\.*", ""));
        }

        out.putNextEntry(new CustomZipEntry(destPath));

        try (InputStream input = filesystem.newFileInputStream(logFile)) {
            ByteStreams.copy(input, out);
        }
        out.closeEntry();
    }
}

From source file:org.apache.jackrabbit.oak.remote.http.handler.GetBinaryHandler.java

/**
 * RFC7233/*  ww w  .j  av a2s .  c  om*/
 * <p/>
 * This handler sends a 200 OK http status, the Content-Length header and
 * the entire file/binary content. This is used when the request Range
 * header is missing or it contains a malformed value.
 */
private void handleFile(HttpServletResponse response, RemoteSession session, RemoteBinaryId binaryId)
        throws IOException {

    InputStream in = session.readBinary(binaryId, new RemoteBinaryFilters());

    long length = session.readBinaryLength(binaryId);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/octet-stream");
    response.setContentLength((int) length);

    OutputStream out = response.getOutputStream();

    ByteStreams.copy(in, out);

    out.close();
}

From source file:org.opennms.netmgt.jasper.measurement.remote.MeasurementApiClient.java

private static void write(byte[] input, OutputStream outputStream) throws IOException {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
    ByteStreams.copy(inputStream, outputStream);
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static File copyMediaFromUri(Context context, Uri uri) throws IOException {
    InputStream is = null;//from ww w  . j av  a 2  s .c  om
    OutputStream os = null;
    try {
        ContentResolver contentResolver = context.getContentResolver();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "MAGE_" + timeStamp;

        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String extension = "." + mime.getExtensionFromMimeType(contentResolver.getType(uri));

        File directory = context.getExternalFilesDir("media");
        File file = File.createTempFile(imageFileName, /* prefix */
                extension, /* suffix */
                directory /* directory */
        );

        is = contentResolver.openInputStream(uri);
        os = new FileOutputStream(file);
        ByteStreams.copy(is, os);

        return file;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.person.RetrievePersonalPhotoAction.java

public static void writeUnavailablePhoto(HttpServletResponse response, ActionServlet actionServlet) {
    try {/* www .j  a v a 2  s  .  co  m*/
        response.setContentType("image/gif");
        InputStream stream = RetrievePersonalPhotoAction.class.getClassLoader()
                .getResourceAsStream("images/photo_placer01_" + I18N.getLocale().getLanguage() + ".gif");
        ByteStreams.copy(stream, response.getOutputStream());
        stream.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.google.gerrit.pgm.util.LogFileCompressor.java

private void compress(Path src) {
    Path dst = src.resolveSibling(src.getFileName() + ".gz");
    Path tmp = src.resolveSibling(".tmp." + src.getFileName());
    try {/*from  w  w  w .  j a v  a  2s.c o  m*/
        try (InputStream in = Files.newInputStream(src);
                OutputStream out = new GZIPOutputStream(Files.newOutputStream(tmp))) {
            ByteStreams.copy(in, out);
        }
        tmp.toFile().setReadOnly();
        try {
            Files.move(tmp, dst);
        } catch (IOException e) {
            throw new IOException("Cannot rename " + tmp + " to " + dst, e);
        }
        Files.delete(src);
    } catch (IOException e) {
        log.error("Cannot compress " + src, e);
        try {
            Files.deleteIfExists(tmp);
        } catch (IOException e2) {
            log.warn("Failed to delete temporary log file " + tmp, e2);
        }
    }
}

From source file:org.abs_models.backend.maude.MaudeCompiler.java

/**
 * @param args/*  w w  w  .jav  a2  s.  c o m*/
 * @throws Exception
 */
public int compile(String[] args) throws Exception {
    if (verbose)
        System.out.println("Generating Maude code...");
    final Model model = parse(args);
    if (model.hasParserErrors() || model.hasErrors() || model.hasTypeErrors()) {
        printErrorMessage();
        return 1;
    }

    PrintStream stream = System.out;
    if (outputfile != null) {
        stream = new PrintStream(outputfile);
    }
    // Are we running in the source directory?
    InputStream is = ClassLoader.getSystemResourceAsStream(RUNTIME_INTERPRETER_PATH);
    if (is == null) {
        // Are we running within absfrontend.jar?
        is = ClassLoader.getSystemResourceAsStream("maude/abs-interpreter.maude");
    }
    if (is == null) {
        throw new InternalBackendException("Could not locate abs-interpreter.maude");
    }
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    stream.println("*** Generated " + dateFormat.format(new Date()));
    ByteStreams.copy(is, stream);
    model.generateMaude(stream, module, mainBlock, clocklimit, defaultResources);
    if (verbose)
        System.out.println("Finished.  Start `maude " + outputfile.toString() + "' to run the model.");
    return 0;
}

From source file:org.haiku.haikudepotserver.support.web.FallbackController.java

private void streamFavicon(RequestMethod method, HttpServletResponse response) throws IOException {
    Preconditions.checkState(null != servletContext, "the servlet context must be supplied");
    response.setContentType(com.google.common.net.MediaType.ICO.toString());

    try (InputStream inputStream = servletContext.getResourceAsStream("/img/favicon.ico")) {
        if (null == inputStream) {
            throw new IllegalStateException("unable to find the favicon resource");
        }//  ww w  . j  a v  a2  s .  c  o m

        if (method != RequestMethod.HEAD) {
            ByteStreams.copy(inputStream, response.getOutputStream());
        }
    }
}

From source file:eu.esdihumboldt.hale.doc.user.examples.internal.extension.ExampleProject.java

/**
 * Create an example project from a configuration element.
 * /*www. j a v a2s . com*/
 * @param id the project identifier
 * @param conf the configuration element
 * @throws URISyntaxException if the project location can't be resolved to a
 *             valid URI
 * @throws IOException if reading the project information fails
 * @throws IOProviderConfigurationException if the project reader wasn't
 *             configured correctly
 */
public ExampleProject(String id, IConfigurationElement conf)
        throws URISyntaxException, IOProviderConfigurationException, IOException {
    super();

    this.id = id;
    this.summary = conf.getAttribute("summary");

    // determine location
    bundleName = conf.getDeclaringExtension().getContributor().getName();
    Bundle bundle = Platform.getBundle(bundleName);

    this.location = conf.getAttribute("location");
    URL url = bundle.getResource(location);
    if (url == null) {
        throw new IllegalStateException("Example project location not found in bundle");
    }
    LocatableInputSupplier<InputStream> in = new DefaultInputSupplier(url.toURI());

    // load project info
    ProjectReader reader = HaleIO.findIOProvider(ProjectReader.class, in, location);
    Map<String, ProjectFile> projectFiles = new HashMap<String, ProjectFile>();
    projectFiles.put(AlignmentIO.PROJECT_FILE_ALIGNMENT, new ProjectFile() {

        @Override
        public void store(LocatableOutputSupplier<OutputStream> target) throws Exception {
            throw new UnsupportedOperationException();
        }

        @Override
        public void reset() {
            // do nothing
        }

        @Override
        public void load(InputStream in) throws Exception {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(alignmentFile));
            // save to alignment file
            ByteStreams.copy(in, out);
            out.close();
            alignmentFile.deleteOnExit();
        }

        @Override
        public void apply() {
            // do nothing
        }
    });
    reader.setProjectFiles(projectFiles);
    reader.setSource(in);
    reader.execute(null);

    Project project = reader.getProject();

    // update paths in project
    updater = new LocationUpdater(project, url.toURI());
    // example projects cannot be saved where they are, so forget about
    // relative paths
    updater.updateProject(false);

    this.info = project;
}