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

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

Introduction

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

Prototype

public abstract InputStream openStream() throws IOException;

Source Link

Document

Opens a new InputStream for reading from this source.

Usage

From source file:org.codice.ddf.security.crl.generator.CrlGenerator.java

/**
 * Validates the given CRL by attempting to create a {@link CRL}
 *
 * @param byteSource - CRL byte source//from www  .j  a va 2s.  c  o  m
 * @return - True if the CRL is valid. False if its invalid
 */
private boolean crlIsValid(ByteSource byteSource) {
    try (InputStream inputStream = byteSource.openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        certificateFactory.generateCRL(inputStream);
    } catch (CertificateException | CRLException | IOException e) {
        LOGGER.warn("An error occurred while validating the CRL. {}", e.getMessage());
        return false;
    }
    return true;
}

From source file:org.dcache.gsi.ServerGsiEngine.java

private void readDelegatedCredentials(ByteSource source) throws GeneralSecurityException, IOException {
    SSLSession session = getSession();

    /* Parse the delegated certificate.
     *//*from w  w w .  j a  va 2 s. c o m*/
    X509Certificate certificate;
    try (InputStream in = source.openStream()) {
        certificate = (X509Certificate) cf.generateCertificate(in);
    }
    LOGGER.trace("Received delegated cert: {}", certificate);

    /* Verify that it matches our certificate request.
     */
    verifyDelegatedCert(certificate);

    /* Build a certificate chain for the delegated certificate.
     */
    Certificate[] chain = session.getPeerCertificates();
    int chainLen = chain.length;
    X509Certificate[] newChain = new X509Certificate[chainLen + 1];
    newChain[0] = certificate;
    for (int i = 0; i < chainLen; i++) {
        newChain[i + 1] = (X509Certificate) chain[i];
    }

    /* Store GSI credentials in the SSL session. Use GsiRequestCustomizer to copy these
     * to the Request objects.
     */
    X509Credential proxy = new KeyAndCertCredential(keyPair.getPrivate(), newChain);
    session.putValue(X509_CREDENTIAL, proxy);
}

From source file:io.prestosql.plugin.example.ExampleRecordCursor.java

public ExampleRecordCursor(List<ExampleColumnHandle> columnHandles, ByteSource byteSource) {
    this.columnHandles = columnHandles;

    fieldToColumnIndex = new int[columnHandles.size()];
    for (int i = 0; i < columnHandles.size(); i++) {
        ExampleColumnHandle columnHandle = columnHandles.get(i);
        fieldToColumnIndex[i] = columnHandle.getOrdinalPosition();
    }/*from www. j a  v  a 2 s.  c  om*/

    try (CountingInputStream input = new CountingInputStream(byteSource.openStream())) {
        lines = byteSource.asCharSource(UTF_8).readLines().iterator();
        totalBytes = input.getCount();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.facebook.presto.example.ExampleRecordCursor.java

public ExampleRecordCursor(List<ExampleColumnHandle> columnHandles, ByteSource byteSource) {
    this.columnHandles = columnHandles;

    fieldToColumnIndex = new int[columnHandles.size()];
    for (int i = 0; i < columnHandles.size(); i++) {
        ExampleColumnHandle columnHandle = columnHandles.get(i);
        fieldToColumnIndex[i] = columnHandle.getOrdinalPosition();
    }//  w  w w  .  j  a va 2  s  . c  o m

    try (CountingInputStream input = new CountingInputStream(byteSource.openStream())) {
        lines = byteSource.asCharSource(UTF_8).readLines().iterator();
        totalBytes = input.getCount();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.obiba.mica.study.service.StudyPackageImportServiceImpl.java

private void saveTempFile(Attachment attachment, ByteSource content) throws IOException {
    TempFile tempFile = new TempFile();
    tempFile.setId(attachment.getId());/*from w ww.  j  ava2s  . c  om*/
    tempFile.setName(attachment.getName());
    tempFileService.addTempFile(tempFile, content.openStream());
    attachment.setMd5(content.hash(Hashing.md5()).toString());
    attachment.setSize(content.size());
}

From source file:net.derquinse.common.io.MemoryByteSourceLoader.java

/**
 * Loads the contents of an existing source into a memory byte source.
 * @return The loaded data in a byte source.
 *//*  ww  w.  j ava2 s . c  om*/
public MemoryByteSource load(ByteSource source) throws IOException {
    checkNotNull(source, "The byte source to load must be provided");
    if (transformer == null && source instanceof MemoryByteSource) {
        return transform((MemoryByteSource) source);
    }
    Closer closer = Closer.create();
    try {
        InputStream is = closer.register(source.openStream());
        return load(is);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java

@VisibleForTesting
HttpUnsuccessfulResponseHandler getHttpUnsuccessfulResponseHandler(Message message) {
    return (request, response, supportsRetry) -> {
        String redirectLocation = response.getHeaders().getLocation();
        if (isRedirect(request, response, redirectLocation)) {
            String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
            HttpContent content = null;/*from w  ww  . j a v a2s .  c om*/
            if (!isRedirectable(method)) {
                try (TemporaryFileBackedOutputStream tfbos = new TemporaryFileBackedOutputStream()) {
                    message.setContent(OutputStream.class, tfbos);
                    BodyWriter bodyWriter = new BodyWriter();
                    bodyWriter.handleMessage(message);
                    ByteSource byteSource = tfbos.asByteSource();
                    content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE),
                            byteSource.openStream()).setLength(byteSource.size());
                }
            }

            // resolve the redirect location relative to the current location
            request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation)));
            request.setRequestMethod(method);
            request.setContent(content);
            // remove Authorization and If-* headers
            request.getHeaders().setAuthorization((String) null);
            request.getHeaders().setIfMatch(null);
            request.getHeaders().setIfNoneMatch(null);
            request.getHeaders().setIfModifiedSince(null);
            request.getHeaders().setIfUnmodifiedSince(null);
            request.getHeaders().setIfRange(null);
            request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0));

            Map<String, List<String>> headers = (Map<String, List<String>>) message
                    .get(Message.PROTOCOL_HEADERS);
            headers.forEach((key, value) -> request.getHeaders().set(key, value));
            return true;
        }
        return false;
    };
}

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

