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.jclouds.azurecompute.suppliers.InMemoryKeyManagersSupplier.java

@Override
public KeyManager[] get() {
    KeyManager[] keyManagers = null;

    // split in private key and certs
    final int privateKeyBeginIdx = identity.indexOf("-----BEGIN PRIVATE KEY");
    final int privateKeyEndIdx = identity.indexOf("-----END PRIVATE KEY");
    if (privateKeyBeginIdx != -1 && privateKeyEndIdx != -1) {
        try {//www .j a  v a  2  s. c o m
            final String pemPrivateKey = identity.substring(privateKeyBeginIdx, privateKeyEndIdx + 26);

            final StringBuilder pemCerts = new StringBuilder();
            int certsBeginIdx = 0;
            do {
                certsBeginIdx = identity.indexOf("-----BEGIN CERTIFICATE", certsBeginIdx);
                if (certsBeginIdx >= 0) {
                    final int certsEndIdx = identity.indexOf("-----END CERTIFICATE", certsBeginIdx) + 26;
                    pemCerts.append(identity.substring(certsBeginIdx, certsEndIdx));
                    certsBeginIdx = certsEndIdx;
                }
            } while (certsBeginIdx != -1);

            // parse private key
            final KeySpec keySpec = Pems
                    .privateKeySpec(ByteSource.wrap(pemPrivateKey.getBytes(Charsets.UTF_8)));
            final PrivateKey privateKey = crypto.rsaKeyFactory().generatePrivate(keySpec);

            // parse cert(s)
            @SuppressWarnings("unchecked")
            final Collection<Certificate> certs = (Collection<Certificate>) CertificateFactory
                    .getInstance("X.509").generateCertificates(
                            new ByteArrayInputStream(pemCerts.toString().getBytes(Charsets.UTF_8)));

            if (certs.isEmpty()) {
                throw new IllegalStateException("Could not find any valid certificate");
            }

            final X509Certificate certificate = (X509Certificate) certs.iterator().next();

            keyManagers = new KeyManager[] { new InMemoryKeyManager(certificate, privateKey) };
        } catch (Exception e) {
            propagate(e);
        }
    }

    return keyManagers;
}

From source file:eu.lp0.cursus.xml.common.AbstractXMLFile.java

public final ByteSource toByteSource() throws ExportException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    to(out);/*from w w  w  . ja v  a  2  s .c o  m*/
    return ByteSource.wrap(out.toByteArray());
}

From source file:org.jasig.cas.authentication.principal.ShibbolethCompatiblePersistentIdGenerator.java

/**
 * Get salt./*from  ww w .j  a v  a  2 s . com*/
 *
 * @return the byte[] for the salt or null
 */
public byte[] getSalt() {
    try {
        return ByteSource.wrap(this.salt).read();
    } catch (final IOException e) {
        LOGGER.warn("Salt cannot be read because the byte array from source could not be consumed");
    }
    return null;
}

From source file:org.jclouds.digitalocean2.ssh.ECDSAKeys.java

/**
 * Executes {@link org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)} on the
 * string which was OpenSSH Base64 Encoded {@code id_rsa.pub}
 * //  w ww  .j a  v  a2  s . c o m
 * @param idRsaPub formatted {@code ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAB...}
 * @see org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)
 */
public static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub) {
    try {
        return publicKeySpecFromOpenSSH(ByteSource.wrap(ecDsaPub.getBytes(Charsets.UTF_8)));
    } catch (IOException e) {
        throw propagate(e);
    }
}

From source file:org.jasig.cas.ticket.registry.encrypt.AbstractCrypticTicketRegistry.java

/**
 * Encode ticket.//  w w  w  . j  a v  a 2  s.c o  m
 *
 * @param ticket the ticket
 * @return the ticket
 */
protected Ticket encodeTicket(final Ticket ticket) {
    if (this.cipherExecutor == null) {
        logger.trace("Ticket encryption is not enabled. Falling back to default behavior");
        return ticket;
    }

    if (ticket == null) {
        return ticket;
    }

    logger.info("Encoding [{}]", ticket);
    final byte[] encodedTicketObject = CompressionUtils.serializeAndEncodeObject(this.cipherExecutor, ticket);
    final String encodedTicketId = encodeTicketId(ticket.getId());
    final Ticket encodedTicket = new EncodedTicket(ByteSource.wrap(encodedTicketObject), encodedTicketId);
    logger.info("Created [{}]", encodedTicket);
    return encodedTicket;
}

From source file:org.apache.airavata.gfac.jclouds.utils.JCloudsFileTransfer.java

public void downloadFilesFromEc2(String localFile, String remoteFile) throws FileTransferException {
    FileOutputStream ops;//  www. j  a  v a 2  s  .com
    try {
        ssh.connect();
        ops = new FileOutputStream(new File(localFile));
        Payload payload = ssh.get(remoteFile);
        InputStream inputStream = payload.openStream();
        byte[] bytes = ByteStreams.toByteArray(inputStream);
        ByteSource byteSource = ByteSource.wrap(bytes);
        byteSource.copyTo(ops);
        inputStream.close();
        ops.close();
    } catch (Exception e) {
        log.error("Error occured while downloading file from ec2");
        throw new FileTransferException(
                "Error occured while downloading file " + remoteFile + " from ec2 host");
    } finally {
        if (ssh != null)
            ssh.disconnect();
    }
}

