List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:com.healthmarketscience.jackcess.Index.java
/** * Writes the logical index definitions into a table definition buffer. * @param buffer Buffer to write to/* www. j av a2s . com*/ * @param indexes List of IndexBuilders to write definitions for */ protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer) throws IOException { // write logical index information for (IndexBuilder idx : creator.getIndexes()) { TableCreator.IndexState idxState = creator.getIndexState(idx); buffer.putInt(Table.MAGIC_TABLE_NUMBER); // seemingly constant magic value which matches the table def buffer.putInt(idxState.getIndexNumber()); // index num buffer.putInt(idxState.getIndexDataNumber()); // index data num buffer.put((byte) 0); // related table type buffer.putInt(INVALID_INDEX_NUMBER); // related index num buffer.putInt(0); // related table definition page number buffer.put((byte) 0); // cascade updates flag buffer.put((byte) 0); // cascade deletes flag buffer.put(idx.getType()); // index type flags buffer.putInt(0); // unknown } // write index names for (IndexBuilder idx : creator.getIndexes()) { Table.writeName(buffer, idx.getName(), creator.getCharset()); } }
From source file:com.blm.orc.ReaderImpl.java
private static FileMetaInfo extractMetaInfoFromFooter(FileSystem fs, Path path, long maxFileLength) throws IOException { FSDataInputStream file = fs.open(path); // figure out the size of the file using the option or filesystem long size;/*www.j a v a 2 s . c o m*/ if (maxFileLength == Long.MAX_VALUE) { size = fs.getFileStatus(path).getLen(); } else { size = maxFileLength; } //read last bytes into buffer to get PostScript int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS); file.seek(size - readSize); ByteBuffer buffer = ByteBuffer.allocate(readSize); file.readFully(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); //read the PostScript //get length of PostScript int psLen = buffer.get(readSize - 1) & 0xff; ensureOrcFooter(file, path, psLen, buffer); int psOffset = readSize - 1 - psLen; CodedInputStream in = CodedInputStream.newInstance(buffer.array(), buffer.arrayOffset() + psOffset, psLen); OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in); checkOrcVersion(LOG, path, ps.getVersionList()); int footerSize = (int) ps.getFooterLength(); int metadataSize = (int) ps.getMetadataLength(); OrcFile.WriterVersion writerVersion; if (ps.hasWriterVersion()) { writerVersion = getWriterVersion(ps.getWriterVersion()); } else { writerVersion = OrcFile.WriterVersion.ORIGINAL; } //check compression codec switch (ps.getCompression()) { case NONE: break; case ZLIB: break; case SNAPPY: break; case LZO: break; default: throw new IllegalArgumentException("Unknown compression"); } //check if extra bytes need to be read int extra = Math.max(0, psLen + 1 + footerSize + metadataSize - readSize); if (extra > 0) { //more bytes need to be read, seek back to the right place and read extra bytes file.seek(size - readSize - extra); ByteBuffer extraBuf = ByteBuffer.allocate(extra + readSize); file.readFully(extraBuf.array(), extraBuf.arrayOffset() + extraBuf.position(), extra); extraBuf.position(extra); //append with already read bytes extraBuf.put(buffer); buffer = extraBuf; buffer.position(0); buffer.limit(footerSize + metadataSize); } else { //footer is already in the bytes in buffer, just adjust position, length buffer.position(psOffset - footerSize - metadataSize); buffer.limit(psOffset); } // remember position for later buffer.mark(); file.close(); return new FileMetaInfo(ps.getCompression().toString(), (int) ps.getCompressionBlockSize(), (int) ps.getMetadataLength(), buffer, ps.getVersionList(), writerVersion); }
From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java
/** * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. * /*from w ww . j a v a 2 s . co m*/ * @param content the portion to decode * @param charset the charset to use * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. * @return */ private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) { if (content == null) return null; ByteBuffer bb = ByteBuffer.allocate(content.length()); CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { char uc = cb.get(); char lc = cb.get(); int u = Character.digit(uc, 16); int l = Character.digit(lc, 16); if (u != -1 && l != -1) bb.put((byte) ((u << 4) + l)); else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else if (plusAsBlank && c == '+') bb.put((byte) ' '); else bb.put((byte) c); } bb.flip(); return charset.decode(bb).toString(); }
From source file:com.ibm.sbt.service.basic.ProxyService.java
private static byte[] decodeBase64(String s) { try {/*w ww . j a v a2 s .com*/ Base64.InputStream b64 = new Base64.InputStream(new ReaderInputStream(new StringReader(s))); ByteBuffer bb = ByteBuffer.allocate(1024 * 4); // max cookie size int byt; while ((byt = b64.read()) >= 0) { bb.put((byte) (byt & 0xFF)); } return bb.array(); } catch (IOException ex) { ex.printStackTrace(); return null; } }
From source file:com.linkedin.databus.core.DbusEventV2.java
public static void setKey(ByteBuffer buf, DbusEventKey key) { switch (key.getKeyType()) { case STRING:/*from w ww .j a v a2s .c o m*/ byte[] keyBytes = key.getStringKeyInBytes(); buf.putInt(keyBytes.length).put(keyBytes); break; case LONG: buf.putLong(key.getLongKey()); break; case SCHEMA: key.getSchemaKey().encode(buf); break; default: throw new UnsupportedOperationException("Unimplemented key type:" + key.getKeyType()); } }
From source file:com.gamesalutes.utils.ByteUtils.java
/** * Extends the size of <code>buf</code> to at least meet <code>minCap</code>. * If <code>buf</code> is too small, then a new buffer is allocated and * any existing contents in <code>buf</code> will be transfered. The position * of the new buffer will be that of the old buffer if it was not <code>null</code>, and * the previous mark will be discarded if one was set. * // w ww. j av a 2 s.co m * @param buf the input <code>ByteBuffer</code> * @param minCap the minimum capacity * @return a <code>ByteBuffer</code> that can meet <code>minCap</code> */ public static ByteBuffer growBuffer(ByteBuffer buf, int minCap) { int myLimit = buf != null ? buf.limit() : 0; // limit can accomidate capacity requirements if (buf != null && myLimit >= minCap) return buf; int myCap = buf != null ? buf.capacity() : 0; // capacity can accomidate but limit is too small if (buf != null && myCap >= minCap) { buf.limit(myCap); return buf; } else //if(myCap < minCap) { ByteBuffer newBuffer = null; if (myCap == 0) myCap = 1; while (myCap < minCap) myCap <<= 1; if (buf != null && buf.isDirect()) newBuffer = ByteBuffer.allocateDirect(myCap); else newBuffer = ByteBuffer.allocate(myCap); // copy contents of original buffer if (buf != null) { int pos = buf.position(); buf.clear(); newBuffer.put(buf); newBuffer.position(pos); } return newBuffer; } }
From source file:Main.java
public static byte[] aesIGEdecrypt(byte[] tmpAESiv, byte[] tmpAesKey, byte[] data) { try {/*from w w w . j ava2s .c o m*/ ByteBuffer out = ByteBuffer.allocate(data.length); byte[] iv2p = Arrays.copyOfRange(tmpAESiv, 0, tmpAESiv.length / 2); byte[] ivp = Arrays.copyOfRange(tmpAESiv, tmpAESiv.length / 2, tmpAESiv.length); int len = data.length / AES_BLOCK_SIZE; byte[] xorInput = null; byte[] xorOutput = null; SecretKeySpec keySpec = null; keySpec = new SecretKeySpec(tmpAesKey, "AES"); Cipher cipher = null; cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] input = null; byte[] output = null; for (int i = 0; i < len; i++) { input = Arrays.copyOfRange(data, i * AES_BLOCK_SIZE, (i + 1) * AES_BLOCK_SIZE); xorInput = xor(input, ivp); output = cipher.doFinal(xorInput); xorOutput = xor(output, iv2p); out.put(xorOutput); ivp = xorOutput; iv2p = input; } return out.array(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return null; }
From source file:edu.umass.cs.gigapaxos.paxosutil.PaxosPacketDemultiplexerFast.java
/** * @param bytes/*from w w w. j av a 2s . c om*/ * @param header * @return A static utility method to convert bytes to RequestPacket with * header processing. */ public static final Object processHeaderUtil(byte[] bytes, NIOHeader header) { if (isByteable(bytes)) { long t = System.nanoTime(); if (PaxosPacket.getType(bytes) == PaxosPacketType.REQUEST) { // affix header info only for request packets byte[] caddress = header.sndr.getAddress().getAddress(); short cport = (short) header.sndr.getPort(); byte[] laddress = header.rcvr.getAddress().getAddress(); short lport = (short) header.rcvr.getPort(); ByteBuffer bbuf = ByteBuffer.wrap(bytes, 0, 16); for (int i = 0; i < 3; i++) bbuf.getInt(); int paxosIDLength = bbuf.get(); int offset = 13 + paxosIDLength + 8 + 1; int expectedPos = offset + 4 + 2 + 4 + 2; assert (bytes.length > offset + 12) : bytes.length + " <= " + expectedPos; bbuf = ByteBuffer.wrap(bytes, offset, 12); boolean noCA = bytes[offset + 4] == 0 && bytes[offset + 5] == 0; boolean noLA = bytes[offset + 6 + 4] == 0 && bytes[offset + 6 + 5] == 0; try { if (noCA) bbuf.put(caddress).putShort(cport); if (noLA) bbuf.put(laddress).putShort(lport); } catch (Exception e) { assert (false) : bytes.length + " ? " + 16 + 4 + paxosIDLength + 8 + 1; } } try { PaxosPacket pp = toPaxosPacket(bytes); if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100)) { if (pp.getType() == PaxosPacketType.REQUEST) DelayProfiler.updateDelayNano("<-request", t); else if (pp.getType() == PaxosPacketType.BATCHED_ACCEPT_REPLY) DelayProfiler.updateDelayNano("<-acceptreply", t); } return pp; } catch (UnsupportedEncodingException | UnknownHostException e) { e.printStackTrace(); } return null; } if (!JSONPacket.couldBeJSON(bytes)) return bytes; String message; long t = System.nanoTime(); try { message = MessageExtractor.decode(bytes); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } net.minidev.json.JSONObject json = MessageExtractor.parseJSONSmart(message); assert (json != null) : message; net.minidev.json.JSONObject retval = MessageExtractor.stampAddressIntoJSONObject(header.sndr, header.rcvr, insertStringifiedSelf(json, message)); assert (retval != null) : message + " " + header; try { if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100)) if (PaxosPacket.getPaxosPacketType(retval) == PaxosPacket.PaxosPacketType.REQUEST) DelayProfiler.updateDelayNano("requestJSONification", t); else if (PaxosPacket.getPaxosPacketType(retval) == PaxosPacket.PaxosPacketType.BATCHED_ACCEPT_REPLY) DelayProfiler.updateDelayNano("batchedAcceptReplyJSONification", t); } catch (JSONException e) { e.printStackTrace(); } return retval; }
From source file:com.mcxiaoke.next.http.util.URLUtils.java
/** * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. * * @param content the portion to decode * @param charset the charset to use * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. * @return encoded string/*w ww . j av a 2 s. c om*/ */ private static String urlDecode(final String content, final Charset charset, final boolean plusAsBlank) { if (content == null) { return null; } final ByteBuffer bb = ByteBuffer.allocate(content.length()); final CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { final char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { final char uc = cb.get(); final char lc = cb.get(); final int u = Character.digit(uc, 16); final int l = Character.digit(lc, 16); if (u != -1 && l != -1) { bb.put((byte) ((u << 4) + l)); } else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else if (plusAsBlank && c == '+') { bb.put((byte) ' '); } else { bb.put((byte) c); } } bb.flip(); return charset.decode(bb).toString(); }
From source file:com.eventsourcing.layout.comparable.ByteArrayComparableSerializer.java
@Override public void serialize(Object value, ByteBuffer buffer) { byte[] bytes = getPrimitiveArray(value); buffer.put(bytes); }