private Stream<ProcessCreateItem> handleProcessCreateItem(ProcessCreateItem processCreateItem) {
    List<ProcessCreateItem> createdItems = new ArrayList<>();
    Metacard metacard = processCreateItem.getMetacard();
    ProcessResource processResource = processCreateItem.getProcessResource();

    if (shouldProcess(processResource)) {
        try (TemporaryFileBackedOutputStream fbos = new TemporaryFileBackedOutputStream(
                DEFAULT_FILE_BACKED_OUTPUT_STREAM_THRESHOLD)) {

            // TODO: 06/21/2018 oconnormi - can probably get rid of this once
            // ProcessResourceImpl.getInputStream can be called multiple times
            fbos.write(IOUtils.toByteArray(processResource.getInputStream()));
            ByteSource byteSource = fbos.asByteSource();
            BufferedImage renderedImage = renderImage(byteSource.openStream());

            if (renderedImage != null) {
                addThumbnailToMetacard(metacard, renderedImage);
                processCreateItem.markMetacardAsModified();
                if (createOverview) {
                    ProcessResource overviewProcessResource = createOverviewResource(renderedImage, metacard);
                    createdItems.add(new ProcessCreateItemImpl(overviewProcessResource, metacard));
                }//  w w w  . jav a2 s. c o m

                if (storeOriginalImage) {
                    ProcessResource originalImageProcessResource = createOriginalImage(
                            renderImageUsingOriginalDataModel(byteSource.openStream()), metacard);

                    createdItems.add(new ProcessCreateItemImpl(originalImageProcessResource, metacard));
                }
            }
        } catch (IOException | NitfFormatException | RuntimeException e) {
            LOGGER.debug("An error occured when rendering a nitf for {}", processResource.getName(), e);
        } catch (InterruptedException e) {
            LOGGER.error("Rendering failed for {}", processResource.getName(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException(String.format("Rendering failed for %s", processResource.getName()), e);
        }
    }
    return createdItems.stream();
}

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

private Stream<ProcessUpdateItem> handleProcessUpdateItem(ProcessUpdateItem processUpdateItem) {
    List<ProcessUpdateItem> updatedItems = new ArrayList<>();
    Metacard metacard = processUpdateItem.getMetacard();
    Metacard originalMetacard = processUpdateItem.getOldMetacard();
    ProcessResource processResource = processUpdateItem.getProcessResource();

    if (shouldProcess(processResource)) {
        try (TemporaryFileBackedOutputStream fbos = new TemporaryFileBackedOutputStream(
                DEFAULT_FILE_BACKED_OUTPUT_STREAM_THRESHOLD)) {

            fbos.write(IOUtils.toByteArray(processResource.getInputStream()));
            ByteSource byteSource = fbos.asByteSource();
            BufferedImage renderedImage = renderImage(byteSource.openStream());

            if (renderedImage != null) {
                addThumbnailToMetacard(metacard, renderedImage);
                processUpdateItem.markMetacardAsModified();

                if (createOverview) {
                    ProcessResource overviewProcessResource = createOverviewResource(renderedImage, metacard);
                    updatedItems.add(/*from w ww . ja va  2 s .c o  m*/
                            new ProcessUpdateItemImpl(overviewProcessResource, metacard, originalMetacard));
                }

                if (storeOriginalImage) {
                    ProcessResource originalImageProcessResource = createOriginalImage(
                            renderImageUsingOriginalDataModel(byteSource.openStream()), metacard);

                    updatedItems.add(new ProcessUpdateItemImpl(originalImageProcessResource, metacard,
                            originalMetacard));
                }
            }
        } catch (IOException | NitfFormatException | RuntimeException e) {
            LOGGER.debug(e.getMessage(), e);
        } catch (InterruptedException e) {
            LOGGER.error("Rendering failed for {}", processResource.getName(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException(String.format("Rendering failed for %s", processResource.getName()), e);
        }
    }
    return updatedItems.stream();
}

From source file:org.codice.ddf.security.crl.generator.CrlGenerator.java

/**
 * Writes out the CRL to the given file and adds its path to the property files.
 *
 * @param byteSource - CRL byte source/*from   ww w  . ja v a  2 s .c  o m*/
 * @param crlFile - the file to write the CRL to
 */
private void writeCrlToFile(ByteSource byteSource, File crlFile) {
    try {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            // Write out to file
            try (OutputStream outStream = new FileOutputStream(crlFile);
                    InputStream inputStream = byteSource.openStream()) {
                IOUtils.copy(inputStream, outStream);
                SecurityLogger.audit("Copied the content of the CRl at {} to the local CRL at {}.",
                        crlLocationUrl, crlFile.getPath());
                setCrlFileLocationInPropertiesFile(crlFile.getPath());
            }
            return null;
        });
    } catch (PrivilegedActionException e) {
        LOGGER.warn("Unable to save the CRL.");
        LOGGER.debug("Unable to save the CRL. {}", e.getCause());
        postErrorEvent("Unable to save the CRL.");
    }
}