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:org.springframework.session.web.http.DefaultCookieSerializer.java

/**
 * Encode the value using Base64./*from  w  w  w .j  av  a  2 s  . c o  m*/
 * @param value the String to Base64 encode
 * @return the Base64 encoded value
 * @since 1.2.2
 */
private String base64Encode(String value) {
    byte[] encodedCookieBytes = Base64.getEncoder().encode(value.getBytes());
    return new String(encodedCookieBytes);
}

From source file:org.pentaho.di.pan.PanCommandExecutorTest.java

@Test
public void testFilesystemBase64Zip() throws Exception {
    String fileName = "test.ktr";
    File zipFile = new File(getClass().getResource("testKtrArchive.zip").toURI());
    String base64Zip = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(zipFile));
    Trans trans = mockedPanCommandExecutor.loadTransFromFilesystem(null, fileName, null, base64Zip);
    assertNotNull(trans);//  w w  w.ja  v a2  s  .c  o  m
}

From source file:org.springframework.session.data.couchbase.CouchbaseSession.java

public String objectToString(Serializable object) {
    String encoded = null;/* w ww .  j av a  2 s.  c  o  m*/
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        encoded = new String(Base64.getEncoder().encode(byteArrayOutputStream.toByteArray()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return encoded;
}

From source file:com.ibasco.agql.examples.base.BaseExample.java

/**
 * @see <a href="https://gist.github.com/bricef/2436364">https://gist.github.com/bricef/2436364</a>
 *//*from w w  w  .jav a  2  s .  com*/
public static String encrypt(String plainText) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(worldsMostSecureUnhackableKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,
            new IvParameterSpec(worldsMostSecureUnhackableIvKey.getBytes("UTF-8")));
    return Base64.getEncoder().encodeToString((cipher.doFinal(padNullBytes(plainText))));
}

From source file:alfio.controller.api.admin.UsersApiController.java

private static String toBase64QRCode(UserWithPassword userWithPassword, String baseUrl) {
    Map<String, Object> info = new HashMap<>();
    info.put("username", userWithPassword.getUsername());
    info.put("password", userWithPassword.getPassword());
    info.put("baseUrl", baseUrl);
    return Base64.getEncoder().encodeToString(ImageUtil.createQRCode(Json.GSON.toJson(info)));
}

From source file:org.locationtech.geomesa.bigtable.spark.BigtableInputFormatBase.java

public static String scanToString(BigtableExtendedScan scan) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] table = scan.getAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME);
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeInt(table.length);//from ww  w.j  a  v a 2  s.co m
    dos.write(table);
    scan.getRowSet().writeTo(dos);
    dos.flush();
    return Base64.getEncoder().encodeToString(baos.toByteArray());
}

From source file:com.arvato.thoroughly.util.RestTemplateUtil.java

/**
 * @return HttpHeaders/*from   w  w  w. j a v a2 s.  c  o m*/
 */
public HttpHeaders createHeaders() {
    String encoding = Base64.getEncoder()
            .encodeToString(String.format("%s:%s", datahubAuthUsername, datahubAuthPwd).getBytes());
    String authHeader = "Basic " + encoding;
    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;
}

From source file:au.edu.unimelb.plantcell.onekp.icprot.servlets.SubfolderTableVisitor.java

