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

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

Introduction

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

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:fi.aalto.seqpig.filter.CoordinateFilter.java

protected void decodeSAMFileHeader() {
    try {//from   w w  w. j a  va  2 s .  com
        Base64 codec = new Base64();
        Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
        String datastr;

        datastr = p.getProperty("samfileheader");
        byte[] buffer = codec.decodeBase64(datastr);
        ByteArrayInputStream bstream = new ByteArrayInputStream(buffer);
        ObjectInputStream ostream = new ObjectInputStream(bstream);

        this.samfileheader = (String) ostream.readObject();
    } catch (Exception e) {
    }

    this.samfileheader_decoded = getSAMFileHeader();
}

From source file:cross.io.misc.Base64Util.java

/**
 *
 * @param floatList//from   w  ww.  j av a  2 s.c  o  m
 * @param bigEndian
 * @return
 * @throws EncoderException
 */
public static String floatListToBase64String(final List<Float> floatList, final boolean bigEndian)
        throws EncoderException {
    final byte[] raw = Base64Util.floatListToByteArray(floatList, bigEndian);
    final Base64 base64 = new Base64();
    final byte[] encoded = base64.encode(raw);
    return new String(encoded);
}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 *///from ww w  . j  a v a  2 s .  co  m
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:com.hazelcast.qasonar.utils.Utils.java

public static String getBasicAuthString(String username, String password) {
    String authString = username + ":" + password;
    return "Basic " + new String(new Base64().encode(authString.getBytes()));
}

From source file:com.ligadata.EncryptUtils.EncryptionUtil.java

/**
 * Decode(Base64 decoding) given string to a byte array
 * /*from  ww  w  .  j a  v  a  2  s.  com*/
 * @param s
 *          : an encoded string 
 * @return byte array
 * @throws java.lang.Exception and exception is thrown
 */

public static byte[] decode(String s) throws Exception {
    try {
        Base64 base64 = new Base64();
        byte[] decoded = base64.decode(s.getBytes());
        return decoded;
    } catch (Exception e) {
        logger.error("Failed to decode a byte array", e);
        throw e;
    }
}

From source file:fi.aalto.seqpig.io.BamStorer.java

@Override
public void putNext(Tuple f) throws IOException {

    if (selectedBAMAttributes == null || allBAMFieldNames == null) {
        try {//from w w w  .j av a  2s.  co m
            Base64 codec = new Base64();
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
            String datastr;

            datastr = p.getProperty("selectedBAMAttributes");
            byte[] buffer = codec.decodeBase64(datastr);
            ByteArrayInputStream bstream = new ByteArrayInputStream(buffer);
            ObjectInputStream ostream = new ObjectInputStream(bstream);

            selectedBAMAttributes = (HashMap<String, Integer>) ostream.readObject();

            datastr = p.getProperty("allBAMFieldNames");
            buffer = codec.decodeBase64(datastr);
            bstream = new ByteArrayInputStream(buffer);
            ostream = new ObjectInputStream(bstream);

            allBAMFieldNames = (HashMap<String, Integer>) ostream.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
    }

    SAMRecordWritable samrecwrite = new SAMRecordWritable();
    SAMRecord samrec = new SAMRecord(samfileheader_decoded);

    int index = getFieldIndex("name", allBAMFieldNames);

    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setReadName((String) f.get(index));
    }

    index = getFieldIndex("start", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setAlignmentStart(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("read", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setReadString((String) f.get(index));
    }

    index = getFieldIndex("cigar", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setCigarString((String) f.get(index));
    }

    index = getFieldIndex("basequal", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setBaseQualityString((String) f.get(index));
    }

    index = getFieldIndex("flags", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setFlags(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("insertsize", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setInferredInsertSize(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("mapqual", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMappingQuality(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("matestart", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMateAlignmentStart(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("materefindex", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMateReferenceIndex(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("refindex", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setReferenceIndex(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("attributes", allBAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.MAP) {
        Set<Map.Entry<String, Object>> set = ((HashMap<String, Object>) f.get(index)).entrySet();

        for (Map.Entry<String, Object> pairs : set) {
            String attributeName = pairs.getKey();

            samrec.setAttribute(attributeName.toUpperCase(), pairs.getValue());
        }
    }

    samrec.hashCode(); // causes eagerDecode()
    samrecwrite.set(samrec);

    try {
        writer.write(null, samrecwrite);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.titilink.camel.rest.util.OtherUtil.java

/**
 * BASE64?/*from   w w  w.  j  a va 2 s.c om*/
 *
 * @param str --?
 * @return --??
 */
public static String strBase64Encode(String str) {
    Base64 b64 = new Base64();
    byte[] b = b64.encode(str.getBytes());
    return new String(b);
}

From source file:fi.aalto.seqpig.io.SamStorer.java

@Override
public void putNext(Tuple f) throws IOException {

    if (selectedSAMAttributes == null || allSAMFieldNames == null) {
        try {/*from w  w w .  j a  v a2  s .c  o  m*/
            Base64 codec = new Base64();
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
            String datastr;

            datastr = p.getProperty("selectedSAMAttributes");
            byte[] buffer = codec.decodeBase64(datastr);
            ByteArrayInputStream bstream = new ByteArrayInputStream(buffer);
            ObjectInputStream ostream = new ObjectInputStream(bstream);

            selectedSAMAttributes = (HashMap<String, Integer>) ostream.readObject();

            datastr = p.getProperty("allSAMFieldNames");
            buffer = codec.decodeBase64(datastr);
            bstream = new ByteArrayInputStream(buffer);
            ostream = new ObjectInputStream(bstream);

            allSAMFieldNames = (HashMap<String, Integer>) ostream.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
    }

    SAMRecordWritable samrecwrite = new SAMRecordWritable();
    SAMRecord samrec = new SAMRecord(samfileheader_decoded);

    int index = getFieldIndex("name", allSAMFieldNames);

    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setReadName((String) f.get(index));
    }

    index = getFieldIndex("start", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setAlignmentStart(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("read", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setReadString((String) f.get(index));
    }

    index = getFieldIndex("cigar", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setCigarString((String) f.get(index));
    }

    index = getFieldIndex("basequal", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        samrec.setBaseQualityString((String) f.get(index));
    }

    index = getFieldIndex("flags", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setFlags(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("insertsize", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setInferredInsertSize(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("mapqual", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMappingQuality(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("matestart", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMateAlignmentStart(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("materefindex", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setMateReferenceIndex(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("refindex", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        samrec.setReferenceIndex(((Integer) f.get(index)).intValue());
    }

    index = getFieldIndex("attributes", allSAMFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.MAP) {
        Set<Map.Entry<String, Object>> set = ((HashMap<String, Object>) f.get(index)).entrySet();

        for (Map.Entry<String, Object> pairs : set) {
            String attributeName = pairs.getKey();

            samrec.setAttribute(attributeName.toUpperCase(), pairs.getValue());
        }
    }

    samrec.hashCode(); // causes eagerDecode()
    samrecwrite.set(samrec);

    try {
        writer.write(null, samrecwrite);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.amazonbird.amazonproxy.SignedRequestsHelper.java

/**
 * Compute the HMAC.//from w  ww  .  j  a v a 2 s.c om
 *  
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64();
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature.trim();
}

From source file:com.cs194.windowshopping.SignedRequestsHelper.java

/**
 * Compute the HMAC.//from  w  w w .j  ava  2 s  .c om
 *  
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64();
        //            Base64 encoder = new Base64(76, new byte[0]);
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}