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:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with kilobytes per minute produced and
 * consumed.//  w  ww  . j  a v a2 s.  c om
 *
 * @return chart as base64 string.
 */
public String getBase64BytesPerMinuteImage() {
    TimeSeries timeSeriesConsumed = new TimeSeries("Consumed");
    TimeSeries timeSeriesProduced = new TimeSeries("Produced");
    TimeSeries timeSeriesTotal = new TimeSeries("Total");
    for (PeriodMetrics m : getMessagesPerMinute()) {
        Minute minute = new Minute(m.getPeriodStart());
        timeSeriesConsumed.add(minute, m.getConsumedBytes() / 1024);
        timeSeriesProduced.add(minute, m.getProducedBytes() / 1024);
        timeSeriesTotal.add(minute, m.getTotalBytes() / 1024);
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeriesConsumed);
    timeSeriesCollection.addSeries(timeSeriesProduced);
    timeSeriesCollection.addSeries(timeSeriesTotal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Kilobytes per minute", "Time", "Bytes (k)",
                timeSeriesCollection);
        chart.getPlot().setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}

From source file:com.cabable.inventory.resources.OAuth2Resource.java

@Path("/register")
@POST/*  w ww .  ja  v a2 s.c o  m*/
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@UnitOfWork
@RolesAllowed("SUPERADMIN")
public User register(User params, @Context final HttpServletRequest request,
        @QueryParam("description") String description, @QueryParam("name") String name,
        @QueryParam("website") String uri) {
    if (params.getOperator_id() <= 0 || (params.getName() == null || params.getName().isEmpty())
            || (params.getUsername() == null || params.getUsername().isEmpty())) {
        throw new WebApplicationException("Operator ID / username / password / name compulsory", 400);
    }

    //check if password is null
    if (params.getPassword() == null || params.getPassword().isEmpty()) {
        params.setPassword(params.getName() + Base64.getEncoder().encodeToString(RandomUtils.nextBytes(5)));
        LOGGER.info("System generated password");
    }

    //check is username is duplicate
    try {
        if (dao.isDuplicate(params.getUsername())) {
            throw new WebApplicationException("Duplicate username, please try something else.", 400);
        }
    } catch (DatabaseException e) {
        throw new WebApplicationException("Blank username, Dont try cute stuff. You ip is "
                + request.getRemoteAddr() + "I will find you, and i will kill you. ", 401);
    }
    ;

    //register an oauth application. 
    OAuthApplication application = new OAuthApplication();
    application.setDescription(description);
    application.setName(params.getUsername());
    application.setRedirect_uri((uri == null) ? "http://" + params.getName() : uri);
    application.setScope(params.getRole());
    application.setStatus(1);
    Map<String, String> mymap = new HashMap<>();
    mymap.put("operator_id", Long.toString(params.getOperator_id()));
    application.setApplication_details(mymap);

    //register an application on oauth
    Response response = client.registerApplication(application);

    if (response.getStatus() == 200) {
        OAuthApplicationResponse re = response.readEntity(OAuthApplicationResponse.class);
        params.setClient_id(re.getClient_id());
        params.setClient_secret(re.getClient_secret());
    } else {
        throw new WebApplicationException(response);
    }

    //create user
    return dao.create(params);
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//from  ww w .j a  v  a 2  s . com
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:edu.kit.scc.backend.HpssCdmi.java

private JSONObject makeHpssRestCall(String op, String path) {
    JSONObject configuration = new JSONObject();
    InputStream in = null;//from w  w w  .  ja  v  a 2 s  .co m

    String configurationPath = System.getProperty("cdmi.hpss.config", DEFAULT_CONFIG_PATH);
    try {

        Path configPath = Paths.get(configurationPath, "configuration.json");
        if (Files.exists(configPath)) {
            in = Files.newInputStream(configPath);
        } else {
            in = getClass().getResourceAsStream("/configuration.json");
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        StringBuffer stringBuffer = new StringBuffer();
        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            stringBuffer.append(inputLine);
        }

        configuration = new JSONObject(stringBuffer.toString());

        log.debug("Use configuration {}", configuration.toString());

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String url = configuration.getString(op) + path;
    String str = configuration.getString("rest_user") + ":" + configuration.getString("rest_password");

    String authorization = "Basic " + Base64.getEncoder().encodeToString(str.getBytes());
    log.info("Authorization {}", authorization);

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5 * 1000).build();
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

    HttpGet httpGet = new HttpGet(url);
    Header authorizationHeader = new BasicHeader("Authorization", authorization);
    httpGet.addHeader(authorizationHeader);
    CloseableHttpResponse response = null;
    BufferedReader buffReader = null;

    JSONObject json = new JSONObject();

    try {
        response = httpclient.execute(httpGet);

        log.info(response.getStatusLine().toString());
        HttpEntity entity = response.getEntity();
        buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));
        StringBuffer stringBuffer = new StringBuffer();
        String inputLine;
        while ((inputLine = buffReader.readLine()) != null) {
            stringBuffer.append(inputLine);
        }
        EntityUtils.consume(entity);

        String content = stringBuffer.toString();
        log.debug(content);

        try {
            json = new JSONObject(content);
            log.info(json.toString());
        } catch (JSONException ex) {
            // ex.printStackTrace();
            log.warn(ex.getMessage());
        }
        try {
            JSONArray arr = new JSONArray(content);
            json.put("children", arr);
            log.info(json.toString());
        } catch (JSONException ex) {
            // ex.printStackTrace();
            log.warn(ex.getMessage());
        }
    } catch (ClientProtocolException ex) {
        // ex.printStackTrace();
        log.warn(ex.getMessage());
    } catch (IOException ex) {
        // ex.printStackTrace();
        log.warn(ex.getMessage());
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException ex) {
            // ex.printStackTrace();
            log.warn(ex.getMessage());
        }
        if (buffReader != null) {
            try {
                if (buffReader != null) {
                    buffReader.close();
                }
            } catch (IOException ex) {
                // ex.printStackTrace();
                log.warn(ex.getMessage());
            }
        }
    }

    return json;
}

