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:org.kiji.scoring.lib.server.ScoringServerScoreFunction.java

/**
 * Build the URL from which to retrieve a score by appending the necessary parameters to the base
 * model URL.//w w  w  .j av a  2 s  .c  om
 *
 * @param modelBaseURL URL of the scoring servlet for this model.
 * @param eid the entity to score.
 * @param clientRequest client's data request which triggered the run of this ScoreFunction.
 * @param params an optional map of per-request parameters to be passed to the server.
 *
 * @return the URL from which to retrieve a score.
 * @throws MalformedURLException in case the URL cannot be created.
 */
private static URL getScoringServerEndpoint(final String modelBaseURL, final EntityId eid,
        final KijiDataRequest clientRequest, final Map<String, String> params) throws MalformedURLException {
    final String base64Request = Base64.encodeBase64URLSafeString(SerializationUtils.serialize(clientRequest));
    final StringBuilder urlStringBuilder;
    try {
        urlStringBuilder = new StringBuilder(String.format("%s?eid=%s&request=%s", modelBaseURL,
                URLEncoder.encode(eid.toShellString(), Charsets.UTF_8.name()), base64Request));
        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlStringBuilder.append(String.format("&fresh.%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"),
                    URLEncoder.encode(entry.getValue(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return new URL(urlStringBuilder.toString());
}

From source file:org.kitesdk.data.spi.SchemaUtil.java

@SuppressWarnings("unchecked")
public static String toString(Object value, Schema schema) {
    switch (schema.getType()) {
    case BOOLEAN:
    case INT:/*from www  .  ja va  2  s . c  o m*/
    case LONG:
    case FLOAT:
    case DOUBLE:
        return value.toString();
    case STRING:
        // TODO: could be null
        try {
            return URLEncoder.encode(value.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new DatasetIOException("Failed to encode value: " + value, e);
        }
    default:
        // otherwise, encode as Avro binary and then base64
        DatumWriter writer = ReflectData.get().createDatumWriter(schema);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
        try {
            writer.write(value, encoder);
            encoder.flush();
        } catch (IOException e) {
            throw new DatasetIOException("Cannot encode Avro value", e);
        }
        return Base64.encodeBase64URLSafeString(out.toByteArray());
    }
}

From source file:org.lightcouch.View.java

/**
 * @return The next page.//w w w.j  a  v  a  2  s .c om
 */
private <T> Page<T> queryNextPage(int rowsPerPage, String currentStartKey, String currentStartKeyDocId,
        String startKey, String startKeyDocId, Class<T> classOfT) {
    // set view query params
    limit(rowsPerPage + 1);
    includeDocs(true);
    if (startKey != null) {
        startKey(startKey);
        startKeyDocId(startKeyDocId);
    }
    // init page, query view
    Page<T> page = new Page<T>();
    List<T> pageList = new ArrayList<T>();
    ViewResult<String, String, T> vr = queryView(String.class, String.class, classOfT);
    List<ViewResult<String, String, T>.Rows> rows = vr.getRows();
    int resultRows = rows.size();
    int offset = vr.getOffset();
    long totalRows = vr.getTotalRows();
    // holds page params
    JsonObject currentKeys = new JsonObject();
    JsonObject jsonNext = new JsonObject();
    JsonObject jsonPrev = new JsonObject();
    currentKeys.addProperty(CURRENT_START_KEY, rows.get(0).getKey());
    currentKeys.addProperty(CURRENT_START_KEY_DOC_ID, rows.get(0).getId());
    for (int i = 0; i < resultRows; i++) {
        // set keys for the next page
        if (i == resultRows - 1) { // last element (i.e rowsPerPage + 1)
            if (resultRows > rowsPerPage) { // if not last page
                page.setHasNext(true);
                jsonNext.addProperty(START_KEY, rows.get(i).getKey());
                jsonNext.addProperty(START_KEY_DOC_ID, rows.get(i).getId());
                jsonNext.add(CURRENT_KEYS, currentKeys);
                jsonNext.addProperty(ACTION, NEXT);
                page.setNextParam(Base64.encodeBase64URLSafeString(jsonNext.toString().getBytes()));
                continue; // exclude 
            }
        }
        pageList.add(rows.get(i).getDoc());
    }
    // set keys for the previous page
    if (offset != 0) { // if not first page
        page.setHasPrevious(true);
        jsonPrev.addProperty(START_KEY, currentStartKey);
        jsonPrev.addProperty(START_KEY_DOC_ID, currentStartKeyDocId);
        jsonPrev.add(CURRENT_KEYS, currentKeys);
        jsonPrev.addProperty(ACTION, PREVIOUS);
        page.setPreviousParam(Base64.encodeBase64URLSafeString(jsonPrev.toString().getBytes()));
    }
    // calculate paging display info
    page.setResultList(pageList);
    page.setTotalResults(totalRows);
    page.setResultFrom(offset + 1);
    int resultTo = rowsPerPage > resultRows ? resultRows : rowsPerPage; // fix when rowsPerPage exceeds returned rows
    page.setResultTo(offset + resultTo);
    page.setPageNumber((int) Math.ceil(page.getResultFrom() / Double.valueOf(rowsPerPage)));
    return page;
}

From source file:org.lightcouch.View.java

/**
 * @return The previous page./*from w  ww  .j a  v a 2 s.c om*/
 */
private <T> Page<T> queryPreviousPage(int rowsPerPage, String currentStartKey, String currentStartKeyDocId,
        String startKey, String startKeyDocId, Class<T> classOfT) {
    // set view query params
    limit(rowsPerPage + 1);
    includeDocs(true);
    descending(true); // read backward
    startKey(currentStartKey);
    startKeyDocId(currentStartKeyDocId);
    // init page, query view
    Page<T> page = new Page<T>();
    List<T> pageList = new ArrayList<T>();
    ViewResult<String, String, T> vr = queryView(String.class, String.class, classOfT);
    List<ViewResult<String, String, T>.Rows> rows = vr.getRows();
    int resultRows = rows.size();
    int offset = vr.getOffset();
    long totalRows = vr.getTotalRows();
    Collections.reverse(rows); // fix order
    // holds page params
    JsonObject currentKeys = new JsonObject();
    JsonObject jsonNext = new JsonObject();
    JsonObject jsonPrev = new JsonObject();
    currentKeys.addProperty(CURRENT_START_KEY, rows.get(0).getKey());
    currentKeys.addProperty(CURRENT_START_KEY_DOC_ID, rows.get(0).getId());
    for (int i = 0; i < resultRows; i++) {
        // set keys for the next page
        if (i == resultRows - 1) { // last element (i.e rowsPerPage + 1)
            if (resultRows >= rowsPerPage) { // if not last page
                page.setHasNext(true);
                jsonNext.addProperty(START_KEY, rows.get(i).getKey());
                jsonNext.addProperty(START_KEY_DOC_ID, rows.get(i).getId());
                jsonNext.add(CURRENT_KEYS, currentKeys);
                jsonNext.addProperty(ACTION, NEXT);
                page.setNextParam(Base64.encodeBase64URLSafeString(jsonNext.toString().getBytes()));
                continue;
            }
        }
        pageList.add(rows.get(i).getDoc());
    }
    // set keys for the previous page
    if (offset != (totalRows - rowsPerPage - 1)) { // if not first page
        page.setHasPrevious(true);
        jsonPrev.addProperty(START_KEY, currentStartKey);
        jsonPrev.addProperty(START_KEY_DOC_ID, currentStartKeyDocId);
        jsonPrev.add(CURRENT_KEYS, currentKeys);
        jsonPrev.addProperty(ACTION, PREVIOUS);
        page.setPreviousParam(Base64.encodeBase64URLSafeString(jsonPrev.toString().getBytes()));
    }
    // calculate paging display info
    page.setResultList(pageList);
    page.setTotalResults(totalRows);
    page.setResultFrom((int) totalRows - (offset + rowsPerPage));
    int resultTo = (int) totalRows - offset - 1;
    page.setResultTo(resultTo);
    page.setPageNumber(resultTo / rowsPerPage);
    return page;
}

From source file:org.lotus.Main.java

/**
 * @param args the command line arguments
 *///from  ww  w .  j  ava2 s  .c o  m
public static void main(String[] args) throws FileNotFoundException, IOException {
    File folder = new File(System.getProperty("user.dir")).getParentFile();
    File inf = new File(folder, "img (1).png");
    FileInputStream in = new FileInputStream(inf);
    byte[] buffer = new byte[(int) inf.length()];
    in.read(buffer);
    in.close();
    String str = Base64.encodeBase64URLSafeString(buffer);
    buffer = Base64.decodeBase64(str);
    FileOutputStream out = new FileOutputStream(new File(folder, "out.png"));
    out.write(buffer);
    out.close();
}

From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ClientDetailsEntityService.java

/**
 * Generates a new clientSecret for the given client and sets it to the client's clientSecret field. Returns the client that was passed in, now with secret set.
 *//*  ww  w  .  j av a  2s .  c  om*/
@Override
public ClientDetailsEntity generateClientSecret(ClientDetailsEntity client) {
    client.setClientSecret(Base64
            .encodeBase64URLSafeString(new BigInteger(512, new SecureRandom()).toByteArray()).replace("=", ""));
    return client;
}

From source file:org.mitre.openid.connect.view.JwkKeyListView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        public boolean shouldSkipField(FieldAttributes f) {

            return false;
        }/*from  w  w  w .j  a  v a2  s . c o  m*/

        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            }
            return false;
        }

    }).create();

    response.setContentType("application/json");

    Writer out = response.getWriter();

    //BiMap<String, PublicKey> keyMap = (BiMap<String, PublicKey>) model.get("keys");
    Map<String, JwtSigner> signers = (Map<String, JwtSigner>) model.get("signers");

    JsonObject obj = new JsonObject();
    JsonArray keys = new JsonArray();
    obj.add("keys", keys);

    for (String keyId : signers.keySet()) {

        JwtSigner src = signers.get(keyId);

        if (src instanceof RsaSigner) {

            RsaSigner rsaSigner = (RsaSigner) src;

            RSAPublicKey rsa = (RSAPublicKey) rsaSigner.getPublicKey(); // we're sure this is an RSAPublicKey b/c this is an RsaSigner

            BigInteger mod = rsa.getModulus();
            BigInteger exp = rsa.getPublicExponent();

            String m64 = Base64.encodeBase64URLSafeString(mod.toByteArray());
            String e64 = Base64.encodeBase64URLSafeString(exp.toByteArray());

            JsonObject o = new JsonObject();

            o.addProperty("use", "sig"); // since we don't do encryption yet
            o.addProperty("alg", "RSA"); //rsaSigner.getAlgorithm()); // we know this is RSA
            o.addProperty("mod", m64);
            o.addProperty("exp", e64);
            o.addProperty("kid", keyId);

            keys.add(o);
        } // TODO: deal with non-RSA key types
    }

    gson.toJson(obj, out);

}

