public ByteBuffer generate(short version, Fields headers) { // TODO: ByteArrayOutputStream is quite inefficient, but grows on demand; optimize using // ByteBuffer ? final Charset iso1 = StandardCharsets.ISO_8859_1; ByteArrayOutputStream buffer = new ByteArrayOutputStream(headers.getSize() * 64); writeCount(version, buffer, headers.getSize()); for (Fields.Field header : headers) { String name = header.getName().toLowerCase(Locale.ENGLISH); byte[] nameBytes = name.getBytes(iso1); writeNameLength(version, buffer, nameBytes.length); buffer.write(nameBytes, 0, nameBytes.length); // Most common path first String value = header.getValue(); byte[] valueBytes = value.getBytes(iso1); if (header.hasMultipleValues()) { List<String> values = header.getValues(); for (int i = 1; i < values.size(); ++i) { byte[] moreValueBytes = values.get(i).getBytes(iso1); byte[] newValueBytes = new byte[valueBytes.length + 1 + moreValueBytes.length]; System.arraycopy(valueBytes, 0, newValueBytes, 0, valueBytes.length); newValueBytes[valueBytes.length] = 0; System.arraycopy( moreValueBytes, 0, newValueBytes, valueBytes.length + 1, moreValueBytes.length); valueBytes = newValueBytes; } } writeValueLength(version, buffer, valueBytes.length); buffer.write(valueBytes, 0, valueBytes.length); } return compress(version, buffer.toByteArray()); }
/** Converts a String into a byte array. */ protected static byte[] byteArrayFromString(String s) throws TextParseException { if (s == null) { s = ""; } byte[] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) { if (array.length > 255) { throw new TextParseException("text string too long"); } return array; } ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException("bad escape"); if (digits < 3) { continue; } b = (byte) intval; } else if (digits > 0 && digits < 3) { throw new TextParseException("bad escape"); } os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else { os.write(array[i]); } } if (digits > 0 && digits < 3) { throw new TextParseException("bad escape"); } array = os.toByteArray(); if (array.length > 255) { throw new TextParseException("text string too long"); } return os.toByteArray(); }
/** * Gets a SerialMessage with the PROTECTION_SUPPORTED_GET command * * @return the serial message, or null if the supported command is not supported. */ public SerialMessage getSupportedMessage() { if (getVersion() == 1) { logger.debug("NODE {}: PROTECTION_SUPPORTED_GET not supported for V1", getNode().getNodeId()); return null; } logger.debug( "NODE {}: Creating new message for command PROTECTION_SUPPORTED_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage( getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(PROTECTION_SUPPORTED_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
private static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[4096]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4096); // Do the first byte via a blocking read outputStream.write(inputStream.read()); // Slurp the rest int available = 0; // inputStream.available(); boolean run = true; while (run && (available = inputStream.available()) > 0) { // Log.d(TAG, "slurp " + available); while (available > 0) { int cbToRead = Math.min(buffer.length, available); int cbRead = inputStream.read(buffer, 0, cbToRead); if (cbRead <= 0) { run = false; break; } outputStream.write(buffer, 0, cbRead); available -= cbRead; } } return outputStream.toByteArray(); }
@Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { if (!chunked) { final HttpRequest request = (HttpRequest) e.getMessage(); final ChannelBuffer buffer = request.getContent(); receivedData.write(buffer.array()); // System.out.println("received "+buffer.array() ); // System.out.println(buffer.array().length); if (!request.isChunked()) { processRequest(e); } else { chunked = true; } // final boolean keepAlive = isKeepAlive(request); } else { final HttpChunk chunk = (HttpChunk) e.getMessage(); final ChannelBuffer buffer = chunk.getContent(); receivedData.write(buffer.array()); if (chunk.isLast()) { processRequest(e); } } }
/** * Writes the initialisation part of the RtfList * * @return A byte array containing the initialisation part */ protected byte[] writeListBeginning() { ByteArrayOutputStream result = new ByteArrayOutputStream(); try { result.write(RtfParagraph.PARAGRAPH_DEFAULTS); if (this.inTable) { result.write(RtfParagraph.IN_TABLE); } switch (this.alignment) { case Element.ALIGN_LEFT: result.write(RtfParagraphStyle.ALIGN_LEFT); break; case Element.ALIGN_RIGHT: result.write(RtfParagraphStyle.ALIGN_RIGHT); break; case Element.ALIGN_CENTER: result.write(RtfParagraphStyle.ALIGN_CENTER); break; case Element.ALIGN_JUSTIFIED: case Element.ALIGN_JUSTIFIED_ALL: result.write(RtfParagraphStyle.ALIGN_JUSTIFY); break; } // .result.write(writeIndentations()); writeIndentations(result); result.write(RtfFont.FONT_SIZE); result.write(intToByteArray(fontNumber.getFontSize() * 2)); if (this.symbolIndent > 0) { result.write("\\tx".getBytes()); result.write(intToByteArray(this.leftIndent)); } } catch (IOException ioe) { ioe.printStackTrace(); } return result.toByteArray(); }
/** * Encodes byte into its quoted-printable representation. * * @param b byte to encode * @param buffer the buffer to write to */ private static final void encodeQuotedPrintable(int b, ByteArrayOutputStream buffer) { buffer.write(ESCAPE_CHAR); char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)); char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16)); buffer.write(hex1); buffer.write(hex2); }
private int writeClass(Class<?> type) throws IOException { SerializeCache cache = getSerializeCache(type, mode); if (cache == null) { cache = new SerializeCache(); ByteArrayOutputStream cachestream = new ByteArrayOutputStream(); Map<String, MemberAccessor> members = HproseHelper.getMembers(type, mode); int count = members.size(); cachestream.write(HproseTags.TagClass); writeUTF8String(HproseHelper.getClassName(type), cachestream); if (count > 0) { writeInt(count, cachestream); } cachestream.write(HproseTags.TagOpenbrace); for (Entry<String, MemberAccessor> member : members.entrySet()) { cachestream.write(HproseTags.TagString); writeUTF8String(member.getKey(), cachestream); ++cache.refcount; } cachestream.write(HproseTags.TagClosebrace); cache.data = cachestream.toByteArray(); putSerializeCache(type, mode, cache); } stream.write(cache.data); lastref += cache.refcount; int cr = lastclassref++; classref.put(type, cr); return cr; }
@Override public void handle(HttpExchange arg0) throws IOException { byte[] utf8b = org.apache.commons.io.ByteOrderMark.UTF_8.getBytes(); String l = "a\tb\tc\t\nb\th\tj\n"; ByteArrayOutputStream ous = new ByteArrayOutputStream(); ous.write(utf8b); ous.write(l.getBytes("UTF-8")); ous.close(); byte[] k = ous.toByteArray(); Headers hdrs = arg0.getResponseHeaders(); hdrs.set("Content-Type", "application/csv"); hdrs.set("Content-Disposition", "attachment; filename=genome.csv"); hdrs.set("Content-Encoding", "binary"); hdrs.set("Charset", "utf-8"); arg0.sendResponseHeaders(200, k.length); arg0.getResponseBody().write(k); arg0.getResponseBody().close(); }
private static void decode(String s, ByteArrayOutputStream bos) { int i = 0; int len = s.length(); while (true) { while (i < len && s.charAt(i) <= ' ') { i++; } if (i == len) { break; } int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3))); bos.write((tri >> 16) & 255); if (s.charAt(i + 2) == '=') { break; } bos.write((tri >> 8) & 255); if (s.charAt(i + 3) == '=') { break; } bos.write(tri & 255); i += 4; } }
/** Utility function for encoding a length as a BER byte sequence */ public static byte[] encodeLength(int length) { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // see if can be represented in single byte // don't forget the first bit is the "long field test" bit!! if (length < 128) { byte[] len = {(byte) length}; outBytes.write(len, 0, 1); } else { // too big for one byte // see how many are needed: int numBytes = 0; int temp = length; while (temp > 0) { ++numBytes; temp = (int) Math.floor(temp / 256); } byte num = (byte) numBytes; num += 128; // set the "long format" bit outBytes.write(num); byte[] len = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; --i) { len[i] = (byte) (length % 256); length = (int) Math.floor(length / 256); } outBytes.write(len, 0, numBytes); } return outBytes.toByteArray(); }
/** * Save the configuration as a Git text style configuration file. * * <p><b>Warning:</b> Although this method uses the traditional Git file locking approach to * protect against concurrent writes of the configuration file, it does not ensure that the file * has not been modified since the last read, which means updates performed by other objects * accessing the same backing file may be lost. * * @throws IOException the file could not be written. */ public void save() throws IOException { final byte[] out; final String text = toText(); if (utf8Bom) { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(0xEF); bos.write(0xBB); bos.write(0xBF); bos.write(text.getBytes(RawParseUtils.UTF8_CHARSET.name())); out = bos.toByteArray(); } else { out = Constants.encode(text); } final LockFile lf = new LockFile(getFile(), fs); if (!lf.lock()) throw new LockFailedException(getFile()); try { lf.setNeedSnapshot(true); lf.write(out); if (!lf.commit()) throw new IOException(MessageFormat.format(JGitText.get().cannotCommitWriteTo, getFile())); } finally { lf.unlock(); } snapshot = lf.getCommitSnapshot(); hash = hash(out); // notify the listeners fireConfigChangedEvent(); }
private static byte[] getLengthEncoding(Integer length) throws IOException { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); try { if (length < 128) { /* Single byte representation if < 128 */ outBytes.write((byte) ((int) length)); } else { /* Multi byte representation if >= 128 */ byte requiredBytes = 0; int temp = length; while (temp > 0) { requiredBytes++; temp = (int) Math.floor(temp / 256.0); } byte num = requiredBytes; num += 128; outBytes.write(num); byte[] len = new byte[requiredBytes]; for (int i = requiredBytes - 1; i >= 0; --i) { len[i] = (byte) (length % 256); length = (int) Math.floor(length / 256.0); } outBytes.write(len, 0, requiredBytes); } return outBytes.toByteArray(); } finally { outBytes.close(); } }
public static byte[] decodeQuotedPrintable(final byte[] bytes) { if (bytes == null) { return null; } final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { final int b = bytes[i]; if (b == '=') { try { final int u = Character.digit((char) bytes[++i], 16); final int l = Character.digit((char) bytes[++i], 16); buffer.write((char) ((u << 4) + l)); } catch (Exception e) { FileLog.e("tmessages", e); return null; } } else { buffer.write(b); } } byte[] array = buffer.toByteArray(); try { buffer.close(); } catch (Exception e) { FileLog.e("tmessages", e); } return array; }
public SerialMessage getValueMessage(SensorType type) { if (getVersion() == 1) { logger.debug( "NODE {}: Node doesn't support SENSOR_BINARY_GET with SensorType", getNode().getNodeId()); return null; } logger.debug( "NODE {}: Creating new message for application command SENSOR_BINARY_GET for {}", getNode().getNodeId(), type); SerialMessage result = new SerialMessage( getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(3); outputData.write(getCommandClass().getKey()); outputData.write(SENSOR_BINARY_GET); outputData.write(type.getKey()); result.setMessagePayload(outputData.toByteArray()); return result; }
private String exec(final String... cmd) throws IOException, InterruptedException { assert cmd != null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); Log.trace("Running: ", cmd); Process p = Runtime.getRuntime().exec(cmd); InputStream in = null; InputStream err = null; OutputStream out = null; try { int c; in = p.getInputStream(); while ((c = in.read()) != -1) { bout.write(c); } err = p.getErrorStream(); while ((c = err.read()) != -1) { bout.write(c); } out = p.getOutputStream(); p.waitFor(); } finally { close(in, out, err); } String result = bout.toString(); Log.trace("Result: ", result); return result; }
public byte[] revert(byte[] current) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream inO = new ByteArrayInputStream(oldData); ByteArrayInputStream inC = new ByteArrayInputStream(current); for (int c = 0; c < commands.length; c++) { int flag = FLAG & commands[c]; int n = (~FLAG) & commands[c]; if (n < 0) n += 256; n++; if (flag == ADD) { // System.out.println("Add: " + n); for (int i = 0; i < n; i++) out.write(inO.read()); } else if (flag == SKIP) { // System.out.println("Skip: " + n); inC.skip(n); } else if (flag == COPY) { // System.out.println("Copy: " + n); for (int i = 0; i < n; i++) out.write(inC.read()); } else if (flag == COPY_WITH_OVERFLOW) { n += (255 & commands[++c]) << 6; // System.out.println("Copy: " + n); for (int i = 0; i < n; i++) out.write(inC.read()); } } return out.toByteArray(); }
/** @return Generated byte array for setting USR module */ private byte[] getBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] mac = BinaryConversion.hexStringToByteArray(mMac); byte[] destIp = BinaryConversion.ipToByteArray(mDestIp); byte[] destPort = BinaryConversion.intToByteArray(mDestPort, 2); byte[] hostIp = BinaryConversion.ipToByteArray(mHostIp); byte[] hostPort = BinaryConversion.intToByteArray(mHostPort, 2); byte[] gatewayIp = BinaryConversion.ipToByteArray(mGatewayIp); byte[] baud = BinaryConversion.intToByteArray(mBaud, 3); try { baos.write(mac); baos.write(SETTING_MSG.getBytes()); baos.write(destIp); baos.write(destPort); baos.write(hostIp); baos.write(hostPort); baos.write(gatewayIp); baos.write((byte) mMode.ordinal()); baos.write(baud); baos.write(SETTING_MSG.getBytes()); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); }
public void sendSupportedChannels() { if (getHandle().playerNetServerHandler == null) return; Set<String> listening = server.getMessenger().getIncomingChannels(); if (!listening.isEmpty()) { Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "REGISTER"; ByteArrayOutputStream stream = new ByteArrayOutputStream(); for (String channel : listening) { try { stream.write(channel.getBytes("UTF8")); stream.write((byte) 0); } catch (IOException ex) { Logger.getLogger(BukkitPlayer.class.getName()) .log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex); } } packet.data = stream.toByteArray(); packet.length = packet.data.length; getHandle().playerNetServerHandler.sendPacketToPlayer(packet); } }
protected static byte[] getWapString(ByteArrayInputStream pduDataStream, int stringType) { assert (null != pduDataStream); ByteArrayOutputStream out = new ByteArrayOutputStream(); int temp = pduDataStream.read(); assert (-1 != temp); while ((-1 != temp) && ('\0' != temp)) { // check each of the character if (stringType == TYPE_TOKEN_STRING) { if (isTokenCharacter(temp)) { out.write(temp); } } else { if (isText(temp)) { out.write(temp); } } temp = pduDataStream.read(); assert (-1 != temp); } if (out.size() > 0) { return out.toByteArray(); } return null; }
public byte[] read() { if (socket != null && !isClose()) { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ins = socket.getInputStream(); byte[] b = new byte[bufferSize]; int fb = ins.read(); bout.write(fb); while ((ins.available()) > 0) { int n = ins.read(b); bout.write(b, 0, n); } bout.flush(); return bout.toByteArray(); } catch (IOException e) { log.info("socket 读取数据出现异常"); if (ins != null) { try { ins.close(); } catch (IOException ie) { ie.printStackTrace(); } } e.printStackTrace(); } } return null; }
/** * Writes to the designated output stream the DER encoding of the current contents of this * instance. * * @param out the destination output stream. * @throws IOException if an I/O related exception occurs during the process. * @throws CRLException if an exception occurs while encoding the certificate revocation lists * associated with this instance. * @throws CertificateEncodingException if an exception occurs while encoding the certificate * chains associated with this instance. */ public void encode(OutputStream out) throws IOException, CRLException, CertificateEncodingException { DERValue derVersion = new DERValue(DER.INTEGER, version); DERValue derDigestAlgorithms = new DERValue(DER.CONSTRUCTED | DER.SET, digestAlgorithms); DERValue derContentType = new DERValue(DER.OBJECT_IDENTIFIER, PKCS7Data.PKCS7_DATA); ArrayList contentInfo = new ArrayList(2); contentInfo.add(derContentType); if (content == null) contentInfo.add(new DERValue(DER.NULL, null)); else contentInfo.add(content); DERValue derContentInfo = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, contentInfo); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); for (int i = 0; i < certificates.length; i++) baos.write(certificates[i].getEncoded()); baos.flush(); byte[] b = baos.toByteArray(); DERValue derExtendedCertificatesAndCertificates = new DERValue(DER.CONSTRUCTED | DER.CONTEXT | 0, b.length, b, null); DERValue derCertificateRevocationLists = null; if (crls != null && crls.length > 0) { baos.reset(); for (int i = 0; i < crls.length; i++) baos.write(((X509CRL) crls[i]).getEncoded()); baos.flush(); byte[] b2 = baos.toByteArray(); derCertificateRevocationLists = new DERValue(DER.CONSTRUCTED | DER.CONTEXT | 1, b2.length, b2, null); } baos.reset(); for (Iterator it = signerInfos.iterator(); it.hasNext(); ) { SignerInfo signerInfo = (SignerInfo) it.next(); signerInfo.encode(baos); } baos.flush(); byte[] b3 = baos.toByteArray(); DERValue derSignerInfos = new DERValue(DER.CONSTRUCTED | DER.SET, b3.length, b3, null); ArrayList signedData = new ArrayList(6); signedData.add(derVersion); signedData.add(derDigestAlgorithms); signedData.add(derContentInfo); signedData.add(derExtendedCertificatesAndCertificates); if (derCertificateRevocationLists != null) signedData.add(derCertificateRevocationLists); signedData.add(derSignerInfos); DERValue derSignedData = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, signedData); // now the outer contents ArrayList outer = new ArrayList(3); outer.add(new DERValue(DER.OBJECT_IDENTIFIER, PKCS7_SIGNED_DATA)); outer.add(new DERValue(DER.CONTEXT | 0, null)); outer.add(derSignedData); DERValue derOuter = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, outer); DERWriter.write(out, derOuter); }
/** * Construct a service description for registrating with JmDNS. The properties hashtable must map * property names to either Strings or byte arrays describing the property values. * * @param type fully qualified service type name, such as <code>_http._tcp.local.</code>. * @param name unqualified service instance name, such as <code>foobar</code> * @param port the local port on which the service runs * @param weight weight of the service * @param priority priority of the service * @param props properties describing the service */ public ServiceInfo( String type, String name, int port, int weight, int priority, Hashtable props) { this(type, name, port, weight, priority, new byte[0]); if (props != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(256); for (Enumeration e = props.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); Object val = props.get(key); ByteArrayOutputStream out2 = new ByteArrayOutputStream(100); writeUTF(out2, key); if (val instanceof String) { out2.write('='); writeUTF(out2, (String) val); } else { if (val instanceof byte[]) { out2.write('='); byte[] bval = (byte[]) val; out2.write(bval, 0, bval.length); } else { if (val != NO_VALUE) { throw new IllegalArgumentException("invalid property value: " + val); } } } byte data[] = out2.toByteArray(); out.write(data.length); out.write(data, 0, data.length); } this.text = out.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected exception: " + e); } } }
byte[] toBER() throws TLVException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] tagBytes = tag.toBER(); out.write(tagBytes); // calculate length according to input data int len = getValueLength(); if (len <= 127) { // short form out.write((byte) len); } else { byte[] lenBytes = IntegerUtils.toByteArray(len); byte lenHeader = (byte) (0x80 | lenBytes.length); out.write(lenHeader); out.write(lenBytes); } // write actual data out.write(getValue()); return out.toByteArray(); } catch (IOException ex) { throw new TLVException(ex); } }
/** * Read the input stream, attach Carriage_Return at the end of each segment * * @param in * @throws IOException */ private void processInupt(InputStream in) throws IOException { // convert the InputStream into a BufferedReader InputStreamReader streamIn = new InputStreamReader(in); BufferedReader br = new BufferedReader(streamIn); byteOutList = new ArrayList<byte[]>(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); // read each line of the file until EOF is reached String curLine = null; // char lfChar=10; //line feed character char crtChar = 13; // Carriage return character while ((curLine = br.readLine()) != null) { curLine = curLine.trim(); // skip blank line if (curLine.equals("")) continue; if (curLine.startsWith("MSH")) { if (byteOut.toByteArray().length > 0) { byteOutList.add(byteOut.toByteArray()); byteOut = new ByteArrayOutputStream(); } } byteOut.write(curLine.getBytes()); byteOut.write((byte) crtChar); } byteOutList.add(byteOut.toByteArray()); byteOut.close(); in.close(); }
private static void SendHeadImageQueryMsg(String _imageID, int _style, boolean _isWeiboOrIM) throws Exception { if (sm_mainApp.m_dontDownloadWeiboHeadImage) { return; } if (!recvMain.isSDCardSupport() || !sm_mainApp.isSDCardAvailable(false)) { return; } int sign = _isWeiboOrIM ? msg_head.msgWeiboHeadImage : msg_head.msgChatHeadImage; ByteArrayOutputStream t_os = new ByteArrayOutputStream(); t_os.write(sign); t_os.write(_style); if (_isWeiboOrIM) { if (_style == fetchWeibo.QQ_WEIBO_STYLE) { sendReceive.WriteString(t_os, _imageID); } else { sendReceive.WriteLong(t_os, Long.parseLong(_imageID)); } } else { sendReceive.WriteString(t_os, _imageID); } // whether large image sendReceive.WriteBoolean(t_os, fsm_headImageWidth == fetchWeibo.fsm_headImageSize_l); sm_mainApp.m_connectDeamon.addSendingData(sign, t_os.toByteArray(), true); }
/** * Load UTF8withBOM or any ansi text file. * * @param filename * @return * @throws java.io.IOException */ public static String loadFileAsString(String filename) throws java.io.IOException { final int BUFLEN = 1024; BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN); byte[] bytes = new byte[BUFLEN]; boolean isUTF8 = false; int read, count = 0; while ((read = is.read(bytes)) != -1) { if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { isUTF8 = true; baos.write(bytes, 3, read - 3); // drop UTF8 bom marker } else { baos.write(bytes, 0, read); } count += read; } return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray()); } finally { try { is.close(); } catch (Exception ex) { } } }
/** * Gets a SerialMessage with the SENSOR_BINARY_GET command * * @return the serial message */ @Override public SerialMessage getValueMessage() { if (isGetSupported == false) { logger.debug("NODE {}: Node doesn't support get requests", getNode().getNodeId()); return null; } logger.debug( "NODE {}: Creating new message for application command SENSOR_BINARY_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage( getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(SENSOR_BINARY_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
public void sendSupportedChannels() { if (getHandle().field_71135_a == null) return; Set<String> listening = server.getMessenger().getIncomingChannels(); if (!listening.isEmpty()) { net.minecraft.network.packet.Packet250CustomPayload packet = new net.minecraft.network.packet.Packet250CustomPayload(); packet.field_73630_a = "REGISTER"; ByteArrayOutputStream stream = new ByteArrayOutputStream(); for (String channel : listening) { try { stream.write(channel.getBytes("UTF8")); stream.write((byte) 0); } catch (IOException ex) { Logger.getLogger(CraftPlayer.class.getName()) .log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex); } } packet.field_73629_c = stream.toByteArray(); packet.field_73628_b = packet.field_73629_c.length; getHandle().field_71135_a.func_72567_b(packet); } }
public static String convertBytes(byte[] contentBytes) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte x0E = 14, x0F = 15, x40 = 79; // 79 '|' 124 '@' List<Byte> dbs = null; for (int b : contentBytes) { if (b == x0E) { bos.write(x40); if (dbs != null) continue; dbs = new ArrayList<Byte>(); } bos.write(b); if (dbs != null) dbs.add(new Byte((byte) b)); if (b == x0F) { if (dbs != null) { bos.write(x40); byte[] cb = checkDoubleByteString(dbs); if (cb != null && cb.length > 0) bos.write(cb); dbs = null; } } } bos.close(); return bos.toString("cp937"); } catch (Exception e) { return ""; } }