List of usage examples for java.nio ByteBuffer clear
public final Buffer clear()
From source file:cn.ac.ncic.mastiff.io.coding.DeltaBinaryArrayZigZarByteReader.java
@Override public byte[] ensureDecompressed() throws IOException { FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray(); dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12); FlexibleEncoding.Parquet.DeltaByteArrayReader reader = new FlexibleEncoding.Parquet.DeltaByteArrayReader(); ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size()); dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size()); byteBuf.flip();//from www . j av a 2 s . com reader.initFromPage(numPairs, byteBuf.array(), 0); DataOutputBuffer decoding = new DataOutputBuffer(); decoding.writeInt(decompressedSize); decoding.writeInt(numPairs); decoding.writeInt(startPos); for (int i = 0; i < numPairs; i++) { byte tmp = Byte.parseByte(reader.readBytes().toStringUsingUTF8()); decoding.writeByte(tmp); } byteBuf.clear(); inBuf.close(); return decoding.getData(); }
From source file:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();/*ww w. ja va2 s . com*/ CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }
From source file:eu.faircode.netguard.SinkholeService.java
private void startDebug(final ParcelFileDescriptor pfd) { if (!debug)/*from ww w.j ava2 s .c o m*/ return; thread = new Thread(new Runnable() { @Override public void run() { try { FileInputStream in = new FileInputStream(pfd.getFileDescriptor()); FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor()); ByteBuffer buffer = ByteBuffer.allocate(32767); buffer.order(ByteOrder.BIG_ENDIAN); Log.i(TAG, "Start receiving"); while (!Thread.currentThread().isInterrupted() && pfd.getFileDescriptor() != null && pfd.getFileDescriptor().valid()) try { buffer.clear(); int length = in.read(buffer.array()); if (length > 0) { buffer.limit(length); Packet pkt = new Packet(buffer); if (pkt.IPv4.protocol == Packet.IPv4Header.TCP && pkt.TCP.SYN) { int uid = pkt.getUid4(); if (uid < 0) Log.w(TAG, "uid not found"); String[] pkg = getPackageManager().getPackagesForUid(uid); if (pkg == null) pkg = new String[] { uid == 0 ? "root" : "unknown" }; Log.i(TAG, "Connect " + pkt.IPv4.destinationAddress + ":" + pkt.TCP.destinationPort + " uid=" + uid + " pkg=" + pkg[0]); // Send RST pkt.swapAddresses(); pkt.TCP.clearFlags(); pkt.TCP.RST = true; long ack = pkt.TCP.acknowledgementNumber; pkt.TCP.acknowledgementNumber = (pkt.TCP.sequenceNumber + 1) & 0xFFFFFFFFL; pkt.TCP.sequenceNumber = (ack + 1) & 0xFFFFFFFFL; pkt.send(out); } } } catch (Throwable ex) { Log.e(TAG, ex.toString()); } Log.i(TAG, "End receiving"); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } }); thread.start(); }
From source file:Proxy.java
/** * Read all data from <code>from</code> and write it to <code>to</code>. * Returns false if channel was closed//w w w.ja v a 2 s.c om */ boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception { int num; StringBuilder sb; buf.clear(); while (true) { num = from.read(buf); if (num < 0) return false; else if (num == 0) return true; buf.flip(); if (verbose) { log(printRelayedData(toString(from), toString(to), buf.remaining())); } if (debug) { sb = new StringBuilder(); sb.append(new String(buf.array()).trim()); sb.append('\n'); log(sb.toString()); } to.write(buf); buf.flip(); } }
From source file:burstcoin.jminer.core.reader.task.ReaderLoadDriveTask.java
private boolean load(PlotFile plotFile) { try (SeekableByteChannel sbc = Files.newByteChannel(plotFile.getFilePath(), EnumSet.of(StandardOpenOption.READ))) { long currentScoopPosition = scoopNumber * plotFile.getStaggeramt() * MiningPlot.SCOOP_SIZE; long partSize = plotFile.getStaggeramt() / plotFile.getNumberOfParts(); ByteBuffer partBuffer = ByteBuffer.allocate((int) (partSize * MiningPlot.SCOOP_SIZE)); // optimized plotFiles only have one chunk! for (int chunkNumber = 0; chunkNumber < plotFile.getNumberOfChunks(); chunkNumber++) { long currentChunkPosition = chunkNumber * plotFile.getStaggeramt() * MiningPlot.PLOT_SIZE; sbc.position(currentScoopPosition + currentChunkPosition); for (int partNumber = 0; partNumber < plotFile.getNumberOfParts(); partNumber++) { sbc.read(partBuffer);//from w ww . j av a2 s .c o m if (Reader.blockNumber != blockNumber) { LOG.trace("loadDriveThread stopped!"); partBuffer.clear(); sbc.close(); return true; } else { long chunkPartStartNonce = plotFile.getStartnonce() + (chunkNumber * plotFile.getStaggeramt()) + (partNumber * partSize); final byte[] scoops = partBuffer.array(); publisher.publishEvent(new ReaderLoadedPartEvent(blockNumber, scoops, chunkPartStartNonce)); } partBuffer.clear(); } } sbc.close(); } catch (NoSuchFileException exception) { LOG.error("File not found ... please restart to rescan plot-files, maybe set rescan to 'true': " + exception.getMessage()); } catch (ClosedByInterruptException e) { // we reach this, if we do not wait for task on shutdown - ByteChannel closed by thread interruption LOG.trace("reader stopped cause of new block ..."); } catch (IOException e) { LOG.error("IOException: " + e.getMessage()); } return false; }
From source file:org.jtrfp.trcl.core.Texture.java
Texture(ByteBuffer imageRGBA8888, ByteBuffer imageESTuTv8888, String debugName, TR tr, boolean uvWrapping) { this(tr, debugName, uvWrapping); if (imageRGBA8888.capacity() == 0) { throw new IllegalArgumentException("Cannot create texture of zero size."); } //end if capacity==0 imageRGBA8888.clear();//Doesn't erase, just resets the tracking vars vqCompress(imageRGBA8888, imageESTuTv8888); }
From source file:org.apache.carbondata.core.util.CarbonUtil.java
/** * Below method will be used to get the surrogate key * * @param data actual data//from w w w . ja v a2 s .co m * @param buffer byte buffer which will be used to convert the data to integer value * @return surrogate key */ public static int getSurrogateKey(byte[] data, ByteBuffer buffer) { int lenght = 4 - data.length; for (int i = 0; i < lenght; i++) { buffer.put((byte) 0); } buffer.put(data); buffer.rewind(); int surrogate = buffer.getInt(); buffer.clear(); return surrogate; }
From source file:org.openhealthtools.openatna.syslog.bsd.BsdMessageFactory.java
public SyslogMessage read(InputStream in) throws SyslogException { try {/*from w w w . ja v a 2s . co m*/ PushbackInputStream pin = new PushbackInputStream(in, 5); int priority = readPriority(pin); int facility; int severity; byte c; int spaces = 4; int count = 0; boolean spaceBefore = false; ByteBuffer buff = ByteBuffer.wrap(new byte[256]); String timestamp; String month = null; String date = null; String time = null; String host = ""; int max = 256; int curr = 0; while (count < spaces && curr < max) { c = (byte) pin.read(); curr++; if (c == ' ') { if (!spaceBefore) { count++; String currHeader = new String(buff.array(), 0, buff.position(), Constants.ENC_UTF8); buff.clear(); switch (count) { case 1: month = currHeader; break; case 2: date = currHeader; break; case 3: time = currHeader; break; case 4: host = currHeader; break; } } spaceBefore = true; } else { spaceBefore = false; buff.put(c); } } if (month == null || date == null || time == null) { timestamp = createDate(new Date()); } else { String gap = " "; if (date.length() == 1) { gap = " "; } timestamp = (month + gap + date + " " + time); try { formatDate(timestamp); } catch (Exception e) { timestamp = createDate(new Date()); } } String tag = null; int tagLen = 32; buff.clear(); for (int i = 0; i < tagLen; i++) { c = (byte) pin.read(); curr++; if (!Character.isLetterOrDigit((char) (c & 0xff))) { pin.unread(c); break; } buff.put(c); } if (buff.position() > 0) { tag = new String(buff.array(), 0, buff.position(), Constants.ENC_UTF8); } LogMessage logMessage = getLogMessage(tag); String encoding = readBom(pin, logMessage.getExpectedEncoding()); logMessage.read(pin, encoding); facility = priority / 8; severity = priority % 8; return new BsdMessage(facility, severity, timestamp, host, logMessage, tag); } catch (IOException e) { e.printStackTrace(); throw new SyslogException(e); } }
From source file:com.google.cloud.hadoop.gcsio.GoogleCloudStorageIntegrationHelper.java
/** * Writes a file with the given buffer repeated numWrites times. * * @param bucketName name of the bucket to create object in * @param objectName name of the object to create * @param buffer Data to write// w ww .j av a2s. c o m * @param numWrites number of times to repeat the data * @return number of bytes written */ protected int writeFile(String bucketName, String objectName, ByteBuffer buffer, int numWrites) throws IOException { int numBytesWritten = -1; int totalBytesWritten = 0; WritableByteChannel writeChannel = null; try { writeChannel = create(bucketName, objectName, new CreateFileOptions(false /* overwrite existing */)); for (int i = 0; i < numWrites; i++) { buffer.clear(); numBytesWritten = writeChannel.write(buffer); Assert.assertEquals("could not write the entire buffer", buffer.capacity(), numBytesWritten); totalBytesWritten += numBytesWritten; } } finally { if (writeChannel != null) { writeChannel.close(); } } return totalBytesWritten; }
From source file:com.emc.ecs.smart.SmartUploader.java
private String computeFileMD5() throws IOException { l4j.debug("Computing File MD5 with NIO"); fileChannel.position(0);//w w w.j av a 2 s . c om MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // Should never happen throw new RuntimeException("Could not load MD5", e); } long start = System.currentTimeMillis(); // Force a 2MB buffer for better performance. ByteBuffer buf = ByteBuffer.allocateDirect(SMALL_SEGMENT); int c; long position = 0; buf.clear(); while ((c = fileChannel.read(buf)) != -1) { buf.rewind(); buf.limit(c); md5.update(buf); buf.clear(); position += c; System.out.printf("\rLocal MD5 computation: %d / %d (%d %%)", position, fileSize, position * 100L / fileSize); } long duration = System.currentTimeMillis() - start; printRate(duration); return MD5Utils.toHexString(md5.digest()); }