Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

In this page you can find the example usage for java.nio ByteBuffer order.

Prototype

Endianness order

To view the source code for java.nio ByteBuffer order.

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

/**
 * This code is intended for use in the scenario in which a datset terminates before properly
 * closing, thereby preventing the multipage tiff writer from putting in the index map,
 * comments, channels, and OME XML in the ImageDescription tag location
 *//*from w  w  w .  j ava2 s  .c om*/
private void fixIndexMap(long firstIFD) throws IOException, JSONException {
    int choice = JOptionPane.showConfirmDialog(null,
            "This dataset cannot be opened bcause it appears to have \n"
                    + "been improperly saved.  Would you like Micro-Manger to attempt to fix it?",
            "Micro-Manager", JOptionPane.YES_NO_OPTION);
    if (choice == JOptionPane.NO_OPTION) {
        return;
    }
    long filePosition = firstIFD;
    indexMap_ = new HashMap<String, Long>();
    //      final ProgressBar progressBar = new ProgressBar("Fixing dataset", 0, (int) (fileChannel_.size() / 2L));
    //      progressBar.setRange(0, (int) (fileChannel_.size() / 2L));
    //      progressBar.setProgress(0);
    //      progressBar.setVisible(true);
    long nextIFDOffsetLocation = 0;
    IFDData data = null;
    while (filePosition > 0) {
        try {
            data = readIFD(filePosition);
            TaggedImage ti = readTaggedImage(data);
            if (ti.tags == null) { //Blank placeholder image, dont add to index map
                filePosition = data.nextIFD;
                nextIFDOffsetLocation = data.nextIFDOffsetLocation;
                continue;
            }
            String label = null;
            label = MDUtils.getLabel(ti.tags);
            if (label == null) {
                break;
            }
            indexMap_.put(label, filePosition);
            final int progress = (int) (filePosition / 2L);
            //            SwingUtilities.invokeLater(new Runnable() {
            //               public void run() {
            //                  progressBar.setProgress(progress);
            //               }
            //            });
            filePosition = data.nextIFD;
            nextIFDOffsetLocation = data.nextIFDOffsetLocation;
        } catch (Exception e) {
            break;
        }
    }
    //progressBar.setVisible(false);

    filePosition += writeIndexMap(filePosition);

    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.order(byteOrder_);
    buffer.putInt(0, 0);
    fileChannel_.write(buffer, nextIFDOffsetLocation);
    raFile_.setLength(filePosition + 8);

    fileChannel_.close();
    raFile_.close();
    //reopen
    createFileChannel();

    ReportingUtils.showMessage("Dataset succcessfully repaired! Resave file to reagain full funtionality");
}

From source file:byps.test.TestSerializePrimitiveTypes.java

public void internalTestBufferRealloc(ByteOrder border) throws BException {
    ByteBuffer buf = ByteBuffer.allocate(17);
    buf.order(border);
    BBuffer bbuf = BBuffer.create(TestUtils.protocol, buf);
    int count = 3;

    for (int i = 0; i < count; i++) {
        bbuf.putDouble(i);/* w  w w  .  j  a v  a 2s  .c om*/
    }
    bbuf.flip();

    TestUtils.printBuffer(log, bbuf);

    if (TestUtils.protocol == BProtocolJson.BINARY_MODEL) {
        BBufferJson jbuf = (BBufferJson) bbuf;
        for (int i = 0; i < count; i++) {
            if (i != 0)
                jbuf.nextExpectedJsonChar(',', true);
            double d = bbuf.getDouble();
            TestUtils.assertEquals(log, "double[" + i + "]", (double) i, d);
        }
    } else {
        for (int i = 0; i < count; i++) {
            double d = bbuf.getDouble();
            TestUtils.assertEquals(log, "double[" + i + "]", (double) i, d);
        }
    }
}

From source file:ome.formats.importer.OMEROWrapper.java

