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:software.coolstuff.springframework.owncloud.service.impl.AbstractOwncloudServiceTest.java

protected final String getSecurityContextBasicAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return "Basic " + Base64.getEncoder()
            .encodeToString((authentication.getName() + ":" + authentication.getCredentials()).getBytes());
}

From source file:com.viettel.util.doc.DocsUtility.java

public String getBase64Pdf() throws IOException {

    String pdfFile = saveToPdf();
    String base64File = "";

    try (InputStream is = new FileInputStream(pdfFile)) {
        base64File = Base64.getEncoder().encodeToString(IOUtils.toByteArray(is));
    }/*w  ww.j a va2  s .c  om*/

    new File(pdfFile).delete();
    return base64File;
}

From source file:org.sakaiproject.gradebookng.tool.model.GbGradebookData.java

private String serializeSmallGrades(final List<Score> gradeList) {
    final StringBuilder sb = new StringBuilder();

    for (final Score score : gradeList) {
        if (score == null || score.isNull()) {
            // No grade set. Use a sentinel value.
            sb.appendCodePoint(this.NULL_SENTINEL);
            continue;
        }/*w w  w .j  a  va  2s .c  o  m*/

        final double grade = score.getScore();

        if (grade < 0) {
            throw new IllegalStateException("serializeSmallGrades doesn't support negative scores");
        }

        final boolean hasFraction = ((int) grade != grade);

        if (grade < 127 && !hasFraction) {
            // single byte, no fraction
            //
            // input number like 0nnnnnnn serialized as 0nnnnnnn
            sb.appendCodePoint((int) grade & 0xFF);
        } else if (grade < 16384 && !hasFraction) {
            // two byte, no fraction
            //
            // input number like 00nnnnnn nnnnnnnn serialized as 10nnnnnn nnnnnnnn
            //
            // where leading '10' means 'two bytes, no fraction part'
            sb.appendCodePoint(((int) grade >> 8) | 0b10000000);
            sb.appendCodePoint(((int) grade & 0xFF));
        } else if (grade < 16384) {
            // three byte encoding, fraction
            //
            // input number like 00nnnnnn nnnnnnnn.25 serialized as 11nnnnnn nnnnnnnn 00011001
            //
            // where leading '11' means 'two bytes plus a fraction part',
            // and the fraction part is stored as an integer between 0-99,
            // where 50 represents 0.5, 25 represents .25, etc.

            sb.appendCodePoint(((int) grade >> 8) | 0b11000000);
            sb.appendCodePoint((int) grade & 0xFF);
            sb.appendCodePoint((int) Math.round((grade * 100) - ((int) grade * 100)));
        } else {
            throw new RuntimeException("Grade too large: " + grade);
        }
    }

    try {
        return Base64.getEncoder().encodeToString(sb.toString().getBytes("ISO-8859-1"));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * @param documentId/*from w w w .j a  v a 2s . c o m*/
 * @param repositoryUniqueId
 * @param homeCommunityId
 * @param patientId
 * @throws IOException
 */
private void logIti43AuditMsg(String documentId, String repositoryUniqueId, String homeCommunityId,
        String patientId) throws IOException {
    String logMsg = FileUtils.readFileToString(new File(iti43AuditMsgTemplate));

    // 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");

    // Repository ID text must be Base64 encoded...
    logMsg = logMsg.replace("$RepositoryIdMtom$",
            Base64.getEncoder().encodeToString(repositoryUniqueId.getBytes()));

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

    logMsg = logMsg.replace("$DocumentId$", documentId);

    if (homeCommunityId != null) {
        logMsg = logMsg.replace("$HomeCommunityId$", homeCommunityId);
    } else {
        logMsg = logMsg.replace("$HomeCommunityId$", "");
    }

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

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

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

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

License:asdf

@Test
public void testReplaceSystemStores() throws Exception {
    KeystoreEditor keystoreEditor = new KeystoreEditor();
    Assert.assertThat(keystoreEditor.getKeystore().size(), Is.is(0));
    Assert.assertThat(keystoreEditor.getTruststore().size(), Is.is(0));

    try (FileInputStream keystoreInputStream = new FileInputStream(systemKeystoreFile);
            FileInputStream truststoreInputStream = new FileInputStream(systemTruststoreFile);) {
        byte[] keystoreCrtBytes = IOUtils.toByteArray(keystoreInputStream);
        byte[] keystoreEncodedBytes = Base64.getEncoder().encode(keystoreCrtBytes);
        byte[] truststoreCrtBytes = IOUtils.toByteArray(truststoreInputStream);
        byte[] truststoreEncodedBytes = Base64.getEncoder().encode(truststoreCrtBytes);
        List<String> errors = keystoreEditor.replaceSystemStores("localhost", password, password,
                new String(keystoreEncodedBytes), systemKeystoreFile.getName(), password,
                new String(truststoreEncodedBytes), systemTruststoreFile.getName());
        Assert.assertThat(errors.size(), Is.is(0));
        List<Map<String, Object>> keystore = keystoreEditor.getKeystore();
        List<Map<String, Object>> truststore = keystoreEditor.getTruststore();
        Assert.assertThat(keystore.size(), Is.is(2));
        String alias1 = (String) keystore.get(0).get("alias");
        String alias2 = (String) keystore.get(1).get("alias");
        Assert.assertThat(alias1, AnyOf.anyOf(Is.is("localhost"), Is.is("ddf demo root ca")));
        Assert.assertThat(alias2, AnyOf.anyOf(Is.is("localhost"), Is.is("ddf demo root ca")));
        Assert.assertThat(truststore.get(0).get("alias"), Is.is("ddf demo root ca"));
    }//ww w  .jav a2 s  . co  m
}

From source file:org.elasticsearch.ingest.attachment.AttachmentProcessorTests.java

protected String getAsBase64(String filename) throws Exception {
    String path = "/org/elasticsearch/ingest/attachment/test/sample-files/" + filename;
    try (InputStream is = AttachmentProcessorTests.class.getResourceAsStream(path)) {
        byte bytes[] = IOUtils.toByteArray(is);
        return Base64.getEncoder().encodeToString(bytes);
    }/*from  w  w  w  .j  a  va 2  s  . c om*/
}

From source file:org.apache.samza.execution.JobNodeConfigurationGenerator.java

/**
 * Serializes the {@link Serde} instances for operators, adds them to the provided config, and
 * sets the serde configuration for the input/output/intermediate streams appropriately.
 *
 * We try to preserve the number of Serde instances before and after serialization. However we don't
 * guarantee that references shared between these serdes instances (e.g. an Jackson ObjectMapper shared
 * between two json serdes) are shared after deserialization too.
 *
 * Ideally all the user defined objects in the application should be serialized and de-serialized in one pass
 * from the same output/input stream so that we can maintain reference sharing relationships.
 *
 * @param configs the configs to add serialized serde instances and stream serde configs to
 *//*  w w  w  . ja va2 s. c om*/
private void configureSerdes(Map<String, String> configs, Map<String, StreamEdge> inEdges,
        Map<String, StreamEdge> outEdges, List<StoreDescriptor> stores, Collection<String> tables,
        JobNode jobNode) {
    // collect all key and msg serde instances for streams
    Map<String, Serde> streamKeySerdes = new HashMap<>();
    Map<String, Serde> streamMsgSerdes = new HashMap<>();
    inEdges.keySet().forEach(streamId -> addSerdes(jobNode.getInputSerdes(streamId), streamId, streamKeySerdes,
            streamMsgSerdes));
    outEdges.keySet().forEach(streamId -> addSerdes(jobNode.getOutputSerde(streamId), streamId, streamKeySerdes,
            streamMsgSerdes));

    Map<String, Serde> storeKeySerdes = new HashMap<>();
    Map<String, Serde> storeMsgSerdes = new HashMap<>();
    stores.forEach(storeDescriptor -> {
        storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde());
        storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde());
    });

    Map<String, Serde> tableKeySerdes = new HashMap<>();
    Map<String, Serde> tableMsgSerdes = new HashMap<>();
    tables.forEach(tableId -> {
        addSerdes(jobNode.getTableSerdes(tableId), tableId, tableKeySerdes, tableMsgSerdes);
    });

    // for each unique stream or store serde instance, generate a unique name and serialize to config
    HashSet<Serde> serdes = new HashSet<>(streamKeySerdes.values());
    serdes.addAll(streamMsgSerdes.values());
    serdes.addAll(storeKeySerdes.values());
    serdes.addAll(storeMsgSerdes.values());
    serdes.addAll(tableKeySerdes.values());
    serdes.addAll(tableMsgSerdes.values());
    SerializableSerde<Serde> serializableSerde = new SerializableSerde<>();
    Base64.Encoder base64Encoder = Base64.getEncoder();
    Map<Serde, String> serdeUUIDs = new HashMap<>();
    serdes.forEach(serde -> {
        String serdeName = serdeUUIDs.computeIfAbsent(serde,
                s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString());
        configs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE(), serdeName),
                base64Encoder.encodeToString(serializableSerde.toBytes(serde)));
    });

    // set key and msg serdes for streams to the serde names generated above
    streamKeySerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String keySerdeConfigKey = streamIdPrefix + StreamConfig.KEY_SERDE();
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    streamMsgSerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String valueSerdeConfigKey = streamIdPrefix + StreamConfig.MSG_SERDE();
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for stores to the serde names generated above
    storeKeySerdes.forEach((storeName, serde) -> {
        String keySerdeConfigKey = String.format(StorageConfig.KEY_SERDE, storeName);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    storeMsgSerdes.forEach((storeName, serde) -> {
        String msgSerdeConfigKey = String.format(StorageConfig.MSG_SERDE, storeName);
        configs.put(msgSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for stores to the serde names generated above
    tableKeySerdes.forEach((tableId, serde) -> {
        String keySerdeConfigKey = String.format(JavaTableConfig.STORE_KEY_SERDE, tableId);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    tableMsgSerdes.forEach((tableId, serde) -> {
        String valueSerdeConfigKey = String.format(JavaTableConfig.STORE_MSG_SERDE, tableId);
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });
}

From source file:SdkUnitTests.java

@Test
public void CreateTemplateTest() {

    byte[] fileBytes = null;
    File f = null;//from w  w w.  j  a v a 2 s  .  c o  m
    try {
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);

        f = new File(path.toString());
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed

    EnvelopeTemplate templateDef = new EnvelopeTemplate();
    templateDef.setEmailSubject("Please Sign my Java SDK Envelope");
    templateDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    templateDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setRoleName("Signer1");
    signer.setRecipientId("1");

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    templateDef.setRecipients(new Recipients());
    templateDef.getRecipients().setSigners(new ArrayList<Signer>());
    templateDef.getRecipients().getSigners().add(signer);

    EnvelopeTemplateDefinition envTemplateDef = new EnvelopeTemplateDefinition();
    envTemplateDef.setName("myTemplate");
    templateDef.setEnvelopeTemplateDefinition(envTemplateDef);

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();
        LoginInformation loginInfo = authApi.login();

        Assert.assertNotNull(loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        TemplatesApi templatesApi = new TemplatesApi();
        TemplateSummary templateSummary = templatesApi.createTemplate(accountId, templateDef);

        Assert.assertNotNull(templateSummary);
        Assert.assertNotNull(templateSummary.getTemplateId());

        System.out.println("TemplateSummary: " + templateSummary);

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }
}

From source file:org.javabeanstack.util.Strings.java

/**
 * Codifica una cadena a base 64/*w  w w. j av a2  s  .com*/
 * @param message cadena
 * @return cadena codificada.
 */
public static String encode64(String message) {
    if (message == null) {
        return null;
    }
    Base64.Encoder encoder = Base64.getEncoder();
    byte[] encodeContent = encoder.encode(message.getBytes());
    return new String(encodeContent);
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java

private String createUaaToken(String clientId, String clientSecret) throws DashboardServiceException {
    LOGGER.info("Creating new UAA token");

    String autorizationString = clientId + ":" + clientSecret;
    autorizationString = new String(Base64.getEncoder().encode(autorizationString.getBytes()));
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER, "Basic " + autorizationString);
    headers.add(CONTENT_TYPE_HEADER, "application/x-www-form-urlencoded");

    ResponseEntity<String> response = executeWithHeaders(CREATE_UAA_TOKEN_URL, HttpMethod.POST,
            CREATE_UAA_TOKEN_BODY_TEMPLATE, headers, uaaTokenApiEndpoint);
    String uaaToken;//  www. j  a  v a 2  s  . c o  m
    try {
        uaaToken = cfCaller.getValueFromJson(response.getBody(), UAA_TOKEN_TYPE) + " "
                + cfCaller.getValueFromJson(response.getBody(), UAA_ACCESS_TOKEN);
    } catch (IOException e) {
        throw new DashboardServiceException("Cannot obtain UAA token.", e);
    }
    LOGGER.debug("UAA access token has been obtained.");
    return uaaToken;
}