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.thoughtworks.go.http.mocks.HttpRequestBuilder.java

public HttpRequestBuilder withBasicAuth(String username, String password) {
    return withHeader("Authorization",
            "basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8)));
}

From source file:com.ecsteam.cloudlaunch.services.jenkins.JenkinsService.java

private HttpEntity<String> getAuthorizationEntity() {
    if (authEntity == null) {
        String unencoded = user + ":" + password;
        String encoded = Base64.getEncoder().encodeToString(unencoded.getBytes());

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Basic " + encoded);

        authEntity = new HttpEntity<String>(headers);
    }/*from   w w w . ja v a2 s.c om*/

    return authEntity;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.KubernetesProviderUtils.java

static void upsertSecret(AccountDeploymentDetails<KubernetesAccount> details, Set<Pair<File, String>> files,
        String secretName, String namespace) {
    KubernetesClient client = getClient(details);

    if (client.secrets().inNamespace(namespace).withName(secretName).get() != null) {
        client.secrets().inNamespace(namespace).withName(secretName).delete();
    }//  w  ww.java  2  s. c  o  m

    Map<String, String> secretContents = new HashMap<>();

    files.forEach(pair -> {
        try {
            File file = pair.getLeft();
            String name = pair.getRight();
            String data = new String(
                    Base64.getEncoder().encode(IOUtils.toByteArray(new FileInputStream(file))));

            secretContents.putIfAbsent(name, data);
        } catch (IOException e) {
            throw new HalException(Severity.ERROR,
                    "Unable to read contents of \"" + pair.getLeft() + "\": " + e);
        }
    });

    SecretBuilder secretBuilder = new SecretBuilder();
    secretBuilder = secretBuilder.withNewMetadata().withName(secretName).withNamespace(namespace).endMetadata()
            .withData(secretContents);

    client.secrets().inNamespace(namespace).create(secretBuilder.build());
}

From source file:net.e2.bw.idreg.client.keycloak.KeycloakClient.java

/**
 * Execute the auth server token request
 *
 * @param code the code//www.  j av  a  2s .  co  m
 * @param callbackUrl the callback URL
 * @param publicClient whether this is a public client or not
 * @return the parsed token result
 */
private AccessTokenData executeAuthServerTokenRequest(String code, String callbackUrl, boolean publicClient)
        throws AuthErrorException {

    // Assemble the POST request
    HttpPost post = new HttpPost(config.getTokenRequest());
    try {
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        formparams.add(new BasicNameValuePair("code", code));
        formparams.add(new BasicNameValuePair("redirect_uri", callbackUrl));
        if (publicClient) {
            formparams.add(new BasicNameValuePair("client_id", config.getClientId()));
        } else if (config.getClientSercret() != null) {
            String secret = config.getClientId() + ":" + config.getClientSercret();
            post.setHeader("Authorization",
                    "Basic " + Base64.getEncoder().encodeToString(secret.getBytes("UTF-8")));
        }
        post.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AuthErrorException("Error composing token request", e);
    }

    // Execute the HTTP request
    String result;
    try (CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        result = (entity == null) ? null : EntityUtils.toString(entity);
        if (result == null || status != 200) {
            throw new AuthErrorException("Error result from token request: " + result);
        }
    } catch (IOException e) {
        throw new AuthErrorException("Error making token request to: " + config.getTokenRequest(), e);
    }

    // Parse the resulting JSON token
    return parseAndValidateTokenResponse(result);
}

From source file:org.wso2.identity.scenarios.commons.util.IdentityScenarioUtil.java

/**
 * Constructs basic authorization header.
 *
 * @param key    Credential identifier./*from  w  ww .  j a  v  a 2 s .co m*/
 * @param secret Credential secret.
 * @return Basic authorization header.
 */
public static String constructBasicAuthzHeader(String key, String secret) {

    Base64.Encoder encoder = Base64.getEncoder();
    String encodedHeader = encoder.encodeToString(String.join(":", key, secret).getBytes());
    return String.join(" ", BASIC, encodedHeader);
}

From source file:org.niord.core.keycloak.KeycloakIntegrationService.java

/**
 * Returns the Keycloak public key for the Niord realm.
 * The public key is returned in the format used by keycloak.json.
 * <p>// w  ww  .  j a v  a2 s  . com
 * If the setting for the public key has not been defined, the public key is
 * fetched directly from Keycloak.
 *
 * @return the Keycloak public key
 */
private String getKeycloakPublicRealmKey() throws Exception {
    if (StringUtils.isNotBlank(authServerRealmKey)) {
        return authServerRealmKey;
    }

    // Fetch the public key from Keycloak
    PublicKey publicKey = resolveKeycloakPublicRealmKey();
    authServerRealmKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()), "utf-8");

    // Update the underlying setting
    settingsService.set("authServerRealmKey", authServerRealmKey);
    return authServerRealmKey;
}

