Java Code Examples for java.nio.ByteOrder

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Java-Chronicle, under directory /src/main/java/vanilla/java/chronicle/tcp/.

Source file: ChronicleSink.java

  18 
vote

public static void main(String... args) throws IOException {
  if (args.length < 3) {
    System.err.println("Usage: java " + ChronicleSink.class.getName() + " {chronicle-base-path} {hostname} {port}");
    System.exit(-1);
  }
  int dataBitsHintSize=Integer.getInteger("dataBitsHintSize",24);
  String def=ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? "Big" : "Little";
  ByteOrder byteOrder=System.getProperty("byteOrder",def).equalsIgnoreCase("Big") ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
  String basePath=args[0];
  String hostname=args[1];
  int port=Integer.parseInt(args[2]);
  IndexedChronicle ic=new IndexedChronicle(basePath,dataBitsHintSize,byteOrder);
  ChronicleSink cs=new ChronicleSink(ic,hostname,port);
}
 

Example 2

From project gecko, under directory /src/main/java/com/taobao/gecko/core/buffer/.

Source file: AbstractIoBuffer.java

  17 
vote

/** 
 * {@inheritDoc}
 */
@Override public final IoBuffer capacity(int newCapacity){
  if (!recapacityAllowed) {
    throw new IllegalStateException("Derived buffers and their parent can't be expanded.");
  }
  if (newCapacity > capacity()) {
    int pos=position();
    int limit=limit();
    ByteOrder bo=order();
    ByteBuffer oldBuf=buf();
    ByteBuffer newBuf=getAllocator().allocateNioBuffer(newCapacity,isDirect());
    oldBuf.clear();
    newBuf.put(oldBuf);
    buf(newBuf);
    buf().limit(limit);
    if (mark >= 0) {
      buf().position(mark);
      buf().mark();
    }
    buf().position(pos);
    buf().order(bo);
  }
  return this;
}
 

Example 3

From project hs4j, under directory /src/main/java/com/google/code/hs4j/network/buffer/.

Source file: AbstractIoBuffer.java

  17 
vote

/** 
 * {@inheritDoc}
 */
@Override public final IoBuffer capacity(int newCapacity){
  if (!recapacityAllowed) {
    throw new IllegalStateException("Derived buffers and their parent can't be expanded.");
  }
  if (newCapacity > capacity()) {
    int pos=position();
    int limit=limit();
    ByteOrder bo=order();
    ByteBuffer oldBuf=buf();
    ByteBuffer newBuf=getAllocator().allocateNioBuffer(newCapacity,isDirect());
    oldBuf.clear();
    newBuf.put(oldBuf);
    buf(newBuf);
    buf().limit(limit);
    if (mark >= 0) {
      buf().position(mark);
      buf().mark();
    }
    buf().position(pos);
    buf().order(bo);
  }
  return this;
}
 

Example 4

From project adbcj, under directory /mysql/codec/src/test/java/org/adbcj/mysql/codec/.

Source file: IoUtilsTest.java

  15 
vote

@Test(dependsOnMethods="testSafeRead") public void testReadShort() throws IOException {
  ByteBuffer buffer=ByteBuffer.allocate(1024);
  buffer.order(ByteOrder.LITTLE_ENDIAN);
  buffer.putShort((short)0).putShort((short)1).putShort((short)2).putShort((short)-1).putShort((short)-2);
  InputStream in=new ByteArrayInputStream(buffer.array(),0,buffer.position());
  Assert.assertEquals(IoUtils.readShort(in),0);
  Assert.assertEquals(IoUtils.readShort(in),1);
  Assert.assertEquals(IoUtils.readShort(in),2);
  Assert.assertEquals(IoUtils.readShort(in),-1);
  Assert.assertEquals(IoUtils.readShort(in),-2);
}
 

Example 5

From project AirReceiver, under directory /src/test/java/org/phlo/audio/.

Source file: TestSampleBuffer.java

  15 
vote

@Test public void testInterleavedBigEndianUnsignedInteger16(){
  SampleDimensions byteDimensions=new SampleDimensions(4,3);
  SampleDimensions sampleDimensions=new SampleDimensions(2,4);
  SampleByteBufferFormat byteFormat=new SampleByteBufferFormat(SampleBufferLayout.Interleaved,ByteOrder.BIG_ENDIAN,SampleByteFormat.UnsignedInteger16);
  byte[] bytes={(byte)0x00,(byte)0x00,(byte)0x80,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0xff,(byte)0xfe,(byte)0x80,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0xff,(byte)0xfe,(byte)0x00,(byte)0x00};
  int[] ints={0x0000,0x8000,0x0001,0x0000,0x0000,0xfffe,0x8000,0x0000,0x0000,0x0001,0xfffe,0x0000};
  ByteBuffer bytesWrapped=byteFormat.wrapBytes(bytes);
  IntBuffer intsWrapped=IntBuffer.wrap(ints);
  float U=Math.scalb(1.0f,-15);
  float[][] values={{0.0f,U * 0.5f,1.0f - U,-1.0f + U},{0.0f,-1.0f + U,U * 0.5f,1.0f - U}};
  SampleBuffer sampleBufferFromBytes=new SampleBuffer(sampleDimensions);
  sampleBufferFromBytes.slice(new SampleOffset(0,1),null).copyFrom(bytesWrapped,byteDimensions,new SampleRange(new SampleOffset(1,0),new SampleDimensions(2,3)),byteFormat);
  SampleBuffer sampleBufferFromInts=new SampleBuffer(sampleDimensions);
  sampleBufferFromInts.slice(new SampleOffset(0,1),null).copyFrom(intsWrapped,byteDimensions,new SampleRange(new SampleOffset(1,0),new SampleDimensions(2,3)),byteFormat.layout,byteFormat.sampleFormat.getSignedness());
  for (int c=0; c < sampleDimensions.channels; ++c) {
    for (int s=0; s < sampleDimensions.samples; ++s) {
      Assert.assertEquals("[" + c + ","+ s+ "]",values[c][s],sampleBufferFromBytes.getSample(c,s),1e-8);
      Assert.assertEquals("[" + c + ","+ s+ "]",values[c][s],sampleBufferFromInts.getSample(c,s),1e-8);
    }
  }
  ByteBuffer byteBuffer=byteFormat.allocateBuffer(byteDimensions);
  sampleBufferFromBytes.slice(new SampleOffset(0,1),new SampleDimensions(2,3)).copyTo(byteBuffer,byteDimensions,new SampleOffset(1,0),byteFormat);
  Assert.assertEquals(bytesWrapped.capacity(),byteBuffer.capacity());
  Assert.assertEquals(0,byteBuffer.compareTo(bytesWrapped));
}
 

