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.woodwardbernsteinprotocol.Utilities.java

public InputStream base64(InputStream input) {
    return new Base64InputStream(input);
}

From source file:org.xwiki.extension.xar.internal.handler.packager.xml.AttachmentHandler.java

@Override
protected void endElementInternal(String uri, String localName, String qName) throws SAXException {
    if (qName.equals("content")) {
        try {/*  ww  w .  j a  v  a  2  s. c o  m*/
            Base64InputStream b64is = new Base64InputStream(IOUtils.toInputStream(this.value));
            getAttachment().setContent(b64is);
        } catch (IOException e) {
            // TODO: log error
        }
    } else {
        super.endElementInternal(uri, localName, qName);
    }
}

From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java

/**
 * Convert string tuple back to the original object.
 *
 * @param tuple string tuple/*from  w ww  . java 2 s. com*/
 *
 * @return cart object of null
 *
 * @throws CartDetuplizationException when cannot deserialize the object
 */
protected ShoppingCart toObject(String tuple) throws CartDetuplizationException {

    if (tuple == null || tuple.length() == 0) {
        return null;
    }
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tuple.getBytes());
    final Base64InputStream base64DecoderStream = new Base64InputStream(byteArrayInputStream);
    final CipherInputStream cipherInputStream = new CipherInputStream(base64DecoderStream, desUnCipher);
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(cipherInputStream);
        return (ShoppingCart) objectInputStream.readObject();

    } catch (Exception exception) {
        try {
            desUnCipher.init(Cipher.DECRYPT_MODE, secretKey); //reinit
        } catch (InvalidKeyException e) {
            LOG.error("Cant reinit desUnCipher", exception);
        }
        final String errMsg = "Unable to convert bytes assembled from tuple into object";
        LOG.error(errMsg, exception);
        throw new CartDetuplizationException(errMsg, exception);
    } finally {
        try {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
            cipherInputStream.close();
            base64DecoderStream.close();
            byteArrayInputStream.close();
        } catch (IOException ioe) { // leave this one silent as we have the object.
            LOG.error("Unable to close object stream", ioe);
        }

    }
}

From source file:photosharing.api.conx.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * /*from  ww w.  j  av  a2s  .  co m*/
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            Executor exec = ExecutorUtil.getExecutor();

            Response apiResponse = exec.execute(post);
            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            logger.info("code is " + code);

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("IOException " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("SAXException " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

            logger.severe("JSONException " + e.toString());
        }
    }
}

From source file:tools.pki.gbay.crypto.keys.validation.CertificateRevocationList.java

/**
 * Read PEM or DER incuded CRL from byte array
 * @param crlbyte/*www .  ja  va 2  s.  c o m*/
 * @return CRL
 * @throws CRLException
 * @throws CertificateException
 */
public static X509CRL fromByteArray(byte[] crlbyte) throws CRLException, CertificateException {
    CertificateFactory factory = null;
    factory = CertificateFactory.getInstance("X509");
    if (org.apache.commons.codec.binary.Base64.isBase64(crlbyte))
        return (X509CRL) factory.generateCRL(new Base64InputStream(new ByteArrayInputStream(crlbyte)));
    else
        return (X509CRL) factory.generateCRL(new ByteArrayInputStream(crlbyte));
}

From source file:tools.pki.gbay.crypto.keys.validation.CertificateRevocationList.java

/**
 * Open CRL file//from   ww  w .j a  v a  2 s . com
 * @param address Address of a PEM or DER encoded CRL
 * @return CRL
 * @throws CertificateException
 * @throws IOException
 * @throws CRLException
 */
public static X509CRL openCRLFile(String address) throws CertificateException, IOException, CRLException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    InputStream in = new FileInputStream(address);
    byte[] data = IOUtils.toByteArray(in);

    X509CRL crl = null;
    if (org.apache.commons.codec.binary.Base64.isBase64(data)) {
        crl = (X509CRL) cf.generateCRL(new Base64InputStream(new ByteArrayInputStream(data)));
    } else {
        crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(data));
    }
    return crl;

}

From source file:tools.pki.gbay.crypto.keys.validation.CertificateRevocationList.java

/**
 * Open a CRL (PEM or DER)/*from  w ww . ja  v  a 2  s  .  co m*/
 * @param data byte array of CRL
 * @return CRL
 * @throws CertificateException
 * @throws IOException
 * @throws CRLException
 */
public static X509CRL openCRLByte(byte[] data) throws CertificateException, IOException, CRLException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    if (org.apache.commons.codec.binary.Base64.isBase64(data)) {
        log.info("Your CRL is BASE64 encoded, we decode and then open");
        return (X509CRL) cf.generateCRL(new Base64InputStream(new ByteArrayInputStream(data)));
    } else {
        log.info("Openning DER encoded CRL...");

        return (X509CRL) cf.generateCRL(new ByteArrayInputStream(data));
    }
}

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

public static byte[] decompress(byte[] contentBytes) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPInputStream bis = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(contentBytes)));
    byte[] buffer = new byte[1024 * 4];
    int n = 0;/*from   w  w  w  .j av a2 s  .c om*/
    while (-1 != (n = bis.read(buffer))) {
        out.write(buffer, 0, n);
    }
    bis.close();
    return out.toByteArray();
}