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:ai.susi.mind.SusiCognition.java

public SusiCognition(final SusiMind mind, final String query, int timezoneOffset, double latitude,
        double longitude, int maxcount, ClientIdentity identity) {
    this.json = new JSONObject(true);

    // get a response from susis mind
    String client = identity.getClient();
    this.setQuery(query);
    this.json.put("count", maxcount);
    SusiThought observation = new SusiThought();
    observation.addObservation("timezoneOffset", Integer.toString(timezoneOffset));

    if (!Double.isNaN(latitude) && !Double.isNaN(longitude)) {
        observation.addObservation("latitude", Double.toString(latitude));
        observation.addObservation("longitude", Double.toString(longitude));
    }/*from   w w  w .  j a  v a  2  s .com*/
    this.json.put("client_id", Base64.getEncoder().encodeToString(UTF8.getBytes(client)));
    long query_date = System.currentTimeMillis();
    this.json.put("query_date", DateParser.utcFormatter.print(query_date));

    // compute the mind reaction
    List<SusiArgument> dispute = mind.react(query, maxcount, client, observation);
    long answer_date = System.currentTimeMillis();

    // store answer and actions into json
    this.json.put("answers", new JSONArray(
            dispute.stream().map(argument -> argument.finding(client, mind)).collect(Collectors.toList())));
    this.json.put("answer_date", DateParser.utcFormatter.print(answer_date));
    this.json.put("answer_time", answer_date - query_date);
    this.json.put("language", "en");
}

From source file:io.syndesis.rest.v1.state.ClientSideStateProperties.java

private static String generateKey() {
    final byte[] key = new byte[32];
    RANDOM.nextBytes(key);//w w  w  . j a  v  a2  s.  co m

    return Base64.getEncoder().encodeToString(key);
}

From source file:mp3downloader.ZingSearch.java

private static String getSearchResult(String term, int searchType)
        throws UnsupportedEncodingException, MalformedURLException, IOException {
    String data = "{\"kw\": \"" + term + "\", \"t\": " + searchType + ", \"rc\": 50}";
    String jsonData = URLEncoder.encode(Base64.getEncoder().encodeToString(data.getBytes("UTF-8")), "UTF-8");
    String signature = hash_hmac(jsonData, privateKey);
    String urlString = searchUrl + "publicKey=" + publicKey + "&signature=" + signature + "&jsondata="
            + jsonData;//from  w  w w.j  a  v  a 2 s  . co m
    URL url = new URL(urlString);
    URLConnection urlConn = url.openConnection();
    urlConn.addRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
    InputStream is = urlConn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }
    is.close();
    String content = sb.toString();
    return content;
}

From source file:com.salesforce.pixelcaptcha.demo.LandingController.java

private String convertBufferedImageToPngBase64(BufferedImage bi) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//w  w  w .j  a v a 2  s .co m
        ImageIO.write(bi, "png", baos);
    } catch (IOException e) {
        System.out.println(e);
    }
    String encoded = Base64.getEncoder().encodeToString(baos.toByteArray());
    return encoded;
}

From source file:jfix.util.Urls.java

/**
 * Returns content from given url as string. The url can contain
 * username:password after the protocol, so that basic authorization is
 * possible./*from   w w  w.  j a  va 2 s . c  o  m*/
 * 
 * Example for url with basic authorization:
 * 
 * http://username:password@www.domain.org/index.html
 */