Example 6

From project android-flip, under directory /FlipView/FlipLibrary/src/com/aphidmobile/utils/.

Source file: TextureUtils.java

  15 
vote

public static FloatBuffer toFloatBuffer(float[] v){
  ByteBuffer buf=ByteBuffer.allocateDirect(v.length * 4);
  buf.order(ByteOrder.nativeOrder());
  FloatBuffer buffer=buf.asFloatBuffer();
  buffer.put(v);
  buffer.position(0);
  return buffer;
}
 

Example 7

From project android-gltron, under directory /GlTron/src/com/glTron/Video/.

Source file: GraphicUtils.java

  15 
vote

public static FloatBuffer ConvToFloatBuffer(float buf[]){
  FloatBuffer ReturnBuffer;
  ByteBuffer vbb=ByteBuffer.allocateDirect(buf.length * 4);
  vbb.order(ByteOrder.nativeOrder());
  ReturnBuffer=vbb.asFloatBuffer();
  ReturnBuffer.put(buf);
  ReturnBuffer.position(0);
  return ReturnBuffer;
}
 

Example 8

From project Android-RTMP, under directory /android-ffmpeg-prototype/src/com/camundo/media/.

Source file: AudioSubscriber.java

  15 
vote

@Override public void run(){
  try {
    pipe.start();
    while (!pipe.initialized()) {
      Log.i(TAG,"[ run() ] pipe not yet running, waiting.");
      try {
        Thread.sleep(1000);
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
    int minBufferSize=AudioTrack.getMinBufferSize(pipe.getSampleRate(),pipe.getChannelConfig(),pipe.getEncoding());
    audioTrack=new AudioTrack(AudioManager.STREAM_VOICE_CALL,pipe.getSampleRate(),pipe.getChannelConfig(),pipe.getEncoding(),minBufferSize * 4,AudioTrack.MODE_STREAM);
    ByteBuffer buffer=ByteBuffer.allocate(minBufferSize);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    Log.d(TAG,"buffer length [" + minBufferSize + "]");
    int len;
    pipe.bootstrap();
    boolean started=false;
    while ((len=pipe.read(buffer.array())) > 0) {
      overallBytesReceived+=audioTrack.write(buffer.array(),0,len);
      if (!started && overallBytesReceived > minBufferSize) {
        audioTrack.play();
        started=true;
      }
    }
  }
 catch (  IOException e) {
    Log.e(TAG,"[ run() ]",e);
  }
  Log.i(TAG,"[ run() ] done");
}
 

Example 9

From project android-thaiime, under directory /latinime/src/com/android/inputmethod/deprecated/voice/.

Source file: RecognitionView.java

  15 
vote

public void showWorking(final ByteArrayOutputStream waveBuffer,final int speechStartPosition,final int speechEndPosition){
  mUiHandler.post(new Runnable(){
    @Override public void run(){
      mState=WORKING;
      prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel));
      final ShortBuffer buf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer();
      buf.position(0);
      waveBuffer.reset();
      showWave(buf,speechStartPosition / 2,speechEndPosition / 2);
    }
  }
);
}
 

Example 10

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/photoeditor/.

Source file: RendererUtils.java

  15 
vote

private static FloatBuffer createVerticesBuffer(float[] vertices){
  if (vertices.length != 8) {
    throw new RuntimeException("Number of vertices should be four.");
  }
  FloatBuffer buffer=ByteBuffer.allocateDirect(vertices.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
  buffer.put(vertices).position(0);
  return buffer;
}
 

Example 11

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: GridQuad.java

  15 
vote

public GridQuad(boolean generateOrientedQuads){
  mOrientedQuad=generateOrientedQuads;
  if (mOrientedQuad) {
    mMatrix=new MatrixStack();
    mMatrix.glLoadIdentity();
  }
  int vertsAcross=2;
  int vertsDown=2;
  mW=vertsAcross;
  mH=vertsDown;
  int size=vertsAcross * vertsDown;
  final int FLOAT_SIZE=4;
  final int CHAR_SIZE=2;
  final int orientationCount=(!generateOrientedQuads) ? 1 : ORIENTATION_COUNT;
  mVertexBuffer=ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3* orientationCount).order(ByteOrder.nativeOrder()).asFloatBuffer();
  mOverlayTexCoordBuffer=ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2* orientationCount).order(ByteOrder.nativeOrder()).asFloatBuffer();
  mBaseTexCoordBuffer=ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2* orientationCount).order(ByteOrder.nativeOrder()).asFloatBuffer();
  int indexCount=INDEX_COUNT;
  mIndexBuffer=ByteBuffer.allocateDirect(CHAR_SIZE * indexCount * orientationCount).order(ByteOrder.nativeOrder()).asCharBuffer();
  CharBuffer buffer=mIndexBuffer;
  for (int i=0; i < INDEX_COUNT * orientationCount; ++i) {
    buffer.put(i,(char)i);
  }
  mVertBufferIndex=0;
}
 

