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:com.github.horrorho.liquiddonkey.cloud.client.Headers.java

public String token(String type, String left, String right) {
    return type + " "
            + Base64.getEncoder().encodeToString((left + ":" + right).getBytes(StandardCharsets.UTF_8));
}

From source file:org.codice.alliance.distribution.branding.AllianceBrandingPlugin.java

@Override
public String getBase64ProductImage() throws IOException {
    byte[] productImageAsBytes = IOUtils
            .toByteArray(AllianceBrandingPlugin.class.getResourceAsStream(getProductImage()));
    if (productImageAsBytes.length > 0) {
        return Base64.getEncoder().encodeToString(productImageAsBytes);
    }//from ww  w. j  a  va 2 s  . co  m
    return "";
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

private static void addAuthorization(HttpRequestBase request, String user, String pwd) {
    try {/*from www . j  ava2 s .com*/
        //String authHeaderStr = String.format("Basic %s", new String(Base64.encodeBase64(String.format("%s:%s", user, pwd).getBytes()), "UTF-8"));
        String authHeaderStr = String.format("Basic %s",
                new String(Base64.getEncoder().encode(String.format("%s:%s", user, pwd).getBytes("UTF-8"))));
        request.addHeader("Authorization", authHeaderStr);
    } catch (Exception e) {
        log.error("ERROR adding authorization header : ", e);
    }
}

From source file:org.apache.accumulo.shell.commands.GetSplitsCommand.java

private static String obscuredTabletName(final KeyExtent extent) {
    MessageDigest digester;//from  ww  w . j av  a 2  s.co  m
    try {
        digester = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    if (extent.getEndRow() != null && extent.getEndRow().getLength() > 0) {
        digester.update(extent.getEndRow().getBytes(), 0, extent.getEndRow().getLength());
    }
    return Base64.getEncoder().encodeToString(digester.digest());
}

From source file:org.apache.syncope.client.console.PreferenceManager.java

public void set(final Request request, final Response response, final Map<String, List<String>> prefs) {
    Map<String, String> current = new HashMap<>();

    String prefString = COOKIE_UTILS.load(COOKIE_NAME);
    if (prefString != null) {
        current.putAll(getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes()))));
    }//from  w  ww . j a  va 2  s .co  m

    // after retrieved previous setting in order to overwrite the key ...
    prefs.entrySet().forEach(entry -> {
        current.put(entry.getKey(), StringUtils.join(entry.getValue(), ";"));
    });

    try {
        COOKIE_UTILS.save(COOKIE_NAME, Base64.getEncoder().encodeToString(setPrefs(current).getBytes()));
    } catch (IOException e) {
        LOG.error("Could not save {} info: {}", getClass().getSimpleName(), current, e);
    }
}

From source file:org.codice.ddf.landing.LandingPage.java

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

From source file:org.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java

@SuppressWarnings("unchecked")
public void testSetupPasswordToolAutoSetup() throws Exception {
    final String testConfigDir = System.getProperty("tests.config.dir");
    logger.info("--> CONF: {}", testConfigDir);
    final Path configPath = PathUtils.get(testConfigDir);
    setSystemPropsForTool(configPath);//  w  w w  .ja v a 2s  .co  m

    Response nodesResponse = client().performRequest("GET", "/_nodes/http");
    Map<String, Object> nodesMap = entityAsMap(nodesResponse);

    Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes");
    Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue();
    Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http");
    String nodePublishAddress = (String) firstNodeHttp.get("publish_address");
    final int lastColonIndex = nodePublishAddress.lastIndexOf(':');
    InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex));
    InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList())
            .resolvePublishHostAddresses(Strings.EMPTY_ARRAY);
    final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1));

    List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml"));
    lines = lines.stream()
            .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false)
            .collect(Collectors.toList());
    lines.add(randomFrom("http.port", "http.publish_port") + ": " + port);
    if (expectedPublishAddress.equals(actualPublishAddress) == false) {
        lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress));
    }
    Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8,
            StandardOpenOption.TRUNCATE_EXISTING);

    MockTerminal mockTerminal = new MockTerminal();
    SetupPasswordTool tool = new SetupPasswordTool();
    final int status;
    if (randomBoolean()) {
        mockTerminal.addTextInput("y"); // answer yes to continue prompt
        status = tool.main(new String[] { "auto" }, mockTerminal);
    } else {
        status = tool.main(new String[] { "auto", "--batch" }, mockTerminal);
    }
    assertEquals(0, status);
    String output = mockTerminal.getOutput();
    logger.info("CLI TOOL OUTPUT:\n{}", output);
    String[] outputLines = output.split("\\n");
    Map<String, String> userPasswordMap = new HashMap<>();
    Arrays.asList(outputLines).forEach(line -> {
        if (line.startsWith("PASSWORD ")) {
            String[] pieces = line.split(" ");
            String user = pieces[1];
            String password = pieces[pieces.length - 1];
            logger.info("user [{}] password [{}]", user, password);
            userPasswordMap.put(user, password);
        }
    });

    assertEquals(4, userPasswordMap.size());
    userPasswordMap.entrySet().forEach(entry -> {
        final String basicHeader = "Basic " + Base64.getEncoder()
                .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8));
        try {
            Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate",
                    new BasicHeader("Authorization", basicHeader));
            assertEquals(200, authenticateResponse.getStatusLine().getStatusCode());
            Map<String, Object> userInfoMap = entityAsMap(authenticateResponse);
            assertEquals(entry.getKey(), userInfoMap.get("username"));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticatorTest.java

