Example usage for java.security DigestOutputStream DigestOutputStream

List of usage examples for java.security DigestOutputStream DigestOutputStream

Introduction

In this page you can find the example usage for java.security DigestOutputStream DigestOutputStream.

Prototype

public DigestOutputStream(OutputStream stream, MessageDigest digest) 

Source Link

Document

Creates a digest output stream, using the specified output stream and message digest.

Usage

From source file:net.sf.jasperreports.virtualization.ReportTest.java

protected String xmlDigest(JasperPrint print)
        throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException {
    File outputFile = createXmlOutputFile();
    log.debug("XML export output at " + outputFile.getAbsolutePath());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    FileOutputStream output = new FileOutputStream(outputFile);
    try {//from w  ww .  j  a  v  a  2s. c  o m
        DigestOutputStream out = new DigestOutputStream(output, digest);
        xmlExport(print, out);
    } finally {
        output.close();
    }

    byte[] digestBytes = digest.digest();
    StringBuilder digestString = new StringBuilder(digestBytes.length * 2);
    for (byte b : digestBytes) {
        digestString.append(String.format("%02x", b));
    }
    return digestString.toString();
}

From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java

private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) {
    DownloadStatus downloadStatus = DownloadStatus.FAILED;
    HttpEntity responseEntity = null;//from   w ww  .  j  a v a  2 s  . co  m
    try {
        String targetUrlString = mediaContent.getUrlString();
        if (forceHttps)
            targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString);

        URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString);

        boolean freshURI = processedURISet.add(targetURI);
        if (!freshURI) {
            LOGGER.warn("Skipping previously processed URI: {}", targetURI);
            return; //abort processing
        }

        LOGGER.info("Attempting to download {}", targetURI);
        HttpGet imageGet = new HttpGet(targetURI);

        for (Header header : headerList)
            imageGet.addHeader(header);

        HttpResponse imageResponse = httpClient.execute(imageGet);

        String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/");
        originalFileName = StringUtils.replace(originalFileName, "/", "_");
        File outputFile = getOutputFile(originalFileName);

        long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent);
        responseEntity = imageResponse.getEntity();

        BufferedInputStream bis = null;
        DigestOutputStream fos = null;
        int bytesRead = 0;
        try {
            bis = new BufferedInputStream(responseEntity.getContent());
            fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA"));

            byte[] buffer = new byte[8192];
            while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.flush();

            MessageDigest messageDigest = fos.getMessageDigest();
            byte[] digestBytes = messageDigest.digest();
            String digestString = Hex.encodeHexString(digestBytes);
            LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString);

            processedItem.setDownloadDate(new Date());
            downloadStatus = DownloadStatus.COMPLETED;
            processedItem.setHash(digestString);
            processedItem.setFilename(outputFile.toString());
        } catch (ConnectionClosedException e) {
            LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(fos);
            EntityUtils.consumeQuietly(responseEntity);
            if (downloadStatus == DownloadStatus.FAILED
                    || (outputFile.exists() && outputFile.length() != expectedContentLength)) {
                LOGGER.warn("Deleted partial/failed file: {}", outputFile);
                outputFile.delete();
                processedItem.setDownloadStatus(DownloadStatus.FAILED);
            }
        }
    } catch (IOException e) {
        LOGGER.error("An Exception was thrown while attempting to download image content", e);
    } catch (URISyntaxException e) {
        LOGGER.error("The supplied URI, {}, violates syntax rules", e);
    } finally {
        EntityUtils.consumeQuietly(responseEntity);
    }

    processedItem.setDownloadStatus(downloadStatus);
    itemDAO.save(processedItem);
}

From source file:it.openutils.mgnlaws.magnolia.datastore.S3DataStore.java

/**
 * {@inheritDoc}// w  w w.  j a v a  2s.  com
 */
public DataRecord addRecord(InputStream input) throws DataStoreException {
    File temporary = null;
    try {
        temporary = newTemporaryFile();
        DataIdentifier tempId = new DataIdentifier(temporary.getName());
        usesIdentifier(tempId);
        // Copy the stream to the temporary file and calculate the
        // stream length and the message digest of the stream
        MessageDigest digest = MessageDigest.getInstance(DIGEST);
        OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest);
        try {
            IOUtils.copyLarge(input, output);
        } finally {
            IOUtils.closeQuietly(output);
        }
        DataIdentifier identifier = new DataIdentifier(digest.digest());
        // File file;
        String tmpKey = PREFIX_TMP + identifier.toString();
        String key = getKey(identifier);

        if (!objectExists(identifier)) {
            Upload upload = transferManager.upload(bucket, tmpKey, temporary);
            try {
                AmazonClientException e;
                if ((e = upload.waitForException()) != null && upload.getState() != TransferState.Completed) {
                    throw new DataStoreException("Error uploading file to s3", e);
                }
            } catch (InterruptedException e) {
                throw new DataStoreException("Upload interrupted", e);
            }
        }

        S3DataRecord record;
        synchronized (this) {
            // Check if the same record already exists, or
            // move the temporary file in place if needed
            usesIdentifier(identifier);
            if (!objectExists(identifier)) {
                amazonS3.copyObject(bucket, tmpKey, bucket, key);
                amazonS3.deleteObject(bucket, tmpKey);
            } else {
                // effettua un touch sul file
                touch(key);
            }
            record = new S3DataRecord(identifier, new S3LazyObject(amazonS3, bucket, key));
            if (useCache) {
                cache.put(new Element(identifier.toString(),
                        new CachedS3DataRecord(record, cacheDirectory, temporary)));
                // no need to remove file
                temporary = null;
            }
        }
        // this will also make sure that
        // tempId is not garbage collected until here
        inUse.remove(tempId);
        return record;
    } catch (NoSuchAlgorithmException e) {
        throw new DataStoreException(DIGEST + " not available", e);
    } catch (IOException e) {
        throw new DataStoreException("Could not add record", e);
    } finally {
        if (temporary != null) {
            temporary.delete();
        }
    }
}

