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

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

Introduction

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

Prototype

public static String encodeBase64URLSafeString(final byte[] binaryData) 

Source Link

Document

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.

Usage

From source file:controllers.submit.Confirm.java

/**
 * Generate security hash for this submission. This method will make sure
 * that it is not being used by another submission before assigning a hash.
 * //from www  .ja  v a  2  s.  com
 * @param sub
 *            The submission to assign the hash too.
 * @return The new hash.
 */
protected static String generateCommitteEmailHash(Submission sub) {

    String hash = null;

    do {
        byte[] randomBytes = new byte[8];
        new Random().nextBytes(randomBytes);
        String proposed = Base64.encodeBase64URLSafeString(randomBytes);
        proposed = proposed.replaceAll("[^A-Za-z0-9]", "");

        // Check if the hash already exists
        if (subRepo.findSubmissionByEmailHash(proposed) == null) {
            // We're done, otherwise keep looping.
            hash = proposed;
        }
    } while (hash == null);

    sub.setCommitteeEmailHash(hash);
    return hash;
}

From source file:com.ibm.jaggr.service.util.BundleVersionsHashBase.java

/**
 * Returns an MD5 hash of the concatenated bundle header values from each of the specified bundles.
 * If any of the specified bundles are not found, a {@link NotFoundException} is thrown.
 *
 * @param headerNames the bundle header values to include in the hash
 * @param bundleNames the bundle names to include in the hash
 *
 * @return the computed hash//from w w w  . jav a2  s .c o m
 * @throws NotFoundException
 */
public String generateHash(String[] headerNames, String[] bundleNames) throws NotFoundException {
    final String sourceMethod = "generateCacheBustHash"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(BundleVersionsHashBase.class.getName(), sourceMethod);
    }

    // Sort the input lists so result is independent of the order the names are specified
    List<String> sortedHeaderNames = Arrays.asList(headerNames);
    List<String> sortedBundleNames = Arrays.asList(bundleNames);
    Collections.sort(sortedHeaderNames);
    Collections.sort(sortedBundleNames);

    StringBuffer sb = new StringBuffer();
    for (String bundleName : sortedBundleNames) {
        Dictionary<?, ?> bundleHeaders = getBundleHeaders(bundleName);
        for (String headerName : sortedHeaderNames) {
            Object value = bundleHeaders.get(headerName);
            if (isTraceLogging) {
                log.finer("Bundle = " + bundleName + ", Header name = " + headerName + ", Header value = " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + value);
            }
            sb.append(sb.length() == 0 ? "" : ",").append(value); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    String result = null;
    if (sb.length() > 0) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
            result = Base64.encodeBase64URLSafeString(md.digest(sb.toString().getBytes("UTF-8"))); //$NON-NLS-1$
        } catch (Exception e) {
            if (log.isLoggable(Level.SEVERE)) {
                log.log(Level.SEVERE, e.getMessage(), e);
            }
            throw new RuntimeException(e);
        }
    }
    if (isTraceLogging) {
        log.exiting(BundleVersionsHashBase.class.getName(), sourceMethod, result);
        ;
    }
    return result;
}

From source file:com.google.gerrit.server.mail.FromAddressGeneratorProvider.java

private static String hashOf(String data) {
    try {/*from w  w  w  .j ava 2 s .c  om*/
        MessageDigest hash = MessageDigest.getInstance("MD5");
        byte[] bytes = hash.digest(data.getBytes(Charsets.UTF_8));
        return Base64.encodeBase64URLSafeString(bytes);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("No MD5 available", e);
    }
}

From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerTest.java

@Test(expected = RuntimeException.class)
public void testInvalidEventType() {
    mockery.checking(new Expectations() {

        {/*from w  w  w. j ava 2  s . c  o m*/
        }
    });
    EventConsumer consumer = injector.getInstance(EventConsumer.class);
    consumer.consume(MSG_TYPE, "CONTENT\nCREATER\n"
            + Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8("random string\nfor test")));
    mockery.assertIsSatisfied();
}

From source file:com.comcast.cmb.common.controller.EndpointServlet.java

private String hashMessage(String message) {

    try {/*from   ww  w. j a v a 2  s . co m*/
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(message.getBytes("UTF-8"));
        byte[] hash = digest.digest();
        return Base64.encodeBase64URLSafeString(hash);
    } catch (Exception e) {
        logger.error("event=hashing_failed", e);
    }

    return null;
}

From source file:com.cliqset.magicsig.MagicKey.java

public String toString(boolean includePrivate) {
    StringBuilder sb = new StringBuilder();
    sb.append(type);//from  ww w  .  jav  a  2  s .com
    sb.append(SEPARATOR);
    sb.append(Base64.encodeBase64URLSafeString(n));
    sb.append(SEPARATOR);
    sb.append(Base64.encodeBase64URLSafeString(e));
    if (includePrivate && null != this.d) {
        sb.append(SEPARATOR);
        sb.append(Base64.encodeBase64URLSafeString(d));
    }
    return sb.toString();
}

From source file:com.squid.kraken.v4.api.core.bookmark.BookmarkFolderServiceBaseImpl.java