@Test(description = "This method tests the behaviour of the authenticate method in BasicAuthenticator with valid "
        + "credentials", dependsOnMethods = "testCanHandleWithRequireParameters")
public void testAuthenticateWithValidCredentials() throws EncoderException, IllegalAccessException {
    String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes()));
    request = new Request();
    context = new StandardContext();
    context.addParameter("basicAuth", "true");
    request.setContext(context);/*from  www. j av  a2  s  .c o m*/
    mimeHeaders = new MimeHeaders();
    bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(BASIC_HEADER + encodedString);
    coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    AuthenticationInfo authenticationInfo = basicAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "For a valid user authentication failed.");
    Assert.assertEquals(authenticationInfo.getUsername(), ADMIN_USER,
            "Authenticated username for from BasicAuthenticator is not matching with the original user.");
    Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            "Authenticated user's tenant domain from BasicAuthenticator is not matching with the "
                    + "original user's tenant domain");
    Assert.assertEquals(authenticationInfo.getTenantId(), MultitenantConstants.SUPER_TENANT_ID,
            "Authenticated user's tenant ID from BasicAuthenticator is not matching with the "
                    + "original user's tenant ID");
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java

@Override
public void init(HttpServletTransactionManager transactionManager, FormatterManager formatterMgr,
        Node configurationNode) throws AdapterHttpInitializationException {

    try {//ww  w  . j ava  2s  .  c om
        action = XMLConfig.get(configurationNode, "@Action");
        dump = XMLConfig.getBoolean(configurationNode, "@dump-in-out", false);

        Node endpointNode = XMLConfig.getNode(configurationNode, "endpoint");
        host = XMLConfig.get(endpointNode, "@host");
        port = XMLConfig.get(endpointNode, "@port", "80");
        contextPath = XMLConfig.get(endpointNode, "@context-path", "");
        secure = XMLConfig.getBoolean(endpointNode, "@secure", false);
        connTimeout = XMLConfig.getInteger(endpointNode, "@conn-timeout", DEFAULT_CONN_TIMEOUT);
        soTimeout = XMLConfig.getInteger(endpointNode, "@so-timeout", DEFAULT_SO_TIMEOUT);

        URL url = new URL(secure ? "https" : "http", host, Integer.valueOf(port), contextPath);

        Node proxyConfigNode = XMLConfig.getNode(endpointNode, "Proxy");
        if (proxyConfigNode != null) {
            String proxyHost = XMLConfig.get(proxyConfigNode, "@host");
            int proxyPort = XMLConfig.getInteger(proxyConfigNode, "@port", 80);

            Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = url.openConnection(proxy);

            String proxyUser = XMLConfig.get(proxyConfigNode, "@user", "");
            String proxyPassword = XMLConfig.getDecrypted(proxyConfigNode, "@password", "");

            if (proxyUser.trim().length() > 0) {
                String proxyAuthorization = proxyUser + ":" + proxyPassword;
                connection.setRequestProperty("Proxy-Authorization",
                        Base64.getEncoder().encodeToString(proxyAuthorization.getBytes()));
            }

        } else {
            connection = url.openConnection();
        }

        connection.setConnectTimeout(connTimeout);

    } catch (Exception exc) {
        throw new AdapterHttpInitializationException("GVHTTP_CONFIGURATION_ERROR",
                new String[][] { { "message", exc.getMessage() } }, exc);
    }

}

From source file:org.elasticsearch.plugin.readonlyrest.utils.containers.ESWithReadonlyRestContainer.java

private Header authorizationHeader(String name, String password) {
    String base64userPass = Base64.getEncoder().encodeToString((name + ":" + password).getBytes());
    return new BasicHeader("Authorization", "Basic " + base64userPass);
}