Example usage for javax.xml.bind DatatypeConverter printBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter printBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printBase64Binary.

Prototype

public static String printBase64Binary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:io.lightlink.output.JSONResponseStream.java

public void writeInputStream(InputStream inputStream) {
    write('"');/*from w w  w  .j  a  va2 s.c  o  m*/

    byte[] buffer = new byte[3 * 1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) != -1) {
            String encodedBlock;
            if (length < buffer.length) {
                byte part[] = new byte[length];
                System.arraycopy(buffer, 0, part, 0, length);
                encodedBlock = DatatypeConverter.printBase64Binary(part);
            } else {
                encodedBlock = DatatypeConverter.printBase64Binary(buffer);
            }
            ByteBuffer bbuffer = CHARSET.encode(encodedBlock);
            write(bbuffer.array(), bbuffer.remaining());

        }
        write('"');

        inputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:jongo.JongoUtils.java

/**
 * Generates a Base64-encoded binary MD5 sum of the content of the response as described by rfc1864
 * @param input the string/*from   w w  w  .j a  v a2  s. c  o m*/
 * @return Base64-encoded binary MD5 sum of the string
 */
public static String getMD5Base64(String input) {
    if (input == null)
        throw new IllegalArgumentException("Invalid null argument");

    String ret = "";
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(input.getBytes("UTF-8"));
        byte[] rawData = digest.digest();
        ret = DatatypeConverter.printBase64Binary(rawData);
    } catch (Exception ex) {
        l.error(ex.getMessage());
    }

    return ret;
}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

private String sign(String toSign)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    Mac hmac = Mac.getInstance("HmacSHA1");
    hmac.init(new SecretKeySpec(awsSecretKey.getBytes("UTF-8"), "HmacSHA1"));

    String signature = DatatypeConverter.printBase64Binary(hmac.doFinal(toSign.getBytes("UTF-8")))
            .replaceAll("\n", "");

    return signature;
}

From source file:eu.europa.esig.dss.tsl.service.TSLRepository.java

private String getSHA256(byte[] data) {
    return DatatypeConverter.printBase64Binary(DSSUtils.digest(DigestAlgorithm.SHA256, data));
}

From source file:fr.inria.oak.paxquery.translation.Logical2Pact.java

private static final Operator<Record>[] translate(Projection proj) {
    Operator<Record>[] childPlan = translate(proj.getChild());

    // create MapOperator for projecting a column
    MapOperator projection = MapOperator.builder(ProjectionOperator.class).input(childPlan).name("Proj")
            .build();/*from w w w.  j av a 2 s .  c  o  m*/

    // projection configuration
    final String encodedNRSMD = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(proj.getNRSMD()));
    projection.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD);
    final String encodedKeepColumns = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(proj.columns));
    projection.setParameter(PACTOperatorsConfiguration.KEEP_COLUMNS_BINARY.toString(), encodedKeepColumns);

    return new Operator[] { projection };
}

From source file:com.marklogic.client.test.EvalTest.java

