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:io.kodokojo.brick.jenkins.JenkinsConfigurer.java

private BrickConfigurerData executeGroovyScript(BrickConfigurerData brickConfigurerData,
        VelocityContext context, String templatePath) {
    String url = brickConfigurerData.getEntrypoint() + SCRIPT_URL_SUFFIX;
    OkHttpClient httpClient = new OkHttpClient();
    Response response = null;/*from  ww  w .  j  av a 2  s.c  o m*/
    try {
        VelocityEngine ve = new VelocityEngine();
        ve.init(VE_PROPERTIES);

        Template template = ve.getTemplate(templatePath);

        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        String script = sw.toString();

        RequestBody body = new FormEncodingBuilder().add(SCRIPT_KEY, script).build();

        Request.Builder builder = new Request.Builder().url(url).post(body);
        User admin = brickConfigurerData.getDefaultAdmin();
        String crendential = String.format("%s:%s", admin.getUsername(), admin.getPassword());
        builder.addHeader("Authorization",
                "Basic " + Base64.getEncoder().encodeToString(crendential.getBytes()));
        Request request = builder.build();
        response = httpClient.newCall(request).execute();
        if (response.code() >= 200 && response.code() < 300) {
            return brickConfigurerData;
        }
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint()
                + ". Jenkins return " + response.code());//Create a dedicate Exception instead.
    } catch (IOException e) {
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestUtils.java

public static String encodeCredentialsForBasicAuthorization(String username, Object password) {
    Validate.notBlank(username);/*from   w  w  w .  ja v  a 2 s. c  o m*/
    Validate.notNull(password);
    Validate.isTrue(ClassUtils.isAssignable(CharSequence.class, password.getClass()));
    Validate.notBlank((CharSequence) password);

    Encoder base64Encoder = Base64.getEncoder();
    String encodedCredentials = base64Encoder.encodeToString((username + ':' + password).getBytes());
    log.trace("Use Basic Authorization with User {}", username);
    return "Basic " + encodedCredentials;
}

From source file:org.codice.ddf.branding.impl.DdfBrandingPluginTest.java

@Test
public void testFavIcon() throws IOException {
    ddfBrandingPlugin.init();//  w ww  .j  a  v  a 2s  .  c  o  m
    assertThat(ddfBrandingPlugin.getBase64FavIcon(), is(equalTo(Base64.getEncoder()
            .encodeToString(IOUtils.toByteArray(DdfBrandingPluginTest.class.getResourceAsStream(favIcon))))));
}

From source file:org.codice.ddf.catalog.ui.security.UserApplication.java

private void setUserPreferences(Subject subject, Map<String, Object> preferences) {
    String json = JsonFactory.create().toJson(preferences);

    LOGGER.trace("preferences JSON text:\n {}", json);

    String userid = subjectIdentity.getUniqueIdentifier(subject);
    PersistentItem item = new PersistentItem();
    item.addIdProperty(userid);// w  w  w  .j  ava 2 s . co  m
    item.addProperty("user", userid);
    item.addProperty("preferences_json", "_bin",
            Base64.getEncoder().encodeToString(json.getBytes(Charset.defaultCharset())));

    try {
        persistentStore.add(PersistenceType.PREFERENCES_TYPE.toString(), item);
    } catch (PersistenceException e) {
        LOGGER.info("PersistenceException while trying to persist preferences for user {}", userid, e);
    }
}

From source file:org.codice.ddf.branding.impl.TestDdfBrandingPlugin.java

@Test
public void testFavIcon() throws IOException {
    ddfBrandingPlugin.init();//from   w ww  .  j  a  va2  s .  c  o  m
    assertThat(ddfBrandingPlugin.getBase64FavIcon(), is(equalTo(Base64.getEncoder()
            .encodeToString(IOUtils.toByteArray(TestDdfBrandingPlugin.class.getResourceAsStream(favIcon))))));
}

From source file:ai.grakn.engine.tasks.manager.redisqueue.RedisTaskStorage.java

@Override
public Boolean updateState(TaskState state) {
    try (Jedis jedis = redis.getResource(); Context ignore = updateTimer.time()) {
        String key = encodeKey.apply(state.getId().getValue());
        LOG.debug("Updating state {}", key);
        String value = new String(Base64.getEncoder().encode(SerializationUtils.serialize(state)),
                Charsets.UTF_8);// ww  w. jav  a  2s. co m
        String status = jedis.setex(key, 60 * 60/*expire time in seconds*/, value);
        return status.equalsIgnoreCase("OK");
    }
}

From source file:org.elasticsearch.xpack.restart.FullClusterRestartIT.java

@Override
protected Settings restClientSettings() {
    String token = "Basic " + Base64.getEncoder()
            .encodeToString("test_user:x-pack-test-password".getBytes(StandardCharsets.UTF_8));
    return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token)
            // we increase the timeout here to 90 seconds to handle long waits for a green
            // cluster health. the waits for green need to be longer than a minute to
            // account for delayed shards
            .put(ESRestTestCase.CLIENT_RETRY_TIMEOUT, "90s").put(ESRestTestCase.CLIENT_SOCKET_TIMEOUT, "90s")
            .build();/*from   ww w.  j  a va 2 s.  c o m*/
}

From source file:org.codice.ddf.configuration.PlatformUiConfiguration.java

private String getBase64(String productImage) throws IOException {
    if (provider != null) {
        byte[] resourceAsBytes = provider.getResourceAsBytes(productImage);
        if (resourceAsBytes.length > 0) {
            return Base64.getEncoder().encodeToString(resourceAsBytes);
        }/* www.  j a va  2  s.c om*/
    }
    return "";
}

From source file:org.wso2.carbon.identity.recovery.util.Utils.java

/**
 * Hash and encode a string./*from   ww w.  ja  v a2s. c  om*/
 *
 * @param value
 * @return
 * @throws NoSuchAlgorithmException
 */
public static String doHash(String value) throws NoSuchAlgorithmException {
    String digsestFunction = "SHA-256";
    MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
    byte[] byteValue = dgst.digest(value.getBytes(StandardCharsets.UTF_8));
    return new String(Base64.getEncoder().encode(byteValue), StandardCharsets.UTF_8);
}

From source file:za.co.bronkode.jwtbroker.Tokenizer.java

public static String GetSignature(String header, String claim) {
    try {//from  ww w  .j  a  va2 s. c  om

        StringBuilder sb = new StringBuilder(header);
        sb.append(".");
        sb.append(claim);
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKey key = new SecretKeySpec(privateKey.getBytes(), "HmacSHA256");

        mac.init(key);
        String signature = Base64.getEncoder().encodeToString(mac.doFinal(sb.toString().getBytes()));
        return signature;
    } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
        Logger.getLogger(Tokenizer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}