Example usage for com.google.common.io ByteSource wrap

List of usage examples for com.google.common.io ByteSource wrap

Introduction

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

Prototype

public static ByteSource wrap(byte[] b) 

Source Link

Document

Returns a view of the given byte array as a ByteSource .

Usage

From source file:org.codice.alliance.plugin.nitf.NitfPreStoragePlugin.java

private ContentItem createOriginalImage(String id, BufferedImage image, Metacard metacard) {

    try {//w w w  .  j a  v a  2  s  . c  om
        byte[] originalBytes = renderToJpeg2k(image);

        ByteSource source = ByteSource.wrap(originalBytes);
        ContentItem contentItem = new ContentItemImpl(id, ORIGINAL, source, IMAGE_JPEG2K,
                buildDerivedImageTitle(metacard.getTitle(), ORIGINAL, JP2), originalBytes.length, metacard);

        addDerivedResourceAttribute(metacard, contentItem);

        return contentItem;

    } catch (IOException e) {
        LOGGER.debug(e.getMessage(), e);
    }

    return null;
}

From source file:org.excalibur.core.ssh.jsch.JschSshClient.java

@Override
public void put(String path, String contents) {
    put(path, Payloads.newByteSourcePayload(ByteSource.wrap(checkNotNull(contents, "contents").getBytes())));
}

From source file:org.jooby.internal.SseRenderer.java

private static ByteSource bytes(final String value) {
    return ByteSource.wrap(value.getBytes(StandardCharsets.UTF_8));
}

From source file:org.jooby.internal.SseRenderer.java

@Override
protected void _send(final byte[] bytes) throws Exception {
    List<Integer[]> lines = split(bytes);
    if (lines.size() == 1) {
        data = ByteSource.concat(data, DATA, ByteSource.wrap(bytes), NL);
    } else {//from  ww  w.  jav a 2 s  . c  om
        for (Integer[] line : lines) {
            data = ByteSource.concat(data, DATA, ByteSource.wrap(bytes).slice(line[0], line[1] - line[0]), NL);
        }
    }
}

From source file:be.iminds.aiolos.cloud.jclouds.CloudManagerImplJClouds.java

