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.illustrationfinder.IllustrationFinderController.java

@RequestMapping(value = "/", method = RequestMethod.GET, params = { "url", "preferred-width",
        "preferred-height" })
public ModelAndView showIllustrationFinderResults(ModelMap modelMap, @RequestParam(value = "url") String pUrl,
        @RequestParam(value = "preferred-width") String pPreferredWidth,
        @RequestParam(value = "preferred-height") String pPreferredHeight) {
    final ModelAndView modelAndView = new ModelAndView("/IllustrationFinderView");

    // Add the URL to attributes
    modelMap.addAttribute("pUrl", pUrl);

    // Check if the URL is valid
    boolean isUrlValid = false;

    String url = pUrl;//from  www  .  j  a  va  2s  . c o m
    if (url != null) {
        url = StringEscapeUtils.escapeHtml4(url);

        if (new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
            isUrlValid = true;
        }
    }

    modelMap.addAttribute("isUrlValid", isUrlValid);

    // Get the images
    try {
        if (isUrlValid) {
            final IPostProcessor postProcessor = new HtmlPostProcessor();
            final GoogleSearchEngine searchEngine = new GoogleSearchEngine();
            final IImageProcessor<BufferedImage, BufferedImageOp> imageProcessor = new BufferedImageProcessor();

            imageProcessor.setPreferredSize(
                    new Dimension(Integer.parseInt(pPreferredWidth), Integer.parseInt(pPreferredHeight)));

            final IllustrationFinder illustrationFinder = new IllustrationFinder();
            illustrationFinder.setPostProcessor(postProcessor);
            illustrationFinder.setSearchEngine(searchEngine);
            illustrationFinder.setImageProcessor(imageProcessor);

            final List<BufferedImage> images = illustrationFinder.getImages(new URL(pUrl));

            // Convert images to base64 strings
            final List<String> imagesAsStrings = new ArrayList<>();

            if (images != null) {
                for (BufferedImage image : images) {
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(image, "png", baos);
                        baos.flush();
                        final byte[] imageInByteArray = baos.toByteArray();
                        baos.close();
                        final String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);

                        imagesAsStrings.add(b64);
                    } catch (IOException e) {
                        // Failed to convert the image
                    }
                }
            }

            modelMap.addAttribute("images", imagesAsStrings);
        }
    } catch (IOException e) {
        // Exception triggered if the URL is malformed, it should not happen because the URL is validated before
    }

    return modelAndView;
}

From source file:com.codepine.api.testrail.Request.java

/**
 * Execute this request.//from  w  w w  .j av a2 s  .co m
 *
 * @return response from TestRail
 */
