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:com.uber.hoodie.common.BloomFilter.java

/**
 * Serialize the bloom filter as a string.
 *//*from   ww  w  . j  a  v  a  2 s . c om*/
public String serializeToString() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    try {
        filter.write(dos);
        byte[] bytes = baos.toByteArray();
        dos.close();
        return DatatypeConverter.printBase64Binary(bytes);
    } catch (IOException e) {
        throw new HoodieIndexException("Could not serialize BloomFilter instance", e);
    }
}

From source file:org.fedoraproject.copr.client.impl.RpcCommand.java

public T execute(DefaultCoprSession session) throws CoprException {
    try {/*from   w w w .  j  ava2  s .c  o m*/
        HttpClient client = session.getClient();

        String baseUrl = session.getConfiguration().getUrl();
        String commandUrl = getCommandUrl();
        String url = baseUrl + commandUrl;

        Map<String, String> extraArgs = getExtraArguments();
        HttpUriRequest request;
        if (extraArgs == null) {
            request = new HttpGet(url);
        } else {
            HttpPost post = new HttpPost(url);
            request = post;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            for (Entry<String, String> entry : extraArgs.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        if (requiresAuthentication()) {
            String login = session.getConfiguration().getLogin();
            if (login == null || login.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String token = session.getConfiguration().getToken();
            if (token == null || token.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String auth = login + ":" + token;
            String encodedAuth = DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.UTF_8));
            request.setHeader("Authorization", "Basic " + encodedAuth);
        }

        request.addHeader("Accept", APPLICATION_JSON.getMimeType());

        HttpResponse response = client.execute(request);
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new CoprException(
                    "Copr RPC failed: HTTP " + returnCode + " " + response.getStatusLine().getReasonPhrase());
        }

        Reader responseReader = new InputStreamReader(response.getEntity().getContent());
        JsonParser parser = new JsonParser();
        JsonObject rpcResponse = parser.parse(responseReader).getAsJsonObject();

        String rpcStatus = rpcResponse.get("output").getAsString();
        if (!rpcStatus.equals("ok")) {
            throw new CoprException("Copr RPC returned failure reponse");
        }

        return parseResponse(rpcResponse);
    } catch (IOException e) {
        throw new CoprException("Failed to call remote Copr procedure", e);
    }
}

From source file:com.github.stephanarts.cas.ticket.registry.RegistryClient.java

/**
 * addTicket Method./*from  w  w  w  . j  a  va2  s. co  m*/
 *
 * @param ticket CAS Ticket object
 *
 * @throws JSONRPCException Throws JSONRPCException containing any error.
 */
public final void addTicket(final Ticket ticket) throws JSONRPCException {

    byte[] serializedTicket = {};
    JSONObject params = new JSONObject();

    /* Check if it's not null */
    if (ticket == null) {
        throw new JSONRPCException(-32501, "Could not encode Ticket");
    }

    try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bo);
        so.writeObject(ticket);
        so.flush();
        serializedTicket = bo.toByteArray();
    } catch (final Exception e) {
        throw new JSONRPCException(-32501, "Could not encode Ticket");
    }

    params.put("ticket-id", ticket.getId());
    params.put("ticket", DatatypeConverter.printBase64Binary(serializedTicket));

    this.call("cas.addTicket", params);
}

From source file:io.lightlink.types.BlobConverter.java

private Object inputStreamToReturnValue(InputStream stream) throws IOException {

    if (encoding.equalsIgnoreCase("base64")) {
        String res = DatatypeConverter.printBase64Binary(IOUtils.toByteArray(stream));
        stream.close();//from www  .  j  a v a  2s.  c om
        return res;
    } else if (StringUtils.isNotBlank(encoding)) {
        String res = new String(IOUtils.toByteArray(stream), encoding);
        stream.close();
        return res;
    } else
        return stream;
}

From source file:mvc.controller.UsuarioController.java