Example 12

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/.

Source file: FireflyRenderer.java

  15 
vote

public FireflyRenderer(Context context){
  mContext=context;
  ByteBuffer vbb=ByteBuffer.allocateDirect(mVertices.length * 4);
  vbb.order(ByteOrder.nativeOrder());
  mVertexBuffer=vbb.asFloatBuffer();
  mVertexBuffer.put(mVertices);
  mVertexBuffer.position(0);
  ByteBuffer ibb=ByteBuffer.allocateDirect(mIndices.length * 2);
  ibb.order(ByteOrder.nativeOrder());
  mIndexBuffer=ibb.asShortBuffer();
  mIndexBuffer.put(mIndices);
  mIndexBuffer.position(0);
  ByteBuffer tbb=ByteBuffer.allocateDirect(mTextCoords.length * 4);
  tbb.order(ByteOrder.nativeOrder());
  mTextureBuffer=tbb.asFloatBuffer();
  mTextureBuffer.put(mTextCoords);
  mTextureBuffer.position(0);
  mFireflies=new Firefly[NUM_FIREFLIES];
  for (int i=0; i < NUM_FIREFLIES; i++) {
    mFireflies[i]=new Firefly();
  }
}
 

Example 13

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/deprecated/voice/.

Source file: RecognitionView.java

  15 
vote

public void showWorking(final ByteArrayOutputStream waveBuffer,final int speechStartPosition,final int speechEndPosition){
  mUiHandler.post(new Runnable(){
    @Override public void run(){
      mState=WORKING;
      prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel));
      final ShortBuffer buf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer();
      buf.position(0);
      waveBuffer.reset();
      showWave(buf,speechStartPosition / 2,speechEndPosition / 2);
    }
  }
);
}
 

Example 14

From project android_wallpaper_flier, under directory /src/fi/harism/wallpaper/flier/.

Source file: FlierPlane.java

  15 
vote

/** 
 * Default constructor.
 */
public FlierPlane(){
  ByteBuffer bBuffer=ByteBuffer.allocateDirect(6 * 3 * 4);
  mBufferVertices=bBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer();
  final float WIDTH=1f, HEIGHT=0.3f, LENGTH=1.2f, BEND=0.3f;
  final float[] vertices={0f,HEIGHT,-LENGTH,WIDTH,HEIGHT,LENGTH,BEND,HEIGHT,LENGTH,0f,-HEIGHT,LENGTH,-BEND,HEIGHT,LENGTH,-WIDTH,HEIGHT,LENGTH};
  mBufferVertices.put(vertices).position(0);
  mBufferLineIndices=ByteBuffer.allocateDirect(9 * 2);
  final byte[] indices={0,1,0,2,0,3,0,4,0,5,1,2,2,3,3,4,4,5};
  mBufferLineIndices.put(indices).position(0);
}
 

Example 15

From project android_wallpaper_flowers, under directory /src/fi/harism/wallpaper/flowers/.

Source file: FlowerObjects.java

  15 
vote

/** 
 * Updates preference values.
 */
public void setPreferences(int flowerCount,float[][] flowerColors,int splineQuality,float branchPropability,float zoomLevel){
  if (flowerCount != mFlowerElements.length) {
    mFlowerElements=new ElementFlower[flowerCount];
    for (int i=0; i < mFlowerElements.length; ++i) {
      mFlowerElements[i]=new ElementFlower();
      mFlowerElements[i].mColor=flowerColors[i];
    }
  }
  for (int i=0; i < mFlowerElements.length; ++i) {
    mFlowerElements[i].mColor=flowerColors[i];
  }
  if (mSplineVertexCount != splineQuality + 2) {
    mSplineVertexCount=splineQuality + 2;
    ByteBuffer bBuffer=ByteBuffer.allocateDirect(4 * 4 * mSplineVertexCount);
    mBufferSpline=bBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer();
    for (int i=0; i < mSplineVertexCount; ++i) {
      float t=(float)i / (mSplineVertexCount - 1);
      mBufferSpline.put(t).put(1);
      mBufferSpline.put(t).put(-1);
    }
    mBufferSpline.position(0);
  }
  mBranchPropability=branchPropability;
  mZoomLevel=zoomLevel;
}
 

Example 16

From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/dictionaries/.

Source file: ResourceBinaryDictionary.java

  15 
vote

private final void loadDictionary(Context context,int[] resId){
  InputStream[] is=null;
  try {
    int total=0;
    is=new InputStream[resId.length];
    for (int i=0; i < resId.length; i++) {
      is[i]=context.getResources().openRawResource(resId[i]);
      final int dictSize=is[i].available();
      Log.d(TAG,"Will load a resource dictionary id " + resId[i] + " whose size is "+ dictSize+ " bytes.");
      total+=dictSize;
    }
    mNativeDictDirectBuffer=ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
    int got=0;
    for (int i=0; i < resId.length; i++) {
      got+=Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
    }
    if (got != total) {
      Log.e(TAG,"Read " + got + " bytes, expected "+ total);
    }
 else {
      mNativeDict=openNative(mNativeDictDirectBuffer,TYPED_LETTER_MULTIPLIER,FULL_WORD_FREQ_MULTIPLIER);
      mDictLength=total;
    }
  }
 catch (  IOException e) {
    Log.w(TAG,"No available memory for binary dictionary: " + e.getMessage());
  }
 finally {
    try {
      if (is != null) {
        for (int i=0; i < is.length; i++) {
          is[i].close();
        }
      }
    }
 catch (    IOException e) {
      Log.w(TAG,"Failed to close input stream");
    }
  }
}
 

