List of usage examples for java.nio ByteBuffer array
public final byte[] array()
From source file:cn.iie.haiep.hbase.value.Bytes.java
/** * Converts the given byte buffer, from its array offset to its limit, to * a string. The position and the mark are ignored. * * @param buf a byte buffer/* w ww. ja v a 2s .com*/ * @return a string representation of the buffer's binary contents */ public static String toStringBinary(ByteBuffer buf) { if (buf == null) return "null"; return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit()); }
From source file:io.lightlink.output.JSONResponseStream.java
public void writeFromReader(Reader reader) { write('"');/* w w w.ja v a 2 s . c om*/ char[] buffer = new char[16000]; long count = 0; int n = 0; try { while (-1 != (n = reader.read(buffer))) { ByteBuffer bbuffer = CHARSET.encode(CharBuffer.wrap(buffer, 0, n)); write(bbuffer.array(), bbuffer.remaining()); count += n; } write('"'); reader.close(); } catch (IOException e) { throw new RuntimeException(e.toString(), e); } }
From source file:com.owncloud.android.lib.common.network.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/*from www.j ava2 s . c o m*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:io.lightlink.output.JSONResponseStream.java
private void writeEscapedString(String valueStr) { char[] chars = valueStr.toCharArray(); StringBuffer sb = new StringBuffer(valueStr); for (int i = chars.length - 1; i >= 0; i--) { char ch = chars[i]; switch (ch) { case '"': sb.replace(i, i + 1, STR_QUOT); break; case '\\': sb.replace(i, i + 1, STR_BACKSLASH); break; case '\b': sb.replace(i, i + 1, STR_B); break; case '\f': sb.replace(i, i + 1, STR_F); break; case '\n': sb.replace(i, i + 1, STR_N); break; case '\r': sb.replace(i, i + 1, STR_R); break; case '\t': sb.replace(i, i + 1, STR_T); break; case '/': sb.replace(i, i + 1, STR_SLASH); break; default://from w w w . j av a 2 s .co m //Reference: http://www.unicode.org/versions/Unicode5.1.0/ if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { StringBuilder encoded = new StringBuilder(); String ss = Integer.toHexString(ch).toUpperCase(); encoded.append(STR_SLASH_U); for (int k = 0; k < 4 - ss.length(); k++) { encoded.append('0'); } encoded.append(ss.toUpperCase()); sb.replace(i, i + 1, encoded.toString()); } } } ByteBuffer buffer = CHARSET.encode(sb.toString()); write(buffer.array(), buffer.remaining()); }
From source file:com.spotify.heroic.metric.bigtable.BigtableBackend.java
ByteString serializeValue(double value) { final ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES).putLong(Double.doubleToLongBits(value)); return ByteString.copyFrom(buffer.array()); }
From source file:org.enotron.EnergySimulatorEndpoint.java
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "listGridsimsRequest") @ResponsePayload// ww w . ja va2 s . c o m public ListGridsimsResponse listGridsims() { ListGridsimsResponse resp = new ListGridsimsResponse(); for (ByteBuffer simId : configuration.getSimList().keySet()) { Simulator sim = configuration.getSimList().get(simId); SimulatorDetails simDetails = new SimulatorDetails(); simDetails.setSimulatorName(sim.getName()); simDetails.setSimulatorUid(simId.array()); simDetails.setSimulatorType(sim.getClass().getSimpleName()); simDetails.setLongitude(sim.getLongitude()); simDetails.setLatitude(sim.getLatitude()); simDetails.setDescription(sim.getDescription()); SimulatorDetailsAndRun sdr = new SimulatorDetailsAndRun(); sdr.setSimulatorDetails(simDetails); if (execution != null) { try { SimulatorRun run = convertRunDetails(execution.getSimulatorStatus(simId.array())); sdr.setSimulatorRun(run); } catch (SimulatorException e) { e.printStackTrace(); } } resp.getSimulatorDetails().add(sdr); } return resp; }
From source file:com.netflix.spectator.tdigest.Json.java
/** Encode the measurement using the generator. */ void encode(Map<String, String> commonTags, TDigestMeasurement m, JsonGenerator gen) throws IOException { TDigest digest = m.value();//w w w. j a va 2s . c om digest.compress(); ByteBuffer buf = ByteBuffer.allocate(digest.byteSize()); digest.asBytes(buf); gen.writeStartArray(); gen.writeStartObject(); gen.writeStringField("name", m.id().name()); for (Map.Entry<String, String> e : commonTags.entrySet()) { gen.writeStringField(e.getKey(), e.getValue()); } for (Tag t : m.id().tags()) { gen.writeStringField(t.key(), t.value()); } gen.writeEndObject(); gen.writeNumber(m.timestamp()); gen.writeBinary(buf.array()); gen.writeEndArray(); }
From source file:cn.iie.haiep.hbase.value.Bytes.java
/** * Returns a new byte array, copied from the passed ByteBuffer. * @param bb A ByteBuffer//from w w w . j av a 2 s. co m * @return the byte array */ public static byte[] toBytes(ByteBuffer bb) { int length = bb.limit(); byte[] result = new byte[length]; System.arraycopy(bb.array(), bb.arrayOffset(), result, 0, length); return result; }
From source file:bamboo.openhash.fileshare.FileShare.java
public void write() { logger.debug("write"); if (is != null) { while (ready.size() < MAX_BUFFER) { ByteBuffer bb = ByteBuffer.wrap(new byte[1024]); bb.putInt(0);// w w w .java2 s . c o m int len = 0; try { len = is.read(bb.array(), 4, bb.limit() - 4); } catch (IOException e) { is = null; break; } if (len == -1) { is = null; break; } logger.debug("position=" + bb.position() + " read " + len + " bytes"); // We're going to flip this later, so set the position // where we want the limit to end up. bb.position(len + 4); wblocks.elementAt(0).addLast(bb); logger.debug("read a block"); if (wblocks.elementAt(0).size() == BRANCHING) make_parents(false); } if (is == null) { make_parents(true); // There should now be only one non-empty level, at it // should have exactly one block in it. for (int l = 0; l < wblocks.size(); ++l) { if (!wblocks.elementAt(l).isEmpty()) { ByteBuffer bb = wblocks.elementAt(l).removeFirst(); bb.flip(); md.update(secret); md.update(bb.array(), 0, bb.limit()); byte[] dig = md.digest(); StringBuffer sb = new StringBuffer(100); bytes_to_sbuf(dig, 0, dig.length, false, sb); logger.info("root digest is 0x" + sb.toString()); ready.addLast(new Pair<byte[], ByteBuffer>(dig, bb)); break; } } } } // Do put. if (ready.isEmpty()) { if (outstanding == 0) { logger.info("all puts finished successfully"); System.exit(0); } } else { Pair<byte[], ByteBuffer> head = ready.removeFirst(); outstanding++; bamboo_put_args put = new bamboo_put_args(); put.application = APPLICATION; // GatewayClient will fill in put.client_library put.value = new bamboo_value(); if (head.second.limit() == head.second.array().length) put.value.value = head.second.array(); else { put.value.value = new byte[head.second.limit()]; head.second.get(put.value.value); } put.key = new bamboo_key(); put.key.value = head.first; put.ttl_sec = 3600; // TODO StringBuffer sb = new StringBuffer(100); bytes_to_sbuf(head.first, 0, head.first.length, false, sb); logger.debug("putting block size=" + put.value.value.length + " key=0x" + sb.toString()); client.put(put, curry(put_done_cb, put)); } }
From source file:edu.berkeley.sparrow.examples.FairnessTestingFrontend.java
public List<TTaskSpec> generateJob(int numTasks, int numPreferredNodes, List<String> backends, int benchmarkId, int benchmarkIterations) { // Pack task parameters ByteBuffer message = ByteBuffer.allocate(8); message.putInt(benchmarkId);//from w w w.j av a 2 s .c om message.putInt(benchmarkIterations); List<TTaskSpec> out = new ArrayList<TTaskSpec>(); for (int taskId = 0; taskId < numTasks; taskId++) { TTaskSpec spec = new TTaskSpec(); spec.setTaskId(Integer.toString((new Random().nextInt()))); spec.setMessage(message.array()); if (numPreferredNodes > 0) { Collections.shuffle(backends); TPlacementPreference preference = new TPlacementPreference(); for (int i = 0; i < numPreferredNodes; i++) { preference.addToNodes(backends.get(i)); } spec.setPreference(preference); } out.add(spec); } return out; }