@Override
public String toString() {
    int carousel_id = 1;
    StringBuilder sb = new StringBuilder();

    if (dir2files.keySet().isEmpty()) {
        sb.append("<p>No files available for download.</p>");
        return sb.toString();
    }//from  www.j a  v  a  2 s  .c om

    log.log(Level.INFO, "Found {0} folders to scan for suitable downloads",
            new Object[] { dir2files.keySet().size() });

    List<File> sorted_dirs = new ArrayList<>();
    sorted_dirs.addAll(dir2files.keySet());
    Collections.sort(sorted_dirs, (final File o1, final File o2) -> {
        // length of absolute path is used for comparison for now...
        int len1 = o1.getAbsolutePath().length();
        int len2 = o2.getAbsolutePath().length();
        if (len1 < len2) {
            return -1;
        } else if (len1 > len2) {
            return 1;
        } else {
            return 0;
        }
    });
    FolderDescription fd = new FolderDescription(cb);
    for (File folder : sorted_dirs) {
        List<File> files = dir2files.get(folder);
        if (files.isEmpty()) {
            log.log(Level.INFO, "Found no files for {0}... ignoring",
                    new Object[] { folder.getAbsolutePath() });
            continue;
        }
        log.log(Level.INFO, "Processing folder {0}", new Object[] { folder.getAbsolutePath() });

        ArrayList<File> other_files = new ArrayList<>();
        ArrayList<File> image_files = new ArrayList<>();
        separateImagesFromOtherFiles(files, image_files, other_files);

        if (other_files.size() < 1) {
            log.log(Level.INFO, "Zero other files but found {0} image files in {1}",
                    new Object[] { image_files.size(), folder.getAbsolutePath() });
            if (image_files.size() > 0) {
                sb.append(fd.get(folder));
            }
            carousel_id++;
            continue;
        }
        log.log(Level.INFO, "File sizes: {0} {1} {2}",
                new Object[] { files.size(), image_files.size(), other_files.size() });

        String suffix = folder.getAbsolutePath();
        if (suffix.startsWith(prefix)) {
            suffix = suffix.substring(prefix.length());
            while (suffix.startsWith("/")) {
                suffix = suffix.substring(1);
            }
        }
        String heading = StringEscapeUtils.escapeHtml4(suffix);

        log.log(Level.INFO, "Heading is {0}, suffix is {1}, folder is {2}",
                new Object[] { heading, suffix, folder });
        if (heading.length() > 0) {
            sb.append(fd.get(folder)); // NB: we assume in this case that <h3> is provided by fd.get()
        } else {
            if (sorted_dirs.size() > 1) {
                sb.append(fd.get(folder));
            } else {
                // even in the case where there is a single folder, we give FolderDescription a chance
                // to add a narrative to the page, not just the downloads
                String descr = fd.get(folder);
                if (descr != null && descr.length() > 0) {
                    sb.append(descr);
                }
            }
        }

        boolean make_collapsed_table = (other_files.size() > 20);
        if (make_collapsed_table) {
            String table_id = "table" + n_large_tables++;
            sb.append(
                    "<button type=\"button\" class=\"btn btn-info\" data-toggle=\"collapse\" data-target=\"#");
            sb.append(table_id);
            sb.append("\">Show/hide files</button>");
            sb.append("<div id=\"");
            sb.append(table_id);
            sb.append("\" class=\"collapse\">");
        }
        sb.append("<table class=\"table table-condensed\">");
        sb.append("<tr>");
        sb.append("<th>Name</th>");
        sb.append("<th>Size</th>");
        sb.append("<th>Last modified</th>");
        sb.append("</tr>");

        for (File f : other_files) {
            sb.append("<tr>");
            sb.append("<td>");
            suffix = f.getName();
            if (suffix.startsWith(prefix)) {
                suffix = suffix.substring(prefix.length());
                while (suffix.startsWith("/")) {
                    suffix = suffix.substring(1);
                }
            }
            sb.append("<a href=\"services/FileDownload?attachment=1&file=");
            String encoded = Base64.getEncoder().encodeToString(f.getAbsolutePath().getBytes());
            sb.append(encoded);
            sb.append("\">");
            sb.append(StringEscapeUtils.escapeHtml4(suffix));
            sb.append("</a>");
            sb.append("</td>");
            sb.append("<td>");
            sb.append(StringEscapeUtils.escapeHtml4(ServiceCore.readableFileSize(f.length())));
            sb.append("</td>");

            // last modified
            long yourmilliseconds = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm");
            Date resultdate = new Date(f.lastModified());
            sb.append("<td>");
            sb.append(StringEscapeUtils.escapeHtml4(sdf.format(resultdate)));
            sb.append("</td>");
            sb.append("</tr>");
        }
        sb.append("</table>");
        if (make_collapsed_table) {
            sb.append("</div>");
        }
    }

    log.log(Level.INFO, "Resulting HTML has length: {0}", new Object[] { sb.length() });
    return sb.toString();
}

From source file:org.wso2.carbon.apimgt.core.impl.LogInKeyManagerImpl.java

/**
 * Create the oauth2 application with calling DCR endpoint of WSO2 IS
 *
 * @param oauthAppRequest - this object contains values of oAuth app properties.
 * @return OAuthApplicationInfo -this object contains oauth2 app details
 * @throws org.wso2.carbon.apimgt.core.exception.KeyManagementException throws KeyManagerException
 *///  www  . j  a  va2s . c  o m