/**
 * Obtains an object which represents a given sub-image of a plane within
 * the file./*  w w  w  .j  a  v  a 2 s .co m*/
 * @param id The path to the file.
 * @param planeNumber The plane or section within the file to obtain.
 * @param buf Pre-allocated buffer which has a <i>length</i> that can fit
 * the byte count of the sub-image.
 * @param x X coordinate of the upper-left corner of the sub-image
 * @param y Y coordinate of the upper-left corner of the sub-image
 * @param w width of the sub-image
 * @param h height of the sub-image
 * @return an object which represents the sub-image of the plane.
 * @throws FormatException If there is an error parsing the file.
 * @throws IOException If there is an error reading from the file or
 * acquiring permissions to read the file.
 */
public PixelData openPlane2D(String id, int planeNumber, byte[] buf, int x, int y, int w, int h)
        throws FormatException, IOException {
    // FIXME: HACK! The ChannelSeparator isn't exactly what one would call
    // "complete" so we have to work around the fact that it still copies
    // all of the plane data (all three channels) from the file if the file
    // is RGB.
    ByteBuffer plane;
    if (iReader.isRGB() || isLeicaReader()) {
        // System.err.println("RGB, not using cached buffer.");
        byte[] bytePlane = openBytes(planeNumber, x, y, w, h);
        plane = ByteBuffer.wrap(bytePlane);
    } else {
        // System.err.println("Not RGB, using cached buffer.");
        plane = ByteBuffer.wrap(openBytes(planeNumber, buf, x, y, w, h));
    }
    plane.order(isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
    return new PixelData(FormatTools.getPixelTypeString(getPixelType()), plane);
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public void setSampleRateManual(int frequency, int divider) throws UsbException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);

    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(frequency);//  w  w  w.  j  ava  2  s  . com
    buffer.putInt(divider);

    write(Request.SET_SAMPLE_RATE, 0, 0, buffer);
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

@Override
public void setTunedFrequency(long frequency) throws SourceException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int mhz = (int) (frequency / 1E6);
    int hz = (int) (frequency - (mhz * 1E6));

    buffer.putInt(mhz);/* w ww  .  ja va  2 s  . c  o  m*/
    buffer.putInt(hz);

    buffer.rewind();

    try {
        write(Request.SET_FREQUENCY, 0, 0, buffer);
    } catch (UsbException e) {
        mLog.error("error setting frequency [" + frequency + "]", e);

        throw new SourceException("error setting frequency [" + frequency + "]", e);
    }
}

From source file:org.apache.hadoop.crypto.CryptoStreamsTestBase.java

private void setCounterBaseForIV(byte[] iv, long counterBase) {
    ByteBuffer buf = ByteBuffer.wrap(iv);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(iv.length - 8, counterBase);
}

From source file:org.bimserver.collada.ColladaSerializer.java

private void printMatrix(PrintWriter out, GeometryInfo geometryInfo) {
    ByteBuffer transformation = ByteBuffer.wrap(geometryInfo.getTransformation());
    transformation.order(ByteOrder.LITTLE_ENDIAN);
    FloatBuffer floatBuffer = transformation.asFloatBuffer();
    // Prepare to create the transform matrix.
    float[] matrix = new float[16];
    // Add the first 16 values of the buffer.
    for (int i = 0; i < matrix.length; i++)
        matrix[i] = floatBuffer.get();//from  w w w .j  a v a 2 s  .  c o m
    // Switch from column-major (x.x ... x.y ... x.z ... 0 ...) to row-major orientation (x.x x.y x.z 0 ...)?
    matrix = Matrix.changeOrientation(matrix);
    // List all 16 elements of the matrix as a single space-delimited String object.
    out.println("    <matrix>" + floatArrayToSpaceDelimitedString(matrix) + "</matrix>");
}

From source file:ffx.numerics.fft.Complex3DCuda.java

/**
 * {@inheritDoc}//from  w w w  .j  a  v  a 2s. com
 */