private VMInstance provisionOSGiRuntime(String bndrun, List<String> resources, NodeMetadata node)
        throws Exception {

    int osgiPort = 9278;
    int httpPort = 8080;

    Activator.logger.log(LogService.LOG_INFO, "Waiting for node " + node.getHostname() + " to come online...");
    SshClient sshClient = computeService.getContext().utils().sshForNode().apply(NodeMetadataBuilder
            .fromNodeMetadata(node).privateAddresses(Collections.<String>emptyList()).build());
    Activator.logger.log(LogService.LOG_INFO, "Node " + node.getHostname() + " online, provision OSGi");

    synchronized (this) {
        try {//from   w w w  .  j a  va 2s.co  m
            sshClient.connect();

            Activator.logger.log(LogService.LOG_INFO, "Connected to node " + node.getHostname() + " at ip "
                    + sshClient.getHostAddress() + ", uploading necessary files...");

            // set build.bnd and copy ext folder
            sshClient.exec("mkdir -p /tmp/AIOLOS/cnf/ext");
            sshClient.exec("touch /tmp/AIOLOS/cnf/build.bnd");

            File ext = new File("../cnf/ext");
            for (String name : ext.list()) {
                uploadFile(sshClient, "../cnf/ext/" + name, "/tmp/AIOLOS/cnf/ext/" + name);
            }

            // upload bnd
            String bnd = null;
            File bndDir = new File("../cnf/plugins/biz.aQute.bnd");
            for (String name : bndDir.list()) {
                bnd = name;
                break;
            }
            if (bnd == null)
                throw new Exception("No bnd present...");

            uploadFile(sshClient, "../cnf/plugins/biz.aQute.bnd/" + bnd,
                    "/tmp/AIOLOS/cnf/plugins/biz.aQute.bnd/" + bnd);

            // upload bnd repository plugin TODO avoid hard coded url?
            uploadFile(sshClient, "../cnf/plugins/biz.aQute.repository/biz.aQute.repository-2.1.0.jar",
                    "/tmp/AIOLOS/cnf/plugins/biz.aQute.repository/biz.aQute.repository-2.1.0.jar");

            // copy all bndrun files present (can be used for cloudmanagers on the new machine)
            sshClient.exec("mkdir -p /tmp/AIOLOS/tools");
            for (File file : getFilteredBndRunFiles()) {
                uploadFile(sshClient, file.getAbsolutePath(), "/tmp/AIOLOS/tools/" + file.getName());
            }

            // Set the rsa.ip property to the public ip of the VM
            try {
                Properties run = new Properties();
                run.load(new FileInputStream(new File(bndrun)));
                String runproperties = run.getProperty("-runproperties");

                // check for port properties
                try {
                    Properties props = new Properties();
                    props.load(new ByteArrayInputStream(runproperties.replaceAll(",", "\n").getBytes("UTF-8")));
                    String osgiPortString = props.getProperty("rsa.port");
                    if (osgiPortString != null) {
                        osgiPort = Integer.parseInt(osgiPortString);
                    }
                    String httpPortString = props.getProperty("org.osgi.service.http.port");
                    if (httpPortString != null) {
                        httpPort = Integer.parseInt(httpPortString);
                    }
                } catch (Exception e) {
                }

                String publicIP = node.getPublicAddresses().iterator().next();
                String privateIP = node.getPrivateAddresses().iterator().next();
                if (runproperties == null)
                    runproperties = "rsa.ip=" + publicIP + ",private.ip=" + privateIP + ",public.ip="
                            + publicIP;
                else
                    runproperties += ",rsa.ip=" + publicIP + ",private.ip=" + privateIP + ",public.ip="
                            + publicIP;
                run.put("-runproperties", runproperties);
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                run.store(bao, "bnd run configuration");
                bao.flush();
                ByteSource byteSource = ByteSource.wrap(bao.toByteArray());
                Payload payload = new ByteSourcePayload(byteSource);
                payload.getContentMetadata().setContentLength(byteSource.size());
                bao.close();
                sshClient.put("/tmp/AIOLOS/tools/" + bndrun, payload);
            } catch (Exception e) {
                throw new Exception("Invalid bndrun configuration provided " + bndrun);
            }

            // copy resources
            if (resources != null) {
                sshClient.exec("mkdir -p /tmp/AIOLOS/tools/resources");
                for (String r : resources) {
                    File f = new File(r);
                    ByteSource byteSource = Files.asByteSource(f);
                    Payload payload = new ByteSourcePayload(byteSource);
                    payload.getContentMetadata().setContentLength(byteSource.size());
                    sshClient.put("/tmp/AIOLOS/tools/resources/" + f.getName(), payload);
                }
            }
            if (publicKeyFile != null && publicKeyFile.exists()) {
                try {
                    uploadFile(sshClient, publicKeyFile.getAbsolutePath(),
                            "/tmp/AIOLOS/tools/resources/shared.pub");
                } catch (IOException e) {
                }
            }

            // upload repositories
            // TODO don't hard code this?
            uploadDir(sshClient, "../cnf/localrepo", "/tmp/AIOLOS/cnf/localrepo");
            uploadDir(sshClient, "../cnf/releaserepo", "/tmp/AIOLOS/cnf/releaserepo");
            uploadDir(sshClient, "../tools/generated/workspacerepo",
                    "/tmp/AIOLOS/tools/generated/workspacerepo");

            // start 
            ByteSource byteSource = ByteSource
                    .wrap(buildBndRunScript(bnd, bndrun, node.getOperatingSystem()).getBytes());
            Payload payload = new ByteSourcePayload(byteSource);
            payload.getContentMetadata().setContentLength(byteSource.size());
            sshClient.put("/tmp/AIOLOS/init.sh", payload);
            sshClient.exec("chmod a+x /tmp/AIOLOS/init.sh");

            Activator.logger.log(LogService.LOG_INFO, "Start OSGi on node " + node.getHostname() + "  ...");
            ExecResponse response = sshClient
                    .exec("nohup /tmp/AIOLOS/init.sh >> /tmp/AIOLOS/init.log 2>&1 < /dev/null");
            if (response.getExitStatus() != 0) {
                Activator.logger.log(LogService.LOG_ERROR,
                        "Execution of script failed: " + response.getError());
            }
        } finally {
            if (sshClient != null)
                sshClient.disconnect();
        }
    }
    return new VMInstance(node.getId(), node.getUri(), node.getName(), node.getGroup(), node.getImageId(),
            node.getStatus().name(), node.getHostname(), node.getPrivateAddresses(), node.getPublicAddresses(),
            node.getHardware().getName(), osgiPort, httpPort);
}