From source file:org.javabeanstack.web.jsf.controller.AbstractUserEnvironment.java

protected String getByteAsString(byte[] avatar) {
    if (avatar == null) {
        return null;
    }/*from  w  w w.  j a v a 2  s  .co  m*/
    String avatarAsString;
    avatarAsString = Base64.getEncoder().encodeToString(avatar);
    return avatarAsString;
}

From source file:com.streamsets.pipeline.lib.remote.SSHDUnitTest.java

protected byte[] getHostsFileEntry(String host) {
    byte[] key = new Buffer.PlainBuffer().putPublicKey(sshdHostKeyPair.getPublic()).getCompactData();
    String entry = host + " ssh-rsa " + Base64.getEncoder().encodeToString(key);
    return entry.getBytes(Charset.forName("UTF-8"));
}

From source file:org.everit.authentication.http.basic.tests.HttpBasicAuthFilterTestComponent.java

private String encode(final String plain) {
    Encoder encoder = Base64.getEncoder();
    String encoded = encoder.encodeToString(plain.getBytes(StandardCharsets.UTF_8));
    return encoded;
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

@Test
public void testSuccess() throws Exception {
    Properties sdcProps = new Properties();
    sdcProps.setProperty("a", "b");
    sdcProps.setProperty("c", "d");
    sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab");
    sdcProps.setProperty("kerberos.client.enabled", "false");
    sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM");
    File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties");

    Properties dpmProps = new Properties();
    dpmProps.setProperty("x", "y");
    dpmProps.setProperty("z", "a");
    dpmProps.setProperty("dpm.enabled", "false");
    dpmProps.setProperty("dpm.base.url", "http://localhost:18631");
    File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties");

    try (FileWriter fw = new FileWriter(sdcFile)) {
        sdcProps.store(fw, "");
    }/* ww w .  j  a  va2  s.c  o m*/

    try (FileWriter fw = new FileWriter(dpmFile)) {
        dpmProps.store(fw, "");
    }

    Response response = null;
    KeyPair keys = generateKeys();
    mockCheckForCredentialsRequiredToTrue();
    System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded()));
    String token = "Frenchies and Pandas";
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(keys.getPrivate());
    sig.update(token.getBytes(Charsets.UTF_8));
    List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2");
    CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM",
            Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)),
            Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631",
            Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org");

    try {
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER
                .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

        // Verify sdc.properties
        sdcProps = new Properties();
        try (FileReader fr = new FileReader(sdcFile)) {
            sdcProps.load(fr);
        }
        Assert.assertEquals("b", sdcProps.getProperty("a"));
        Assert.assertEquals("d", sdcProps.getProperty("c"));
        Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM",
                sdcProps.getProperty("kerberos.client.principal"));
        Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled"));
        Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab"));
        byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab"));
        Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8));
        response = target("/v1/definitions").request().get();
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        dpmProps = new Properties();
        try (FileReader fr = new FileReader(dpmFile)) {
            dpmProps.load(fr);
        }
        Assert.assertEquals("y", dpmProps.getProperty("x"));
        Assert.assertEquals("a", dpmProps.getProperty("z"));
        Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled"));
        Assert.assertEquals(
                Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX,
                dpmProps.getProperty("dpm.appAuthToken"));
        Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url"));

        Assert.assertEquals(StringUtils.join(labels.toArray(), ","),
                dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS));
        Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID));

        File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt");
        try (FileInputStream fr = new FileInputStream(tokenFile)) {
            int len = token.length();
            byte[] tokenBytes = new byte[len];
            Assert.assertEquals(len, fr.read(tokenBytes));
            Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8));
        }
        //Test redeploying the credentials again
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(),
                CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:com.hybris.datahub.outbound.utils.RestTemplateUtil.java

/**
 * @return HttpHeaders/*from w w w  .  ja va 2s. com*/
 */
public HttpHeaders createHeaders() {
    final String encoding = Base64.getEncoder()
            .encodeToString(String.format("%s:%s", baseAuthUser, baseAuthPwd).getBytes());
    final String authHeader = "Basic " + encoding;
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", authHeader);
    headers.add("Content-Type", defaultContentType);
    headers.add("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36");
    headers.add("Accept-Encoding", "gzip,deflate");
    headers.add("Accept-Language", "zh-CN");
    headers.add("Connection", "Keep-Alive");
    return headers;
}