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.transformer.nitf.image.NitfPreStoragePlugin.java

private ContentItem createOverview(String id, BufferedImage image, Metacard metacard) {
    try {//from   ww  w.  jav  a2s. c o  m
        byte[] overviewBytes = scaleImage(image, image.getWidth(), image.getHeight());
        ByteSource source = ByteSource.wrap(overviewBytes);
        ContentItem contentItem = new ContentItemImpl(id, OVERVIEW, source, IMAGE_JPEG,
                buildOverviewTitle(metacard.getTitle()), overviewBytes.length, metacard);

        metacard.setAttribute(new AttributeImpl(Core.DERIVED_RESOURCE_URI, contentItem.getUri()));

        return contentItem;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return null;
}

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

private ContentItem createDerivedImage(String id, String qualifier, BufferedImage image, Metacard metacard,
        int maxWidth, int maxHeight) {
    try {/*from w ww. java2 s.  c  o m*/
        byte[] overviewBytes = scaleImage(image, maxWidth, maxHeight);

        ByteSource source = ByteSource.wrap(overviewBytes);
        ContentItem contentItem = new ContentItemImpl(id, qualifier, source, IMAGE_JPEG,
                buildDerivedImageTitle(metacard.getTitle(), qualifier), overviewBytes.length, metacard);

        addDerivedResourceAttribute(metacard, contentItem);

        return contentItem;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return null;
}

From source file:org.jasig.cas.extension.clearpass.EncryptedMapDecorator.java

/**
 * Decorates a map using the provided algorithms.
 * <p>Takes a salt and secretKey so that it can work with a distributed cache.
 *
 * @param decoratedMap the map to decorate.  CANNOT be NULL.
 * @param hashAlgorithm the algorithm to use for hashing.  CANNOT BE NULL.
 * @param salt the salt, as a String. Gets converted to bytes.   CANNOT be NULL.
 * @param secretKeyAlgorithm the encryption algorithm. CANNOT BE NULL.
 * @param secretKey the secret to use.  CANNOT be NULL.
 * @throws RuntimeException if the algorithm cannot be found or the iv size cant be determined.
 *///from w  w w  . j av  a 2  s  .com
public EncryptedMapDecorator(final Map<String, String> decoratedMap, final String hashAlgorithm,
        final byte[] salt, final String secretKeyAlgorithm, final Key secretKey) {
    try {
        this.decoratedMap = decoratedMap;
        this.key = secretKey;
        this.salt = ByteSource.wrap(salt);
        this.secretKeyAlgorithm = secretKeyAlgorithm;
        this.messageDigest = MessageDigest.getInstance(hashAlgorithm);
        this.ivSize = getIvSize();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.qi4j.entitystore.jclouds.JCloudsMapEntityStoreMixin.java

@Override
public void applyChanges(MapChanges changes) throws IOException {
    final BlobStore blobStore = storeContext.getBlobStore();
    changes.visitMap(new MapChanger() {
        @Override//from w  ww .j av  a  2  s  .  co m
        public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            return new StringWriter() {
                @Override
                public void close() throws IOException {
                    super.close();
                    Blob blob = blobStore.blobBuilder(ref.identity())
                            .payload(ByteSource.wrap(toString().getBytes(UTF_8))).build();
                    blobStore.putBlob(container, blob);
                }
            };
        }

        @Override
        public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            if (!blobStore.blobExists(container, ref.identity())) {
                throw new EntityNotFoundException(ref);
            }
            return new StringWriter() {
                @Override
                public void close() throws IOException {
                    super.close();
                    Blob blob = blobStore.blobBuilder(ref.identity())
                            .payload(ByteSource.wrap(toString().getBytes(UTF_8))).build();
                    blobStore.putBlob(container, blob);
                }
            };
        }

        @Override
        public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor)
                throws EntityNotFoundException {
            if (!blobStore.blobExists(container, ref.identity())) {
                throw new EntityNotFoundException(ref);
            }
            blobStore.removeBlob(container, ref.identity());
        }
    });
}

From source file:org.eclipse.che.core.db.schema.impl.flyway.CustomSqlMigrationResolver.java

private List<ResolvedMigration> resolveSqlMigrations() throws IOException, SQLException {
    LOG.info("Searching for sql scripts in locations {}", Arrays.toString(flywayConfiguration.getLocations()));
    final Map<Location, List<Resource>> allResources = finder.findResources(flywayConfiguration);
    LOG.debug("Found scripts: {}", allResources);

    final Map<String, Map<String, SqlScript>> scriptsInDir = new HashMap<>();
    for (Location location : allResources.keySet()) {
        final List<Resource> resources = allResources.get(location);
        for (Resource resource : resources) {
            final SqlScript newScript = scriptsCreator.createScript(location, resource);
            if (!scriptsInDir.containsKey(newScript.dir)) {
                scriptsInDir.put(newScript.dir, new HashMap<>(4));
            }/* w w w  .  j av  a 2 s  .co m*/
            final Map<String, SqlScript> existingScripts = scriptsInDir.get(newScript.dir);
            final SqlScript existingScript = existingScripts.get(newScript.name);
            if (existingScript == null) {
                existingScripts.put(newScript.name, newScript);
            } else if (Objects.equals(existingScript.vendor, newScript.vendor)) {
                throw new FlywayException(format(
                        "More than one script with name '%s' is registered for "
                                + "database vendor '%s', script '%s' conflicts with '%s'",
                        newScript.name, existingScript.vendor, newScript, existingScript));
            } else if (vendorName.equals(newScript.vendor)) {
                existingScripts.put(newScript.name, newScript);
            }
        }
    }

    final Map<MigrationVersion, ResolvedMigration> migrations = new HashMap<>();
    for (SqlScript script : scriptsInDir.values().stream().flatMap(scripts -> scripts.values().stream())
            .collect(toList())) {
        final ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
        migration.setVersion(versionResolver.resolve(script, flywayConfiguration));
        migration.setScript(script.resource.getLocation());
        migration.setPhysicalLocation(script.resource.getLocationOnDisk());
        migration.setType(MigrationType.SQL);
        migration.setDescription(script.name);
        migration.setChecksum(ByteSource.wrap(script.resource.loadAsBytes()).hash(Hashing.crc32()).asInt());
        migration.setExecutor(new SqlMigrationExecutor(dbSupport, script.resource, placeholderReplacer,
                flywayConfiguration.getEncoding()));
        if (migrations.put(migration.getVersion(), migration) != null) {
            throw new FlywayException("Two migrations with the same version detected");
        }
    }
    return new ArrayList<>(migrations.values());
}

From source file:org.jclouds.s3.filters.Aws4SignerBase.java

/**
 * hash input with sha256/* w w w .j av  a  2  s. c om*/
 *
 * @param bytes input bytes
 * @return hash result
 * @throws HTTPException
 */
public static byte[] hash(byte[] bytes) throws HTTPException {
    try {
        return ByteSource.wrap(bytes).hash(Hashing.sha256()).asBytes();
    } catch (IOException e) {
        throw new HttpException("Unable to compute hash while signing request: " + e.getMessage(), e);
    }
}

From source file:com.googlecode.fascinator.storage.jclouds.BlobStorePayload.java

public void writePayload(InputStream in, boolean determineContentType) throws StorageException {
    if (getLabel() == null) {
        setLabel(getId());/*from  ww  w.  j  av  a  2  s .  co  m*/
    }
    if (getType() == null) {
        setType(PayloadType.Source);
    }
    byte[] bytes = null;
    if (determineContentType) {
        // We need to read the stream locally to determine the content type
        try {

            bytes = IOUtils.toByteArray(in);
            setContentType(MimeTypeUtil.getMimeType(bytes, getId()));

        } catch (IOException e) {
            throw new StorageException("Failed to determine content type", e);
        }
    }
    String payloadPath = oid + "/" + getId();

    Map<String, String> userMetadata = new HashMap<String, String>();

    userMetadata.put("id", getId());
    userMetadata.put(PAYLOAD_TYPE_KEY, getType().toString());
    userMetadata.put(LABEL_KEY, getLabel());
    userMetadata.put("linked", String.valueOf(isLinked()));
    // Sometimes we just can't get it
    if (getContentType() != null) {
        userMetadata.put(CONTENT_TYPE_KEY, getContentType());
    } else {
        userMetadata.put(CONTENT_TYPE_KEY, MimeTypeUtil.DEFAULT_MIME_TYPE);
    }

    BlobStore blobStore = BlobStoreClient.getClient();

    if (bytes != null) {

        blob = blobStore.blobBuilder(payloadPath).userMetadata(userMetadata).build();
        blob.setPayload(ByteSource.wrap(bytes));
    } else {
        blob = blobStore.blobBuilder(payloadPath).userMetadata(userMetadata).build();
        blob.setPayload(in);
    }

    blobStore.putBlob(BlobStoreClient.getContainerName(), blob);
    if (!BlobStoreClient.supportsUserMetadata()) {
        writePayloadMetadata(userMetadata);
    }

}

From source file:io.github.mike10004.vhs.testsupport.NanohttpdFormDataParser.java

/**
 * Decodes the Multipart Body data and put it into Key/Value pairs.
 *///from w w  w.  j a v a 2  s . c om
@Override
public List<FormDataPart> decodeMultipartFormData(MediaType contentType, byte[] data)
        throws BadMultipartFormDataException {
    Charset parentTypeEncoding = contentType.charset().or(DEFAULT_MULTIPART_FORM_DATA_ENCODING);
    String boundary = MultipartFormDataParser.getBoundaryOrDie(contentType);
    byte[] boundaryBytes = boundary.getBytes(BOUNDARY_ENCODING);
    ByteBuffer fbuf = ByteBuffer.wrap(data);
    int[] boundaryIdxs = getBoundaryPositions(fbuf, boundaryBytes);
    List<FormDataPart> parts = new ArrayList<>(boundaryIdxs.length);
    byte[] partHeaderBuff = new byte[MAX_HEADER_SIZE];
    for (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) {
        Multimap<String, String> headers = ArrayListMultimap.create();
        fbuf.position(boundaryIdxs[boundaryIdx]);
        int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
        fbuf.get(partHeaderBuff, 0, len);
        MemoryBufferedReader in = new MemoryBufferedReader(partHeaderBuff, 0, len, parentTypeEncoding, len);
        int headerLines = 0;
        // First line is boundary string
        String mpline = in.readLine();
        headerLines++;
        if (mpline == null || !mpline.contains(boundary)) {
            throw new MalformedMultipartFormDataException(
                    "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.");
        }

        // Parse the reset of the header lines
        mpline = in.readLine();
        headerLines++;
        @Nullable
        String partContentType = null;
        @Nullable
        ContentDisposition disposition = null;
        while (mpline != null && mpline.trim().length() > 0) {
            Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);
            if (matcher.matches()) {
                String attributeString = matcher.group(2);
                headers.put(HttpHeaders.CONTENT_DISPOSITION, attributeString);
                disposition = ContentDisposition.parse(attributeString);
            }
            matcher = CONTENT_TYPE_PATTERN.matcher(mpline);
            if (matcher.matches()) {
                partContentType = matcher.group(2).trim();
                headers.put(HttpHeaders.CONTENT_TYPE, partContentType);
            }
            mpline = in.readLine();
            headerLines++;
        }
        int partHeaderLength = 0;
        while (headerLines-- > 0) {
            partHeaderLength = skipOverNewLine(partHeaderBuff, partHeaderLength);
        }
        // Read the part data
        if (partHeaderLength >= len - 4) {
            throw new BadMultipartFormDataException("Multipart header size exceeds MAX_HEADER_SIZE.");
        }
        int partDataStart = boundaryIdxs[boundaryIdx] + partHeaderLength;
        int partDataEnd = boundaryIdxs[boundaryIdx + 1] - 4;

        fbuf.position(partDataStart);

        if (partContentType == null) {
            partContentType = DEFAULT_FORM_DATA_PART_CONTENT_TYPE.toString();
        }
        // Read it into a file
        byte[] fileData = copyRegion(fbuf, partDataStart, partDataEnd - partDataStart);
        TypedContent file = TypedContent.identity(ByteSource.wrap(fileData), MediaType.parse(partContentType));
        parts.add(new FormDataPart(headers, disposition, file));
    }
    return parts;
}

From source file:com.hpe.caf.worker.datastore.cs.StorageServiceDataStore.java

@Override
public String store(byte[] bytes, String partialReference) throws DataStoreException {
    return store(ByteSource.wrap(bytes), partialReference);
}

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

private ContentItem createDerivedImage(String id, String qualifier, BufferedImage image, Metacard metacard,
        int maxWidth, int maxHeight) {
    try {/* www. j  a  v a 2  s.  c  o m*/
        byte[] overviewBytes = scaleImage(image, maxWidth, maxHeight);

        ByteSource source = ByteSource.wrap(overviewBytes);
        ContentItem contentItem = new ContentItemImpl(id, qualifier, source, IMAGE_JPEG,
                buildDerivedImageTitle(metacard.getTitle(), qualifier, JPG), overviewBytes.length, metacard);

        addDerivedResourceAttribute(metacard, contentItem);

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

    return null;
}