From source file:net.sf.jasperreports.Report.java

protected String xmlDigest(JasperPrint print)
        throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException {
    File outputFile = createXmlOutputFile();
    log.debug("XML export output at " + outputFile.getAbsolutePath());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    FileOutputStream output = new FileOutputStream(outputFile);
    try {/*w  ww  .j  av a 2  s . c  om*/
        DigestOutputStream out = new DigestOutputStream(output, digest);
        xmlExport(print, out);
    } finally {
        output.close();
    }

    return toDigestString(digest);
}

From source file:com.quixey.hadoop.fs.oss.MultiPartUploaderTest.java

private BufferedOutputStream newOutputStream(Path file, MessageDigest digest) throws IOException {
    return new BufferedOutputStream(new DigestOutputStream(Files.newOutputStream(file), digest));
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageManifest.java

/**
 * Generate random contents for the image and store it together with the md5
 * for later comparison./*  ww w.  j a v  a 2 s .co m*/
 */
private ContentBody genContent(long txid) throws IOException {
    MessageDigest digester = MD5Hash.getDigester();

    // write through digester so we can roll the written image
    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    DigestOutputStream ds = new DigestOutputStream(bos, digester);

    // generate random bytes
    new Random().nextBytes(randomBytes);
    ds.write(randomBytes);
    ds.flush();

    // get written hash
    MD5Hash hash = new MD5Hash(digester.digest());

    // store contents and digest
    digests.put(txid, hash);
    content.put(txid, Arrays.copyOf(randomBytes, randomBytes.length));

    return new ByteArrayBody(bos.toByteArray(), "filename");
}

From source file:com.lightboxtechnologies.spectrum.ExtractDataMapper.java

protected void hashAndExtract(final Map<String, Object> rec, OutputStream out, FSDataInputStream file,
        Map<String, ?> map, Context context) throws IOException {
    MD5Hash.reset();/*from www .  j  a v a2 s .  c  om*/
    SHA1Hash.reset();

    OutputStream dout = null;
    try {
        dout = new DigestOutputStream(new DigestOutputStream(out, MD5Hash), SHA1Hash);
        extract(file, dout, map, context);
    } finally {
        IOUtils.closeQuietly(dout);
    }

    rec.put("md5", MD5Hash.digest());
    rec.put("sha1", SHA1Hash.digest());
}

From source file:net.sf.jasperreports.AbstractTest.java

protected String xmlExportDigest(JasperPrint print)
        throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException {
    File outputFile = createXmlOutputFile();
    log.debug("XML export output at " + outputFile.getAbsolutePath());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    FileOutputStream output = new FileOutputStream(outputFile);
    try {//from ww w .j  a  va2 s .c  o m
        DigestOutputStream out = new DigestOutputStream(output, digest);
        xmlExport(print, out);
    } finally {
        output.close();
    }

    return toDigestString(digest);
}

From source file:net.sf.jasperreports.AbstractTest.java

protected String errExportDigest(Throwable t)
        throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException {
    File outputFile = createXmlOutputFile();
    log.debug("Error stack trace at " + outputFile.getAbsolutePath());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    FileOutputStream output = new FileOutputStream(outputFile);
    OutputStreamWriter osw = null;
    try {//w  w  w .j  av  a 2 s  .c o m
        DigestOutputStream out = new DigestOutputStream(output, digest);
        //PrintStream ps = new PrintStream(out);
        //t.printStackTrace(ps);
        osw = new OutputStreamWriter(out, "UTF-8");
        osw.write(String.valueOf(t.getMessage()));
    } finally {
        osw.close();
        output.close();
    }

    return toDigestString(digest);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.io.FileProtection.java

/**
 * Returns an {@link OutputStream} for writing to the specified file and
 * saves a digest file for validating its contents when the {@code close}
 * method is invoked./*from  w  w  w.  jav a  2s  .c o  m*/
 * 
 * @param file the file to be opened
 * @return an {@code OutputStream} for writing to the specified file
 * @throws FileNotFoundException if the specified file does not exist
 */
public static OutputStream openOutputStream(final File file) throws FileNotFoundException {
    return new DigestOutputStream(new FileOutputStream(file), createMessageDigest()) {

        @Override
        public void close() throws IOException {
            super.close();

            saveDigest(file, getMessageDigest().digest());
        }

    };
}