From source file:org.eclipse.che.api.vfs.server.impl.memory.MemoryVirtualFile.java

@Override
public LazyIterator<Pair<String, String>> countMd5Sums() throws ServerException {
    checkExist();/*from  w w  w .ja  v  a2  s.  c o  m*/
    if (isFile()) {
        return LazyIterator.emptyIterator();
    }

    final List<Pair<String, String>> hashes = new ArrayList<>();
    final int trimPathLength = getPath().length() + 1;
    final HashFunction hashFunction = Hashing.md5();
    final ValueHolder<ServerException> errorHolder = new ValueHolder<>();
    accept(new VirtualFileVisitor() {
        @Override
        public void visit(final VirtualFile virtualFile) {
            try {
                if (virtualFile.isFile()) {
                    try (InputStream stream = virtualFile.getContent().getStream()) {
                        final String hexHash = ByteSource.wrap(ByteStreams.toByteArray(stream))
                                .hash(hashFunction).toString();
                        hashes.add(Pair.of(hexHash, virtualFile.getPath().substring(trimPathLength)));
                    } catch (ForbiddenException e) {
                        throw new ServerException(e.getServiceError());
                    } catch (IOException e) {
                        throw new ServerException(e);
                    }
                } else {
                    final LazyIterator<VirtualFile> children = virtualFile.getChildren(VirtualFileFilter.ALL);
                    while (children.hasNext()) {
                        children.next().accept(this);
                    }
                }
            } catch (ServerException e) {
                errorHolder.set(e);
            }
        }
    });
    final ServerException error = errorHolder.get();
    if (error != null) {
        throw error;
    }
    return LazyIterator.fromList(hashes);
}

From source file:org.jclouds.kinetic.strategy.internal.KineticStorageStrategyImpl.java

