Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.FormsDocumentServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Map<String, Object> response = new HashMap<>();

    try {/*from w ww  .  ja  va 2 s.c o m*/

        FileItem fileItem = getFileItem(req);

        String id = UUID.randomUUID().toString();

        String content = Base64.getEncoder().encodeToString(fileItem.get());

        DocumentUploadChunk chunk = new DocumentUploadChunk(id, fileItem.getName(), 0, 1, content);

        DocumentUploadSession session = new DocumentUploadSession(chunk.getDocumentId(),
                chunk.getDocumentName(), chunk.getMaxChunks());

        session.add(chunk);

        storage.uploadContentChunk(chunk);

        session.setState(DocumentUploadSession.State.MERGING);

        storage.merge(session);

        DocumentData data = new DocumentData(id, fileItem.getName(), fileItem.getSize(), "",
                System.currentTimeMillis());

        response.put("document", data);
    } catch (Exception e) {
        response.put("error", "error");
    } finally {
        writeResponse(resp, response);
    }
}

From source file:org.kie.workbench.common.stunner.core.backend.util.URLUtils.java

public static String buildDataURIFromStream(final String fileName, final InputStream inputStream)
        throws Exception {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final String contentType = guessContentType(fileName, inputStream);
    if (null != contentType) {
        final byte[] chunk = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(chunk)) > 0) {
            os.write(chunk, 0, bytesRead);
        }// w  w w . j a  va 2 s  .  co  m
        os.flush();
        inputStream.close();
        return "data:" + contentType + ";base64," + Base64.getEncoder().encodeToString(os.toByteArray());
    } else {
        throw new UnsupportedOperationException("Content type is undefined.");
    }
}

From source file:br.com.ufjf.labredes.rest.EleitorResource.java

@POST
@Path("/{eleitor}")
//3. Envia Credenciais
public String login(@PathParam("eleitor") String elector) {
    byte[] elector_decoded = Base64.getDecoder().decode(elector);
    SealedObject aux = (SealedObject) SerializationUtils.deserialize(elector_decoded);
    Eleitor eleitor = (Eleitor) rsa.decrypt(aux, client_aes);
    eleitor = eleitorService.getEleitor(eleitor.getCpf(), eleitor.getSenha());

    Response ans = new Response();
    CandidatoList candidatos = new CandidatoList();

    if (eleitor != null) {
        //3.1 Responde
        candidatos.setCandidatos(candidatoService.getAll());
        byte[] data = SerializationUtils.serialize(rsa.encrypt(candidatos, client_aes));
        String retorno = Base64.getEncoder().encodeToString(data);
        return retorno;
    } else {//  w  ww .j a v a2  s. c  om
        ans.Error("Erro ao decriptar chave");
        //3.1 Responde
        byte[] data = SerializationUtils.serialize(rsa.encrypt(ans, client_aes));
        String retorno = Base64.getEncoder().encodeToString(data);
        return retorno;
    }

}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ResultSetTransformer.java

private static Object parseValue(Object object) {
    try {//w w  w  . ja  va  2s  . co  m
        if (object instanceof Blob) {

            byte[] blob = IOUtils.toByteArray(Blob.class.cast(object).getBinaryStream());
            object = Base64.getEncoder().encodeToString(blob);
        }
    } catch (Exception e) {
        LOG.error("Something goes wrong parsing BLOB field", e);
        object = "Unparsable BLOB";
    }

    try {

        if (object instanceof Clob) {

            byte[] clob = IOUtils.toByteArray(Clob.class.cast(object).getAsciiStream());
            object = new String(clob, "UTF-8");
        }

    } catch (Exception e) {
        LOG.error("Something goes wrong parsing CLOB field", e);
        object = "Unparsable CLOB";
    }

    if (object instanceof String) {

        String value = String.class.cast(object).trim();

        try {
            if (value.startsWith("{") && value.endsWith("}")) {
                return new JSONObject(value);

            } else if (value.startsWith("[") && value.endsWith("]")) {
                return new JSONArray(value);
            }
        } catch (JSONException e) {
            LOG.warn("Something goes wrong parsing " + value + " as JSON");
        }

    }

    return object;

}

From source file:automenta.climatenet.ImportKML.java

public static String getSerial(String layer, int serial) {
    return (Base64.getEncoder().encodeToString(
            BigInteger.valueOf(serial).add(BigInteger.valueOf(layer.hashCode()).shiftRight(32)).toByteArray()));
}