public T execute() {
    try {

        String url = getUrl();
        HttpURLConnection con = (HttpURLConnection) urlConnectionFactory.getUrlConnection(url);
        con.setRequestMethod(method.name());
        if (config.getApplicationName().isPresent()) {
            con.setRequestProperty("User-Agent", config.getApplicationName().get());
        }
        con.setRequestProperty("Content-Type", "application/json");
        String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(
                (config.getUsername() + ":" + config.getPassword()).getBytes(Charset.forName("UTF-8")));
        con.setRequestProperty("Authorization", basicAuth);
        if (method == Method.POST) {
            Object content = getContent();
            if (content != null) {
                con.setDoOutput(true);
                try (OutputStream outputStream = new BufferedOutputStream(con.getOutputStream())) {
                    JSON.writerWithView(this.getClass()).writeValue(outputStream, content);
                }
            }
        }
        log.debug("Sending " + method + " request to URL : " + url);
        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            // swallow it since for 401 getResponseCode throws an IOException
            responseCode = con.getResponseCode();
        }
        log.debug("Response Code : " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            try (InputStream errorStream = con.getErrorStream()) {
                TestRailException.Builder exceptionBuilder = new TestRailException.Builder()
                        .setResponseCode(responseCode);
                if (errorStream == null) {
                    throw exceptionBuilder.setError("<server did not send any error message>").build();
                }
                throw JSON.readerForUpdating(exceptionBuilder).<TestRailException.Builder>readValue(
                        new BufferedInputStream(errorStream)).build();
            }
        }

        try (InputStream responseStream = new BufferedInputStream(con.getInputStream())) {
            Object supplementForDeserialization = getSupplementForDeserialization();
            if (responseClass != null) {
                if (responseClass == Void.class) {
                    return null;
                }
                if (supplementForDeserialization != null) {
                    return JSON
                            .reader(responseClass).with(new InjectableValues.Std()
                                    .addValue(responseClass.toString(), supplementForDeserialization))
                            .readValue(responseStream);
                }
                return JSON.readValue(responseStream, responseClass);
            } else {
                if (supplementForDeserialization != null) {
                    String supplementKey = responseType.getType().toString();
                    if (responseType.getType() instanceof ParameterizedType) {
                        Type[] actualTypes = ((ParameterizedType) responseType.getType())
                                .getActualTypeArguments();
                        if (actualTypes.length == 1 && actualTypes[0] instanceof Class<?>) {
                            supplementKey = actualTypes[0].toString();
                        }
                    }
                    return JSON.reader(responseType).with(
                            new InjectableValues.Std().addValue(supplementKey, supplementForDeserialization))
                            .readValue(responseStream);
                }
                return JSON.readValue(responseStream, responseType);
            }
        }

    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ocean.common.asserts.Base64Utils.java

/**
 * Base64-encode the given byte array to a String.
 * //from www  .  j  a va2  s  . c om
 * @param src
 *            the original byte array (may be {@code null})
 * @return the encoded byte array as a UTF-8 String (or {@code null} if the
 *         input was {@code null})
 */
public static String encodeToString(byte[] src) {
    if (src == null) {
        return null;
    }
    if (src.length == 0) {
        return "";
    }

    if (delegate != null) {
        // Full encoder available
        return new String(delegate.encode(src), DEFAULT_CHARSET);
    } else {
        // JAXB fallback for String case
        return DatatypeConverter.printBase64Binary(src);
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ObsController1_9Test.java

@Test
public void shouldPostValueInJsonAndFetchComplexObs() throws Exception {
    ConceptComplex conceptComplex = newConceptComplex();

    InputStream in = getClass().getClassLoader().getResourceAsStream("customTestDataset.xml");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);//from w ww. j av a 2 s  .co  m

    String value = DatatypeConverter.printBase64Binary(out.toByteArray());

    String json = "{\"concept\":\"" + conceptComplex.getUuid() + "\"," + "\"value\":\"" + value
            + "\",\"person\":\"5946f880-b197-400b-9caa-a3c661d23041\","
            + "\"obsDatetime\":\"2015-09-07T00:00:00.000+0530\"}";

    SimpleObject response = deserialize(handle(newPostRequest(getURI(), json)));

    MockHttpServletResponse rawResponse = handle(
            newGetRequest(getURI() + "/" + response.get("uuid") + "/value"));

    assertThat(out.toByteArray(), is(equalTo(rawResponse.getContentAsByteArray())));
}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

private void setRockBlockPassword(String password) {
    if (password == null)
        this.rockBlockPassword = null;

    this.rockBlockPassword = DatatypeConverter.printBase64Binary(password.getBytes(Charset.forName("UTF8")));
}

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

@Test
public void testDuplicateTicket() throws Exception {
    final byte[] serializedTicket;
    final HashMap<Integer, Ticket> map = new HashMap<Integer, Ticket>();
    final JSONObject params = new JSONObject();
    final IMethod method = new AddMethod(map);

    final String ticketId = "ST-1234567890ABCDEFGHIJKL-crud";
    final ServiceTicket ticket = mock(ServiceTicket.class, withSettings().serializable());
    when(ticket.getId()).thenReturn(ticketId);

    map.put(ticketId.hashCode(), ticket);

    try {//ww  w . j a v  a2s  .  co  m
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bo);
        so.writeObject(ticket);
        so.flush();
        serializedTicket = bo.toByteArray();

        params.put("ticket-id", ticketId);
        params.put("ticket", DatatypeConverter.printBase64Binary(serializedTicket));
        method.execute(params);

    } catch (final JSONRPCException e) {
        Assert.assertEquals(-32502, e.getCode());
        Assert.assertTrue(e.getMessage().equals("Duplicate Ticket"));
        return;
    } catch (final Exception e) {
        throw new Exception(e);
    }

    Assert.fail("No Exception Thrown");
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from www.j  a va  2s  . c o  m*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

private HttpsURLConnection createHttpUrlConnection(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new TrustAllHosts());
    conn.setSSLSocketFactory(TrustAllCerts.createInsecureSslContext().getSocketFactory());
    conn.setInstanceFollowRedirects(false);
    String credentials = TEST_USERNAME + ":" + TEST_PASSWORD;
    conn.setRequestProperty("Authorization",
            "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
    return conn;/*from ww w .j  a v  a 2 s  .co m*/
}

From source file:com.ning.billing.recurly.RecurlyClient.java

public RecurlyClient(final String apiKey, final String host, final int port, final String version) {
    this.key = DatatypeConverter.printBase64Binary(apiKey.getBytes());
    this.baseUrl = String.format("https://%s:%d/%s", host, port, version);
    this.xmlMapper = RecurlyObject.newXmlMapper();
    this.userAgent = buildUserAgent();
}

From source file:com.silverpeas.ical.StringUtils.java

/**
 * Encode the input bytes into BASE64 format.
 * @param data - byte array to encode/*w  w w .ja va2  s  .  c om*/
 * @return encoded string
 */
public static String encodeBASE64(byte[] data) {
    return DatatypeConverter.printBase64Binary(data);
}