List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:it.crs4.seal.prq.PairReadsQSeqReducer.java
private void ensureCapacity(int required) { int current = sequence[0].capacity(); if (required > current) { int newSize = required * 2; // grow/*from w w w . ja v a 2 s.c o m*/ for (int i = 0; i < sequence.length; ++i) { ByteBuffer temp; // allocate and copy sequence first temp = ByteBuffer.allocate(newSize); temp.put(sequence[i]).rewind().mark().limit(sequence[i].limit()); sequence[i] = temp; if (mapping[i].getSequence() != null) mapping[i].setSequence(sequence[i]); // repeat for quality temp = ByteBuffer.allocate(newSize); temp.put(quality[i]).rewind().mark().limit(quality[i].limit()); quality[i] = temp; if (mapping[i].getBaseQualities() != null) mapping[i].setBaseQualities(quality[i]); } } }
From source file:io.stallion.dataAccess.file.FilePersisterBase.java
/** * Derives a Long id by hashing the file path and then taking the first 8 bytes * of the path./* w w w. j a v a 2 s. c o m*/ * * This is used if the model object doesn't have a defined id field. * * @param path * @return */ public Long makeIdFromFilePath(String path) { path = path.toLowerCase(); path = path.replace(getBucketFolderPath().toLowerCase(), ""); path = StringUtils.stripStart(path, "/"); path = getBucket() + "-----" + path; // Derive a long id by hashing the file path byte[] bs = Arrays.copyOfRange(DigestUtils.md5(path), 0, 6); bs = ArrayUtils.addAll(new byte[] { 0, 0 }, bs); ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(bs); buffer.flip();//need flip Long l = buffer.getLong(); if (l < 0) { l = -l; } Log.finest("calculated id is {0}", l); return l; }
From source file:net.jenet.Packet.java
/** * Copies part of this packet's data into the given buffer. * @param buffer//w ww. j av a2s . c o m * Destination buffer * @param offset * Initial position of the destination buffer * @param length * Total number of bytes to copy */ public void toBuffer(ByteBuffer buffer, int offset, int length) { int position = data.position(); int limit = data.limit(); data.flip(); data.position(offset); for (int i = 0; i < length; i++) { buffer.put(data.get()); } data.position(position); data.limit(limit); }
From source file:AutoDJ.metaReader.OggIndexer.java
/** * Extracts the Image from a FLAC picture structure * http://flac.sourceforge.net/format.html#metadata_block_picture * Expects a base64 encoded string/* ww w .j a v a2 s .co m*/ * * @param String pictureBlock (base64) * @return BufferedImage */ BufferedImage readAlbumImage(String pictureBlock) { if (pictureBlock == null || pictureBlock.isEmpty()) return null; byte[] pictureBytes = Base64.decodeBase64(pictureBlock); BufferedImage img = null; String mimeString = "", description = ""; ByteBuffer picBuff = ByteBuffer.allocate(pictureBytes.length); picBuff.put(pictureBytes); picBuff.rewind(); /*int picType = */picBuff.getInt(); // not interesting, discard // read the mime type string int mimeStrLength = picBuff.getInt(); byte[] mimeBytes = new byte[mimeStrLength]; picBuff.get(mimeBytes); mimeString = new String(mimeBytes); // read the string describing the image int descStrLength = picBuff.getInt(); byte[] descBytes = new byte[descStrLength]; picBuff.get(descBytes); try { description = new String(descBytes, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } // skip over some unnecessary information /*int picWidth = */picBuff.getInt(); /*int picHeight = */picBuff.getInt(); /*int colDepth = */picBuff.getInt(); /*int idxColors = */picBuff.getInt(); // read the image data int picDataLength = picBuff.getInt(); byte[] picBytes = new byte[picDataLength]; picBuff.get(picBytes); try { img = ImageIO.read(new ByteArrayInputStream(picBytes)); } catch (Exception e) { e.printStackTrace(); } return img; }
From source file:com.dreamwork.web.FrontJsonController.java
private byte[] read(InputStream in) throws IOException { ByteBuffer fullBytesRed = ByteBuffer.allocate(0); int n;/*w ww. j a v a 2 s . c o m*/ while (true) { byte[] b = new byte[2048]; n = in.read(b); if (n == -1) { break; } byte[] currBytes = fullBytesRed.array(); fullBytesRed = ByteBuffer.allocate(currBytes.length + n); fullBytesRed.put(currBytes); fullBytesRed.put(b, 0, n); } byte[] data = fullBytesRed.array(); return data; }
From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java
@Override protected List<NearbyItem> doInBackground(Void... params) { if (DBG)/*from w w w. j a va2s . c om*/ Log.d(TAG, "Scanning for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { if (DBG) Log.d(TAG, "Querying gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); Log.i(TAG, "coords: " + Arrays.toString(coords)); //TODO: encrypt coords with mmPassword for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } Log.i(TAG, "buckets: " + buckets); httpPost.setEntity(new StringEntity(buckets.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } } catch (Exception e) { e.printStackTrace(); } HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>(); String response = sb.toString(); JSONArray groupsJSON = new JSONArray(response); Log.d(TAG, "Got " + groupsJSON.length() + " groups"); for (int i = 0; i < groupsJSON.length(); i++) { try { String s_enc_data = groupsJSON.get(i).toString(); byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(enc_data, 0, 16); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { data = cipher.doFinal(enc_data, 16, enc_data.length - 16); } catch (Exception e) { throw new RuntimeException("body decryption failed", e); } JSONObject group = new JSONObject(new String(data)); String group_name = group.getString("group_name"); byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT); String sharer_name = group.getString("sharer_name"); byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT); byte[] thumbnail = null; if (group.has("thumbnail")) thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT); int member_count = group.getInt("member_count"); int sharer_type = group.getInt("sharer_type"); Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash), new TByteArrayList(group_capability)); if (dupes.contains(p)) continue; dupes.add(p); addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name, Authority.values()[sharer_type], sharer_hash, thumbnail, member_count)); } catch (Throwable e) { Log.e(TAG, "Failed to parse group " + i, e); } } } catch (Exception e) { if (DBG) Log.d(TAG, "Error searching nearby feeds", e); } return null; }
From source file:com.github.cambierr.lorawanpacket.semtech.PullResp.java
@Override public void toRaw(ByteBuffer _bb) throws MalformedPacketException { super.toRaw(_bb); JSONObject json = new JSONObject(); if (!txpks.isEmpty()) { JSONArray txpk = new JSONArray(); for (Txpk s : txpks) { txpk.put(s.toJson());//from w ww . jav a 2s. c om } json.put("txpk", txpks); } _bb.put(json.toString().getBytes()); }
From source file:edu.stanford.slac.archiverappliance.PB.data.BoundaryConditionsSimulationValueGenerator.java
/** * Get a value based on the DBR type. /*w ww. j a v a 2 s. c o m*/ * We should check for boundary conditions here and make sure PB does not throw exceptions when we come close to MIN_ and MAX_ values * @param type * @param secondsIntoYear * @return */ public SampleValue getSampleValue(ArchDBRTypes type, int secondsIntoYear) { switch (type) { case DBR_SCALAR_STRING: return new ScalarStringSampleValue(Integer.toString(secondsIntoYear)); case DBR_SCALAR_SHORT: if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value return new ScalarValue<Short>((short) (Short.MIN_VALUE + secondsIntoYear)); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value return new ScalarValue<Short>((short) (Short.MAX_VALUE - (secondsIntoYear - 1000))); } else { // Check for some numbers around 0 return new ScalarValue<Short>((short) (secondsIntoYear - 2000)); } case DBR_SCALAR_FLOAT: if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value return new ScalarValue<Float>(Float.MIN_VALUE + secondsIntoYear); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value return new ScalarValue<Float>(Float.MAX_VALUE - (secondsIntoYear - 1000)); } else { // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits return new ScalarValue<Float>((secondsIntoYear - 2000.0f) / secondsIntoYear); } case DBR_SCALAR_ENUM: return new ScalarValue<Short>((short) secondsIntoYear); case DBR_SCALAR_BYTE: return new ScalarValue<Byte>(((byte) (secondsIntoYear % 255))); case DBR_SCALAR_INT: if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value return new ScalarValue<Integer>(Integer.MIN_VALUE + secondsIntoYear); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value return new ScalarValue<Integer>(Integer.MAX_VALUE - (secondsIntoYear - 1000)); } else { // Check for some numbers around 0 return new ScalarValue<Integer>(secondsIntoYear - 2000); } case DBR_SCALAR_DOUBLE: if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value return new ScalarValue<Double>(Double.MIN_VALUE + secondsIntoYear); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value return new ScalarValue<Double>(Double.MAX_VALUE - (secondsIntoYear - 1000)); } else { // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits return new ScalarValue<Double>((secondsIntoYear - 2000.0) / (secondsIntoYear * 1000000)); } case DBR_WAVEFORM_STRING: // Varying number of copies of a typical value return new VectorStringSampleValue( Collections.nCopies(secondsIntoYear, Integer.toString(secondsIntoYear))); case DBR_WAVEFORM_SHORT: return new VectorValue<Short>(Collections.nCopies(1, (short) secondsIntoYear)); case DBR_WAVEFORM_FLOAT: // Varying number of copies of a typical value return new VectorValue<Float>( Collections.nCopies(secondsIntoYear, (float) Math.cos(secondsIntoYear * Math.PI / 3600))); case DBR_WAVEFORM_ENUM: return new VectorValue<Short>(Collections.nCopies(1024, (short) secondsIntoYear)); case DBR_WAVEFORM_BYTE: // Large number of elements in the array return new VectorValue<Byte>( Collections.nCopies(65536 * secondsIntoYear, ((byte) (secondsIntoYear % 255)))); case DBR_WAVEFORM_INT: // Varying number of copies of a typical value return new VectorValue<Integer>( Collections.nCopies(secondsIntoYear, secondsIntoYear * secondsIntoYear)); case DBR_WAVEFORM_DOUBLE: // Varying number of copies of a typical value return new VectorValue<Double>( Collections.nCopies(secondsIntoYear, Math.sin(secondsIntoYear * Math.PI / 3600))); case DBR_V4_GENERIC_BYTES: // Varying number of copies of a typical value ByteBuffer buf = ByteBuffer.allocate(1024 * 10); buf.put(Integer.toString(secondsIntoYear).getBytes()); buf.flip(); return new ByteBufSampleValue(buf); default: throw new RuntimeException("We seemed to have missed a DBR type when generating sample data"); } }
From source file:net.fenyo.extension.Dns.TcpSocket.java
@Override public void run() { if (read_thread) { read_thread = false;/*from ww w .j a v a2s .c om*/ 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:com.openteach.diamond.network.waverider.network.Packet.java
/** * ByteBuffer/*from w ww . j a v a 2 s . co m*/ * @return */ public ByteBuffer marshall() { int size = getSize(); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.put(magic.getBytes()); buffer.putLong(sequence); buffer.putLong(type); buffer.putInt(size); buffer.put(payLoad); buffer.flip(); return buffer; }