From source file:org.motechproject.server.decisiontree.web.VxmlController.java

/**
 * Handles Decision Tree Node HTTP requests and generates a VXML document based on a Velocity template.
 * The HTTP request should contain the Tree ID, Node ID, Patient ID and Selected Transition Key (optional) parameters
 *
 *//*from w  w w .  j  a v a  2 s .  c o  m*/
public ModelAndView node(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generating decision tree node VXML");

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    Node node = null;
    String transitionPath = null;
    Map<String, Object> params = convertParams(request.getParameterMap());

    String patientId = request.getParameter(PATIENT_ID_PARAM);
    String language = request.getParameter(LANGUAGE_PARAM);
    String treeNameString = request.getParameter(TREE_NAME_PARAM);
    String encodedParentTransitionPath = request.getParameter(TRANSITION_PATH_PARAM);
    String transitionKey = request.getParameter(TRANSITION_KEY_PARAM);

    logger.info(" Node HTTP  request parameters: " + PATIENT_ID_PARAM + ": " + patientId + ", " + LANGUAGE_PARAM
            + ": " + language + ", " + TREE_NAME_PARAM + ": " + treeNameString + ", " + TRANSITION_PATH_PARAM
            + ": " + encodedParentTransitionPath + ", " + TRANSITION_KEY_PARAM + ": " + transitionKey);

    if (StringUtils.isBlank(patientId) || StringUtils.isBlank(language)
            || StringUtils.isBlank(treeNameString)) {

        logger.error("Invalid HTTP request - the following parameters: " + PATIENT_ID_PARAM + ", "
                + LANGUAGE_PARAM + " and " + TREE_NAME_PARAM + " are mandatory");
        return getErrorModelAndView(Errors.NULL_PATIENTID_LANGUAGE_OR_TREENAME_PARAM);
    }

    String[] treeNames = treeNameString.split(TREE_NAME_SEPARATOR);
    String currentTree = treeNames[0];
    // put only one tree name in params
    params.put(TREE_NAME_PARAM, currentTree);

    if (transitionKey == null) { // get root node
        try {
            String rootTransitionPath = TreeNodeLocator.PATH_DELIMITER;
            node = decisionTreeService.getNode(currentTree, rootTransitionPath);
            transitionPath = rootTransitionPath;
        } catch (Exception e) {
            logger.error("Can not get node by Tree Name: " + currentTree + " transition path: " + patientId, e);
        }
    } else { // get not root node
        String parentTransitionPath = null;
        try {
            if (encodedParentTransitionPath == null) {

                logger.error(
                        "Invalid HTTP request - the  " + TRANSITION_PATH_PARAM + " parameter is mandatory");
                return getErrorModelAndView(Errors.NULL_TRANSITION_PATH_PARAM);
            }

            parentTransitionPath = new String(Base64.decodeBase64(encodedParentTransitionPath));
            Node parentNode = decisionTreeService.getNode(currentTree, parentTransitionPath);

            Transition transition = parentNode.getTransitions().get(transitionKey);

            if (transition == null) {
                logger.error("Invalid Transition Key. There is no transition with key: " + transitionKey
                        + " in the Node: " + parentNode);
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY);
            }

            treeEventProcessor.sendActionsAfter(parentNode, parentTransitionPath, params);

            treeEventProcessor.sendTransitionActions(transition, params);

            node = transition.getDestinationNode();

            if (node == null || (node.getPrompts().isEmpty() && node.getActionsAfter().isEmpty()
                    && node.getActionsBefore().isEmpty() && node.getTransitions().isEmpty())) {
                if (treeNames.length > 1) {
                    //reduce the current tree and redirect to the next tree
                    treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
                    String view = String.format(
                            "redirect:/tree/vxml/node?" + PATIENT_ID_PARAM + "=%s&" + TREE_NAME_PARAM + "=%s&"
                                    + LANGUAGE_PARAM + "=%s",
                            patientId, StringUtils.join(treeNames, TREE_NAME_SEPARATOR), language);
                    ModelAndView mav = new ModelAndView(view);
                    return mav;
                } else {
                    //TODO: Add support for return url
                    ModelAndView mav = new ModelAndView(EXIT_TEMPLATE_NAME);
                    return mav;
                }

            } else {
                transitionPath = parentTransitionPath
                        + (TreeNodeLocator.PATH_DELIMITER.equals(parentTransitionPath) ? ""
                                : TreeNodeLocator.PATH_DELIMITER)
                        + transitionKey;
            }

        } catch (Exception e) {
            logger.error("Can not get node by Tree ID : " + currentTree + " and Transition Path: "
                    + parentTransitionPath, e);
        }
    }

    if (node != null) {

        //validate node
        for (Map.Entry<String, Transition> transitionEntry : node.getTransitions().entrySet()) {

            try {
                Integer.parseInt(transitionEntry.getKey());
            } catch (NumberFormatException e) {
                logger.error("Invalid node: " + node
                        + "\n In order  to be used in VXML transition keys should be an Integer");
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY_TYPE);
            }

            Transition transition = transitionEntry.getValue();
            if (transition.getDestinationNode() == null) {
                logger.error(
                        "Invalid node: " + node + "\n Null Destination Node in the Transition: " + transition);
                return getErrorModelAndView(Errors.NULL_DESTINATION_NODE);
            }
        }

        treeEventProcessor.sendActionsBefore(node, transitionPath, params);

        ModelAndView mav = new ModelAndView();
        if (node.getTransitions().size() > 0) {
            mav.setViewName(NODE_TEMPLATE_NAME);
            mav.addObject("treeName", treeNameString);
        } else { // leaf
            //reduce the current tree and redirect to the next tree
            treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
            mav.setViewName(LEAF_TEMPLATE_NAME);
            mav.addObject("treeName", StringUtils.join(treeNames, TREE_NAME_SEPARATOR));
        }
        mav.addObject("contentPath", request.getContextPath());
        mav.addObject("node", node);
        mav.addObject("patientId", patientId);
        mav.addObject("language", language);
        mav.addObject("transitionPath", Base64.encodeBase64URLSafeString(transitionPath.getBytes()));
        mav.addObject("escape", new StringEscapeUtils());

        return mav;
    } else {
        return getErrorModelAndView(Errors.GET_NODE_ERROR);
    }

}

From source file:org.nerve.utils.encode.EncodeUtils.java

public static String base64UrlSafeEncode(byte[] input) {
    return Base64.encodeBase64URLSafeString(input);
}

From source file:org.noerp.base.crypto.HashCrypt.java

private static String getCryptedBytes(String hashType, String salt, byte[] bytes) {
    try {//  w  w w.  j a v a2s.co m
        MessageDigest messagedigest = MessageDigest.getInstance(hashType);
        messagedigest.update(salt.getBytes(UTF8));
        messagedigest.update(bytes);
        return Base64.encodeBase64URLSafeString(messagedigest.digest()).replace('+', '.');
    } catch (NoSuchAlgorithmException e) {
        throw new GeneralRuntimeException("Error while comparing password", e);
    }
}