Java Code Examples for java.io.ByteArrayOutputStream#write()

The following examples show how to use java.io.ByteArrayOutputStream#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PubChemStealer.java    From QNotified with GNU General Public License v3.0 6 votes vote down vote up
@NonUiThread
public static Molecule getMoleculeByCid(long cid) throws IOException, MdlMolParser.BadMolFormatException {
    HttpURLConnection conn = (HttpURLConnection) new URL(FAKE_PUB_CHEM_SITE + "/rest/pug/compound/CID/" + cid + "/record/SDF/?record_type=2d&response_type=display").openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    if (conn.getResponseCode() != 200) {
        conn.disconnect();
        throw new IOException("Bad ResponseCode: " + conn.getResponseCode());
    }
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    in.close();
    conn.disconnect();
    String str = outStream.toString();
    return MdlMolParser.parseString(str);
}
 
Example 2
Source File: CraftPlayer.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public void sendSupportedChannels() {
    if (getHandle().connection == null) return;
    Set<String> listening = server.getMessenger().getIncomingChannels();

    if (!listening.isEmpty()) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        for (String channel : listening) {
            try {
                stream.write(channel.getBytes(StandardCharsets.UTF_8));
                stream.write((byte) 0);
            } catch (IOException ex) {
                Logger.getLogger(CraftPlayer.class.getName()).log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex);
            }
        }

        getHandle().connection.sendPacket(new SPacketCustomPayload("REGISTER", new PacketBuffer(Unpooled.wrappedBuffer(stream.toByteArray()))));
    }
}
 
Example 3
Source File: SmartPost.java    From Android-POS with MIT License 6 votes vote down vote up
/**
 * 
 * @param cmd ��������������CMD��
 * @param code ACK/NAK����
 * @return
 */
public static byte[] InitMessage(byte cmd, String code) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		baos.write(PostDefine.START);
		baos.write(cmd);
		if (code != null) {
			baos.write(PostDefine.FS);
			baos.write(code.getBytes());
		}
		baos.write(PostDefine.END);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return baos.toByteArray();
}
 
Example 4
Source File: ConnectorCryptoUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void decrypt(byte[] encryptedBytes, ByteArrayOutputStream baos, int index, int blockSize, ConnectorCryptoUtils.Decryptor decryptor) throws IOException, IllegalBlockSizeException, BadPaddingException {
   if (blockSize == 0) {
      baos.write(decryptor.doFinal(encryptedBytes, 0, encryptedBytes.length));
   } else {
      for(; index < encryptedBytes.length; index += blockSize) {
         if (index + blockSize >= encryptedBytes.length) {
            baos.write(decryptor.doFinal(encryptedBytes, index, blockSize));
         } else {
            byte[] blockResult = decryptor.update(encryptedBytes, index, blockSize);
            if (blockResult != null) {
               baos.write(blockResult);
            }
         }
      }
   }

}
 
Example 5
Source File: GPInstallForPersonalizeRequest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public byte[] toBytes() {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        bos.write(0); // never any data
        bos.write(0); // never any data
        if(appletAID == null) {
            throw new IOException("Applet AID is mandatory");
        } else {
            bos.write(appletAID.getLength());
            bos.write(appletAID.getBytes());
        }
        bos.write(0); // never any data
        bos.write(0); // never any data
        bos.write(0); // never any data
    } catch (IOException e) {
        throw new Error("Error serializing INSTALL [for PERSONALIZE] request", e);
    }
    return bos.toByteArray();
}
 
Example 6
Source File: Script.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG.
 */
