List of usage examples for java.util Base64 getDecoder
public static Decoder getDecoder()
From source file:pt.ist.fenix.api.SupportFormResource.java
private void sendEmail(String from, String subject, String body, SupportBean bean) { Properties props = new Properties(); props.put("mail.smtp.host", Objects .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {/*from www.ja va2s . c om*/ message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress())); message.setSubject(subject); message.setText(body); Multipart multipart = new MimeMultipart(); { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } if (!Strings.isNullOrEmpty(bean.attachment)) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType))); messageBodyPart.setFileName(bean.fileName); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); Transport.send(message); } catch (Exception e) { logger.error("Could not send support email! Original message was: " + body, e); } }
From source file:com.exalttech.trex.ui.controllers.daemon.TRexDaemonDialogController.java
private void loadDefaultConfig() { try {/*from ww w. j av a2 s .com*/ String defaultConfigB64 = client.createRequest().id(getId()).method("get_trex_config") .returnAs(String.class).execute(); String decoded = new String(Base64.getDecoder().decode(defaultConfigB64.trim()), Charsets.US_ASCII); userConfigModel.fromYAMLString(decoded); initConfigTree(); updateYAML(); } catch (RuntimeException ex) { log(LogType.ERROR, MessageFormat.format("Unable to get default config from TRex Daemon: {0}", ex)); } catch (IOException ex) { log(LogType.ERROR, MessageFormat.format("Unable to parse received default config YAML: {0}", ex)); } }
From source file:com.streamsets.pipeline.stage.cloudstorage.origin.GoogleCloudStorageSource.java
@Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { maxBatchSize = Math.min(maxBatchSize, gcsOriginConfig.basicConfig.maxBatchSize); long minTimestamp = 0; String blobGeneratedId = ""; String fileOffset = START_FILE_OFFSET; if (!Strings.isNullOrEmpty(lastSourceOffset)) { minTimestamp = getMinTimestampFromOffset(lastSourceOffset); fileOffset = getFileOffsetFromOffset(lastSourceOffset); blobGeneratedId = getBlobIdFromOffset(lastSourceOffset); }//w w w . j av a 2 s. c om if (minMaxPriorityQueue.isEmpty()) { poolForFiles(minTimestamp, blobGeneratedId, fileOffset); } // Process Blob if (parser == null) { //Get next eligible blob to read, if none throw no more data event do { blob = minMaxPriorityQueue.pollFirst(); //We don't have any spooled files to read from and we don't have anything available from the existing parser //(in case of sdc restart with stored offset, we still want some blob to be available for us to start reading) if (blob == null) { //No more data available if (noMoreDataRecordCount > 0 || noMoreDataErrorCount > 0) { LOG.info("sending no-more-data event. records {} errors {} files {} ", noMoreDataRecordCount, noMoreDataErrorCount, noMoreDataFileCount); CommonEvents.NO_MORE_DATA.create(getContext()).with("record-count", noMoreDataRecordCount) .with("error" + "-count", noMoreDataErrorCount) .with("file-count", noMoreDataFileCount).createAndSend(); noMoreDataRecordCount = 0; noMoreDataErrorCount = 0; noMoreDataFileCount = 0; } return lastSourceOffset; } } while (!isBlobEligible(blob, minTimestamp, blobGeneratedId, fileOffset)); //If we are picking up from where we left off from previous offset //(i.e after sdc restart use the last offset, else use start file offset) fileOffset = (blobGeneratedId.equals(blob.getGeneratedId())) ? fileOffset : START_FILE_OFFSET; blobGeneratedId = blob.getGeneratedId(); if (gcsOriginConfig.dataFormat == DataFormat.WHOLE_FILE) { GCSFileRef.Builder gcsFileRefBuilder = new GCSFileRef.Builder() .bufferSize(gcsOriginConfig.dataParserFormatConfig.wholeFileMaxObjectLen) .createMetrics(true).totalSizeInBytes(blob.getSize()) .rateLimit(FileRefUtil.evaluateAndGetRateLimit(rateLimitElEval, rateLimitElVars, gcsOriginConfig.dataParserFormatConfig.rateLimit)) .blob(blob); if (gcsOriginConfig.dataParserFormatConfig.verifyChecksum) { gcsFileRefBuilder = gcsFileRefBuilder.verifyChecksum(true) .checksum(Hex.encodeHexString(Base64.getDecoder().decode(blob.getMd5()))) .checksumAlgorithm(HashingUtil.HashType.MD5); } Map<String, Object> metadata = new HashMap<>(); metadata.put(BUCKET, blob.getBucket()); metadata.put(FILE, blob.getName()); metadata.put(SIZE, blob.getSize()); Optional.ofNullable(blob.getMetadata()).ifPresent(metadata::putAll); parser = gcsOriginConfig.dataParserFormatConfig.getParserFactory().getParser(blobGeneratedId, metadata, gcsFileRefBuilder.build()); } else { parser = gcsOriginConfig.dataParserFormatConfig.getParserFactory().getParser(blobGeneratedId, Channels.newInputStream(blob.reader()), fileOffset); } minTimestamp = blob.getUpdateTime(); } try { int recordCount = 0; while (recordCount < maxBatchSize) { try { Record record = parser.parse(); if (record != null) { batchMaker.addRecord(record); fileOffset = parser.getOffset(); noMoreDataRecordCount++; recordCount++; } else { fileOffset = END_FILE_OFFSET; IOUtils.closeQuietly(parser); parser = null; noMoreDataFileCount++; break; } } catch (RecoverableDataParserException e) { LOG.error("Error when parsing record from object '{}' at offset '{}'. Reason : {}", blobGeneratedId, fileOffset, e); getContext().toError(e.getUnparsedRecord(), e.getErrorCode(), e.getParams()); } } } catch (IOException | DataParserException e) { LOG.error("Error when parsing records from Object '{}'. Reason : {}, moving to next file", blobGeneratedId, e); getContext().reportError(Errors.GCS_00, blobGeneratedId, fileOffset, e); fileOffset = END_FILE_OFFSET; noMoreDataErrorCount++; try { errorBlobHandler.handleError(blob.getBlobId()); } catch (StorageException se) { LOG.error("Error handling failed for {}. Reason{}", blobGeneratedId, e); getContext().reportError(Errors.GCS_06, blobGeneratedId, se); } } return String.format(OFFSET_FORMAT, minTimestamp, fileOffset, blobGeneratedId); }
From source file:com.simiacryptus.mindseye.lang.Tensor.java
/** * From json tensor./*from w w w . ja va 2s . c o m*/ * * @param json the json * @param resources the resources * @return the tensor */ @Nullable public static Tensor fromJson(@Nullable final JsonElement json, @Nullable Map<CharSequence, byte[]> resources) { if (null == json) return null; if (json.isJsonArray()) { final JsonArray array = json.getAsJsonArray(); final int size = array.size(); if (array.get(0).isJsonPrimitive()) { final double[] doubles = IntStream.range(0, size).mapToObj(i -> { return array.get(i); }).mapToDouble(element -> { return element.getAsDouble(); }).toArray(); @Nonnull Tensor tensor = new Tensor(doubles); assert tensor.isValid(); return tensor; } else { final List<Tensor> elements = IntStream.range(0, size).mapToObj(i -> { return array.get(i); }).map(element -> { return Tensor.fromJson(element, resources); }).collect(Collectors.toList()); @Nonnull final int[] dimensions = elements.get(0).getDimensions(); if (!elements.stream().allMatch(t -> Arrays.equals(dimensions, t.getDimensions()))) { throw new IllegalArgumentException(); } @Nonnull final int[] newDdimensions = Arrays.copyOf(dimensions, dimensions.length + 1); newDdimensions[dimensions.length] = size; @Nonnull final Tensor tensor = new Tensor(newDdimensions); @Nullable final double[] data = tensor.getData(); for (int i = 0; i < size; i++) { @Nullable final double[] e = elements.get(i).getData(); System.arraycopy(e, 0, data, i * e.length, e.length); } for (@Nonnull Tensor t : elements) { t.freeRef(); } assert tensor.isValid(); return tensor; } } else if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); @Nonnull int[] dims = fromJsonArray(jsonObject.getAsJsonArray("length")); @Nonnull Tensor tensor = new Tensor(dims); SerialPrecision precision = SerialPrecision .valueOf(jsonObject.getAsJsonPrimitive("precision").getAsString()); JsonElement base64 = jsonObject.get("base64"); if (null == base64) { if (null == resources) throw new IllegalArgumentException("No Data Resources"); CharSequence resourceId = jsonObject.getAsJsonPrimitive("resource").getAsString(); tensor.setBytes(resources.get(resourceId), precision); } else { tensor.setBytes(Base64.getDecoder().decode(base64.getAsString()), precision); } assert tensor.isValid(); JsonElement id = jsonObject.get("id"); if (null != id) { tensor.setId(UUID.fromString(id.getAsString())); } return tensor; } else { @Nonnull Tensor tensor = new Tensor(json.getAsJsonPrimitive().getAsDouble()); assert tensor.isValid(); return tensor; } }
From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStream.java
/** * Initializes the cipher with the object's IV. * * @return number of bytes to skip ahead after initialization */// ww w.j a v a 2s . c om private long initializeCipher() { String ivString = getHeaderAsString(MantaHttpHeaders.ENCRYPTION_IV); if (ivString == null || ivString.isEmpty()) { String msg = "Initialization Vector (IV) was not set for the object. Unable to decrypt."; MantaClientEncryptionException e = new MantaClientEncryptionException(msg); annotateException(e); throw e; } byte[] iv = Base64.getDecoder().decode(ivString); if (LOGGER.isTraceEnabled()) { LOGGER.trace("IV: {}", Hex.encodeHexString(iv)); } final int mode = Cipher.DECRYPT_MODE; try { this.cipher.init(mode, secretKey, cipherDetails.getEncryptionParameterSpec(iv)); if (startPosition != null && startPosition > 0) { return cipherDetails.updateCipherToPosition(this.cipher, startPosition); } else { return 0L; } } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { String msg = "Error initializing cipher"; MantaClientEncryptionException mce = new MantaClientEncryptionException(msg, e); annotateException(mce); throw mce; } }
From source file:org.dragonet.proxy.protocol.packet.LoginPacket.java
private JSONObject decodeToken(String token) throws JSONException, IOException { String[] base = token.split("\\."); String strToken = new String(Base64.getDecoder().decode(base[1]), "UTF-8"); //System.out.println(" decoded: " + strToken); if (base.length < 2) { return null; }//from w ww .j a v a 2 s . co m return new JSONObject(strToken); }
From source file:org.apache.syncope.core.spring.security.Encryptor.java
public String decode(final String encodedValue, final CipherAlgorithm cipherAlgorithm) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String value = null;/*from w w w .ja v a2s.c om*/ if (encodedValue != null && cipherAlgorithm == CipherAlgorithm.AES) { final byte[] encoded = encodedValue.getBytes(StandardCharsets.UTF_8); final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, keySpec); value = new String(cipher.doFinal(Base64.getDecoder().decode(encoded)), StandardCharsets.UTF_8); } return value; }
From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java
/** * Decodes the cookie and splits it into a set of token strings using the ":" * delimiter./* w ww. j a v a 2 s. c o m*/ * * @param cookieValue the value obtained from the submitted cookie * @return the array of tokens. * @throws InvalidCookieException if the cookie was not base64 encoded. */ protected String[] decodeCookie(String cookieValue) throws InvalidCookieException { for (int j = 0; j < cookieValue.length() % 4; j++) { cookieValue = cookieValue + "="; } try { Base64.getDecoder().decode(cookieValue.getBytes()); } catch (IllegalArgumentException e) { throw new InvalidCookieException( "Cookie token was not Base64 encoded; value was '" + cookieValue + "'"); } String cookieAsPlainText = new String(Base64.getDecoder().decode(cookieValue.getBytes())); String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER); for (int i = 0; i < tokens.length; i++) { try { tokens[i] = URLDecoder.decode(tokens[i], StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } } return tokens; }
From source file:org.apache.spark.streaming.amqp.JavaAMQPBrokerStreamSuite.java
@Test public void testAMQPReceiveBinaryBody() { Function converter = new JavaAMQPJsonFunction(); String sendMessage = "Spark Streaming & AMQP"; JavaReceiverInputDStream<String> receiveStream = AMQPUtils.createStream(this.jssc, this.amqpTestUtils.host(), this.amqpTestUtils.port(), this.address, converter, StorageLevel.MEMORY_ONLY()); JavaDStream<String> binaryStream = receiveStream.map(jsonMsg -> { ObjectMapper mapper = new ObjectMapper(); String body = new String( Base64.getDecoder().decode(mapper.readTree(jsonMsg).get("body").get("section").asText())); return body; });//from w w w . j a v a2s . c o m List<String> receivedMessage = new ArrayList<>(); binaryStream.foreachRDD(rdd -> { if (!rdd.isEmpty()) { receivedMessage.add(rdd.first()); } }); jssc.start(); this.amqpTestUtils.sendBinaryMessage(address, sendMessage.getBytes()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } assert (receivedMessage.get(0).equals(sendMessage)); jssc.stop(); }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding//from w w w .j av a 2 s . co m * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String decryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String decPass = null; try { String decoded = new String(Base64.getDecoder().decode(value)); String iv = decoded.split(":")[0]; String property = decoded.split(":")[1]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv))); decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidAlgorithmParameterException iapx) { throw new SecurityException(iapx.getMessage(), iapx); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } return decPass; }