From source file:org.teavm.html4j.ResourcesInterceptor.java

@Override
public void begin(RenderingManager manager, BuildTarget buildTarget) throws IOException {
    boolean hasOneResource = false;
    for (String className : manager.getClassSource().getClassNames()) {
        final int lastDot = className.lastIndexOf('.');
        if (lastDot == -1) {
            continue;
        }//from w  w w.j a  v a2s  . c om
        String packageName = className.substring(0, lastDot);
        String resourceName = packageName.replace('.', '/') + "/" + "jvm.txt";
        try (InputStream input = manager.getClassLoader().getResourceAsStream(resourceName)) {
            if (input == null || !processed.add(resourceName)) {
                continue;
            }
            ByteArrayOutputStream arr = new ByteArrayOutputStream();
            IOUtils.copy(input, arr);
            String base64 = Base64.getEncoder().encodeToString(arr.toByteArray());
            input.close();
            final SourceWriter w = manager.getWriter();
            w.append("// Resource " + resourceName + " included by " + className).newLine();
            w.append("if (!window.teaVMResources) window.teaVMResources = {};").newLine();
            w.append("window.teaVMResources['" + resourceName + "'] = '");
            w.append(base64).append("';").newLine().newLine();
        }
        hasOneResource = true;
    }
    if (hasOneResource) {
        manager.getWriter().append("// TeaVM generated classes").newLine();
    }
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *
 * Decode the request received by the samlecp servlet.
 * Validate the SOAP message//ww w .ja v  a2 s  .  c  o m
 * Check whether the SOAP body contains a valid SAML request
 * @param soapMessage
 * @return
 * @throws IdentitySAML2ECPException
 */
public static String decodeSOAPMessage(SOAPMessage soapMessage)
        throws IdentitySAML2ECPException, TransformerException {
    SOAPBody body;
    String samlRequest = null;
    String strElement;
    if (soapMessage != null) {
        try {
            body = soapMessage.getSOAPPart().getEnvelope().getBody();
        } catch (SOAPException e) {
            String err = "Invalid SOAP Request";
            throw new IdentitySAML2ECPException(err, e);
        }
        int elementSize = 0;
        Iterator<?> elements = body.getChildElements();
        while (elements.hasNext()) {
            SOAPElement element = (SOAPElement) elements.next();
            strElement = convertSOAPElementToString(element);
            samlRequest = Base64.getEncoder().encodeToString(strElement.getBytes());
            elementSize += 1;
        }
        if (elementSize == 0) {
            String err = "SOAP message body cannot be Null";
            throw new IdentitySAML2ECPException(err);
        } else if (elementSize > 1) {
            String err = "SOAP Message body should Only contain a valid SAML Request";
            throw new IdentitySAML2ECPException(err);
        }
    } else {
        String err = "Empty SOAP Request";
        throw new IdentitySAML2ECPException(err);
    }
    return samlRequest;
}

From source file:org.jgrades.monitor.restart.SystemStateServiceImpl.java

private void setAuthProperty(URLConnection connection) {
    if (masterScriptUser != null && masterScriptPwd != null) {
        String userPass = masterScriptUser + ":" + masterScriptPwd;
        String encoded = Base64.getEncoder().encodeToString(userPass.getBytes(Charset.defaultCharset()));
        connection.setRequestProperty("Authorization", "Basic " + encoded);
    }//www .  j a  va  2s  .  c om
}

From source file:org.apache.accumulo.test.util.SerializationUtil.java

public static String serializeBase64(Serializable obj) {
    byte[] b = serialize(obj);
    return Base64.getEncoder().encodeToString(b);
}

From source file:ua.com.rocketlv.spb.UserController.java

@RequestMapping(value = "/list/{name}")
public String find(@PathVariable String name, Model model) {
    Locale locale = LocaleContextHolder.getLocale();
    String mess = messages.getMessage("wellcome", null, locale);
    System.out.println(mess);//from www. j  a va  2s . c  om
    Iterable<Users> lst = null;
    if (name.equals("all")) {
        lst = repository.findAll();
    } else {
        lst = repository.findByNameuIgnoreCaseContaining(name);
    }

    try {
        String encoded = Base64.getEncoder()
                .encodeToString("Wellcome on Andrey secured web site !".getBytes("utf-8"));
        model.addAttribute("encoded", encoded);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }

    model.addAttribute("data", lst);
    model.addAttribute("store", store);
    return "search";
}