public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) {
    checkArgument(threshold > 0);
    checkArgument(threshold <= pubkeys.size());
    checkArgument(pubkeys.size() <= 16);  // That's the max we can represent with a single opcode.
    if (pubkeys.size() > 3) {
        log.warn("Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3", pubkeys.size());
    }
    try {
        ByteArrayOutputStream bits = new ByteArrayOutputStream();
        bits.write(encodeToOpN(threshold));
        for (ECKey key : pubkeys) {
            writeBytes(bits, key.getPubKey());
        }
        bits.write(encodeToOpN(pubkeys.size()));
        bits.write(OP_CHECKMULTISIG);
        return bits.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
Example 7
Source File: WDataTransferer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 8
Source File: Dump.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static byte[] hexToBin(String src) {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    int i = 0;
    while (i < src.length()) {
            char x = src.charAt(i);
            if (!((x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f'))) {
                    i++;
                    continue;
            }
            try {
                    result.write(Integer.valueOf("" + src.charAt(i) + src.charAt(i + 1), 16));
                    i += 2;
            }
            catch (Exception e) {
                    return null;
            }
    }
    return result.toByteArray();
}
 
Example 9
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private byte[] generateTimestampDigest(Element baseElement, String c14nMethodValue) {
   try {
      Node signatureValue = DomUtils.getMatchingChilds(baseElement, "http://www.w3.org/2000/09/xmldsig#", "SignatureValue").item(0);
      Transform transform = new Transform(signatureValue.getOwnerDocument(), c14nMethodValue);
      XMLSignatureInput refData = transform.performTransform(new XMLSignatureInput(signatureValue));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      if (refData.isByteArray()) {
         baos.write(refData.getBytes());
      } else if (refData.isOctetStream()) {
         baos.write(ConnectorIOUtils.getBytes(refData.getOctetStream()));
      }

      return baos.toByteArray();
   } catch (Exception var7) {
      throw new IllegalArgumentException("Unable to calculateDigest", var7);
   }
}
 
Example 10
Source File: EscPosTest.java    From escpos-coffee with MIT License 5 votes vote down vote up
@Test
void setPrinterCharacterTableTest() throws Exception{
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    EscPos escpos = new EscPos(result);

    escpos.setPrinterCharacterTable(10);
    escpos.close();
    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    expected.write(ESC);
    expected.write('t');
    expected.write(10);

    assertArrayEquals(expected.toByteArray(), result.toByteArray());

}
 
Example 11
Source File: ResourceUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 Raw 资源文件数据并保存到本地
 * @param resId 资源 id
 * @param file  文件保存地址
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveRawFormFile(@RawRes final int resId, final File file) {
    try {
        // 获取 raw 文件
        InputStream is = openRawResource(resId);
        // 存入 SDCard
        FileOutputStream fos = new FileOutputStream(file);
        // 设置数据缓冲
        byte[] buffer = new byte[1024];
        // 创建输入输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        // 保存数据
        byte[] bytes = baos.toByteArray();
        // 写入保存的文件
        fos.write(bytes);
        // 关闭流
        CloseUtils.closeIOQuietly(baos, is);
        fos.flush();
        CloseUtils.closeIOQuietly(fos);
        return true;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "saveRawFormFile");
    }
    return false;
}
 
Example 12
Source File: DataFrame.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public byte[] getHttp() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	baos.write("HTTP/2 200 OK\r\n".getBytes());
	baos.write(new String("X-PacketProxy-HTTP2-Stream-Id: " + streamId + "\r\n").getBytes());
	baos.write(new String("X-PacketProxy-HTTP2-Flags: " + flags + "\r\n").getBytes());
	baos.write("\r\n".getBytes());
	baos.write(payload);
	return baos.toByteArray();
}
 
Example 13
Source File: OpenApiHandler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext event) {
    if (event.request().method().equals(HttpMethod.OPTIONS)) {
        addCorsResponseHeaders(event.response());
        event.response().headers().set("Allow", ALLOWED_METHODS);
    } else {
        HttpServerRequest req = event.request();
        HttpServerResponse resp = event.response();
        String accept = req.headers().get("Accept");

        List<String> formatParams = event.queryParam(QUERY_PARAM_FORMAT);
        String formatParam = formatParams.isEmpty() ? null : formatParams.get(0);

        // Default content type is YAML
        Format format = Format.YAML;

        // Check Accept, then query parameter "format" for JSON; else use YAML.
        if ((accept != null && accept.contains(Format.JSON.getMimeType())) ||
                ("JSON".equalsIgnoreCase(formatParam))) {
            format = Format.JSON;
        }

        addCorsResponseHeaders(resp);
        resp.headers().set("Content-Type", format.getMimeType() + ";charset=UTF-8");
        ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
        try (InputStream in = cl.getResourceAsStream(BASE_NAME + format)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int r;
            byte[] buf = new byte[1024];
            while ((r = in.read(buf)) > 0) {
                out.write(buf, 0, r);
            }
            resp.end(Buffer.buffer(out.toByteArray()));
        } catch (IOException e) {
            event.fail(e);
        }

    }
}
 
Example 14
Source File: ZipSigner.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the content from the given stream and return it as a byte array.
 */
public byte[] readContentAsBytes(InputStream input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[2048];

    int numRead = input.read(buffer);
    while (numRead != -1) {
        baos.write(buffer, 0, numRead);
        numRead = input.read(buffer);
    }

    byte[] bytes = baos.toByteArray();
    return bytes;
}
 
Example 15
Source File: ValidateCertPath.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] getTotalBytes(InputStream is) throws IOException {
    byte[] buffer = new byte[8192];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
    int n;
    baos.reset();
    while ((n = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, n);
    }
    return baos.toByteArray();
}
 