From source file:org.spka.cursus.publish.website.results.ResultsPagesGenerator.java

public ResultsPagesGenerator(File scoresFile) throws IOException, ImportException, ExportException {
    ScoresXMLFile scores = new TransformResults(Files.asByteSource(scoresFile));
    XSLTHTMLGenerator gen = new XSLTHTMLGenerator(Constants.DATA_FILE_PREFIX + scoresFile.getName(),
            Files.getNameWithoutExtension(scoresFile.getName()), scores);

    gen.getFooters().add("footer.xml");
    gen.getStyleSheets().add("spka.css");
    if (scores.getData().getSeries().getName().startsWith("Celtic Challenge ")) {
        gen.getStyleSheets().add("spka-cc.css");
    }//from w w  w. j  ava  2 s  .  co m
    gen.getFlags().put("compact-race", "10");
    gen.getFlags().put("compact-event", "10");
    if (Constants.TOP_COUNTRY_SCORERS.contains(scores.getData().getSeriesResults().getScorer())) {
        gen.getFlags().put("top-country", null);
    }

    Map<String, String> classes = new TreeMap<String, String>(
            Ordering.explicit(new ArrayList<String>(CLASSES.keySet())));
    for (DataXMLClass class_ : scores.getData().getSeries().getClasses()) {
        if (CLASSES.containsKey(class_.getName())) {
            classes.put(class_.getName(), CLASSES.get(class_.getName()));
        }
    }
    gen.getClasses().putAll(classes);

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    scores.to(buf);
    buf.close();
    pages.put(Constants.RESULTS_DIR + "/" + Constants.DATA_FILE_PREFIX + scoresFile.getName(),
            ByteSource.wrap(buf.toByteArray()));

    for (String styleSheet : gen.getStyleSheets()) {
        pages.put(Constants.RESULTS_DIR + "/" + styleSheet,
                Resources.asByteSource(Resources.getResource(Constants.RESOURCE_PATH + styleSheet)));
    }

    for (Map.Entry<String, ByteSource> page : Iterables.concat(gen.getMenuPage().entrySet(),
            gen.getSimplePage().entrySet(), gen.getSplitPages().entrySet(), gen.getCodePages().entrySet())) {
        pages.put(Constants.RESULTS_DIR + "/" + page.getKey(), page.getValue());
    }
}

From source file:io.druid.storage.hdfs.HdfsDataSegmentPusher.java

private DataSegment createDescriptorFile(DataSegment segment, Path outDir, final FileSystem fs)
        throws IOException {
    final Path descriptorFile = new Path(outDir, "descriptor.json");
    log.info("Creating descriptor file at[%s]", descriptorFile);
    ByteSource.wrap(jsonMapper.writeValueAsBytes(segment))
            .copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile));
    return segment;
}

From source file:ratpack.consul.RatpackConsulConfig.java

/**
 * Read the specified key as a {@link ByteSource} using the specified configuration to connection to Consul and the provided {@link QueryOptions}.
 * The returned value can then be passed to the existing parsing options in {@link ratpack.server.ServerConfigBuilder} to provide configuration.
 * <p>//from www . j  ava  2 s  .co  m
 * <pre class="java-args">{@code
 * import ratpack.consul.RatpackConsulConfig;
 * import ratpack.test.embed.EmbeddedApp;
 * import com.orbitz.consul.option.ImmutableQueryOptions;
 *
 * public class Example {
 *   public static class Config {
 *     public String name;
 *     public String environment;
 *     public String secret;
 *   }
 *
 *   public static void main(String... args) throws Exception {
 *     EmbeddedApp.of(a -> a
 *       .serverConfig(s -> s
 *         .yaml(RatpackConsulConfig.value("default/app"))
 *         .json(RatpackConsulConfig.value("default/environment", ImmutableQueryOptions.builder().token("app-acl-token").build()))
 *         .props(RatpackConsulConfig.value("app/environment", b -> b.withUrl("https://consul.domain.io")))
 *         .require("/config", Config.class)
 *       )
 *       .handlers(c -> c
 *         .get(ctx -> ctx.render(ctx.get(Config.class)))
 *       )
 *     );
 *   }
 * }
 * }</pre>
 * @param key the key to read from Consul Key-Value store
 * @param queryOptions the options to use when querying Consul
 * @param clientConfig he configuration for the Consul connection
 * @return a {@link ByteSource} representing the value stored in the key
 */
static ByteSource value(String key, QueryOptions queryOptions, Action<? super Consul.Builder> clientConfig) {
    return Exceptions.uncheck(() -> ByteSource.wrap(clientConfig.with(Consul.builder()).build().keyValueClient()
            .getValue(key, queryOptions).transform(v -> v.getValueAsString().or("")).or("").getBytes()));
}

From source file:net.sf.lucis.core.impl.FSStore.java

public void setCheckpoint(T checkpoint) {
    byte[] data;//w w w  .j  a  va 2 s.  c om
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream(256);
        serializer.write(checkpoint, bos);
        data = bos.toByteArray();
        DurableFiles.copy(ByteSource.wrap(data), control);
    } catch (IOException e) {
        throw new StoreException(e);
    } finally {
        changed();
    }
}