private Blob getChunkedBlob(final String container, final String key, final long chunkId) {
    BlobBuilder builder = blobBuilders.get();
    builder.name(key);//  w  w w.j  a  va2  s. c om
    File file = getFileForBlobKey(container, key);

    try {
        List<String> chunkKeys = KineticDatabaseUtils.getInstance()
                .getFileChunkKeysFromDatabase(file.getPath());
        byte[] blobData = new byte[0];
        for (String chunkKey : chunkKeys) {
            byte[] data = KineticDatabaseUtils.getInstance().getChunkFromDatabase(chunkKey);
            blobData = ArrayUtils.addAll(blobData, data);
        }

        return this.createBlobFromByteSource(container, key, ByteSource.wrap(blobData));

    } catch (SQLException sqle) {

        ByteSource byteSource;

        if (getDirectoryBlobSuffix(key) != null) {
            logger.debug("%s - %s is a directory", container, key);
            byteSource = ByteSource.empty();
        } else {
            byteSource = Files.asByteSource(file).slice(chunkId, KineticConstants.PROPERTY_CHUNK_SIZE_BYTES
                    - KineticConstants.PROPERTY_CHUNK_FULL_HEADER_SIZE_BYTES);
        }

        return this.createBlobFromByteSource(container, key, byteSource);
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.LayerController.java

@RequestMapping(value = "/{wsName}/{name}/style", method = RequestMethod.PUT, consumes = YsldHandler.MIMETYPE)
@ResponseStatus(value = HttpStatus.OK)//from  w  w w  .j  a  v a2 s  .com
public void style(@RequestBody byte[] rawStyle, @PathVariable String wsName, @PathVariable String name,
        @RequestParam(value = "map", required = false) String mapName) throws IOException {
    // first thing is sanity check on the style content
    List<MarkedYAMLException> errors = (List) Styles.handler(YsldHandler.FORMAT)
            .validate(ByteSource.wrap(rawStyle).openStream(), null, null);

    if (!errors.isEmpty()) {
        throw new InvalidYsldException(errors);
    }

    Catalog cat = geoServer.getCatalog();
    WorkspaceInfo ws = findWorkspace(wsName, cat);
    LayerInfo l = findLayer(wsName, name, cat);

    StyleInfo s = l.getDefaultStyle();

    //Style does not exist, create one
    if (s == null) {
        // create one
        s = createYsld(name, ws);
        l.getStyles().add(s);
        l.setDefaultStyle(s);
    }
    //Converting from an existing style in a different format
    else if (!YsldHandler.FORMAT.equalsIgnoreCase(s.getFormat())) {

        // reuse base file name
        String base = FilenameUtils.getBaseName(s.getFilename());
        l.getStyles().add(s);

        //Create a new style and set as the default
        s = createYsld(base + "_YSLD", ws);
        l.getStyles().add(s);
        l.setDefaultStyle(s);
    }

    s.setFormat(YsldHandler.FORMAT);
    s.setFormatVersion(new Version("1.0.0"));

    // write out the resource
    OutputStream output = dataDir().style(s).out();
    try {
        try {
            IOUtils.copy(ByteSource.wrap(rawStyle).openStream(), output);
            output.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        try {
            //For a FileSystemResource, a temp file is copied to the actual file on close().
            output.close();
        } catch (NullPointerException npe) {
            //The temp file has already been saved and deleted, therefore npe (not an error).
        } catch (IOException ioe) {
            //Failed to modify one of the files. We have probably failed to save the changes.
            throw new RuntimeException("Failed to modify resource", ioe);
        }
    }

    if (s.getId() == null) {
        cat.add(s);
    } else {
        cat.save(s);
    }

    Date mod = new Date();
    Metadata.modified(l, mod);

    LayerGroupInfo map = null;
    if (mapName != null) {
        map = findMap(wsName, mapName, cat);
    }

    cat.save(l);
    recent.add(LayerInfo.class, l, wsName);
    recent.add(WorkspaceInfo.class, ws);
    if (map != null) {
        Metadata.modified(map, mod);
        cat.save(map);

        recent.add(LayerGroupInfo.class, map);
    }
}

From source file:com.android.builder.internal.packaging.zip.StoredEntry.java

/**
 * Loads all data in memory and replaces {@link #mSource} with one that contains all the data
 * in memory.//from  ww  w.j  a  va 2 s  . c  o m
 *
 * <p>If the entry's contents are already in memory, this call does nothing.
 *
 * @throws IOException failed to replace the source
 */
void loadSourceIntoMemory() throws IOException {
    if (mCdh.getOffset() == -1) {
        /*
         * No offset in the CDR means data has not been written to disk which, in turn,
         * means data is already loaded into memory.
         */
        return;
    }

    ProcessedAndRawByteSources oldSource = mSource;
    byte[] rawContents = oldSource.getRawByteSource().read();
    mSource = createSourcesFromRawContents(
            new CloseableDelegateByteSource(ByteSource.wrap(rawContents), rawContents.length));
    mCdh.setOffset(-1);
    oldSource.close();
}

From source file:org.jclouds.blobstore.config.LocalBlobStore.java

@Override
public Blob getBlob(String containerName, String key, GetOptions options) {
    logger.debug("Retrieving blob with key %s from container %s", key, containerName);
    // If the container doesn't exist, an exception is thrown
    if (!storageStrategy.containerExists(containerName)) {
        logger.debug("Container %s does not exist", containerName);
        throw cnfe(containerName);
    }//from  w  w  w.  j ava2s .c  o  m
    // If the blob doesn't exist, a null object is returned
    if (!storageStrategy.blobExists(containerName, key)) {
        logger.debug("Item %s does not exist in container %s", key, containerName);
        return null;
    }

    Blob blob = loadBlob(containerName, key);

    if (options != null) {
        String eTag = blob.getMetadata().getETag();
        if (eTag != null) {
            eTag = maybeQuoteETag(eTag);
            if (options.getIfMatch() != null) {
                if (!eTag.equals(maybeQuoteETag(options.getIfMatch())))
                    throw returnResponseException(412);
            }
            if (options.getIfNoneMatch() != null) {
                if (eTag.equals(maybeQuoteETag(options.getIfNoneMatch())))
                    throw returnResponseException(304);
            }
        }
        if (options.getIfModifiedSince() != null) {
            Date modifiedSince = options.getIfModifiedSince();
            if (blob.getMetadata().getLastModified().before(modifiedSince)) {
                HttpResponse response = HttpResponse.builder().statusCode(304).build();
                throw new HttpResponseException(String.format("%1$s is before %2$s",
                        blob.getMetadata().getLastModified(), modifiedSince), null, response);
            }

        }
        if (options.getIfUnmodifiedSince() != null) {
            Date unmodifiedSince = options.getIfUnmodifiedSince();
            if (blob.getMetadata().getLastModified().after(unmodifiedSince)) {
                HttpResponse response = HttpResponse.builder().statusCode(412).build();
                throw new HttpResponseException(String.format("%1$s is after %2$s",
                        blob.getMetadata().getLastModified(), unmodifiedSince), null, response);
            }
        }
        blob = copyBlob(blob);

        if (options.getRanges() != null && !options.getRanges().isEmpty()) {
            long size = 0;
            ImmutableList.Builder<ByteSource> streams = ImmutableList.builder();

            // Try to convert payload to ByteSource, otherwise wrap it.
            ByteSource byteSource;
            try {
                byteSource = (ByteSource) blob.getPayload().getRawContent();
            } catch (ClassCastException cce) {
                try {
                    byteSource = ByteSource
                            .wrap(ByteStreams2.toByteArrayAndClose(blob.getPayload().openStream()));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            for (String s : options.getRanges()) {
                // HTTP uses a closed interval while Java array indexing uses a
                // half-open interval.
                long offset = 0;
                long last = blob.getPayload().getContentMetadata().getContentLength() - 1;
                if (s.startsWith("-")) {
                    offset = last - Long.parseLong(s.substring(1)) + 1;
                    if (offset < 0) {
                        offset = 0;
                    }
                } else if (s.endsWith("-")) {
                    offset = Long.parseLong(s.substring(0, s.length() - 1));
                } else if (s.contains("-")) {
                    String[] firstLast = s.split("\\-");
                    offset = Long.parseLong(firstLast[0]);
                    last = Long.parseLong(firstLast[1]);
                } else {
                    throw new IllegalArgumentException("illegal range: " + s);
                }

                if (offset >= blob.getPayload().getContentMetadata().getContentLength()) {
                    throw new IllegalArgumentException("illegal range: " + s);
                }
                if (last + 1 > blob.getPayload().getContentMetadata().getContentLength()) {
                    last = blob.getPayload().getContentMetadata().getContentLength() - 1;
                }
                streams.add(byteSource.slice(offset, last - offset + 1));
                size += last - offset + 1;
                blob.getAllHeaders().put(HttpHeaders.CONTENT_RANGE, "bytes " + offset + "-" + last + "/"
                        + blob.getPayload().getContentMetadata().getContentLength());
            }
            ContentMetadata cmd = blob.getPayload().getContentMetadata();
            blob.setPayload(ByteSource.concat(streams.build()));
            HttpUtils.copy(cmd, blob.getPayload().getContentMetadata());
            blob.getPayload().getContentMetadata().setContentLength(size);
            blob.getMetadata().setSize(size);
        }
    }
    checkNotNull(blob.getPayload(), "payload " + blob);
    return blob;
}