Example 16
Source File: Util.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static String readFully(InputStream in) throws IOException {
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  byte[] buffer              = new byte[4096];
  int read;

  while ((read = in.read(buffer)) != -1) {
    bout.write(buffer, 0, read);
  }

  in.close();

  return new String(bout.toByteArray());
}
 
Example 17
Source File: Utils.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
/**
 * EXEを実行する。MACの場合はmonoで実行する
 * @return 標準出力に表示されたデータ
 */
public static byte[] executeRuby(String... command) throws Exception
{

	Process p = Runtime.getRuntime().exec(addRubyPath(command));
	InputStream in = p.getInputStream();
	ByteArrayOutputStream bout = new ByteArrayOutputStream();
	byte [] buffer = new byte[4096];
	int len = 0;
	while ((len = in.read(buffer, 0, 4096)) > 0) {
		bout.write(buffer, 0, len);
	}
	return Base64.decodeBase64(bout.toByteArray());
}
 
Example 18
Source File: HessianInput.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a byte array
 *
 * <pre>
 * B b16 b8 data value
 * </pre>
 */
public byte []readBytes()
  throws IOException
{
  int tag = read();

  switch (tag) {
  case 'N':
    return null;

  case 'B':
  case 'b':
    _isLastChunk = tag == 'B';
    _chunkLength = (read() << 8) + read();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    int data;
    while ((data = parseByte()) >= 0)
      bos.write(data);

    return bos.toByteArray();
    
  default:
    throw expect("bytes", tag);
  }
}
 
Example 19
Source File: EncodingUtils.java    From client-encryption-java with MIT License 4 votes vote down vote up
@SuppressWarnings({"squid:S3776", "squid:ForLoopCounterChangedCheck"})
public static byte[] base64Decode(String value) {
    if (null == value) {
        throw new IllegalArgumentException("Can't base64 decode a null value!");
    }
    byte[] valueBytes = value.getBytes();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    for (int i = 0; i < valueBytes.length;) {
        int b;
        if (b64ints[valueBytes[i]] != -1) {
            b = (b64ints[valueBytes[i]] & 0xFF) << 18;
        }
        // skip unknown characters
        else {
            i++;
            continue;
        }

        int num = 0;
        if (i + 1 < valueBytes.length && b64ints[valueBytes[i + 1]] != -1) {
            b = b | ((b64ints[valueBytes[i + 1]] & 0xFF) << 12);
            num++;
        }
        if (i + 2 < valueBytes.length && b64ints[valueBytes[i + 2]] != -1) {
            b = b | ((b64ints[valueBytes[i + 2]] & 0xFF) << 6);
            num++;
        }
        if (i + 3 < valueBytes.length && b64ints[valueBytes[i + 3]] != -1) {
            b = b | (b64ints[valueBytes[i + 3]] & 0xFF);
            num++;
        }

        while (num > 0) {
            int c = (b & 0xFF0000) >> 16;
            outputStream.write((char)c);
            b <<= 8;
            num--;
        }
        i += 4;
    }
    return outputStream.toByteArray();
}
 
Example 20
Source File: HttpPostGet.java    From bidder with Apache License 2.0 4 votes vote down vote up
/**
 * Send an HTTP Post
 * @param targetURL
 *    String. The URL to transmit to.
 * @param data
 *            byte[]. The payload bytes.
 * @param connTimeout
 * 			  int. The connection timeout in ms
 * @param readTimeout
 * 			  int. The read timeout in ms.
 * @return byte[]. The contents of the POST return.
 * @throws Exception
 *             on network errors.
 */
public byte [] sendPost(String targetURL,  byte [] data, int connTimeout, int readTimeout) throws Exception {
	URLConnection connection = new URL(targetURL).openConnection();
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setConnectTimeout(connTimeout);
	connection.setReadTimeout(readTimeout);
	OutputStream output = connection.getOutputStream();
	
	try {
		output.write(data);
	} finally {
		try {
			output.close();
		} catch (IOException logOrIgnore) {
			logOrIgnore.printStackTrace();
		}
	}
	InputStream response = connection.getInputStream();
	
	http = (HttpURLConnection) connection;
	code = http.getResponseCode();
	
	String value = http.getHeaderField("Content-Encoding");
	
	if (value != null && value.equals("gzip")) {
		byte bytes [] = new byte[4096];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPInputStream gis = new GZIPInputStream(http.getInputStream());
		while(true) {
			int n = gis.read(bytes);
			if (n < 0) break;
			baos.write(bytes,0,n);
		}
		return baos.toByteArray();
	}
	
		

	byte [] b = getContents(response);
	if (b.length == 0)
		return null;
	return b;
}