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.github.jrialland.ajpclient.AbstractTomcatTest.java

protected static String computeMd5(final InputStream is) {
    try {//from www  .  java2 s. c  om
        final MessageDigest md5 = MessageDigest.getInstance("md5");
        final byte[] buf = new byte[1024];
        int c = 0;
        while ((c = is.read(buf)) > -1) {
            md5.update(buf, 0, c);
        }
        return DatatypeConverter.printBase64Binary(md5.digest());
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

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

private void setGmailPassword(String password) {
    if (password == null)
        this.gmailPassword = null;

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

From source file:de.uni_koblenz.aggrimm.icp.interfaceAgents.bing.BingRetriever.java

/**
 *
 * <p>Returns the results queried for.
 *
 * @param encodedSearchTerm the term to search for.
 * @param source            where to search.
 * @param market            for localised results.
 * @param top               number of results.
 * @param skip              offset for the starting point of results returned.
 *
 * For more details on the parameters, please have a look at:
 *
 * @see #createBasicQueryString(java.lang.String, java.lang.String,
 * java.lang.String, int, int)/*  ww  w  . ja v a  2 s  . co  m*/
 *
 * @return {@code IWebResult} if {@code market} is "web"
 *          and {@code IImageResult} if market is "image" in an
 *          {@code BingResultsContainer}.
 * @throws MalformedURLException if {@code createBasicQueryString}'s result
 *                                cannot be transformed into a URL.
 * @throws URISyntaxException    if {@code createBasicQueryString}'s result
 *                                cannot be transformed into a URL.
 * @throws IOException           if an I/O exception occurs while trying to
 *                                open the URL connection or while trying to
 *                                read the results.
 * @throws ParseException        if the resultString cannot be properly parsed
 *                                from.
 */
@Override
public BingResultsContainer<IResult> doSearch(String encodedSearchTerm, String source, String market, int top,
        int skip) throws MalformedURLException, URISyntaxException, IOException, ParseException {
    String queryString = createBasicQueryString(encodedSearchTerm, source, market, top, skip);
    URL query = new URL(queryString);
    URLConnection queryURLConnection = query.openConnection();

    if (API_KEY == null) {
        throw new IllegalStateException(
                "The API key for bing could not be read from the application.xml. Make sure it was set.");
    }
    byte[] apiRequestBytes = ("ignored:" + API_KEY).getBytes(Charset.forName("UTF-8"));
    String encodedApiKey = DatatypeConverter.printBase64Binary(apiRequestBytes);

    queryURLConnection.setRequestProperty("Authorization", "Basic " + encodedApiKey);
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(queryURLConnection.getInputStream(), Charset.forName("UTF-8")))) {
        String resultString = in.readLine(); // it's a one-liner, so this is enough
        IResultsContainer<IResult> resultList = brc.parseJSONString(resultString, source, skip);

        assert (resultList instanceof BingResultsContainer<?>);
        return (BingResultsContainer<IResult>) resultList;
    } catch (IOException e) {
        LOGGER.log(Level.INFO, "Bing input stream could not be fetched: {0}", e);
        throw new IOException("Couldn't fetch Bing input stream.");
    }
}

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

/**
 * updateTicket Method.// w w w . ja va2 s. c  o m
 *
 * @param ticket CAS Ticket object
 *
 * @return Response Object
 *
 * @throws JSONRPCException Throws JSONRPCException containing any error.
 */
public final JSONObject updateTicket(final Ticket ticket) throws JSONRPCException {

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

    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 decode Ticket");
    }

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

    return this.call("cas.updateTicket", params);
}

From source file:ddf.catalog.transformer.metacard.propertyjson.PropertyJsonMetacardTransformer.java

@Nullable
private static Object convertValue(String name, Serializable value, AttributeType.AttributeFormat format)
        throws CatalogTransformerException {
    if (value == null) {
        return null;
    }//from w  w  w .  j a v  a 2 s.c  o m

    switch (format) {
    case DATE:
        if (!(value instanceof Date)) {
            LOGGER.debug("Dropping attribute date value {} for {} because it isn't a Date object.", value,
                    name);
            return null;
        }
        // Creating date format instance each time is inefficient, however
        // it is not a threadsafe class so we are not able to put it in a static
        // class variable. If this proves to be a slowdown this class should be refactored
        // such that we don't need this method to be static.
        SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.format((Date) value);
    case BINARY:
        byte[] bytes = (byte[]) value;
        return DatatypeConverter.printBase64Binary(bytes);
    case BOOLEAN:
    case DOUBLE:
    case LONG:
    case INTEGER:
    case SHORT:
        return value;
    case STRING:
    case XML:
    case FLOAT:
    case GEOMETRY:
        return value.toString();
    case OBJECT:
    default:
        return null;
    }
}

From source file:com.silverpeas.util.EncodeHelper.java

/**
   * Encode an UTF-8 filename in Base64 for the content-disposition header according to RFC2047.
   *//w  w  w .j ava 2 s  .  c o m
   * @see http://www.ietf.org/rfc/rfc2047.txt
   * @param filename the UTF-8 filename to be encoded.
   * @return the filename to be inserted in the content-disposition header.
   */
  public static String encodeFilename(String filename) {
      StringBuilder buffer = new StringBuilder(256);
      buffer.append("=?UTF-8?B?");
      buffer.append(DatatypeConverter.printBase64Binary(filename.getBytes(Charsets.UTF_8)));
      buffer.append("?=");
      return buffer.toString();
  }

From source file:info.san.books.app.model.listener.LivreListener.java

private String getImageAsBase64(String imagePath) throws IOException {
    if (imagePath != null && !imagePath.isEmpty()) {
        InputStream is = null;//from   w w  w. j  a  v a  2 s.c o m
        try {
            URL imgUrl = new URL(imagePath);
            is = imgUrl.openStream();
            byte[] imgAsByte = IOUtils.toByteArray(is);

            return DatatypeConverter.printBase64Binary(imgAsByte);
        } catch (MalformedURLException mue) {
            LivreListener.LOGGER.error("MalformedURLException", mue);
            throw mue;
        } catch (IOException ioe) {
            LivreListener.LOGGER.error("IOException", ioe);
            throw ioe;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ioe) {
                    LivreListener.LOGGER.warn("IOException", ioe);
                }
            }
        }
    }

    return null;
}

From source file:com.aurel.track.admin.user.avatar.AvatarAction.java

/**
 * This method based on personID returns in JSON format: the avatar image with checksum. 
 * @return/*w w  w.  j  a v  a 2  s. c  o  m*/
 */
public String downloadAvatarWithCheckSum() {
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    if (personID != null) {

        byte[] oneAvatar = AvatarBL.getAvatarInByteArray(personID, iconKey);
        String oneAvatarString = DatatypeConverter.printBase64Binary(oneAvatar);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(oneAvatar);
            String checksum = DatatypeConverter.printBase64Binary(thedigest);
            JSONUtility.appendBooleanValue(sb, "success", true);
            JSONUtility.appendStringValue(sb, "img", oneAvatarString);
            JSONUtility.appendStringValue(sb, "checkSum", checksum, true);
        } catch (Exception ex) {
            JSONUtility.appendBooleanValue(sb, "success", false, true);
        }
        sb.append("}");
        JSONUtility.encodeJSON(servletResponse, sb.toString());
    }

    return null;
}

From source file:bi.meteorite.util.ITestBootstrap.java

private String getBasicAuthentication(String user, String password) {
    String token = user + ":" + password;
    try {//  ww  w .  j a  v  a 2s . c om
        return "Basic " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        throw new IllegalStateException("Cannot encode with UTF-8", ex);
    }
}