Example 17

From project apps-for-android, under directory /AndroidGlobalTime/src/com/android/globaltime/.

Source file: Shape.java

  15 
vote

/** 
 * Copies the given data into the instance variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, and mIndexBuffer.
 * @param vertices an array of fixed-point vertex coordinates
 * @param texcoords an array of fixed-point texture coordinates
 * @param normals an array of fixed-point normal vector coordinates
 * @param colors an array of fixed-point color channel values
 * @param indices an array of short indices
 */
public void allocateBuffers(int[] vertices,int[] texcoords,int[] normals,int[] colors,short[] indices){
  allocate(vertices,texcoords,normals,colors);
  ByteBuffer ibb=ByteBuffer.allocateDirect(indices.length * SHORT_BYTES);
  ibb.order(ByteOrder.nativeOrder());
  ShortBuffer shortIndexBuffer=ibb.asShortBuffer();
  shortIndexBuffer.put(indices);
  shortIndexBuffer.position(0);
  this.mIndexBuffer=shortIndexBuffer;
}
 

Example 18

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.

Source file: JLnkParser.java

  15 
vote

private String parseString(int offset,boolean unicode,int maxlen){
  ByteBuffer bb=ByteBuffer.wrap(content);
  bb.order(ByteOrder.LITTLE_ENDIAN);
  bb.position(offset);
  StringBuilder sb=new StringBuilder(bb.limit());
  int i=0;
  while (bb.remaining() > 0 && (i < maxlen || maxlen == -1)) {
    char c;
    if (unicode) {
      c=bb.getChar();
    }
 else {
      c=(char)bb.get();
    }
    if (c == '\0') {
      break;
    }
    sb.append(c);
    i++;
  }
  return sb.toString();
}
 

Example 19

From project Backyard-Brains-Android-App, under directory /src/com/backyardbrains/audio/.

Source file: MicListener.java

  15 
vote

/** 
 * Find the appropriate buffer size for working on this device and allocate space for the audioInfo  {@link ByteBuffer} based on that size, then tellAndroid we'll be using high-priority audio-processing.
 */
MicListener(){
  setBufferSize();
  audioInfo=ByteBuffer.allocateDirect(buffersize);
  audioInfo.order(ByteOrder.nativeOrder());
  android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
}
 

Example 20

From project BioMAV, under directory /ParrotControl/JavaDroneControl/src/nl/ru/ai/projects/parrot/dronecontrol/javadronecontrol/.

Source file: NavdataPacket.java

  15 
vote

/** 
 * Initializes the demo data using the raw data from the demo header.
 * @param ba Byte information read from the demo-section of the navdata.
 */
public DemoDataStruct(byte[] ba){
  ByteBuffer bb=ByteBuffer.wrap(ba);
  bb.order(ByteOrder.LITTLE_ENDIAN);
  controlState=bb.getInt();
  batteryPercentage=bb.getInt();
  euler=new float[3];
  euler[0]=bb.getFloat();
  euler[1]=bb.getFloat();
  euler[2]=bb.getFloat();
  altitude=bb.getInt();
  velocity=new float[3];
  velocity[0]=bb.getFloat();
  velocity[1]=bb.getFloat();
  velocity[2]=bb.getFloat();
}
 

Example 21

From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.

Source file: BlacktieAdminServiceXATMI.java

  15 
vote

private byte[] convertLong(long response) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  DataOutputStream dos=new DataOutputStream(baos);
  ByteBuffer bbuf=ByteBuffer.allocate(BufferImpl.LONG_SIZE);
  bbuf.order(ByteOrder.BIG_ENDIAN);
  bbuf.putLong(response);
  bbuf.order(ByteOrder.LITTLE_ENDIAN);
  long toWrite=bbuf.getLong(0);
  dos.writeLong(toWrite);
  dos.flush();
  baos.flush();
  return baos.toByteArray();
}
 

Example 22

From project bson4jackson, under directory /src/main/java/de/undercouch/bson4jackson/.

Source file: BsonParser.java

  15 
vote

/** 
 * Can be called when a new embedded document is found. Reads the document's header and creates a new context on the stack.
 * @param array true if the document is an embedded array
 * @return the json token read
 * @throws IOException if an I/O error occurs
 */
protected JsonToken handleNewDocument(boolean array) throws IOException {
  if (_in == null) {
    byte[] buf=new byte[Integer.SIZE / Byte.SIZE];
    int len=0;
    while (len < buf.length) {
      int l=_rawInputStream.read(buf,len,buf.length - len);
      if (l == -1) {
        throw new IOException("Not enough bytes for length of document");
      }
      len+=l;
    }
    int documentLength=ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt();
    InputStream in=new BoundedInputStream(_rawInputStream,documentLength - buf.length);
    if (!(_rawInputStream instanceof BufferedInputStream)) {
      in=new StaticBufferedInputStream(in);
    }
    _counter=new CountingInputStream(in);
    _in=new LittleEndianInputStream(_counter);
  }
 else {
    _in.readInt();
  }
  _contexts.push(new Context(array));
  return (array ? JsonToken.START_ARRAY : JsonToken.START_OBJECT);
}
 

