List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:com.offbynull.portmapper.natpmp.NatPmpController.java
private <T extends NatPmpResponse> T performRequest(int sendAttempts, NatPmpRequest request, Creator<T> creator) throws InterruptedException { Validate.inclusiveBetween(1, 9, sendAttempts); ByteBuffer sendBuffer = ByteBuffer.allocate(12); request.dump(sendBuffer);/*w w w . jav a2s. com*/ sendBuffer.flip(); for (int i = 1; i <= sendAttempts; i++) { T response = attemptRequest(sendBuffer, i, creator); if (response != null) { return response; } } throw new ResponseException(); }
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/*from w w w . j a v a2 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:org.apache.htrace.impl.PackedBuffer.java
public String toHexString() { String prefix = ""; StringBuilder bld = new StringBuilder(); ByteBuffer b = bb.duplicate(); b.flip(); while (b.hasRemaining()) { bld.append(String.format("%s%02x", prefix, b.get())); prefix = " "; }//w w w . ja va2 s .co m return bld.toString(); }
From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java
/** * /*from ww w .j a va 2 s .c o m*/ */ public void excute() { String tmpOutFile = outFile.getPath().concat(File.separator) .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf")); List<String> commandArray = new ArrayList<String>(); commandArray.add(defaultCommand); commandArray.add(inFile.getPath()); commandArray.add("-o"); commandArray.add(tmpOutFile); ProcessBuilder pbObj = new ProcessBuilder(); pbObj.command(commandArray); pbObj.directory(outFile); pbObj.redirectErrorStream(true); try { Process proObj = pbObj.start(); final InputStream ins = proObj.getInputStream(); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); Thread th = new Thread() { public void run() { ReadableByteChannel rbcObj = Channels.newChannel(ins); try { while (rbcObj.read(byteBuffer) != -1) { byteBuffer.flip(); logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer)); byteBuffer.clear(); } } catch (IOException e) { logger.error(e); } } }; th.setDaemon(true); th.start(); try { proObj.waitFor(); logger.error("??." + tmpOutFile); } catch (InterruptedException e) { logger.error(e); } } catch (IOException e) { logger.error(e); } }
From source file:org.apache.hadoop.hbase.client.TestResult.java
public void testBasicLoadValue() throws Exception { KeyValue[] kvs = genKVs(row, family, value, 1, 100); Arrays.sort(kvs, KeyValue.COMPARATOR); Result r = Result.create(kvs); ByteBuffer loadValueBuffer = ByteBuffer.allocate(1024); for (int i = 0; i < 100; ++i) { final byte[] qf = Bytes.toBytes(i); loadValueBuffer.clear();//w ww.j a va2 s . c o m r.loadValue(family, qf, loadValueBuffer); loadValueBuffer.flip(); assertEquals(ByteBuffer.wrap(Bytes.add(value, Bytes.toBytes(i))), loadValueBuffer); assertEquals(ByteBuffer.wrap(Bytes.add(value, Bytes.toBytes(i))), r.getValueAsByteBuffer(family, qf)); } }
From source file:net.fenyo.extension.Dns.TcpSocket.java
@Override public void run() { if (read_thread) { read_thread = false;//from w ww . j ava2 s . c o m new Thread(this).start(); try { // thread de lecture locale pour envoi au serveur while (true) { final ByteBuffer tmp_read_buf = ByteBuffer.allocate(1024); int ret = socket_channel.read(tmp_read_buf); if (ret >= 0) { tmp_read_buf.flip(); synchronized (read_buf) { read_buf.put(tmp_read_buf); } } else { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } return; } } } catch (IOException e) { Log.e("TcpSocket:run(): read(): ", "IOException"); e.printStackTrace(); try { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } } catch (IOException e1) { Log.e("TcpSocket:run(): close(): ", "IOException"); e1.printStackTrace(); } return; } finally { tcp_init.removeSocket(id); terminateLocalWriteThread(); // Log.i("Alex", "femeture thread 1 id=" + id); } } else { try { // thread de lecture distante pour crire sur socket locale while (true) { synchronized (write_buf_sem) { if (must_exit == true) return; try { if (write_buf.length == 0) { if (must_exit_when_all_data_read_locally) { try { socket_channel.close(); } catch (IOException e) { Log.e("TcpSocket:closeSocket()", "Exception"); e.printStackTrace(); } return; } write_buf_sem.wait(); } } catch (InterruptedException e) { // e.printStackTrace(); return; } } ByteBuffer _write_buf; synchronized (write_buf_sem) { _write_buf = ByteBuffer.allocate(write_buf.length); _write_buf.put(write_buf); } _write_buf.flip(); int nbytes = socket_channel.write(_write_buf); synchronized (write_buf_sem) { final byte[] new_write_buf = new byte[write_buf.length - nbytes]; for (int i = 0; i < write_buf.length - nbytes; i++) new_write_buf[i] = write_buf[i + nbytes]; write_buf = new_write_buf; } } } catch (IOException e) { Log.e("TcpSocket:run(): write(): ", "IOException"); e.printStackTrace(); try { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } } catch (IOException e1) { Log.e("TcpSocket:run(): close(): ", "IOException"); e1.printStackTrace(); } return; } finally { // Log.i("Alex", "femeture thread 2 id=" + id); } } }
From source file:org.apache.axis2.transport.nhttp.ClientHandler.java
/** * Process ready input (i.e. response from remote server) * @param conn connection being processed * @param decoder the content decoder in use *//* w ww . j a va 2s. c om*/ public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); Pipe.SinkChannel sink = (Pipe.SinkChannel) context.getAttribute(RESPONSE_SINK_CHANNEL); ByteBuffer inbuf = (ByteBuffer) context.getAttribute(REQUEST_BUFFER); try { while (decoder.read(inbuf) > 0) { inbuf.flip(); sink.write(inbuf); inbuf.compact(); } if (decoder.isCompleted()) { sink.close(); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { ConnectionPool.release(conn); } } } catch (IOException e) { handleException("I/O Error : " + e.getMessage(), e, conn); } }
From source file:net.librec.data.convertor.appender.SocialDataAppender.java
/** * Read data from the data file. Note that we didn't take care of the * duplicated lines./* ww w . j a v a2s .c o m*/ * * @param inputDataPath * the path of the data file * @throws IOException if I/O error occurs during reading */ private void readData(String inputDataPath) throws IOException { // Table {row-id, col-id, rate} Table<Integer, Integer, Double> dataTable = HashBasedTable.create(); // Map {col-id, multiple row-id}: used to fast build a rating matrix Multimap<Integer, Integer> colMap = HashMultimap.create(); // BiMap {raw id, inner id} userIds, itemIds final List<File> files = new ArrayList<File>(); final ArrayList<Long> fileSizeList = new ArrayList<Long>(); SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { fileSizeList.add(file.toFile().length()); files.add(file.toFile()); return super.visitFile(file, attrs); } }; Files.walkFileTree(Paths.get(inputDataPath), finder); long allFileSize = 0; for (Long everyFileSize : fileSizeList) { allFileSize = allFileSize + everyFileSize.longValue(); } // loop every dataFile collecting from walkFileTree for (File dataFile : files) { FileInputStream fis = new FileInputStream(dataFile); FileChannel fileRead = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); int len; String bufferLine = new String(); byte[] bytes = new byte[BSIZE]; while ((len = fileRead.read(buffer)) != -1) { buffer.flip(); buffer.get(bytes, 0, len); bufferLine = bufferLine.concat(new String(bytes, 0, len)).replaceAll("\r", "\n"); String[] bufferData = bufferLine.split("(\n)+"); boolean isComplete = bufferLine.endsWith("\n"); int loopLength = isComplete ? bufferData.length : bufferData.length - 1; for (int i = 0; i < loopLength; i++) { String line = new String(bufferData[i]); String[] data = line.trim().split("[ \t,]+"); String userA = data[0]; String userB = data[1]; Double rate = (data.length >= 3) ? Double.valueOf(data[2]) : 1.0; if (userIds.containsKey(userA) && userIds.containsKey(userB)) { int row = userIds.get(userA); int col = userIds.get(userB); dataTable.put(row, col, rate); colMap.put(col, row); } } if (!isComplete) { bufferLine = bufferData[bufferData.length - 1]; } buffer.clear(); } fileRead.close(); fis.close(); } int numRows = userIds.size(), numCols = userIds.size(); // build rating matrix userSocialMatrix = new SparseMatrix(numRows, numCols, dataTable, colMap); // release memory of data table dataTable = null; }
From source file:com.cloud.maint.UpgradeManagerImpl.java
public String deployNewAgent(String url) { s_logger.info("Updating agent with binary from " + url); final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); int response; File file = null;// ww w . ja v a 2s . co m try { response = client.executeMethod(method); if (response != HttpURLConnection.HTTP_OK) { s_logger.warn("Retrieving the agent gives response code: " + response); return "Retrieving the file from " + url + " got response code: " + response; } final InputStream is = method.getResponseBodyAsStream(); file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime())); file.deleteOnExit(); s_logger.debug("Retrieving new agent into " + file.getAbsolutePath()); final FileOutputStream fos = new FileOutputStream(file); final ByteBuffer buffer = ByteBuffer.allocate(2048); final ReadableByteChannel in = Channels.newChannel(is); final WritableByteChannel out = fos.getChannel(); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } in.close(); out.close(); s_logger.debug("New Agent zip file is now retrieved"); } catch (final HttpException e) { return "Unable to retrieve the file from " + url; } catch (final IOException e) { return "Unable to retrieve the file from " + url; } finally { method.releaseConnection(); } file.delete(); return "File will be deployed."; }
From source file:gridool.memcached.gateway.BinaryCommandProxy.java
private void xferMemcacheCmd(final byte opcode, final Header reqHeader, final ChannelBuffer body, final byte[] key, final MessageEvent e) { int bodylen = body.readableBytes(); final ByteBuffer cmd = ByteBuffer.allocate(BinaryProtocol.HEADER_LENGTH + bodylen); reqHeader.encode(cmd);//ww w . j a va 2s . c om if (bodylen > 0) { body.readBytes(cmd); } cmd.flip(); final SocketAddress sockAddr = getSocket(key); final SocketChannel channel = sockPool.borrowObject(sockAddr); try { NIOUtils.writeFully(channel, cmd); xferResponse(opcode, channel, e.getChannel(), StringUtils.toByteString(key)); } catch (IOException ioe) { LOG.error(ioe); sendError(reqHeader.getOpcode(), ResponseStatus.INTERNAL_ERROR, reqHeader, e); } finally { sockPool.returnObject(sockAddr, channel); } }