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.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

public void refreshToken() {
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
    // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in
    builder.queryParam("grant_type", "refresh_token");
    builder.queryParam("refresh_token", refreshToken);

    // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
    HttpHeaders headers = new HttpHeaders();
    Encoder encoder = Base64.getEncoder();
    headers.add("Authorization",
            "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));

    HttpEntity<String> entity = new HttpEntity<>("", headers);
    ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, OAuth2AccessToken.class);

    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);//from w ww. j a  va2s .c o m

    refreshToken = result2.getBody().getRefreshToken().getValue();
    assertNotNull(refreshToken);
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdminTest.java

@Test(expected = FederationAdminException.class)
public void testCreateLocalEntryStringWithTransformerException() throws Exception {
    String encodeThisString = "aPretendXmlRegistryPackage";
    String base64EncodedString = Base64.getEncoder().encodeToString(encodeThisString.getBytes());

    when(registryTransformer.transform(any(InputStream.class))).thenThrow(CatalogTransformerException.class);

    federationAdmin.createLocalEntry(base64EncodedString);

    verify(registryTransformer).transform(any(InputStream.class));
    verify(federationAdminService, never()).addRegistryEntry(any(Metacard.class));
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java

License:asdf

@Test
public void testAddKeyP12() throws KeystoreEditor.KeystoreEditorException, IOException {
    KeystoreEditor keystoreEditor = new KeystoreEditor();
    FileInputStream fileInputStream = new FileInputStream(pkcs12StoreFile);
    byte[] keyBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addPrivateKey("asdf", password, password, Base64.getEncoder().encodeToString(keyBytes),
            KeystoreEditor.PKCS12_TYPE, pkcs12StoreFile.toString());
    List<Map<String, Object>> keystore = keystoreEditor.getKeystore();
    Assert.assertThat(keystore.size(), Is.is(1));
    Assert.assertThat((String) keystore.get(0).get("alias"), Is.is("asdf"));

    List<Map<String, Object>> truststore = keystoreEditor.getTruststore();
    Assert.assertThat(truststore.size(), Is.is(0));
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }//  w w  w  .  j a v a2s  . com
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());
    boolean isKeyCol = false;

    boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, Element> keyCols = new TreeMap<String, Element>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];
            String colName = colNames[j];

            isKeyCol = (!noKey && keyField.contains(new Integer(j)));
            isNull = false;
            col = parser.createElementNS(doc, colName, NS);
            if (isKeyCol) {
                parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j));
            }
            switch (metadata.getColumnType(j)) {
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                isNull = dateVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat());
                        textVal = fF.formatDate(dateVal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                        textVal = dateFormatter.format(dateVal);
                    }
                }
            }
                break;
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                if (fF != null) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                    textVal = fF.formatNumber(numVal);
                } else {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                    textVal = numberFormatter.format(numVal);
                }
            }
                break;
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.NUMERIC:
            case Types.SMALLINT:
            case Types.TINYINT: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (isKeyCol) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyCols.put(String.valueOf(j), col);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS);
            data.appendChild(key);
            for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) {
                key.appendChild(keyColsEntry.getValue());
            }
            keyCols.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*from   ww w . java 2 s  .  c  o m*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:net.sourceforge.fenixedu.webServices.jersey.api.FenixAPIv1.java

private FenixPhoto getPhoto(final Person person) {
    FenixPhoto photo = null;/* w  ww  .  ja  v a2s.  c  om*/
    try {
        final Photograph personalPhoto = person.getPersonalPhoto();
        if (person.isPhotoAvailableToCurrentUser()) {
            final byte[] avatar = personalPhoto.getDefaultAvatar();
            String type = ContentType.PNG.getMimeType();
            String data = Base64.getEncoder().encodeToString(avatar);
            photo = new FenixPhoto(type, data);
        }
    } catch (Exception npe) {
    }
    return photo;
}

From source file:org.silverpeas.core.util.StringUtil.java

/**
 * Encodes the specified binary data into a text of Base64 characters.
 *
 * @param binaryData the binary data to convert in Base64-based String.
 * @return a String representation of the binary data in Base64 characters.
 *///from w  w w.  j  a  v a 2 s.  c o  m
public static String asBase64(byte[] binaryData) {
    return Base64.getEncoder().encodeToString(binaryData);
}

From source file:org.iexhub.connectors.PDQQueryManager.java

/**
 * @param queryText//from  w w  w  .j av  a 2s . c o  m
 * @param patientId
 * @throws IOException
 */
