List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:com.jrestless.aws.gateway.handler.GatewayRequestObjectHandlerIntTest.java
@Test public void testBase64Decoding() { DefaultGatewayRequest request = new DefaultGatewayRequestBuilder().httpMethod("PUT") .resource("/binary-data") .body(new String(Base64.getEncoder().encode("test".getBytes()), StandardCharsets.UTF_8)) .base64Encoded(true).build(); handler.handleRequest(request, context); verify(testService).binaryData("test".getBytes()); }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java
License:asdf
@Test public void testAddKeyJks() throws KeystoreEditor.KeystoreEditorException, IOException { KeystoreEditor keystoreEditor = new KeystoreEditor(); FileInputStream fileInputStream = new FileInputStream(jksFile); byte[] keyBytes = IOUtils.toByteArray(fileInputStream); IOUtils.closeQuietly(fileInputStream); keystoreEditor.addPrivateKey("asdf", password, password, Base64.getEncoder().encodeToString(keyBytes), "", jksFile.toString());//from ww w. j a v a2s. co m 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:org.apache.pulsar.functions.sink.PulsarSink.java
@Override public void write(Record<T> record) throws Exception { TypedMessageBuilder<T> msg = pulsarSinkProcessor.newMessage(record); if (record.getKey().isPresent()) { msg.key(record.getKey().get());// www. jav a 2 s .c om } msg.value(record.getValue()); if (!record.getProperties().isEmpty()) { msg.properties(record.getProperties()); } SinkRecord<T> sinkRecord = (SinkRecord<T>) record; if (sinkRecord.getSourceRecord() instanceof PulsarRecord) { PulsarRecord<T> pulsarRecord = (PulsarRecord<T>) sinkRecord.getSourceRecord(); // forward user properties to sink-topic msg.property("__pfn_input_topic__", pulsarRecord.getTopicName().get()).property("__pfn_input_msg_id__", new String(Base64.getEncoder().encode(pulsarRecord.getMessageId().toByteArray()))); } else { // It is coming from some source Optional<Long> eventTime = sinkRecord.getSourceRecord().getEventTime(); if (eventTime.isPresent()) { msg.eventTime(eventTime.get()); } } pulsarSinkProcessor.sendOutputMessage(msg, record); }
From source file:org.apache.samza.execution.JobNode.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 *//*from w ww . j a v a 2 s . c om*/ void addSerdeConfigs(Map<String, String> configs) { // collect all key and msg serde instances for streams Map<String, Serde> streamKeySerdes = new HashMap<>(); Map<String, Serde> streamMsgSerdes = new HashMap<>(); Map<StreamSpec, InputOperatorSpec> inputOperators = streamGraph.getInputOperators(); inEdges.forEach(edge -> { String streamId = edge.getStreamSpec().getId(); InputOperatorSpec inputOperatorSpec = inputOperators.get(edge.getStreamSpec()); streamKeySerdes.put(streamId, inputOperatorSpec.getKeySerde()); streamMsgSerdes.put(streamId, inputOperatorSpec.getValueSerde()); }); Map<StreamSpec, OutputStreamImpl> outputStreams = streamGraph.getOutputStreams(); outEdges.forEach(edge -> { String streamId = edge.getStreamSpec().getId(); OutputStreamImpl outputStream = outputStreams.get(edge.getStreamSpec()); streamKeySerdes.put(streamId, outputStream.getKeySerde()); streamMsgSerdes.put(streamId, outputStream.getValueSerde()); }); // collect all key and msg serde instances for stores Map<String, Serde> storeKeySerdes = new HashMap<>(); Map<String, Serde> storeMsgSerdes = new HashMap<>(); streamGraph.getAllOperatorSpecs().forEach(opSpec -> { if (opSpec instanceof StatefulOperatorSpec) { ((StatefulOperatorSpec) opSpec).getStoreDescriptors().forEach(storeDescriptor -> { storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde()); storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde()); }); } }); // collect all key and msg serde instances for tables Map<String, Serde> tableKeySerdes = new HashMap<>(); Map<String, Serde> tableValueSerdes = new HashMap<>(); tables.forEach(tableSpec -> { tableKeySerdes.put(tableSpec.getId(), tableSpec.getSerde().getKeySerde()); tableValueSerdes.put(tableSpec.getId(), tableSpec.getSerde().getValueSerde()); }); // 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(tableValueSerdes.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 tables to the serde names generated above tableKeySerdes.forEach((tableId, serde) -> { String keySerdeConfigKey = String.format(JavaTableConfig.TABLE_KEY_SERDE, tableId); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); tableValueSerdes.forEach((tableId, serde) -> { String valueSerdeConfigKey = String.format(JavaTableConfig.TABLE_VALUE_SERDE, tableId); configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde)); }); }
From source file:org.codice.ddf.security.idp.client.IdpHandler.java
private String encodePostRequest(String request) throws WSSecurityException, IOException { return Base64.getEncoder().encodeToString(request.getBytes(StandardCharsets.UTF_8)); }
From source file:org.egov.mrs.web.controller.application.registration.UpdateMarriageRegistrationController.java
private void buildMrgRegistrationUpdateResult(final MarriageRegistration marriageRegistration, final Model model) { if (LOGGER.isInfoEnabled()) LOGGER.info("..........InsidebuildMrgRegistrationUpdateResult........ " + marriageRegistration.getApplicationNo()); if (!marriageRegistration.isLegacy()) { if (LOGGER.isInfoEnabled()) LOGGER.info("..........No legacy entry........ "); final AppConfigValues allowValidation = marriageFeeService.getDaysValidationAppConfValue(MODULE_NAME, MARRIAGEREGISTRATION_DAYS_VALIDATION); model.addAttribute("allowDaysValidation", allowValidation != null && !allowValidation.getValue().isEmpty() ? allowValidation.getValue() : "NO"); } else/*from ww w. j a v a2 s. c om*/ model.addAttribute("allowDaysValidation", "NO"); if (LOGGER.isInfoEnabled()) LOGGER.info(".........prepareDocumentsForView........ "); marriageRegistrationService.prepareDocumentsForView(marriageRegistration); marriageApplicantService.prepareDocumentsForView(marriageRegistration.getHusband()); marriageApplicantService.prepareDocumentsForView(marriageRegistration.getWife()); model.addAttribute("applicationHistory", marriageRegistrationService.getHistory(marriageRegistration)); if (LOGGER.isInfoEnabled()) LOGGER.info(".........before prepareWorkFlowForNewMarriageRegistration........ "); prepareWorkFlowForNewMarriageRegistration(marriageRegistration, model); marriageRegistration.getWitnesses().forEach(witness -> { try { if (witness.getPhotoFileStore() != null) { final File file = fileStoreService.fetch(witness.getPhotoFileStore().getFileStoreId(), FILESTORE_MODULECODE); if (file != null) witness.setEncodedPhoto( Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(file))); } } catch (final IOException e) { LOG.error("Error while preparing the document for view", e); } }); if (LOGGER.isInfoEnabled()) LOGGER.info(".........after prepare Witnesses........ "); model.addAttribute(MARRIAGE_REGISTRATION, marriageRegistration); }
From source file:org.iexhub.connectors.PIXManager.java
/** * @param patientId/*from w w w. j a va2s . com*/ * @throws IOException */ private void logIti44AuditMsg(String patientId) throws IOException { String logMsg = FileUtils.readFileToString(new File(iti44AuditMsgTemplate)); // Substitutions... patientId = patientId.replace("'", ""); patientId = patientId.replace("&", "&"); 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$", PIXManager.endpointUri); logMsg = logMsg.replace("$DestinationUserId$", "IExHub"); logMsg = logMsg.replace("$PatientIdMtom$", Base64.getEncoder().encodeToString(patientId.getBytes())); logMsg = logMsg.replace("$PatientId$", patientId); if (logSyslogAuditMsgsLocally) { log.info(logMsg); } if ((sysLogConfig == null) || (iti44AuditMsgTemplate == null)) { return; } // Log the syslog message and close connection Syslog.getInstance("sslTcp").info(logMsg); Syslog.getInstance("sslTcp").flush(); }
From source file:com.jrestless.aws.gateway.handler.GatewayRequestObjectHandlerIntTest.java
@Test public void testEncodedBase64Decoding() throws IOException { DefaultGatewayRequest request = new DefaultGatewayRequestBuilder().httpMethod("PUT") .resource("/binary-data") .body(new String(Base64.getEncoder().encode("test".getBytes()), StandardCharsets.UTF_8)) .base64Encoded(true).headers(Collections.singletonMap(HttpHeaders.CONTENT_ENCODING, "gzip")) .build();//www. j a v a 2s . c o m ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPOutputStream zipOut = new GZIPOutputStream(baos, true)) { zipOut.write("test".getBytes()); } // finish + flush request.setBody(Base64.getEncoder().encodeToString(baos.toByteArray())); handler.handleRequest(request, context); verify(testService).binaryData("test".getBytes()); }
From source file:org.mycore.common.content.MCRContent.java
/** * Uses provided parameter to compute simple weak ETag. * //from w w w . jav a 2 s .co m * @param systemId * != null, {@link #getSystemId()} * @param length * >= 0, {@link #length()} * @param lastModified * >= 0, {@link #lastModified()} * @return null if any preconditions are not met. */ protected String getSimpleWeakETag(String systemId, long length, long lastModified) { if (systemId == null || length < 0 || lastModified < 0) { return null; } StringBuilder b = new StringBuilder(32); b.append("W/\""); long lhash = systemId.hashCode(); byte[] unencodedETag = ByteBuffer.allocate(Long.SIZE / 4).putLong(lastModified ^ lhash) .putLong(length ^ lhash).array(); b.append(Base64.getEncoder().encodeToString(unencodedETag)); b.append('"'); return b.toString(); }
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceTest.java
private String getBasicAuthorizationHeader() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Encoder base64Encoder = Base64.getEncoder(); String encodedCredentials = base64Encoder.encodeToString( (authentication.getName() + ':' + (String) authentication.getCredentials()).getBytes()); return "Basic " + encodedCredentials; }