private void setImagePath(List<Usuario> listaUsuarios) throws IOException {

    for (Usuario usuario : listaUsuarios) {

        BufferedImage bImage = ImageIO.read(new File(usuario.getPhoto()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bImage, "jpg", baos);
        baos.flush();//from  w  w w  .j a v a 2s .c  o  m
        byte[] imageInByteArray = baos.toByteArray();
        baos.close();
        String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
        usuario.setPhoto(b64);

    }

}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Create a client using a specified base URL (for advanced use only - the default URL will work for all normal cases).
*
* @param url API base URL/*from   www.j  av  a2  s  .co  m*/
* @param apiKeyId API key identifier for authentication
* @param apiPassword API key password
*/
public HttpClient(URL url, String apiKeyId, String apiPassword) {
    baseUrl = url;
    try {
        // HTTP header is "Basic base64(username:password)"
        authorizationHeader = "Basic "
                + DatatypeConverter.printBase64Binary((apiKeyId + ":" + apiPassword).getBytes("UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        // should never happen
        throw new RuntimeException("JVM claims not to support UTF-8 encoding...", uee);
    }
}

From source file:com.redhat.lightblue.metadata.types.BinaryTypeTest.java

License:asdf

@Test
public void testEmbeddedPDF() throws FileNotFoundException, IOException, JSONException {
    String pdfFilename = "./BinaryTypeTest-sample.pdf";

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(pdfFilename);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int read;//from   w  w  w  .  j ava  2 s .co m
    byte[] bytes = new byte[1000];

    while ((read = is.read(bytes, 0, bytes.length)) != -1) {
        buffer.write(bytes, 0, read);
    }

    String encoded = DatatypeConverter.printBase64Binary(buffer.toByteArray());

    String jsonString = "{\"binaryData\": \"" + encoded + "\"}";

    JsonNode nodeIn = JsonUtils.json(jsonString);
    JsonNode binaryDataNodeIn = nodeIn.get("binaryData");

    byte[] bytesOut = binaryDataNodeIn.binaryValue();

    JsonNodeFactory jsonNodeFactory = new JsonNodeFactory(true);
    JsonNode binaryDataNodeOut = binaryType.toJson(jsonNodeFactory, bytesOut);

    ObjectNode nodeOut = jsonNodeFactory.objectNode();
    nodeOut.set("binaryData", binaryDataNodeOut);

    JSONAssert.assertEquals(jsonString, nodeOut.toString(), JSONCompareMode.LENIENT);
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.DefaultRequestConfigurer.java

@Override
public void configure(HttpMethodBase method) {
    if (username != null && password != null) {
        String login = username + ":" + password;
        String encodedLogin = DatatypeConverter.printBase64Binary(login.getBytes());

        method.setRequestHeader("Authorization", "Basic " + encodedLogin);
    }//from  ww  w  . ja  va 2  s  .  c  o  m

    method.setRequestHeader("Content-type", contentType);

    if (headerNames != null && headerVals != null && headerNames.length == headerVals.length) {
        for (int i = 0; i < headerNames.length; i++) {
            method.setRequestHeader(headerNames[i], headerVals[i]);
        }
    }

    if (method instanceof PostMethod) {
        PostMethod postVersion = (PostMethod) method;
        if (parameterNames != null && parameterVals != null && parameterNames.length == parameterVals.length) {
            for (int i = 0; i < parameterNames.length; i++) {
                postVersion.setParameter(parameterNames[i], parameterVals[i]);
            }
        }

        if (requestBody != null) {
            postVersion.setRequestEntity(getRequestEntity());
        }
    } // if it's a get then the parameters should be in the URL
}

From source file:fr.paris.lutece.plugins.asynchronousupload.util.JSONUtils.java

private static String getPreviewImage(FileItem fileItem) throws IOException {

    if (FileUtil.hasImageExtension(fileItem.getName())) {

        String preview = "data:image/png;base64," + DatatypeConverter.printBase64Binary(fileItem.get());

        return preview;
    }/*from  www  .j  a v  a2s .  com*/

    return StringUtils.EMPTY;
}