private void logIti47AuditMsg(String queryText, String patientId) throws IOException {
    String logMsg = FileUtils.readFileToString(new File(iti47AuditMsgTemplate));

    // Substitutions...
    patientId = patientId.replace("'", "");
    patientId = patientId.replace("&", "&amp;");

    DateTime now = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    logMsg = logMsg.replace("$DateTime$", fmt.print(now));

    logMsg = logMsg.replace("$AltUserId$", "IExHub");

    logMsg = logMsg.replace("$IexhubIpAddress$", InetAddress.getLocalHost().getHostAddress());

    logMsg = logMsg.replace("$IexhubUserId$", "http://" + InetAddress.getLocalHost().getCanonicalHostName());

    logMsg = logMsg.replace("$DestinationIpAddress$", PDQQueryManager.endpointUri);

    logMsg = logMsg.replace("$DestinationUserId$", "IExHub");

    logMsg = logMsg.replace("$PatientIdMtom$", Base64.getEncoder().encodeToString(patientId.getBytes()));

    logMsg = logMsg.replace("$QueryByParameterMtom$", Base64.getEncoder().encodeToString(queryText.getBytes()));

    logMsg = logMsg.replace("$PatientId$", patientId);

    if (logSyslogAuditMsgsLocally) {
        log.info(logMsg);
    }

    if ((sysLogConfig == null) || (iti47AuditMsgTemplate == null)) {
        return;
    }

    // Log the syslog message and close connection
    Syslog.getInstance("sslTcp").info(logMsg);
    Syslog.getInstance("sslTcp").flush();
}

From source file:org.iexhub.connectors.XdsB.java

/**
 * @param queryText//  w  ww  . j a  v a2  s.c  om
 * @param patientId
 * @throws IOException
 */
private void logIti18AuditMsg(String queryText, String patientId) throws IOException {
    String logMsg = FileUtils.readFileToString(new File(iti18AuditMsgTemplate));

    // Substitutions...
    if ((patientId != null) && (patientId.length() > 0)) {
        patientId = patientId.replace("'", "");
        patientId = patientId.replace("&", "&amp;");
    } else {
        patientId = new String("");
    }

    DateTime now = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    logMsg = logMsg.replace("$DateTime$", fmt.print(now));

    logMsg = logMsg.replace("$AltUserId$", "IExHub");

    logMsg = logMsg.replace("$IexhubIpAddress$", InetAddress.getLocalHost().getHostAddress());

    logMsg = logMsg.replace("$IexhubUserId$", "http://" + InetAddress.getLocalHost().getCanonicalHostName());

    logMsg = logMsg.replace("$DestinationIpAddress$", XdsB.registryEndpointUri);

    logMsg = logMsg.replace("$DestinationUserId$", "IExHub");

    // Query text must be Base64 encoded...
    logMsg = logMsg.replace("$RegistryQueryMtom$", Base64.getEncoder().encodeToString(queryText.getBytes()));

    logMsg = logMsg.replace("$PatientId$", patientId);

    if (logSyslogAuditMsgsLocally) {
        log.info(logMsg);
    }

    if ((sysLogConfig == null) || (iti18AuditMsgTemplate == null)) {
        return;
    }

    // Log the syslog message and close connection
    Syslog.getInstance("sslTcp").info(logMsg);
    Syslog.getInstance("sslTcp").flush();
}

From source file:com.joyent.manta.client.crypto.EncryptingEntityTest.java

private void validateCiphertext(SupportedCipherDetails cipherDetails, SecretKey secretKey, byte[] plaintext,
        byte[] iv, byte[] ciphertext) throws IOException {
    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength((long) ciphertext.length);

    if (!cipherDetails.isAEADCipher()) {
        responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE,
                SupportedHmacsLookupMap.hmacNameFromInstance(cipherDetails.getAuthenticationHmac()));
    }/*  ww w  . java  2s. c  o  m*/
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV, Base64.getEncoder().encodeToString(iv));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    final MantaEncryptedObjectInputStream decryptingStream = new MantaEncryptedObjectInputStream(
            new MantaObjectInputStream(new MantaObjectResponse("/path", responseHttpHeaders),
                    Mockito.mock(CloseableHttpResponse.class),
                    new EofSensorInputStream(new ByteArrayInputStream(ciphertext), null)),
            cipherDetails, secretKey, true);

    ByteArrayOutputStream decrypted = new ByteArrayOutputStream();
    IOUtils.copy(decryptingStream, decrypted);
    decryptingStream.close();
    AssertJUnit.assertArrayEquals(plaintext, decrypted.toByteArray());
}