@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws KeyManagementException {
    // OAuthApplications are created by calling to DCR endpoint of WSO2 IS
    OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();

    String applicationName = oAuthApplicationInfo.getClientName();
    String keyType = (String) oAuthApplicationInfo.getParameter(KeyManagerConstants.APP_KEY_TYPE);
    if (keyType != null) { //Derive oauth2 app name based on key type and user input for app name
        applicationName = applicationName + "_" + keyType;
    }

    APIUtils.logDebug("Trying to create OAuth application :", log);

    //Create json payload for DCR endpoint
    JsonObject json = new JsonObject();
    JsonArray callbackArray = new JsonArray();
    if (oAuthApplicationInfo.getCallbackUrl() != null) {
        callbackArray.add(oAuthApplicationInfo.getCallbackUrl());
    } else {
        callbackArray.add("");
    }
    json.add(KeyManagerConstants.OAUTH_REDIRECT_URIS, callbackArray);
    json.addProperty(KeyManagerConstants.OAUTH_CLIENT_NAME, applicationName);
    json.addProperty(KeyManagerConstants.OAUTH_CLIENT_OWNER, oAuthApplicationInfo.getAppOwner());
    JsonArray grantArray = new JsonArray();
    if (oAuthApplicationInfo.getGrantTypes() != null) {
        for (String grantType : oAuthApplicationInfo.getGrantTypes()) {
            grantArray.add(grantType);
        }
        json.add(KeyManagerConstants.OAUTH_CLIENT_GRANTS, grantArray);
    } else { // Temp if condition because generate keys in store application does not send any of the grant types
        grantArray.add(GRANT_TYPE_VALUE);
        json.add(KeyManagerConstants.OAUTH_CLIENT_GRANTS, grantArray);
    }

    URL url;
    HttpURLConnection urlConn = null;
    try {
        createSSLConnection();
        // Calling DCR endpoint of IS
        String dcrEndpoint = getKeyManagerEndPoint("/identity/connect/register");
        /*System.getProperty("dcrEndpoint",
        "https://localhost:9443/identity/connect/register");*/
        url = new URL(dcrEndpoint);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("content-type", "application/json");
        String clientEncoded = Base64.getEncoder().encodeToString((System.getProperty("systemUsername", "admin")
                + ":" + System.getProperty("systemUserPwd", "admin")).getBytes(StandardCharsets.UTF_8));
        urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); //temp fix
        urlConn.getOutputStream().write((json.toString()).getBytes("UTF-8"));
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 201) { //If the DCR call is success
            String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8");
            JsonParser parser = new JsonParser();
            JsonObject jObj = parser.parse(responseStr).getAsJsonObject();
            String consumerKey = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_ID).getAsString();
            String consumerSecret = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SECRET)
                    .getAsString();
            String clientName = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_NAME).getAsString();
            String grantTypes = "";
            if (jObj.has(KeyManagerConstants.OAUTH_CLIENT_GRANTS)) {
                grantTypes = jObj.getAsJsonArray(KeyManagerConstants.OAUTH_CLIENT_GRANTS).toString();
            }

            oAuthApplicationInfo.setClientName(clientName);
            oAuthApplicationInfo.setClientId(consumerKey);
            oAuthApplicationInfo.setClientSecret(consumerSecret);
            oAuthApplicationInfo.setGrantTypes(Arrays.asList(grantTypes.split(",")));

        } else { //If DCR call fails
            throw new KeyManagementException("OAuth app does not contains required data  : " + applicationName,
                    ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } catch (IOException e) {
        String errorMsg = "Can not create OAuth application  : " + applicationName;
        log.error(errorMsg, e);
        throw new KeyManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    } catch (JsonSyntaxException e) {
        String errorMsg = "Error while processing the response returned from DCR endpoint.Can not create"
                + " OAuth application : " + applicationName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) {
        String errorMsg = "Error while connecting to the DCR endpoint.Can not create" + " OAuth application : "
                + applicationName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
    return oAuthApplicationInfo;
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with message flight times.
 *
 * @return chart as base64 string./*from w ww . java2  s.  c om*/
 */
public String getBase64EncodedFlightTimeMetricsImage() {
    TimeSeries timeSeries50p = new TimeSeries("Median");
    TimeSeries timeSeries95p = new TimeSeries("95 percentile");
    TimeSeries timeSeriesMax = new TimeSeries("Max");
    for (FlightTimeMetrics m : getFlightTimeMetrics()) {
        Minute minute = new Minute(m.getPeriod());
        timeSeries50p.add(minute, m.getMedian());
        timeSeries95p.add(minute, m.getPercentile95());
        timeSeriesMax.add(minute, m.getMax());
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeries50p);
    timeSeriesCollection.addSeries(timeSeries95p);
    timeSeriesCollection.addSeries(timeSeriesMax);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Flight time", "Time", "ms",
                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());
}