private void runAndTestXQuery(ServerEvaluationCall call) throws JsonProcessingException, IOException,
        SAXException, ParserConfigurationException, DatatypeConfigurationException {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(this.getClass().getClassLoader().getResourceAsStream("1-empty-1.0.xml"));
    call = call.addNamespace("myPrefix", "http://marklogic.com/test").addVariable("myPrefix:myString", "Mars")
            .addVariable("myArray",
                    new JacksonHandle().with(new ObjectMapper().createArrayNode().add("item1").add("item2")))
            .addVariable("myObject",
                    new JacksonHandle().with(new ObjectMapper().createObjectNode().put("item1", "value1")))
            .addVariable("myAnyUri", "http://marklogic.com/a")
            .addVariable("myBinary", DatatypeConverter.printHexBinary(",".getBytes()))
            .addVariable("myBase64Binary", DatatypeConverter.printBase64Binary(new byte[] { 1, 2, 3 }))
            .addVariable("myHexBinary", DatatypeConverter.printHexBinary(new byte[] { 1, 2, 3 }))
            .addVariable("myDuration", "P100D").addVariable("myDocument", new DOMHandle(document))
            .addVariable("myQName", "myPrefix:a")
            //.addVariable("myAttribute", "<a a=\"a\"/>")
            .addVariable("myComment", "<!--a-->").addVariable("myElement", "<a a=\"a\"/>")
            .addVariable("myProcessingInstruction", "<?a?>")
            .addVariable("myText", new StringHandle("a").withFormat(Format.TEXT))
            // the next three use built-in methods of ServerEvaluationCall
            .addVariable("myBool", true).addVariable("myInteger", 1234567890123456789l)
            .addVariable("myBigInteger", "123456789012345678901234567890")
            .addVariable("myDecimal", "1111111111111111111.9999999999")
            .addVariable("myDouble", 11111111111111111111.7777777777).addVariable("myFloat", 1.1)
            .addVariable("myGDay", "---01").addVariable("myGMonth", "--01")
            .addVariable("myGMonthDay", "--01-01").addVariable("myGYear", "1901")
            .addVariable("myGYearMonth", "1901-01").addVariable("myDate", "2014-09-01")
            .addVariable("myDateTime",
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(septFirst).toString())
            .addVariable("myTime", "00:01:01");
    EvalResultIterator results = call.eval();
    try {/*from  w  w w  .  j av  a 2  s .c  om*/
        EvalResult result = results.next();
        assertEquals("myString should = 'Mars'", "Mars", result.getAs(String.class));
        assertEquals("myString should be Type.STRING", EvalResult.Type.STRING, result.getType());
        assertEquals("myString should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myArray should = [\"item1\",\"item2\"]",
                new ObjectMapper().readTree("[\"item1\",\"item2\"]"), result.getAs(JsonNode.class));
        assertEquals("myArray should be Type.JSON", EvalResult.Type.JSON, result.getType());
        assertEquals("myArray should be Format.JSON", Format.JSON, result.getFormat());
        result = results.next();
        assertEquals("myObject should = {\"item1\":\"value1\"}",
                new ObjectMapper().readTree("{\"item1\":\"value1\"}"), result.getAs(JsonNode.class));
        assertEquals("myObject should be Type.JSON", EvalResult.Type.JSON, result.getType());
        assertEquals("myObject should be Format.JSON", Format.JSON, result.getFormat());
        result = results.next();
        assertEquals("myAnyUri looks wrong", "http://marklogic.com/a", result.getString());
        assertEquals("myAnyUri should be Type.ANYURI", EvalResult.Type.ANYURI, result.getType());
        assertEquals("myAnyUri should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBinary looks wrong", ",", result.getString());
        assertEquals("myBinary should be Type.BINARY", EvalResult.Type.BINARY, result.getType());
        assertEquals("myBinary should be Format.UNKNOWN", Format.UNKNOWN, result.getFormat());
        result = results.next();
        assertArrayEquals("myBase64Binary should = 1, 2, 3", new byte[] { 1, 2, 3 },
                DatatypeConverter.parseBase64Binary(result.getString()));
        assertEquals("myBase64Binary should be Type.BASE64BINARY", EvalResult.Type.BASE64BINARY,
                result.getType());
        assertEquals("myBase64Binary should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertArrayEquals("myHexBinary should = 1, 2, 3", new byte[] { 1, 2, 3 },
                DatatypeConverter.parseHexBinary(result.getString()));
        assertEquals("myHexBinary should be Type.HEXBINARY", EvalResult.Type.HEXBINARY, result.getType());
        assertEquals("myHexBinary should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDuration should = P100D", "P100D", result.getString());
        assertEquals("myDuration should be Type.DURATION", EvalResult.Type.DURATION, result.getType());
        assertEquals("myDuration should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myQName doesn't look right", "myPrefix:a", result.getString());
        assertEquals("myQName should be Type.QNAME", EvalResult.Type.QNAME, result.getType());
        assertEquals("myQName should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDocument doesn't look right",
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                        + "<search:options xmlns:search=\"http://marklogic.com/appservices/search\"/>",
                result.getString());
        assertEquals("myDocument should be Type.XML", EvalResult.Type.XML, result.getType());
        assertEquals("myDocument should be Format.XML", Format.XML, result.getFormat());
        result = results.next();
        assertEquals("myAttribute looks wrong", "a", result.getString());
        assertEquals("myAttribute should be Type.ATTRIBUTE", EvalResult.Type.ATTRIBUTE, result.getType());
        assertEquals("myAttribute should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myComment should = <!--a-->", "<!--a-->", result.getString());
        assertEquals("myComment should be Type.COMMENT", EvalResult.Type.COMMENT, result.getType());
        assertEquals("myComment should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myElement looks wrong", "<a a=\"a\"/>", result.getString());
        assertEquals("myElement should be Type.XML", EvalResult.Type.XML, result.getType());
        assertEquals("myElement should be Format.XML", Format.XML, result.getFormat());
        result = results.next();
        assertEquals("myProcessingInstruction should = <?a?>", "<?a?>", result.getString());
        assertEquals("myProcessingInstruction should be Type.PROCESSINGINSTRUCTION",
                EvalResult.Type.PROCESSINGINSTRUCTION, result.getType());
        assertEquals("myProcessingInstruction should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myText should = a", "a", result.getString());
        assertEquals("myText should be Type.TEXTNODE", EvalResult.Type.TEXTNODE, result.getType());
        assertEquals("myText should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBool should = true", true, result.getBoolean());
        assertEquals("myBool should be Type.BOOLEAN", EvalResult.Type.BOOLEAN, result.getType());
        assertEquals("myBool should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myInteger should = 1234567890123456789l", 1234567890123456789l,
                result.getNumber().longValue());
        assertEquals("myInteger should be Type.INTEGER", EvalResult.Type.INTEGER, result.getType());
        assertEquals("myInteger should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBigInteger looks wrong", new BigInteger("123456789012345678901234567890"),
                new BigInteger(result.getString()));
        assertEquals("myBigInteger should be Type.STRING", EvalResult.Type.STRING, result.getType());
        assertEquals("myBigInteger should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDecimal looks wrong", 1111111111111111111.9, result.getNumber().doubleValue(), .001);
        assertEquals("myDecimal should be Type.DECIMAL", EvalResult.Type.DECIMAL, result.getType());
        assertEquals("myDecimal should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDouble looks wrong", 1.11111111111111E19, result.getNumber().doubleValue(), .001);
        assertEquals("myDouble should be Type.DOUBLE", EvalResult.Type.DOUBLE, result.getType());
        assertEquals("myDouble should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myFloat looks wrong", 1.1, result.getNumber().floatValue(), .001);
        assertEquals("myFloat should be Type.FLOAT", EvalResult.Type.FLOAT, result.getType());
        assertEquals("myFloat should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGDay looks wrong", "---01", result.getString());
        assertEquals("myGDay should be Type.GDAY", EvalResult.Type.GDAY, result.getType());
        assertEquals("myGDay should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGMonth looks wrong", "--01", result.getString());
        assertEquals("myGMonth should be Type.GMONTH", EvalResult.Type.GMONTH, result.getType());
        assertEquals("myGMonth should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGMonthDay looks wrong", "--01-01", result.getString());
        assertEquals("myGMonthDay should be Type.GMONTHDAY", EvalResult.Type.GMONTHDAY, result.getType());
        assertEquals("myGMonthDay should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGYear looks wrong", "1901", result.getString());
        assertEquals("myGYear should be Type.GYEAR", EvalResult.Type.GYEAR, result.getType());
        assertEquals("myGYear should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGYearMonth looks wrong", "1901-01", result.getString());
        assertEquals("myGYearMonth should be Type.GYEARMONTH", EvalResult.Type.GYEARMONTH, result.getType());
        assertEquals("myGYearMonth should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        // the lexical format MarkLogic uses to serialize a date
        assertEquals("myDate should = '2014-09-01", "2014-09-01", result.getString());
        assertEquals("myDate should be Type.DATE", EvalResult.Type.DATE, result.getType());
        assertEquals("myDate should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        // the lexical format MarkLogic uses to serialize a dateTime
        assertEquals("myDateTime should = '2014-09-01T00:00:00+02:00'", "2014-09-01T00:00:00+02:00",
                result.getString());
        assertEquals("myDateTime should be Type.DATETIME", EvalResult.Type.DATETIME, result.getType());
        assertEquals("myDateTime should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myTime looks wrong", "00:01:01", result.getString());
        assertEquals("myTime should be Type.TIME", EvalResult.Type.TIME, result.getType());
        assertEquals("myTime should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myCtsQuery should be Type.OTHER", EvalResult.Type.OTHER, result.getType());
        assertEquals("myCtsQuery should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myFunction should be Type.OTHER", EvalResult.Type.OTHER, result.getType());
        assertEquals("myFunction should be Format.TEXT", Format.TEXT, result.getFormat());
    } finally {
        results.close();
    }
}

From source file:com.norconex.commons.lang.url.URLStreamer.java

private static String base64BasicAuth(String username, String password) {
    String userpass = username + ':' + password;
    return "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
}

From source file:br.org.gdt.beans.GchFormularioBean.java

public String salvarPessoasFormulario() {

    if (gchFormulariopessoa != null) {

        RequestContext contextReq = RequestContext.getCurrentInstance();

        Iterator<RecPessoa> keyIterrator = checked.keySet().iterator();

        ArrayList<ParametrosEmail> parametros = new ArrayList<>();

        ParametrosEmail ItemParametro;//from  www. ja  va 2s . c  om
        FacesContext context = FacesContext.getCurrentInstance();

        EncryptDecryptString cripto = new EncryptDecryptString();

        //Configuraes da caixa de e-mail padro do sistema
        String emailResponsavel = "murphyrhnotifica@gmail.com";
        String senha = "murphy2017";
        String assunto = "Preenchimento de Formulrio";
        String url = context.getExternalContext().getRequestServerName() + ":"
                + context.getExternalContext().getRequestServerPort()
                + context.getExternalContext().getApplicationContextPath()
                + "/ModuloCapitalHumano/ResponderFormulario.xhtml?%1s";
        String mensagem = "";

        boolean vinculou = false;
        parametros.clear();

        while (keyIterrator.hasNext()) {

            RecPessoa pessoa = keyIterrator.next();
            Boolean value = checked.get(pessoa);

            if (value) {

                //Seta null para no dar pau no Hibernate
                gchFormulariopessoa.setFormPesCodigo(0);

                gchFormulariopessoa.setRecIdpessoa(pessoa);
                gchFormulariopessoa.setFormulario(gchFormulario);
                gchFormulariopessoa.setFormRespondido(false);

                gchFormularioPessoaService.save(gchFormulariopessoa);

                String parametroUrl = gchFormulario.getFormCodigo() + "&" + pessoa.getRecIdpessoa();

                String parametroBase64 = DatatypeConverter.printBase64Binary(parametroUrl.getBytes());

                String urlFormatada = String.format(url, "id=" + parametroBase64);

                String msgFormatada = "<html></br></br><div style='border:2px solid #0094ff;'><h2 style='background:#87CEEB;color:white;padding:10px;color: #222;'>Formulrio "
                        + gchFormulario.getFormNome()
                        + "</h2><div style='color:#333;padding:10px;'><p style='font-size:120%;text-shadow: 0px 2px 3px #555;'>Voc acaba de receber um formulrio com algumas perguntas para que possamos lhe conhecer melhor. O prazo de respostas  at \""
                        + gchFormulario.getFormPrazoResposta().toString()
                        + "\"</p></br>Para acess-lo clique <a href='http://" + urlFormatada
                        + "'>aqui</a></br></br><h3>Instrues de Preenchimento</h3></br><p>- Responda com sinceridade!</p><p>- Somente  possvel marcar uma alternativa por pergunta!</p><p>- S  possvel responder o formulrio uma nica vez!</p></div><h4 style='background:#ADD8E6;padding:8px;'>Murphy RH - Todos os direitos Reservados</h4></div></html>";

                //Cria item de parametro de email
                ItemParametro = new ParametrosEmail();

                ItemParametro.setRemetente(emailResponsavel);
                ItemParametro.setSenha(senha);
                ItemParametro.setAssunto(assunto);
                ItemParametro.setMensagem(msgFormatada);
                ItemParametro.setDestinatario(pessoa.getRecEmail());
                ItemParametro.setFormularioPessoa(gchFormulariopessoa);

                parametros.add(ItemParametro);

                vinculou = true;

            }
        }

        this.formAtivo = false;
        gchFormulariopessoa = new GchFormularioPessoa();
        checked = new HashMap<RecPessoa, Boolean>();
        keyIterrator.remove();
        //Se vinculou ao menos 1 envia e-mail
        if (vinculou) {

            GerenciadorEmail novoEnvio = new GerenciadorEmail();

            try {
                novoEnvio.EnviarEmail(parametros);
                parametros.clear();
            } catch (Exception ex) {
                Logger.getLogger(GchFormularioBean.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        String MsgNotificacao = "Formulrio disponibilizado para as pessoas selecionadas!";
        Helper.mostrarNotificacao("Sucesso", MsgNotificacao, "success");

    }
    gchTodosFormularios = null; //isso faz com que a listagem se atualize
    return "Formularios";
}

From source file:fr.inria.oak.paxquery.translation.Logical2Pact.java

private static final Operator<Record>[] translate(Navigation nav) {
    Operator<Record>[] childPlan = translate(nav.getChild());

    // create MapOperator for navigating in a column
    MapOperator navigation = MapOperator.builder(NavigationOperator.class).input(childPlan).name("TPNav")
            .build();/* w  w w.  j  a  va  2 s  .c o m*/

    // navigation configuration
    final String encodedNRSMD = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(nav.getNRSMD()));
    navigation.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD);
    navigation.setParameter(PACTOperatorsConfiguration.NAVIGATION_COLUMN_INT.toString(), nav.pos);
    navigation.setParameter(PACTOperatorsConfiguration.NTP_STRING.toString(),
            NavigationTreePatternUtils.getParsableStringFromTreePattern(nav.navigationTreePattern));

    return new Operator[] { navigation };
}

From source file:com.basistech.ReleaseNoteMojo.java

private void setupBasicAuthentication(Client client, final String username, final String password) {
    client.register(new ClientRequestFilter() {

        public void filter(ClientRequestContext requestContext) throws IOException {
            MultivaluedMap<String, Object> headers = requestContext.getHeaders();
            final String basicAuthentication = getBasicAuthentication();
            headers.add("Authorization", basicAuthentication);

        }//from w  ww. j  a  va 2  s  . c o  m

        private String getBasicAuthentication() {
            String token = username + ":" + password;
            try {
                return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                throw new IllegalStateException("Cannot encode with UTF-8", ex);
            }
        }
    });
}