List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:co.paralleluniverse.galaxy.core.BackupImpl.java
private Message.BACKUP makeBackup(CacheLine line, long version) { if (line.getVersion() != version) return null; final Message.BACKUP backup; if (line.getData() == null) { backup = Message.BACKUP(line.getId(), line.getVersion(), null); } else {//from www .j av a 2s . co m final ByteBuffer buffer = ByteBuffer.allocate(line.getData().limit()); // storage.allocateStorage(line.getData().limit()); line.rewind(); buffer.put(line.getData()); line.rewind(); buffer.flip(); backup = Message.BACKUP(line.getId(), line.getVersion(), buffer); } LOG.debug("Copying version {} of line {} data: {}", new Object[] { backup.getVersion(), hex(backup.getLine()), backup.getData() != null ? "(" + backup.getData().remaining() + " bytes)" : "null" }); return backup; }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Lecture du fichier et envoi sur la socket. * * @param resultat// w w w .ja v a 2 s .co m * resultat * @param fileForTestSize * fileForTestSize * @param channel * channel * @param bufFileForTestRead * bufFileForTestRead * @throws IOException * IOException */ protected void readAndSendFile(final StringBuilder resultat, final long fileForTestSize, final SocketChannel channel, final MappedByteBuffer bufFileForTestRead) throws IOException { // Envoi de la commande final ByteBuffer writeReadBuffer = ByteBuffer.allocate(BUFFER_SIZE); writeReadBuffer.put(ClamAVCheckService.COMMANDE.getBytes(UTF_8)); writeReadBuffer.put(this.intToByteArray((int) fileForTestSize)); writeReadBuffer.flip(); channel.write(writeReadBuffer); // Envoi du fichier long size = fileForTestSize; // envoi du fichier while (size > 0) { size -= channel.write(bufFileForTestRead); } final ByteBuffer writeBuffer = ByteBuffer.allocate(4); writeBuffer.put(new byte[] { 0, 0, 0, 0 }); writeBuffer.flip(); channel.write(writeBuffer); // lecture de la rponse ByteBuffer readBuffer; readBuffer = ByteBuffer.allocate(BUFFER_SIZE); // lecture de la rponse readBuffer.clear(); boolean readLine = false; while (!readLine) { final int numReaden = channel.read(readBuffer); if (numReaden > 0) { readLine = readBuffer.get(numReaden - 1) == '\n'; resultat.append(new String(readBuffer.array(), 0, numReaden, UTF_8)); readBuffer.clear(); } else { if (numReaden == -1) { readLine = true; readBuffer.clear(); } } } }
From source file:com.linkedin.databus.bootstrap.utils.BootstrapTableReader.java
public void execute() throws Exception { String query = getQuery();//w ww . j ava 2 s . c o m Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(); LOG.info("Executing query : " + query); rs = stmt.executeQuery(query); byte[] b1 = new byte[1024 * 1024]; ByteBuffer buffer = ByteBuffer.wrap(b1); DbusEventInternalReadable event = _eventFactory.createReadOnlyDbusEventFromBuffer(buffer, 0); int count = 0; _eventHandler.onStart(query); while (rs.next()) { buffer.clear(); buffer.put(rs.getBytes("val")); event = event.reset(buffer, 0); GenericRecord record = _decoder.getGenericRecord(event); _eventHandler.onRecord(event, record); count++; } _eventHandler.onEnd(count); } finally { DBHelper.close(rs, stmt, conn); } }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testReadStrings() throws IOException { // good case//from w w w . j av a 2 s .co m ByteBuffer buffer = ByteBuffer.allocate(10); buffer.putShort((short) 8); String s = getRandomString(8); buffer.put(s.getBytes()); buffer.flip(); String outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertEquals(s, outputString); // 0-length buffer.rewind(); buffer.putShort(0, (short) 0); outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(outputString.isEmpty()); // failed case buffer.rewind(); buffer.putShort((short) 10); buffer.put(s.getBytes()); buffer.flip(); try { outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(false); } catch (IllegalArgumentException e) { Assert.assertTrue(true); } buffer.rewind(); buffer.putShort(0, (short) -1); try { outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { } // good case buffer = ByteBuffer.allocate(40004); buffer.putInt(40000); s = getRandomString(40000); buffer.put(s.getBytes()); buffer.flip(); outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); Assert.assertEquals(s, outputString); // 0-length buffer.rewind(); buffer.putInt(0, 0); outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(outputString.isEmpty()); // failed case buffer.rewind(); buffer.putInt(50000); buffer.put(s.getBytes()); buffer.flip(); try { outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); fail("Should have failed"); } catch (IllegalArgumentException e) { // expected. } buffer.rewind(); buffer.putInt(0, -1); try { Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { // expected. } }
From source file:de.csdev.ebus.command.EBusCommandUtils.java
/** * @param commandMethod// w w w.j a v a 2 s . co m * @param values * @return * @throws EBusTypeException */ public static ByteBuffer composeMasterData(IEBusCommandMethod commandMethod, Map<String, Object> values) throws EBusTypeException { ByteBuffer buf = ByteBuffer.allocate(50); Map<Integer, IEBusComplexType<?>> complexTypes = new HashMap<Integer, IEBusComplexType<?>>(); if (commandMethod.getMasterTypes() != null) { for (IEBusValue entry : commandMethod.getMasterTypes()) { IEBusType<?> type = entry.getType(); byte[] b = null; // use the value from the values map if set if (values != null && values.containsKey(entry.getName())) { b = type.encode(values.get(entry.getName())); } else { if (type instanceof IEBusComplexType) { // add the complex to the list for post processing complexTypes.put(buf.position(), (IEBusComplexType<?>) type); // add placeholder b = new byte[entry.getType().getTypeLength()]; } else { b = type.encode(entry.getDefaultValue()); } } if (b == null) { throw new RuntimeException("Encoded value is null! " + type.toString()); } // buf.p buf.put(b); // len += type.getTypeLength(); } } // replace the placeholders with the complex values if (!complexTypes.isEmpty()) { int orgPos = buf.position(); for (Entry<Integer, IEBusComplexType<?>> entry : complexTypes.entrySet()) { // jump to position buf.position(entry.getKey()); // put new value buf.put(entry.getValue().encodeComplex(buf)); } buf.position(orgPos); } // reset pos to zero and set the new limit buf.limit(buf.position()); buf.position(0); return buf; }
From source file:intelligentWebAlgorithms.util.internet.crawling.transport.http.HTTPTransport.java
private FetchedDocument createDocument(String targetURL, HttpEntity entity, String groupId, int docSequenceInGroup) throws IOException, HTTPTransportException { FetchedDocument doc = new FetchedDocument(); String documentId = DocumentIdUtils.getDocumentId(groupId, docSequenceInGroup); BufferedInputStream bufferedInput = null; byte[] buffer = new byte[MINIMUM_BUFFER_SIZE]; int contentLength = (int) entity.getContentLength(); if (contentLength > MAX_DOCUMENT_LENGTH) P.println("WARNING: Retrieved document larger than " + MAX_DOCUMENT_LENGTH + " [bytes]"); // If the size is smaller than the minimum then extend it // if (contentLength < MINIMUM_BUFFER_SIZE) // contentLength = MINIMUM_BUFFER_SIZE; ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_DOCUMENT_LENGTH); // Construct the BufferedInputStream object bufferedInput = new BufferedInputStream(entity.getContent()); // Keep reading while there is content // when the end of the stream has been reached, -1 is returned while (bufferedInput.read(buffer) != -1) { // Process the chunk of bytes read byteBuffer.put(buffer); }// www . j ava 2 s. c o m /* IOException will be thrown for documents that exceed max length */ byte[] data = byteBuffer.array(); /* * Check if server sent content in compressed form and uncompress the * content if necessary. */ Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { data = HTTPUtils.decodeContent(contentEncodingHeader.getValue(), data); } /* 'Content-Type' HTTP header value */ String contentTypeHeaderValue = null; Header header = entity.getContentType(); if (header != null) { contentTypeHeaderValue = header.getValue(); } /* * Determine MIME type of the document. * * It is easy if we have Content-Type http header. In cases when this * header is missing or for protocols that don't pass metadata about the * documents (ftp://, file://) we would have to resort to url and/or * content analysis to determine MIME type. */ String DEFAULT_CONTENT_TYPE = "text/html"; String contentType = HTTPUtils.getContentType(contentTypeHeaderValue, targetURL, data); if (contentType == null) { contentType = DEFAULT_CONTENT_TYPE; } /* * Determine Character encoding used in the document. In some cases it * may be specified in the http header, in html file itself or we have * to perform content analysis to choose the encoding. */ String DEFAULT_CONTENT_CHARSET = "UTF-8"; String contentCharset = HTTPUtils.getCharset(contentTypeHeaderValue, contentType, data); if (contentCharset == null) { contentCharset = DEFAULT_CONTENT_CHARSET; } doc.setDocumentId(documentId); doc.setContentType(contentType); doc.setDocumentURL(targetURL); doc.setContentCharset(contentCharset); doc.setDocumentContent(data); doc.setDocumentMetadata(new HashMap<String, String>()); return doc; }
From source file:com.googlecode.mp4parser.boxes.microsoft.XtraBox.java
@Override protected void getContent(ByteBuffer byteBuffer) { if (successfulParse) { for (int i = 0; i < tags.size(); i++) { tags.elementAt(i).getContent(byteBuffer); }/*www. ja v a2 s. c o m*/ } else { data.rewind(); byteBuffer.put(data); } }
From source file:org.opendaylight.controller.topology.web.Topology.java
/** * Add regular hosts to main topology//from ww w .ja v a2 s. c o m * * @param hostEdges - node-nodeconnectors host-specific mapping from topology * @param topology - topology instance */ private void addHostNodes(Map<Node, Set<NodeConnector>> hostEdges, ITopologyManager topology, String containerName) { for (Map.Entry<Node, Set<NodeConnector>> e : hostEdges.entrySet()) { for (NodeConnector connector : e.getValue()) { List<Host> hosts = topology.getHostsAttachedToNodeConnector(connector); for (Host host : hosts) { EthernetAddress dmac = (EthernetAddress) host.getDataLayerAddress(); ByteBuffer addressByteBuffer = ByteBuffer.allocate(8); addressByteBuffer.putShort((short) 0); addressByteBuffer.put(dmac.getValue()); addressByteBuffer.rewind(); long hid = addressByteBuffer.getLong(); String hostId = String.valueOf(hid); NodeBean hostBean = new NodeBean(hostId, host.getNetworkAddressAsString(), NodeType.HOST); List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>(); EdgeBean edge = new EdgeBean(connector, hid); adjacencies.add(edge.out()); hostBean.setLinks(adjacencies); if (metaCache.get(containerName).containsKey(hostId)) { Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId); hostEntry.put("adjacencies", adjacencies); stagedNodes.put(hostId, hostEntry); } else { newNodes.put(String.valueOf(hid), hostBean.out()); } } } } }
From source file:com.meidusa.venus.benchmark.FileLineRandomData.java
private final String readLine(ByteBuffer buffer) { if (closed)// www . ja v a2 s. c o m throw new IllegalStateException("file closed.."); ByteBuffer tempbuffer = localTempBuffer.get(); tempbuffer.position(0); tempbuffer.limit(tempbuffer.capacity()); byte c = -1; boolean eol = false; while (!eol) { switch (c = buffer.get()) { case -1: case '\n': eol = true; break; case '\r': eol = true; int cur = buffer.position(); if ((buffer.get()) != '\n') { buffer.position(cur); } break; default: tempbuffer.put(c); break; } } if ((c == -1) && (tempbuffer.position() == 0)) { return null; } tempbuffer.flip(); try { return new String(tempbuffer.array(), encoding); } catch (UnsupportedEncodingException e) { return new String(tempbuffer.array()); } }
From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java
public final byte[] encrypt(final byte[] bytes) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { ready();/*from w w w. j a v a 2s. c o m*/ activecrypts++; try { final Cipher ecipher = this.crypter.getEcipher(); byte[] salt = ecipher.getIV(); final ByteBuffer outbuf = ByteBuffer .allocate(ecipher.getOutputSize(bytes.length) + (salt != null ? salt.length : 0) + 1); if (salt != null) { outbuf.put((byte) salt.length); outbuf.put(salt); } else outbuf.put((byte) 0); try { ecipher.doFinal(ByteBuffer.wrap(bytes), outbuf); } catch (ShortBufferException e) { // not going to happen since we specifically allocate based on the cipher output size } return outbuf.array(); } finally { activecrypts--; } }