Example 23

From project ceres, under directory /ceres-binio/src/main/java/com/bc/ceres/binio/.

Source file: DataFormat.java

  15 
vote

public DataFormat(CompoundType type,ByteOrder byteOrder){
  setType(type);
  setName(type.getName());
  setVersion("1.0.0");
  setByteOrder(byteOrder);
  this.typeDefMap=new HashMap<String,Type>(16);
}
 

Example 24

From project cocos2d, under directory /cocos2d-android/src/com/badlogic/gdx/utils/.

Source file: BufferUtils.java

  15 
vote

/** 
 * Allocates a new direct ByteBuffer from native heap memory using the native byte order. Needs to be disposed with {@link #freeMemory(ByteBuffer)}.
 * @param numBytes 
 */
public static ByteBuffer newUnsafeByteBuffer(int numBytes){
  ByteBuffer buffer=newDisposableByteBuffer(numBytes);
  buffer.order(ByteOrder.nativeOrder());
  allocatedUnsafe+=numBytes;
synchronized (unsafeBuffers) {
    unsafeBuffers.add(buffer);
  }
  return buffer;
}
 

Example 25

From project Collections, under directory /src/main/java/vanilla/java/collections/impl/.

Source file: AbstractHugeMap.java

  15 
vote

private void growBuffer(int loHash){
  final IntBuffer buffer1=keysBuffers[loHash];
  final IntBuffer buffer2=ByteBuffer.allocate(buffer1.capacity() * 8).order(ByteOrder.nativeOrder()).asIntBuffer();
  keysBuffers[loHash]=buffer2;
  KE ke=acquireKeyElement(0);
  int used=0;
  OUTER:   for (int j=0; j < buffer1.capacity(); j++) {
    int index=buffer1.get(j);
    if (index == 0)     continue;
    ke.index(index - 1);
    int hiHash=(int)(ke.longHashCode() & HASH_MASK / keysBuffers.length);
    for (int i=0, len=buffer2.limit(); i < len; i++) {
      final int i1=buffer2.get((hiHash + i) % len);
      if (i1 == 0) {
        buffer2.put((hiHash + i) % len,index);
        used++;
        continue OUTER;
      }
    }
  }
  recycle(ke);
  buffer2.position(used);
}
 

Example 26

From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre10/.

Source file: GLSurfaceViewCube.java

  15 
vote

protected static FloatBuffer createFloatBuffer(float[] array){
  ByteBuffer bytes=ByteBuffer.allocateDirect(array.length * 4);
  bytes.order(ByteOrder.nativeOrder());
  FloatBuffer buffer=bytes.asFloatBuffer();
  buffer.put(array);
  buffer.position(0);
  return buffer;
}
 

Example 27

From project encog-java-core, under directory /src/main/java/org/encog/ml/data/buffer/.

Source file: EncogEGBFile.java

  15 
vote

/** 
 * Check a write, make sure there is enough room to write.
 * @param writeBuffer The buffer.
 * @param inWriteLocation The write location.
 * @return The new write location.
 * @throws IOException If an IO error occurs.
 */
private long checkWrite(final ByteBuffer writeBuffer,final long inWriteLocation) throws IOException {
  long writeLocation=inWriteLocation;
  if (!writeBuffer.hasRemaining()) {
    this.fc.position(writeLocation);
    writeBuffer.flip();
    this.fc.write(writeBuffer);
    writeLocation=this.fc.position();
    writeBuffer.clear();
    writeBuffer.order(ByteOrder.LITTLE_ENDIAN);
  }
  return writeLocation;
}
 

Example 28

From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/tabs/.

Source file: AboutTab.java

  15 
vote

public void generate(){
  HTMLReport report=new HTMLReport();
  report.beginHTML();
  String title="Encog Workbench v" + EncogWorkBench.VERSION;
  report.title(title);
  report.beginBody();
  report.h1(title);
  report.para("Encog Workbench is released under the Apache License.  For more information see the license file released with the Encog Workbench.");
  report.h3(EncogWorkBench.COPYRIGHT);
  report.beginTable();
  report.tablePair("Java Version",System.getProperty("java.version"));
  report.tablePair("Java 64/32-Bit",System.getProperty("sun.arch.data.model"));
  report.tablePair("Processor Count","" + Runtime.getRuntime().availableProcessors());
  report.tablePair("OS Name/Version","" + ByteOrder.nativeOrder().toString());
  report.tablePair("Encog Core Version","" + Encog.VERSION);
  report.endTable();
  report.h3("Active JAR Files");
  report.beginList();
  for (  final String file : this.jars) {
    report.listItem(file);
  }
  report.endList();
  report.endBody();
  report.endHTML();
  this.display(report.toString());
}
 

Example 29

From project erjang, under directory /src/main/java/erjang/console/.

Source file: TTYTextAreaDriverControl.java

  15 
vote

@Override protected ByteBuffer control(EPID pid,int command,ByteBuffer cmd) throws Pausable {
  if (command == CTRL_OP_GET_WINSIZE) {
    ByteBuffer rep=ByteBuffer.allocate(8);
    rep.order(ByteOrder.nativeOrder());
    rep.putInt(80);
    rep.putInt(25);
    return rep;
  }
 else   if (command == CTRL_OP_GET_UNICODE_STATE) {
    ByteBuffer rep=ByteBuffer.allocate(1);
    rep.put((byte)(utf8_mode ? 1 : 0));
    return rep;
  }
 else   if (command == CTRL_OP_SET_UNICODE_STATE && cmd.remaining() == 1) {
    ByteBuffer rep=ByteBuffer.allocate(1);
    rep.put((byte)(utf8_mode ? 1 : 0));
    utf8_mode=cmd.get() == 0 ? false : true;
    return rep;
  }
 else {
    return null;
  }
}
 

