Example usage for org.apache.commons.codec.binary Base64InputStream Base64InputStream

List of usage examples for org.apache.commons.codec.binary Base64InputStream Base64InputStream

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64InputStream Base64InputStream.

Prototype

public Base64InputStream(InputStream in) 

Source Link

Usage

From source file:org.apache.abdera2.activities.model.objects.BinaryObject.java

/**
 * Returns an InputStream that will decode the Base64 encoded 
 * content on the fly. The data is stored encoded in memory and
 * only decoded as the InputStream is consumed.
 *//* w  w  w . j av a 2 s .c o  m*/
public InputStream getInputStream() throws IOException {
    String content = super.getProperty("data");
    if (content == null)
        return null;
    ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"));
    InputStream bin = new Base64InputStream(in);
    if (has("compression")) {
        String comp = getProperty("compression");
        bin = Compression.wrap(bin, comp);
    }
    return bin;
}

From source file:org.apache.nifi.processors.standard.Base64EncodeContent.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();//from w  w w  . jav a 2 s.co  m
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();

    boolean encode = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCODE_MODE);
    try {
        final StopWatch stopWatch = new StopWatch(true);
        if (encode) {
            flowFile = session.write(flowFile, new StreamCallback() {
                @Override
                public void process(InputStream in, OutputStream out) throws IOException {
                    try (Base64OutputStream bos = new Base64OutputStream(out)) {
                        int len = -1;
                        byte[] buf = new byte[8192];
                        while ((len = in.read(buf)) > 0) {
                            bos.write(buf, 0, len);
                        }
                        bos.flush();
                    }
                }
            });
        } else {
            flowFile = session.write(flowFile, new StreamCallback() {
                @Override
                public void process(InputStream in, OutputStream out) throws IOException {
                    try (Base64InputStream bis = new Base64InputStream(new ValidatingBase64InputStream(in))) {
                        int len = -1;
                        byte[] buf = new byte[8192];
                        while ((len = bis.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        out.flush();
                    }
                }
            });
        }

        logger.info("Successfully {} {}", new Object[] { encode ? "encoded" : "decoded", flowFile });
        session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (ProcessException e) {
        logger.error("Failed to {} {} due to {}", new Object[] { encode ? "encode" : "decode", flowFile, e });
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:org.candlepin.util.CrlFileUtil.java

/**
 * Updates the specified CRL file by adding or removing entries. If both lists are either null
 * or empty, the CRL file will not be modified by this method. If the file does not exist or
 * appears to be empty, it will be initialized before processing the lists.
 *
 * @param file//from  ww  w .  j  a v a  2s.c  om
 *  The CRL file to update
 *
 * @param revoke
 *  A collection of serials to revoke (add)
 *
 * @param unrevoke
 *  A collection of serials to unrevoke (remove)
 *
 * @throws IOException
 *  if an IO error occurs while updating the CRL file
 */
public void updateCRLFile(File file, final Collection<BigInteger> revoke, final Collection<BigInteger> unrevoke)
        throws IOException {

    if (!file.exists() || file.length() == 0) {
        this.initializeCRLFile(file, revoke);
        return;
    }

    File strippedFile = stripCRLFile(file);

    InputStream input = null;
    InputStream reaper = null;

    BufferedOutputStream output = null;
    OutputStream filter = null;
    OutputStream encoder = null;

    try {
        // Impl note:
        // Due to the way the X509CRLStreamWriter works (and the DER format in general), we have
        // to make two passes through the file.
        input = new Base64InputStream(new FileInputStream(strippedFile));
        reaper = new Base64InputStream(new FileInputStream(strippedFile));

        // Note: This will break if we ever stop using RSA keys
        PrivateKey key = this.pkiReader.getCaKey();
        X509CRLStreamWriter writer = new X509CRLStreamWriter(input, (RSAPrivateKey) key,
                this.pkiReader.getCACert());

        // Add new entries
        if (revoke != null) {
            Date now = new Date();
            for (BigInteger serial : revoke) {
                writer.add(serial, now, CRLReason.privilegeWithdrawn);
            }
        }

        // Unfortunately, we need to do the prescan before checking if we have changes queued,
        // or we could miss cases where we have entries to remove, but nothing to add.
        if (unrevoke != null && !unrevoke.isEmpty()) {
            writer.preScan(reaper, new CRLEntryValidator() {
                public boolean shouldDelete(X509CRLEntryObject entry) {
                    return unrevoke.contains(entry.getSerialNumber());
                }
            });
        } else {
            writer.preScan(reaper);
        }

        // Verify we actually have work to do now
        if (writer.hasChangesQueued()) {
            output = new BufferedOutputStream(new FileOutputStream(file));
            filter = new FilterOutputStream(output) {
                private boolean needsLineBreak = true;

                public void write(int b) throws IOException {
                    this.needsLineBreak = (b != (byte) '\n');
                    super.write(b);
                }

                public void write(byte[] buffer) throws IOException {
                    this.needsLineBreak = (buffer[buffer.length - 1] != (byte) '\n');
                    super.write(buffer);
                }

                public void write(byte[] buffer, int off, int len) throws IOException {
                    this.needsLineBreak = (buffer[off + len - 1] != (byte) '\n');
                    super.write(buffer, off, len);
                }

                public void close() throws IOException {
                    if (this.needsLineBreak) {
                        super.write((int) '\n');
                        this.needsLineBreak = false;
                    }

                    // Impl note:
                    // We're intentionally not propagating the call here.
                }
            };
            encoder = new Base64OutputStream(filter, true, 76, new byte[] { (byte) '\n' });

            output.write("-----BEGIN X509 CRL-----\n".getBytes());

            writer.lock();
            writer.write(encoder);
            encoder.close();
            filter.close();

            output.write("-----END X509 CRL-----\n".getBytes());
            output.close();
        }
    } catch (GeneralSecurityException e) {
        // This should never actually happen
        log.error("Unexpected security error occurred while retrieving CA key", e);
    } catch (CryptoException e) {
        // Something went horribly wrong with the stream writer
        log.error("Unexpected error occurred while writing new CRL file", e);
    } finally {
        for (Closeable stream : Arrays.asList(encoder, output, reaper, input)) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Unexpected exception occurred while closing stream: {}", stream, e);
                }
            }
        }

        if (!strippedFile.delete()) {
            log.error("Unable to delete temporary CRL file: {}", strippedFile);
        }
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testPemReadThroughBase64Stream() throws Exception {
    /* NB: Base64InputStream only takes base64.  The "-----BEGIN X509 CRL-----" and
     * corresponding footer must be removed.  Luckily in Base64InputStream stops the
     * minute it sees a padding character and our test file has some padding.  Thus,
     * we don't need to worry about removing the footer.  If the Base64 file didn't
     * require padding, I'm not sure what happens so the footer should be removed
     * somehow for real uses *//* www .  j  ava  2  s  .  c  o m*/

    InputStream referenceStream = new BufferedInputStream(new FileInputStream(pemFile));
    byte[] header = "-----BEGIN X509 CRL-----".getBytes("ASCII");
    Streams.readFully(referenceStream, header);

    referenceStream = new Base64InputStream(referenceStream);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL referenceCrl = (X509CRL) cf.generateCRL(referenceStream);

    Set<BigInteger> referenceSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : referenceCrl.getRevokedCertificates()) {
        referenceSerials.add(entry.getSerialNumber());
    }

    X509CRLEntryStream stream = new X509CRLEntryStream(derFile);
    try {
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(referenceSerials, streamedSerials);
    } finally {
        referenceStream.close();
        stream.close();
    }
}

From source file:org.cesecore.certificates.certificate.CertificateDataSerializationTest.java

@Test
public void testDeserializeOld() throws Exception {
    log.trace(">testDeserializeOld");
    final ByteArrayInputStream bais = new ByteArrayInputStream(OLD_DATA.getBytes("US-ASCII"));
    final Base64InputStream b64is = new Base64InputStream(bais);
    final ObjectInputStream ois = new ObjectInputStream(b64is);
    final CertificateData certData = (CertificateData) ois.readObject();
    ois.close();//from ww  w .  j  av a 2s  .com
    assertEquals("certuser", certData.getUsername()); // unrelated column. should not be affected
    assertNull("End Entity Profile Id in CertificateData with old serialization.",
            certData.getEndEntityProfileId());
    assertEquals(EndEntityInformation.NO_ENDENTITYPROFILE, certData.getEndEntityProfileIdOrZero());
    log.trace("<testDeserializeOld");
}

From source file:org.cesecore.certificates.certificate.CertificateDataSerializationTest.java

@Test
public void testDeserializeFuture() throws Exception {
    log.trace(">testDeserializeFuture");
    final ByteArrayInputStream bais = new ByteArrayInputStream(FUTURE_DATA.getBytes("US-ASCII"));
    final Base64InputStream b64is = new Base64InputStream(bais);
    final ObjectInputStream ois = new ObjectInputStream(b64is);
    final CertificateData certData = (CertificateData) ois.readObject();
    ois.close();/*from w w w. ja va2 s. c  om*/
    assertEquals("certuser", certData.getUsername()); // unrelated column. should not be affected
    log.trace("<testDeserializeFuture");
}

From source file:org.cesecore.certificates.certificate.CertificateDataSerializationTest.java

@Test
public void testDeserializeFutureFieldNewClass() throws Exception {
    log.trace(">testDeserializeFutureFieldNewClass");
    final ByteArrayInputStream bais = new ByteArrayInputStream(FUTURE_NEW_CLASS_DATA.getBytes("US-ASCII"));
    final Base64InputStream b64is = new Base64InputStream(bais);
    final ObjectInputStream ois = new ObjectInputStream(b64is);
    final CertificateData certData = (CertificateData) ois.readObject();
    ois.close();/* www  .  j av a2  s  .c  o  m*/
    assertEquals("certuser", certData.getUsername()); // unrelated column. should not be affected
    log.trace("<testDeserializeFutureFieldNewClass");
}

From source file:org.eclipse.vorto.perspective.view.GeneratorItem.java

/**
 * Create the composite./*  w w w .j a v  a  2s .  c o  m*/
 * 
 * @param parent
 * @param style
 */
public GeneratorItem(final Composite parent, int style, final ModelResource model,
        final GeneratorResource codegen) {
    super(parent, SWT.BORDER | SWT.NO_FOCUS);

    setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
    setSize(500, 120);

    Label lblIcon = new Label(this, SWT.NONE);
    lblIcon.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
    lblIcon.setAlignment(SWT.CENTER);
    lblIcon.setBounds(27, 21, 36, 36);
    ImageDescriptor generatorImage = ImageDescriptor.createFromImageData(
            new ImageData(new Base64InputStream(new ByteArrayInputStream(codegen.getImage32x32().getBytes()))));
    lblIcon.setImage(generatorImage.createImage());
    Label lblName = new Label(this, SWT.NONE);
    lblName.setAlignment(SWT.CENTER);
    lblName.setBounds(10, 63, 70, 15);
    lblName.setText(codegen.getName());
    lblName.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    StyledText txtDescription = new StyledText(this, SWT.READ_ONLY | SWT.WRAP);
    txtDescription.setBounds(96, 10, 390, 75);
    txtDescription.setText(codegen.getDescription());
    txtDescription.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    Label lblCreatedBy = new Label(this, SWT.NONE);
    lblCreatedBy.setBounds(96, 91, 60, 15);
    lblCreatedBy.setText("Created by ");
    lblCreatedBy.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    Label lblAuthor = new Label(this, SWT.NONE);
    lblAuthor.setBounds(157, 91, 131, 15);
    lblAuthor.setText(codegen.getCreator());
    lblAuthor.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    Label lblStarImage = new Label(this, SWT.NONE);
    lblStarImage.setAlignment(SWT.CENTER);
    lblStarImage.setBounds(10, 83, 70, 23);
    lblStarImage.setText("Rating: " + formatRating(codegen.getRating()));
    lblStarImage.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    lblGenerated.setBounds(320, 91, 85, 15);
    lblGenerated.setText("");
    lblGenerated.setAlignment(SWT.RIGHT);
    lblGenerated.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

    final Button btnGenerate = new Button(this, SWT.NONE);
    btnGenerate.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            lblGenerated.setText("Generating...");

            final IModelRepository modelRepo = ModelRepositoryFactory.getModelRepository();
            final Attachment attachment = modelRepo.generateCode(model.getId(), codegen.getKey());

            CodeGenerationHelper.createEclipseProject(model.getId(), codegen.getKey(),
                    toGenerationResult(attachment));

            lblGenerated.setText("Generated.");
            btnGenerate.setEnabled(false);
        }
    });
    btnGenerate.setBounds(411, 86, 75, 25);
    btnGenerate.setText("Generate");
}

From source file:org.n52.wps.io.datahandler.parser.AbstractParser.java

@Override
public IData parseBase64(InputStream input, String mimeType, String schema) {
    return parse(new Base64InputStream(input), mimeType, schema);
}

From source file:org.n52.wps.io.IOUtils.java

public static File writeBase64ToFile(InputStream input, String extension) throws IOException {

    File file = File.createTempFile("file" + UUID.randomUUID(), "." + extension,
            new File(System.getProperty("java.io.tmpdir")));
    OutputStream outputStream = null;
    try {/*from w  ww . j  av  a2  s .  c  o  m*/
        outputStream = new FileOutputStream(file);
        copyLarge(new Base64InputStream(input), outputStream);
    } finally {
        closeQuietly(outputStream);
    }

    return file;
}