public List<BookmarkFolder> readFolders(AppContext ctx, String pathBase64) {
    List<BookmarkFolder> bfList = new ArrayList<BookmarkFolder>();
    String fullPath = buildBookmarksPath(ctx, pathBase64);
    List<Bookmark> bookmarks = getBookmarks(ctx, fullPath, pathBase64 == null);

    // compute the folders
    List<BookmarkPK> pkList = new ArrayList<BookmarkPK>();
    Set<String> folders = new HashSet<String>();
    for (Bookmark o : bookmarks) {
        String p = o.getPath();//from   w w w  .j  a v a  2 s  .co  m
        // ignore leading mypath
        p = p.substring(fullPath.length());
        // process the trailing path
        if (p != null) {
            String[] split = p.split(Bookmark.SEPARATOR);
            if (split.length > 0) {
                if (split[0].equals("")) {
                    if (split.length > 1) {
                        folders.add(split[1]);
                    }
                } else {
                    folders.add(split[0]);
                }
            } else {
                folders.add(p);
            }
        }
        pkList.add(o.getId());
    }
    // build the BookmarkFolder list
    for (String s : folders) {
        String folderPath = fullPath + Bookmark.SEPARATOR + s;
        String bookmarkFolderOid = Base64.encodeBase64URLSafeString(folderPath.getBytes());
        BookmarkFolder bf = read(ctx, bookmarkFolderOid);
        bfList.add(bf);
    }
    return bfList;
}

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * apache codec Base64 encoding//from  w w w.  j a  va  2  s.c  o  m
 * @param str -
 * @return
 * @throws UnsupportedEncodingException
 */
public static String encodeBase64(String str) throws UnsupportedEncodingException {
    return Base64.encodeBase64URLSafeString(str.getBytes("UTF-8"));
}

From source file:com.basho.yokozuna.handler.EntropyData.java

@Override
public void handleRequestBody(final SolrQueryRequest req, final SolrQueryResponse rsp)
        throws Exception, InstantiationException, IllegalAccessException {

    final String contParam = req.getParams().get("continue");
    final BytesRef cont = contParam != null ? decodeCont(contParam) : DEFAULT_CONT;

    final int n = req.getParams().getInt("n", DEFAULT_N);

    final String partition = req.getParams().get("partition");
    if (partition == null) {
        throw new Exception("Parameter 'partition' is required");
    }/*w  ww  . jav  a  2  s. c o m*/

    final SolrDocumentList docs = new SolrDocumentList();

    // Add docs here and modify object inline in code
    rsp.add("response", docs);

    try {
        final SolrIndexSearcher searcher = req.getSearcher();
        final AtomicReader rdr = searcher.getAtomicReader();
        BytesRef tmp = null;
        final Terms terms = rdr.terms(ENTROPY_DATA_FIELD);

        if (terms == null) {
            rsp.add("more", false);
            return;
        }

        final TermsEnum te = terms.iterator(null);

        if (isContinue(cont)) {
            if (log.isDebugEnabled()) {
                log.debug("continue from " + cont);
            }

            final TermsEnum.SeekStatus status = te.seekCeil(cont);

            if (status == TermsEnum.SeekStatus.END) {
                rsp.add("more", false);
                return;
            } else if (status == TermsEnum.SeekStatus.FOUND) {
                // If this term has already been seen then skip it.
                tmp = te.next();

                if (endOfItr(tmp)) {
                    rsp.add("more", false);
                    return;
                }
            } else if (status == TermsEnum.SeekStatus.NOT_FOUND) {
                tmp = te.next();
            }
        } else {
            tmp = te.next();
        }

        String text;
        String[] vals;
        String docPartition;
        String vsn;
        String riakBType;
        String riakBName;
        String riakKey;
        String hash;
        int count = 0;
        BytesRef current = null;
        final Bits liveDocs = rdr.getLiveDocs();

        while (!endOfItr(tmp) && count < n) {
            if (isLive(liveDocs, te)) {
                current = BytesRef.deepCopyOf(tmp);
                text = tmp.utf8ToString();
                if (log.isDebugEnabled()) {
                    log.debug("text: " + text);
                }
                vals = text.split(" ");

                vsn = vals[0];
                docPartition = vals[1];
                riakBType = vals[2];
                riakBName = vals[3];
                riakKey = vals[4];
                hash = vals[5];

                if (partition.equals(docPartition)) {
                    SolrDocument tmpDoc = new SolrDocument();
                    tmpDoc.addField("vsn", vsn);
                    tmpDoc.addField("riak_bucket_type", riakBType);
                    tmpDoc.addField("riak_bucket_name", riakBName);
                    tmpDoc.addField("riak_key", riakKey);
                    tmpDoc.addField("base64_hash", hash);
                    docs.add(tmpDoc);
                    count++;
                }
            }
            tmp = te.next();
        }

        if (count < n) {
            rsp.add("more", false);
        } else {
            rsp.add("more", true);
            final String newCont = Base64.encodeBase64URLSafeString(current.bytes);
            // The continue context for next req to start where
            // this one finished.
            rsp.add("continuation", newCont);
        }

        docs.setNumFound(count);

    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:com.distrimind.madkit.kernel.KernelAddress.java

private static String getHexString(byte[] bytes) {
    return Base64.encodeBase64URLSafeString(bytes);
}