Example 30

From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.

Source file: OffHeapLocalStorage.java

  15 
vote

public Page(PageGroup group,int bufferKbSize,int cellSize,int power){
  this.group=group;
  buffer=ByteBuffer.allocateDirect(bufferKbSize * 1024);
  buffer.order(ByteOrder.nativeOrder());
  setViewed(buffer,this);
  this.cellSize=cellSize;
  this.freeCells=(bufferKbSize * 1024) >> power;
  int prev=-1;
  for (int i=freeCells - 1; i >= 0; i--) {
    final int ptr=i << power;
    buffer.putInt(ptr,prev);
    prev=ptr;
  }
  this.head=0;
}
 

Example 31

From project galaxyCar, under directory /AndroidColladaLoader/src/ckt/projects/acl/.

Source file: ColladaObject.java

  15 
vote

public ColladaObject(float[] vertices,byte[] indices,int[] upAxis){
  this.upAxis=upAxis;
  ByteBuffer vbb=ByteBuffer.allocateDirect(vertices.length * 4);
  vbb.order(ByteOrder.nativeOrder());
  mVertexBuffer=vbb.asFloatBuffer();
  mVertexBuffer.put(vertices);
  mVertexBuffer.position(0);
  mIndexBuffer=ByteBuffer.allocateDirect(indices.length);
  mIndexBuffer.put(indices);
  mIndexBuffer.position(0);
}
 

Example 32

From project Game_3, under directory /core/src/playn/core/.

Source file: AbstractImage.java

  15 
vote

private ByteBuffer getRgba(){
  int w=(int)width();
  int h=(int)height();
  int size=w * h;
  int[] rawPixels=new int[size];
  ByteBuffer pixels=ByteBuffer.allocateDirect(size * 4);
  pixels.order(ByteOrder.nativeOrder());
  IntBuffer rgba=pixels.asIntBuffer();
  getRgb(0,0,w,h,rawPixels,0,w);
  for (int i=0; i < size; i++) {
    int argb=rawPixels[i];
    rgba.put(i,((argb >> 16) & 0x0ff) | (argb & 0x0ff00ff00) | ((argb & 0xff) << 16));
  }
  return pixels;
}
 

Example 33

From project genobyte, under directory /genobyte/src/main/java/org/obiba/bitwise/client/.

Source file: SeparatedValuesParser.java

  15 
vote

private InputStream getInputStream(File f) throws IOException {
  InputStream is=new FileInputStream(f);
  byte magicBytes[]=new byte[4];
  is.read(magicBytes,0,2);
  is.close();
  ByteBuffer bb=ByteBuffer.wrap(magicBytes);
  bb.order(ByteOrder.LITTLE_ENDIAN);
  int magicNumber=bb.getInt();
  if (magicNumber == GZIPInputStream.GZIP_MAGIC) {
    return new LargeGZIPInputStream(new FileInputStream(f));
  }
  return new FileInputStream(f);
}
 

Example 34

From project Gingerbread-Keyboard, under directory /src/com/android/inputmethod/latin/.

Source file: BinaryDictionary.java

  15 
vote

private final void loadDictionary(Context context,int[] resId){
  InputStream[] is=null;
  try {
    int total=0;
    is=new InputStream[resId.length];
    for (int i=0; i < resId.length; i++) {
      is[i]=context.getResources().openRawResource(resId[i]);
      total+=is[i].available();
    }
    mNativeDictDirectBuffer=ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
    int got=0;
    for (int i=0; i < resId.length; i++) {
      got+=Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
    }
    if (got != total) {
      Log.e(TAG,"Read " + got + " bytes, expected "+ total);
    }
 else {
      mNativeDict=openNative(mNativeDictDirectBuffer,TYPED_LETTER_MULTIPLIER,FULL_WORD_FREQ_MULTIPLIER);
      mDictLength=total;
    }
  }
 catch (  IOException e) {
    Log.w(TAG,"No available memory for binary dictionary");
  }
 finally {
    try {
      if (is != null) {
        for (int i=0; i < is.length; i++) {
          is[i].close();
        }
      }
    }
 catch (    IOException e) {
      Log.w(TAG,"Failed to close input stream");
    }
  }
}
 

Example 35

From project gs-core, under directory /src/org/graphstream/stream/file/.

Source file: FileSinkSWF.java

  15 
vote