@Override
public void run() {
    JCudaDriver.setExceptionsEnabled(true);
    JCufft.setExceptionsEnabled(true);
    JCudaDriver.setLogLevel(LogLevel.LOG_INFO);
    JCufft.setLogLevel(LogLevel.LOG_INFO);
    JCufft.initialize();

    // Initialize the driver and create a context for the first device.
    cuInit(0);
    CUcontext pctx = new CUcontext();
    CUdevice dev = new CUdevice();
    CUdevprop prop = new CUdevprop();
    cuDeviceGetProperties(prop, dev);
    logger.log(Level.INFO, "   CUDA {0}", prop.toFormattedString());
    cuDeviceGet(dev, 0);

    // Create a context that allows the GPU to map pinned host memory.
    if (usePinnedMemory) {
        cuCtxCreate(pctx, CUctx_flags.CU_CTX_MAP_HOST, dev);
    } else {
        // Create a context that does not allows the GPU to map pinned host memory.
        cuCtxCreate(pctx, 0, dev);
    }

    // Load the CUBIN file and obtain the "recipSummation" function.
    try {
        String bit = System.getProperty("sun.arch.data.model").trim();
        URL source = getClass().getClassLoader()
                .getResource("ffx/numerics/fft/recipSummation-" + bit + ".cubin");
        File cubinFile = File.createTempFile("recipSummation", "cubin");
        FileUtils.copyURLToFile(source, cubinFile);
        module = new CUmodule();
        cuModuleLoad(module, cubinFile.getCanonicalPath());
        function = new CUfunction();
        cuModuleGetFunction(function, module, "recipSummation");
    } catch (Exception e) {
        String message = " Error loading the reciprocal summation kernel";
        logger.log(Level.SEVERE, message, e);
    }

    pinnedMemory = new Pointer();

    if (usePinnedMemory) {
        // Allocate pinned memory mapped into the GPU address space.
        cuMemHostAlloc(pinnedMemory, len * 2 * Sizeof.DOUBLE, CU_MEMHOSTALLOC_DEVICEMAP);
    } else {
        // Allocate memory
        cuMemHostAlloc(pinnedMemory, len * 2 * Sizeof.DOUBLE, 0);
    }

    ByteBuffer byteBuffer = pinnedMemory.getByteBuffer(0, len * 2 * Sizeof.DOUBLE);
    byteBuffer.order(ByteOrder.nativeOrder());
    pinnedMemoryBuffer = byteBuffer.asDoubleBuffer();

    // Allocate a work array on the device.
    dataDevice = new CUdeviceptr();
    cuMemAlloc(dataDevice, len * 2 * Sizeof.DOUBLE);

    // Allocate memory on the device for the reciprocal space array.
    recipDevice = new CUdeviceptr();
    cuMemAlloc(recipDevice, len * Sizeof.DOUBLE);

    // Create and execute a JCufft plan for the data
    plan = new cufftHandle();

    cufftPlan3d(plan, nZ, nY, nX, cufftType.CUFFT_Z2Z);
    //cufftSetCompatibilityMode(plan, cufftCompatibility.CUFFT_COMPATIBILITY_FFTW_ALL);

    dataGPUPtr = Pointer.to(dataDevice);
    recipGPUPtr = Pointer.to(recipDevice);

    int threads = prop.maxThreadsPerBlock;
    int nBlocks = len / threads + (len % threads == 0 ? 0 : 1);
    int gridSize = (int) Math.floor(Math.sqrt(nBlocks)) + 1;

    logger.info(format("   CUDA thread initialized: %d threads per block", threads));
    logger.info(format("   Grid Size:                     (%3d,%3d,%3d)", gridSize, gridSize, 1));

    assert (gridSize * gridSize * threads >= len);

    synchronized (this) {
        while (!free) {
            if (mode != null) {
                switch (mode) {

                case RECIP:
                    cuMemcpyHtoD(recipDevice, recipCPUPtr, len * Sizeof.DOUBLE);
                    break;

                case FFT:
                    // Zero Copy
                    if (usePinnedMemory) {
                        cufftExecZ2Z(plan, pinnedMemory, pinnedMemory, CUFFT_FORWARD);
                    } else {
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_FORWARD);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;

                case CONVOLUTION:

                    if (usePinnedMemory) {
                        // Zero Copy
                        cufftExecZ2Z(plan, pinnedMemory, dataDevice, CUFFT_FORWARD);
                    } else {
                        // Copy data to device and run forward FFT.
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_FORWARD);
                    }

                    // Set up the execution parameters for the kernel
                    cuFuncSetBlockShape(function, threads, 1, 1);
                    int offset = 0;
                    offset = align(offset, Sizeof.POINTER);
                    cuParamSetv(function, offset, dataGPUPtr, Sizeof.POINTER);
                    offset += Sizeof.POINTER;
                    offset = align(offset, Sizeof.POINTER);
                    cuParamSetv(function, offset, recipGPUPtr, Sizeof.POINTER);
                    offset += Sizeof.POINTER;
                    offset = align(offset, Sizeof.INT);
                    cuParamSeti(function, offset, len);
                    offset += Sizeof.INT;
                    cuParamSetSize(function, offset);
                    // Call the kernel function.
                    cuLaunchGrid(function, gridSize, gridSize);
                    if (usePinnedMemory) {
                        // Zero Copy
                        cufftExecZ2Z(plan, dataDevice, pinnedMemory, CUFFT_INVERSE);
                    } else {
                        // Perform inverse FFT and copy memory back to the CPU.
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_INVERSE);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;

                case IFFT:
                    // Zero Copy
                    if (usePinnedMemory) {
                        cufftExecZ2Z(plan, pinnedMemory, pinnedMemory, CUFFT_INVERSE);
                    } else {
                        cuMemcpyHtoD(dataDevice, pinnedMemory, 2 * len * Sizeof.DOUBLE);
                        cufftExecZ2Z(plan, dataDevice, dataDevice, CUFFT_INVERSE);
                        cuMemcpyDtoH(pinnedMemory, dataDevice, 2 * len * Sizeof.DOUBLE);
                    }
                    break;
                }

                // Block for the context's tasks to complete.
                cuCtxSynchronize();

                // Reset the mode to null and notify the calling thread.
                mode = null;
                notify();
            }
            // The CUDA thread will wait until it's notified again.
            try {
                wait();
            } catch (InterruptedException e) {
                logger.severe(e.toString());
            }
        }
        cufftDestroy(plan);
        cuMemFree(dataDevice);
        cuMemFree(recipDevice);
        cuMemFreeHost(pinnedMemory);
        dead = true;
        notify();
    }
    logger.info(" CUDA Thread Done!");
}