From source file:halive.shootinoutside.common.core.game.map.GameMap.java

public JSONObject serializeMapToJSONObject() {
    JSONObject obj = new JSONObject();
    //Write Standard Header Info
    obj.put("type", "soTileMap");
    obj.put("version", "1.0");
    //Write misc Map Information
    obj.put("mapName", this.mapName);
    obj.put("width", this.width);
    obj.put("height", this.height);
    //Write the map Data (encoded in Base64
    byte[] map = getMapData();
    String mapData = Base64.getEncoder().encodeToString(map);
    obj.put("mapDataB64", mapData);
    //Write the ItemLayer
    obj.put("itemLayer", itemLayer.serializeToJSON());
    //write the SpawnPositions
    obj.put("amtTeams", spawnPositions.length);
    for (int i = 0; i < spawnPositions.length; i++) {
        JSONObject tmpObj = new JSONObject();
        tmpObj.put("length", spawnPositions[i].size());
        for (int j = 0; j < spawnPositions[i].size(); j++) {
            Vector2D v = spawnPositions[i].get(j);
            tmpObj.put("" + j, v.toJSONObject());
        }// ww w  .  java2  s  . c om
        obj.put("spawn_team_" + i, tmpObj);
    }
    //Write the image File as Base64
    obj.put("tileImageB64", Base64.getEncoder().encodeToString(textureSheet));
    return obj;
}

From source file:net.menthor.editor.v2.util.Util.java

/** Write the object to a Base64 string. */
public static String toBase64String(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);// w w w . j  a  v a  2s  . c  om
    oos.close();
    return Base64.getEncoder().encodeToString(baos.toByteArray());
}

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

private String getEncodedQr(Image qr) {
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.data = new ImageData[] { qr.getImageData() };
        imageLoader.compression = 100;// w  w w. ja  va2s . c om
        imageLoader.save(output, SWT.IMAGE_JPEG);
        return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
    } catch (IOException e) {
        LoggerFactory.getLogger(getClass()).error("Error encoding QR", e);
    }
    return "";
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.converter.impl.GenericFeatureConverter.java

private void writeAttributeToXml(Attribute attribute, QName qname, AttributeFormat format,
        MarshallingContext context, HierarchicalStreamWriter writer) {
    // Loop to handle multi-valued attributes

    String name = qname.getPrefix() + ":" + attribute.getName();
    for (Serializable value : attribute.getValues()) {
        String xmlValue = null;/*from   www  .  j  a va  2s.c om*/

        switch (format) {
        case XML:
            String cdata = (String) value;
            if (cdata != null && (writer.underlyingWriter() instanceof EnhancedStaxWriter)) {
                writer.startNode(name);
                EnhancedStaxWriter eWriter = (EnhancedStaxWriter) writer.underlyingWriter();
                eWriter.writeCdata(cdata);
                writer.endNode();
            }
            break;
        case GEOMETRY:
            XmlNode.writeGeometry(name, context, writer, XmlNode.readGeometry((String) value));
            break;
        case BINARY:
            xmlValue = Base64.getEncoder().encodeToString((byte[]) value);
            break;
        case DATE:
            Date date = (Date) value;
            xmlValue = DateFormatUtils.formatUTC(date,
                    DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
            break;
        case OBJECT:
            // Probably won't translate at all.
            break;
        default:
            xmlValue = value.toString();
            break;
        }
        // Write the node if we were able to convert it.
        if (xmlValue != null) {

            writer.startNode(name);
            writer.setValue(xmlValue);
            writer.endNode();
        }
    }
}