@SuppressWarnings("unused") private void initChannelAndBuffer(String path){
  if (channel != null)   closeCurrentChannel();
  try {
    RandomAccessFile file=new RandomAccessFile(path,"rw");
    channel=file.getChannel();
    buffer=ByteBuffer.allocateDirect(BUFFER_SIZE);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    position=0;
    currentSize=0;
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
}
 

Example 36

From project heritrix3, under directory /commons/src/main/java/org/archive/util/ms/.

Source file: DefaultBlockFileSystem.java

  15 
vote

/** 
 * Returns the BAT block with the given block number. If the BAT block were previously cached, then the cached version is returned.  Otherwise, the file pointer is repositioned to  the start of the given block, and the 512 bytes are read and stored in the cache.
 * @param block   the block number of the BAT block to return
 * @return   the BAT block
 * @throws IOException
 */
private ByteBuffer getBATBlock(int block) throws IOException {
  ByteBuffer r=cache.get(block);
  if (r != null) {
    return r;
  }
  byte[] buf=new byte[BLOCK_SIZE];
  input.position((block + 1) * BLOCK_SIZE);
  ArchiveUtils.readFully(input,buf);
  r=ByteBuffer.wrap(buf);
  r.order(ByteOrder.LITTLE_ENDIAN);
  cache.put(block,r);
  return r;
}
 

Example 37

From project Holo-Edit, under directory /holoedit/opengl/.

Source file: OpenGLUt.java

  15 
vote

private static void makeRGBTexture(GL gl,GLU glu,BufferedImage img,int target,boolean mipmapped){
  if (img == null)   return;
  ByteBuffer dest=null;
switch (img.getType()) {
case BufferedImage.TYPE_3BYTE_BGR:
case BufferedImage.TYPE_CUSTOM:
{
      byte[] data=((DataBufferByte)img.getRaster().getDataBuffer()).getData();
      dest=ByteBuffer.allocateDirect(data.length);
      dest.order(ByteOrder.nativeOrder());
      dest.put(data,0,data.length);
      dest.rewind();
      break;
    }
case BufferedImage.TYPE_INT_RGB:
{
    int[] data=((DataBufferInt)img.getRaster().getDataBuffer()).getData();
    dest=ByteBuffer.allocateDirect(data.length * BufferUtil.SIZEOF_INT);
    dest.order(ByteOrder.nativeOrder());
    dest.asIntBuffer().put(data,0,data.length);
    dest.rewind();
    break;
  }
default :
throw new RuntimeException("Unsupported image type " + img.getType());
}
try {
if (mipmapped) {
glu.gluBuild2DMipmaps(target,GL.GL_RGB8,img.getWidth(),img.getHeight(),GL.GL_RGB,GL.GL_UNSIGNED_BYTE,dest);
}
 else {
gl.glTexImage2D(target,0,GL.GL_RGB,img.getWidth(),img.getHeight(),0,GL.GL_RGB,GL.GL_UNSIGNED_BYTE,dest);
}
}
 catch (java.nio.BufferUnderflowException e) {
}
}
 

Example 38

From project ICS_LatinIME_QHD, under directory /java/src/com/android/inputmethod/deprecated/voice/.

Source file: RecognitionView.java

  15 
vote

public void showWorking(final ByteArrayOutputStream waveBuffer,final int speechStartPosition,final int speechEndPosition){
  mUiHandler.post(new Runnable(){
    @Override public void run(){
      mState=WORKING;
      prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel));
      final ShortBuffer buf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer();
      buf.position(0);
      waveBuffer.reset();
      showWave(buf,speechStartPosition / 2,speechEndPosition / 2);
    }
  }
);
}
 

Example 39

From project IOCipher, under directory /src/info/guardianproject/libcore/io/.

Source file: Memory.java

  15 
vote

public static int peekInt(byte[] src,int offset,ByteOrder order){
  if (order == ByteOrder.BIG_ENDIAN) {
    return (((src[offset++] & 0xff) << 24) | ((src[offset++] & 0xff) << 16) | ((src[offset++] & 0xff) << 8)| ((src[offset] & 0xff) << 0));
  }
 else {
    return (((src[offset++] & 0xff) << 0) | ((src[offset++] & 0xff) << 8) | ((src[offset++] & 0xff) << 16)| ((src[offset] & 0xff) << 24));
  }
}
 

Example 40

From project jaffl, under directory /src/com/kenai/jaffl/provider/.

Source file: AbstractArrayMemoryIO.java

  15 
vote

public static final ArrayIO getArrayIO(Runtime runtime){
  if (runtime.byteOrder().equals(ByteOrder.BIG_ENDIAN)) {
    return runtime.addressSize() == 8 ? BE64ArrayIO.INSTANCE : BE32ArrayIO.INSTANCE;
  }
 else {
    return runtime.addressSize() == 8 ? LE64ArrayIO.INSTANCE : LE32ArrayIO.INSTANCE;
  }
}
 

Example 41

From project Jandig, under directory /src/edu/dhbw/andobjviewer/util/.

Source file: MemUtil.java

  15 
vote

public static FloatBuffer makeFloatBufferFromArray(float[] arr){
  ByteBuffer bb=ByteBuffer.allocateDirect(arr.length * 4);
  bb.order(ByteOrder.nativeOrder());
  FloatBuffer fb=bb.asFloatBuffer();
  fb.put(arr);
  fb.position(0);
  return fb;
}
 

Example 42

From project javAX25, under directory /src/sivantoledo/agwpe/.

Source file: TNC.java

  15 
vote

public void handlePacket(byte[] bytes){
  System.out.printf("Packet from RF: %s\n",Packet.format(bytes));
  byte[] header_data=new byte[37 + bytes.length];
  ByteBuffer bb=ByteBuffer.wrap(header_data).order(ByteOrder.LITTLE_ENDIAN);
  bb.position(28);
  bb.putInt(bytes.length);
  System.arraycopy(bytes,0,header_data,36,bytes.length);
  try {
    os.write(header_data);
  }
 catch (  IOException e) {
  }
}
 

Example 43

From project jboss-websockets, under directory /src/main/java/org/jboss/websockets/oio/internal/protocol/ietf00/.

Source file: Hybi00Handshake.java

  15 
vote

