List of usage examples for java.io ByteArrayOutputStream close
public void close() throws IOException
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>/*from ww w . java 2s . c o m*/ * * </p> * * @param data ?? * @param publicKey (BASE64?) * @return byte * @throws Exception Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // ? Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int index = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); index++; offSet = index * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
From source file:com.streamsets.pipeline.lib.util.ProtobufTypeUtil.java
/** * Converts a protobuf message to an SDC Record Field. * * @param record SDC Record to add field to * @param fieldPath location in record where to insert field. * @param descriptor protobuf descriptor instance * @param messageTypeToExtensionMap protobuf extensions map * @param message message to decode and insert into the specified field path * @return new Field instance representing the decoded message * @throws DataParserException/*from w ww. j ava 2 s . c om*/ */ public static Field protobufToSdcField(Record record, String fieldPath, Descriptors.Descriptor descriptor, Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap, Object message) throws DataParserException { Map<String, Field> sdcRecordMapFieldValue = new HashMap<>(); // get all the expected fields from the proto file Map<String, Descriptors.FieldDescriptor> protobufFields = new LinkedHashMap<>(); for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) { protobufFields.put(fieldDescriptor.getName(), fieldDescriptor); } // get all fields in the read message Map<Descriptors.FieldDescriptor, Object> values = ((DynamicMessage) message).getAllFields(); // for every field present in the proto definition create an sdc field. for (Descriptors.FieldDescriptor fieldDescriptor : protobufFields.values()) { Object value = values.get(fieldDescriptor); sdcRecordMapFieldValue.put(fieldDescriptor.getName(), createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value)); } // handle applicable extensions for this message type if (messageTypeToExtensionMap.containsKey(descriptor.getFullName())) { for (Descriptors.FieldDescriptor fieldDescriptor : messageTypeToExtensionMap .get(descriptor.getFullName())) { if (values.containsKey(fieldDescriptor)) { Object value = values.get(fieldDescriptor); sdcRecordMapFieldValue.put(fieldDescriptor.getName(), createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value)); } } } // handle unknown fields // unknown fields can go into the record header UnknownFieldSet unknownFields = ((DynamicMessage) message).getUnknownFields(); if (!unknownFields.asMap().isEmpty()) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { unknownFields.writeDelimitedTo(bOut); bOut.flush(); bOut.close(); } catch (IOException e) { throw new DataParserException(Errors.PROTOBUF_10, e.toString(), e); } String path = fieldPath.isEmpty() ? FORWARD_SLASH : fieldPath; byte[] bytes = org.apache.commons.codec.binary.Base64.encodeBase64(bOut.toByteArray()); record.getHeader().setAttribute(PROTOBUF_UNKNOWN_FIELDS_PREFIX + path, new String(bytes, StandardCharsets.UTF_8)); } return Field.create(sdcRecordMapFieldValue); }
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <P>/*w w w . j a v a 2 s . c o m*/ * ? * </p> * * @param encryptedData ? * @param privateKey ?(BASE64?) * @return byte * @throws Exception Exception */ @SuppressWarnings({ "PMD.ShortVariable", "PMD.AvoidDuplicateLiterals" }) public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
From source file:Main.java
/** * @param data -- the data to decompress * @param uncompressedChunkSize -- an estimate of the uncompressed chunk size. This need not be exact. * @return//from w ww . j a va 2 s .c o m */ public static byte[] decompress(byte[] data, int uncompressedChunkSize) { // mpd: new code int rem = data.length; // Create an expandable byte array to hold the decompressed data ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedChunkSize); // Decompress the data byte[] outbuf = new byte[uncompressedChunkSize]; Inflater decompressor = new Inflater(); decompressor.setInput(data); while (rem > 0) { // If we are finished with the current chunk start a new one if (decompressor.finished()) { decompressor = new Inflater(); int offset = data.length - rem; decompressor.setInput(data, offset, rem); } try { int count = decompressor.inflate(outbuf, 0, outbuf.length); rem = decompressor.getRemaining(); bos.write(outbuf, 0, count); } catch (Exception e) { e.printStackTrace(); } } try { bos.close(); } catch (IOException e) { // Ignore -- no resources open } // Return the decompressed data return bos.toByteArray(); }
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>/*from ww w . ja v a 2 s. c o m*/ * * </p> * * @param encryptedData ? * @param publicKey (BASE64?) * @return byte * @throws Exception Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int index = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); index++; offSet = index * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
From source file:GZIPUtils.java
/** * Returns an gunzipped copy of the input array, truncated to * <code>sizeLimit</code> bytes, if necessary. If the gzipped input * has been truncated or corrupted, a best-effort attempt is made to * unzip as much as possible. If no data can be extracted * <code>null</code> is returned. */// ww w .j av a 2 s. c o m public static final byte[] unzipBestEffort(byte[] in, int sizeLimit) { try { // decompress using GZIPInputStream ByteArrayOutputStream outStream = new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length); GZIPInputStream inStream = new GZIPInputStream(new ByteArrayInputStream(in)); byte[] buf = new byte[BUF_SIZE]; int written = 0; while (true) { try { int size = inStream.read(buf); if (size <= 0) break; if ((written + size) > sizeLimit) { outStream.write(buf, 0, sizeLimit - written); break; } outStream.write(buf, 0, size); written += size; } catch (Exception e) { break; } } try { outStream.close(); } catch (IOException e) { } return outStream.toByteArray(); } catch (IOException e) { return null; } }
From source file:com.marklogic.xcc.ContentFactory.java
private static byte[] bytesFromStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[64 * 1024]; int rc;/* w ww . j a v a 2 s . c o m*/ while ((rc = is.read(buffer)) != -1) { os.write(buffer, 0, rc); } is.close(); os.flush(); buffer = os.toByteArray(); os.close(); return (buffer); }
From source file:com.jredrain.base.utils.CommandUtils.java
public static String executeShell(File shellFile, String... args) { String info = null;//from w w w. j a v a 2 s. com ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { String params = " "; if (CommonUtils.notEmpty(args)) { for (String p : args) { params += p + " "; } } CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath() + params); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandLine); info = outputStream.toString().trim(); } catch (Exception e) { e.printStackTrace(); } finally { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return info; } }
From source file:edu.umn.msi.tropix.proteomics.conversion.impl.ConversionUtils.java
public static byte[] decompress(byte[] compressedData) { byte[] decompressedData; // using a ByteArrayOutputStream to not having to define the result array size beforehand Inflater decompressor = new Inflater(); decompressor.setInput(compressedData); // Create an expandable byte array to hold the decompressed data ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length); byte[] buf = new byte[1024]; while (!decompressor.finished()) { try {//from w w w. j a v a 2s .c o m int count = decompressor.inflate(buf); if (count == 0 && decompressor.needsInput()) { break; } bos.write(buf, 0, count); } catch (DataFormatException e) { throw new IllegalStateException( "Encountered wrong data format " + "while trying to decompress binary data!", e); } } try { bos.close(); } catch (IOException e) { // ToDo: add logging e.printStackTrace(); } // Get the decompressed data decompressedData = bos.toByteArray(); if (decompressedData == null) { throw new IllegalStateException("Decompression of binary data produced no result (null)!"); } return decompressedData; }
From source file:com.beetle.framework.util.ObjectUtil.java
/** * ???/*from ww w. jav a 2s. co m*/ * * @param obj * @return */ public final static int sizeOf(Object obj) { ByteArrayOutputStream bao = null; ObjectOutputStream oos; try { bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(obj); oos.flush(); oos.close(); return bao.size(); } catch (Exception e) { e.printStackTrace(); return 0; } finally { try { if (bao != null) { bao.close(); bao = null; } } catch (IOException e) { } } }