public static String readString(String url, int timeout) {
    Reader reader = null;
    try {
        URLConnection uc = new URL(url).openConnection();
        if (uc instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) uc;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
        }
        Matcher matcher = Pattern.compile("://(\\w+:\\w+)@").matcher(url);
        if (matcher.find()) {
            String auth = matcher.group(1);
            String encoding = Base64.getEncoder().encodeToString(auth.getBytes());
            uc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        String charset = (uc.getContentType() != null && uc.getContentType().contains("charset="))
                ? uc.getContentType().split("charset=")[1]
                : "utf-8";
        reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset));
        StringBuilder sb = new StringBuilder();
        for (int chr; (chr = reader.read()) != -1;) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:APIRequest.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //2. Merchant server makes an api request to the snap backend to get the SNAP_TOKEN
    //initialize settings.
    response.setHeader("Accept", "application/json");
    response.setContentType("application/json");
    response.setHeader("Authorization", Base64.getEncoder().encodeToString((serverKey + ":").getBytes()));

    String orderID = request.getParameterValues("gross_amount")[0];
    int grossAmount = Integer.parseInt(request.getParameterValues("gross_amount")[0]);
    //dummy data/*from  ww w .j a v  a 2 s.  c o m*/
    orderID = "Testing Order-01";
    grossAmount = 150000;

    //JSON object
    JSONObject jso = new JSONObject();
    JSONObject transactionDetails = new JSONObject();
    try {
        transactionDetails.put("order_id", orderID);
        transactionDetails.put("gross_amount", grossAmount);
        jso.put("transaction_details", transactionDetails);
    } catch (JSONException ex) {
        Logger.getLogger(APIRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    // send the jso to the server.
    response.getWriter().write(jso.toString());
    //3. Snap backend responds to the api call with the SNAP_TOKEN
}

From source file:io.openvidu.test.e2e.utils.CustomHttpClient.java

public CustomHttpClient(String openviduUrl, String openviduSecret) {
    this.openviduUrl = openviduUrl.replaceFirst("/*$", "");
    this.headerAuth = "Basic "
            + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + openviduSecret).getBytes());

    SSLContext sslContext = null;
    try {/*from   ww w  . j  a  v  a2 s  . c  o m*/
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Assert.fail("Error building custom HttpClient: " + e.getMessage());
    }
    HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    Unirest.setHttpClient(unsafeHttpClient);
}

From source file:org.flowable.job.service.impl.history.async.util.AsyncHistoryJsonUtil.java

public static String convertToBase64(VariableInstanceEntity variable) {
    byte[] bytes = variable.getBytes();
    if (bytes != null) {
        return new String(Base64.getEncoder().encode(variable.getBytes()), StandardCharsets.US_ASCII);
    } else {/*from w  w  w. ja v a 2s.  c  om*/
        return null;
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.services.v1.VaultService.java

public void publishSecret(DeploymentConfiguration deploymentConfiguration, String name, String contents) {
    String vaultAddress = deploymentConfiguration.getDeploymentEnvironment().getVault().getAddress();
    String encodedContents = Base64.getEncoder().encodeToString(contents.getBytes());
    String secretName = vaultSecretPrefix + name;

    List<String> command = new ArrayList<>();
    command.add("vault");
    command.add("write");
    command.add("--address");
    command.add(vaultAddress);//from w  ww .ja  v  a2s . c o  m
    command.add(secretName);
    command.add(encodedContents);

    JobRequest request = new JobRequest().setTokenizedCommand(command)
            .setTimeoutMillis(TimeUnit.SECONDS.toMillis(vaultTimeoutSeconds));

    String id = jobExecutor.startJob(request);
    DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(5));
    JobStatus status = jobExecutor.updateJob(id);

    if (!status.getResult().equals(JobStatus.Result.SUCCESS)) {
        throw new HalException(Problem.Severity.FATAL,
                "Failed to publish secret " + name + ": " + status.getStdOut() + status.getStdErr());
    }
}

From source file:com.joyent.manta.config.IntegrationTestConfigContext.java

private static <T> SettableConfigContext<T> enableTestEncryption(final SettableConfigContext<T> context,
        final boolean usingEncryption, final String encryptionCipher) {
    if (usingEncryption) {
        context.setClientEncryptionEnabled(true);
        context.setEncryptionKeyId("integration-test-key");
        context.setEncryptionAuthenticationMode(EncryptionAuthenticationMode.Optional);

        SupportedCipherDetails cipherDetails = SupportedCiphersLookupMap.INSTANCE.getOrDefault(encryptionCipher,
                DefaultsConfigContext.DEFAULT_CIPHER);

        context.setEncryptionAlgorithm(cipherDetails.getCipherId());
        SecretKey key = SecretKeyUtils.generate(cipherDetails);
        context.setEncryptionPrivateKeyBytes(key.getEncoded());

        System.out.printf("Unique secret key used for test (base64):\n%s\n",
                Base64.getEncoder().encodeToString(key.getEncoded()));
    }/*from   w w w .  jav  a  2 s . c  o  m*/

    return context;
}