From source file:rb.app.GLObject.java

public void allocateBuffer() {
    int SHORT_MAX = 250000;
    int FLOAT_MAX = 1000000;

    Log.d("GLRenderer", "Allocate (short):" + SHORT_MAX * 2 + " bytes");
    ByteBuffer vbb = ByteBuffer.allocateDirect(SHORT_MAX * 2);
    vbb.order(ByteOrder.nativeOrder());
    _shortBuffer = vbb.asShortBuffer();/*from  w w w  .  jav  a 2s .  c o  m*/
    _shortBuffer.position(0);

    Log.d("GLRenderer", "Allocate (float):" + FLOAT_MAX * 4 + " bytes");
    ByteBuffer fbb = ByteBuffer.allocateDirect(FLOAT_MAX * 4);
    fbb.order(ByteOrder.nativeOrder());
    _floatBuffer = fbb.asFloatBuffer();
    _floatBuffer.position(0);
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void _write(String command, Object args) throws IOException {
    // Write a command to the server
    // Format: ENQ + commandcode + length + payload
    Pickler pickler = new Pickler();
    byte[] data = pickler.dumps(args);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    buffer.write(daemon.ENQ);//from   www  .j  a  va2s .c o m
    // frame format requires: length of (ENQ + commandcode) == 3 bytes
    // That's why an empty byte gets inserted here.
    buffer.write((byte) 0x00);
    buffer.write(daemon.command2code(command));
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.putInt(data.length);
    buffer.write(bb.array());
    buffer.write(data);
    socketOut.write(buffer.toByteArray());
    socketOut.flush();
}