public static byte[] solve(final String hashAlgorithm,long key1,long key2,byte[] key3){
  ByteBuffer buffer=ByteBuffer.allocate(16).order(ByteOrder.BIG_ENDIAN);
  buffer.putInt((int)key1);
  buffer.putInt((int)key2);
  buffer.put(key3);
  final byte[] solution=new byte[16];
  buffer.rewind();
  buffer.get(solution,0,16);
  try {
    final MessageDigest digest=MessageDigest.getInstance(hashAlgorithm);
    return digest.digest(solution);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("error generating hash",e);
  }
}
 

Example 44

From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.

Source file: AmibeReader.java

  15 
vote

/** 
 * Read a group and write it to a channel 
 */
public void readGroup(Group group,WritableByteChannel out) throws IOException {
  int[] trias=group.readTria3();
  int[] nodesIds=new TIntHashSet(trias).toArray();
  Arrays.sort(nodesIds);
  ByteBuffer bb=ByteBuffer.allocate(128 * 1024);
  bb.order(ByteOrder.nativeOrder());
  bb.putInt(nodesIds.length * 3);
  TIntIntHashMap nodeMap=new TIntIntHashMap(nodesIds.length);
  DoubleFileReader nodes=getNodes();
  double[] coords=new double[3];
  int k=0;
  for (  int id : nodesIds) {
    nodes.get(3 * id,coords);
    if (bb.remaining() < 24)     flushByteBuffer(bb,out);
    for (int i=0; i < 3; i++)     bb.putDouble(coords[i]);
    nodeMap.put(id,k++);
  }
  nodesIds=null;
  nodes.close();
  flushByteBuffer(bb,out);
  bb.putInt(group.getNumberOfTrias() * 3);
  for (int i=0; i < trias.length / 3; i++) {
    if (bb.remaining() < 12)     flushByteBuffer(bb,out);
    for (int j=0; j < 3; j++)     bb.putInt(nodeMap.get(trias[3 * i + j]));
  }
  flushByteBuffer(bb,out);
}
 

Example 45

From project jcollectd, under directory /src/main/java/org/collectd/protocol/.

Source file: PacketWriter.java

  15 
vote

private void writeDouble(double val) throws IOException {
  ByteBuffer bb=ByteBuffer.wrap(new byte[8]);
  bb.order(ByteOrder.LITTLE_ENDIAN);
  bb.putDouble(val);
  _os.write(bb.array());
}
 

Example 46

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: GitIndex.java

  15 
vote

/** 
 * Read the cache file into memory.
 * @throws IOException
 */
public void read() throws IOException {
  changed=false;
  statDirty=false;
  if (!cacheFile.exists()) {
    header=null;
    entries.clear();
    lastCacheTime=0;
    return;
  }
  cache=new RandomAccessFile(cacheFile,"r");
  try {
    FileChannel channel=cache.getChannel();
    ByteBuffer buffer=ByteBuffer.allocateDirect((int)cacheFile.length());
    buffer.order(ByteOrder.BIG_ENDIAN);
    int j=channel.read(buffer);
    if (j != buffer.capacity())     throw new IOException("Could not read index in one go, only " + j + " out of "+ buffer.capacity()+ " read");
    buffer.flip();
    header=new Header(buffer);
    entries.clear();
    for (int i=0; i < header.entries; ++i) {
      Entry entry=new Entry(buffer);
      entries.put(entry.name,entry);
    }
    lastCacheTime=cacheFile.lastModified();
  }
  finally {
    cache.close();
  }
}
 

Example 47

From project JitCask, under directory /src/com/afewmoreamps/.

Source file: HintCaskOutput.java

  15 
vote

void close() throws IOException {
  flushHints(m_pendingMetadataIndex,m_keyHashes,m_positions);
  m_thread.shutdown();
  try {
    m_thread.awaitTermination(356,TimeUnit.DAYS);
  }
 catch (  InterruptedException e) {
    throw new IOException(e);
  }
  m_fc.force(false);
  ByteBuffer allCRCBuf=ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
  allCRCBuf.putInt(0,(int)m_allCRC.getValue());
  while (allCRCBuf.hasRemaining()) {
    m_fc.write(allCRCBuf,allCRCBuf.position());
  }
  m_fc.force(false);
  m_fc.close();
}
 

Example 48

From project JMaNGOS, under directory /Auth/src/main/java/org/jmangos/auth/network/decoder/.

Source file: RealmPacketFrameDecoder.java

  15 
vote

@Override protected Object decode(final ChannelHandlerContext ctx,final Channel channel,final ChannelBuffer msg) throws Exception {
  final ChannelBuffer message=msg;
  if (message.readableBytes() < 3) {
    return null;
  }
  message.markReaderIndex();
  final AuthToClientChannelHandler channelHandler=(AuthToClientChannelHandler)ctx.getPipeline().getLast();
  final Crypt crypt=channelHandler.getCrypt();
  final byte[] header=new byte[3];
  message.readBytes(header);
  final ChannelBuffer clientHeader=ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN,header);
  final byte opcode=clientHeader.readByte();
  final int size=clientHeader.readShort();
  if ((size < 0) || (size > 10240)) {
    log.error("PacketFrameDecoder::decode: realm sent malformed packet size = " + size + " , opcode = "+ opcode);
    channel.close();
    return null;
  }
  if (message.readableBytes() < size) {
    message.resetReaderIndex();
    return null;
  }
  byte[] tmpa=new byte[message.readableBytes()];
  message.readBytes(tmpa);
  tmpa=crypt.decrypt(tmpa);
  final ChannelBuffer frame=ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN,(size + 1));
  frame.writeByte(opcode);
  frame.writeBytes(tmpa);
  return frame;
}