Example usage for java.nio ByteOrder nativeOrder

List of usage examples for java.nio ByteOrder nativeOrder

Introduction

In this page you can find the example usage for java.nio ByteOrder nativeOrder.

Prototype

public static ByteOrder nativeOrder() 

Source Link

Document

Returns the current platform byte order.

Usage

From source file:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {/*www. ja v a  2  s. co m*/
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}

From source file:com.sveder.cardboardpassthrough.MainActivity.java

/**
 * Creates the buffers we use to store information about the 3D world. OpenGL doesn't use Java
 * arrays, but rather needs data in a format it can understand. Hence we use ByteBuffers.
 * @param config The EGL configuration used when creating the surface.
 *//*from   w w w  . j a va 2 s.com*/
@Override
public void onSurfaceCreated(EGLConfig config) {
    Log.i(TAG, "onSurfaceCreated");
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up well

    ByteBuffer bb = ByteBuffer.allocateDirect(squareVertices.length * 4);
    bb.order(ByteOrder.nativeOrder());
    vertexBuffer = bb.asFloatBuffer();
    vertexBuffer.put(squareVertices);
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2);
    dlb.order(ByteOrder.nativeOrder());
    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);

    ByteBuffer bb2 = ByteBuffer.allocateDirect(textureVertices.length * 4);
    bb2.order(ByteOrder.nativeOrder());
    textureVerticesBuffer = bb2.asFloatBuffer();
    textureVerticesBuffer.put(textureVertices);
    textureVerticesBuffer.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
    int fragmentShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

    mProgram = GLES20.glCreateProgram(); // create empty OpenGL ES Program
    GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
    GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
    GLES20.glLinkProgram(mProgram);

    texture = createTexture();
    startCamera(texture);

    //        ByteBuffer bbVertices = ByteBuffer.allocateDirect(DATA.CUBE_COORDS.length * 4);
    //        bbVertices.order(ByteOrder.nativeOrder());
    //        mCubeVertices = bbVertices.asFloatBuffer();
    //        mCubeVertices.put(DATA.CUBE_COORDS);
    //        mCubeVertices.position(0);
    //
    //        ByteBuffer bbColors = ByteBuffer.allocateDirect(DATA.CUBE_COLORS.length * 4);
    //        bbColors.order(ByteOrder.nativeOrder());
    //        mCubeColors = bbColors.asFloatBuffer();
    //        mCubeColors.put(DATA.CUBE_COLORS);
    //        mCubeColors.position(0);
    //
    //        ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(DATA.CUBE_FOUND_COLORS.length * 4);
    //        bbFoundColors.order(ByteOrder.nativeOrder());
    //        mCubeFoundColors = bbFoundColors.asFloatBuffer();
    //        mCubeFoundColors.put(DATA.CUBE_FOUND_COLORS);
    //        mCubeFoundColors.position(0);
    //
    //        ByteBuffer bbNormals = ByteBuffer.allocateDirect(DATA.CUBE_NORMALS.length * 4);
    //        bbNormals.order(ByteOrder.nativeOrder());
    //        mCubeNormals = bbNormals.asFloatBuffer();
    //        mCubeNormals.put(DATA.CUBE_NORMALS);
    //        mCubeNormals.position(0);
    //
    //        // make a floor
    //        ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(DATA.FLOOR_COORDS.length * 4);
    //        bbFloorVertices.order(ByteOrder.nativeOrder());
    //        mFloorVertices = bbFloorVertices.asFloatBuffer();
    //        mFloorVertices.put(DATA.FLOOR_COORDS);
    //        mFloorVertices.position(0);
    //
    //        ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(DATA.FLOOR_NORMALS.length * 4);
    //        bbFloorNormals.order(ByteOrder.nativeOrder());
    //        mFloorNormals = bbFloorNormals.asFloatBuffer();
    //        mFloorNormals.put(DATA.FLOOR_NORMALS);
    //        mFloorNormals.position(0);
    //
    //        ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(DATA.FLOOR_COLORS.length * 4);
    //        bbFloorColors.order(ByteOrder.nativeOrder());
    //        mFloorColors = bbFloorColors.asFloatBuffer();
    //        mFloorColors.put(DATA.FLOOR_COLORS);
    //        mFloorColors.position(0);
    //
    //        int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, R.raw.light_vertex);
    //        int gridShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.grid_fragment);
    //
    //        mGlProgram = GLES20.glCreateProgram();
    //        GLES20.glAttachShader(mGlProgram, vertexShader);
    //        GLES20.glAttachShader(mGlProgram, gridShader);
    //        GLES20.glLinkProgram(mGlProgram);
    //
    //        GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    //
    //        // Object first appears directly in front of user
    //        Matrix.setIdentityM(mModelCube, 0);
    //        Matrix.translateM(mModelCube, 0, 0, 0, -mObjectDistance);
    //
    //        Matrix.setIdentityM(mModelFloor, 0);
    //        Matrix.translateM(mModelFloor, 0, 0, -mFloorDepth, 0); // Floor appears below user
    //
    //        checkGLError("onSurfaceCreated");
}

From source file:com.alvermont.terraj.fracplanet.geom.VertexBufferArray.java

/**
 * Resize the buffer. This is done by reallocating a new one and copying
 * data from the old buffer to the new one. This is necessary as buffers
 * cannot be dynamically resized.//from w  w  w. j  a v  a  2s  . co m
 */
protected void resizeBuffer() {
    // we can't resize it so we have to allocate a new one and copy the data
    final int slots = (buffer.capacity() / ELEMENTSIZE);
    final int newCapacity = buffer.capacity()
            + (((slots * CAPACITY_PCT_INCREASE) / HUNDRED_PERCENT) * ELEMENTSIZE);

    final ByteBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity).order(ByteOrder.nativeOrder());

    if (log.isDebugEnabled()) {
        log.debug("Resizing vertex buffer capacity to: " + newBuffer.capacity());
    }

    final FloatBuffer oldVertexBuffer = positionBuffer;
    final FloatBuffer oldNormalBuffer = normalBuffer;
    final ByteBuffer oldColourBuffer = colourBuffer;
    final ByteBuffer oldEmissiveBuffer = emissiveBuffer;

    this.buffer = newBuffer;

    sliceAndDice(newCapacity / ELEMENTSIZE);

    oldVertexBuffer.rewind();
    positionBuffer.rewind();
    positionBuffer.limit(oldVertexBuffer.limit());
    positionBuffer.put(oldVertexBuffer);

    oldNormalBuffer.rewind();
    normalBuffer.rewind();
    normalBuffer.limit(oldNormalBuffer.limit());
    normalBuffer.put(oldNormalBuffer);

    oldColourBuffer.rewind();
    colourBuffer.rewind();
    colourBuffer.limit(oldColourBuffer.limit());
    colourBuffer.put(oldColourBuffer);

    oldEmissiveBuffer.rewind();
    emissiveBuffer.rewind();
    emissiveBuffer.limit(oldEmissiveBuffer.limit());
    emissiveBuffer.put(oldEmissiveBuffer);
}

From source file:x10.x10rt.yarn.ApplicationMaster.java

private void processMessage(ByteBuffer msg, SocketChannel sc) {
    assert (msg.capacity() >= headerLength);

    msg.rewind(); // reset the buffer for reading from the beginning
    CTRL_MSG_TYPE type = CTRL_MSG_TYPE.values()[msg.getInt()];
    int destination = msg.getInt();
    final int source = msg.getInt();
    int datalen = msg.getInt();
    assert (datalen == msg.remaining());

    LOG.info("Processing message of type " + type + ", size " + (headerLength + datalen) + " from place "
            + source);//w  w w .ja  v  a 2  s . c  o m
    /*      System.err.print("Message contents:");
          for (int i=0; i<msg.capacity(); i++)
             System.err.print(" "+Integer.toHexString(msg.get(i)).toUpperCase());
          System.err.println();
    */
    switch (type) {
    case HELLO: {
        // read the port information, and update the record for this place
        assert (datalen == 4 && source < numRequestedContainers.get() && source >= 0);
        final CommunicationLink linkInfo;
        LOG.info("Getting link for place " + source);
        synchronized (links) {
            linkInfo = links.get(source);
        }
        linkInfo.port = ((msg.get() & 0xFF) << 8) | (msg.get() & 0xFF); // unsigned short in network order
        linkInfo.sc = sc;

        // check if there are pending port requests for this place
        if (linkInfo.pendingPortRequests != null) {
            // prepare response message
            String linkString = linkInfo.node.getHost() + ":" + linkInfo.port;
            byte[] linkBytes = linkString.getBytes(); // matches existing code.  TODO: switch to UTF8
            ByteBuffer response = ByteBuffer.allocateDirect(headerLength + linkBytes.length)
                    .order(ByteOrder.nativeOrder());
            response.putInt(CTRL_MSG_TYPE.PORT_RESPONSE.ordinal());
            response.putInt(-1);
            response.putInt(source);
            response.putInt(linkBytes.length);
            response.put(linkBytes);
            // send response to each waiting place
            for (int place : linkInfo.pendingPortRequests) {
                response.putInt(4, place); // set the destination to the requesting place
                response.rewind();
                // TODO: this code may get stuck here if the reciever isn't reading properly
                try {
                    while (response.hasRemaining())
                        links.get(place).sc.write(response);
                } catch (IOException e) {
                    LOG.warn("Unable to send out port response for place " + place + " to place " + source, e);
                }
            }
            linkInfo.pendingPortRequests = null;
        }
        LOG.info("HELLO from place " + source + " at port " + linkInfo.port);

        if (pendingKills != null && pendingKills.containsKey(source)) {
            int delay = pendingKills.remove(source);
            LOG.info("Scheduling a takedown of place " + source + " in " + delay + " seconds");
            placeKiller.schedule(new Runnable() {
                @Override
                public void run() {
                    LOG.info("KILLING CONTAINER FOR PLACE " + source);
                    nodeManager.stopContainerAsync(linkInfo.container, linkInfo.node);
                }
            }, delay, TimeUnit.SECONDS);
        }
    }
        break;
    case GOODBYE: {
        try {
            CommunicationLink link = links.get(source);
            assert (link.pendingPortRequests == null);
            sc.close();
            link.port = PORT_DEAD;
        } catch (IOException e) {
            LOG.warn("Error closing socket channel", e);
        }
        LOG.info("GOODBYE to place " + source);
    }
        break;
    case PORT_REQUEST: {
        LOG.info("Got PORT_REQUEST from place " + source + " for place " + destination);
        // check to see if we know the requested information
        CommunicationLink linkInfo = links.get(destination);
        if (linkInfo.port != PORT_UNKNOWN) {
            String linkString;
            if (linkInfo.port == PORT_DEAD)
                linkString = DEAD;
            else
                linkString = linkInfo.node.getHost() + ":" + linkInfo.port;
            LOG.info("Telling place " + source + " that place " + destination + " is at " + linkString);
            byte[] linkBytes = linkString.getBytes(); // matches existing code.  TODO: switch to UTF8
            ByteBuffer response = ByteBuffer.allocateDirect(headerLength + linkBytes.length)
                    .order(ByteOrder.nativeOrder());
            response.putInt(CTRL_MSG_TYPE.PORT_RESPONSE.ordinal());
            response.putInt(source);
            response.putInt(destination);
            response.putInt(linkBytes.length);
            response.put(linkBytes);
            response.rewind();
            // TODO: this code may get stuck here if the reciever isn't reading properly
            try {
                while (response.hasRemaining())
                    sc.write(response);
            } catch (IOException e) {
                LOG.warn("Unable to send out port response for place " + destination + " to place " + source,
                        e);
            }
        } else { // port is not known.  remember we have a place asking for it when it becomes available
            if (linkInfo.pendingPortRequests == null)
                linkInfo.pendingPortRequests = new ArrayList<Integer>(2);
            linkInfo.pendingPortRequests.add(source);
            LOG.info("Stashing PORT_REQUEST from place " + source + " for place " + destination
                    + " until the answer is known");
        }
    }
        break;
    case LAUNCH_REQUEST: {
        assert (datalen == 8);
        int numPlacesRequested = (int) msg.getLong();

        int oldvalue = numRequestedContainers.getAndAdd((int) numPlacesRequested);

        // Send request for containers to RM
        for (int i = 0; i < numPlacesRequested; i++) {
            Resource capability = Resource.newInstance(memoryPerPlaceInMb, coresPerPlace);
            ContainerRequest request = new ContainerRequest(capability, null, null, Priority.newInstance(0));
            LOG.info("Adding a new container request " + request.toString());
            resourceManager.addContainerRequest(request);
            pendingRequests.add(request);
        }

        LOG.info("Requested an increase of " + numPlacesRequested + " places on top of the previous " + oldvalue
                + " places");
        msg.rewind();
        msg.putInt(CTRL_MSG_TYPE.LAUNCH_RESPONSE.ordinal());
        msg.rewind();
        try {
            while (msg.hasRemaining())
                sc.write(msg);
        } catch (IOException e) {
            LOG.warn("Unable to send out launch response to place " + source, e);
        }
    }
        break;
    default:
        LOG.warn("unknown message type " + type);
    }
    LOG.info("Finished processing message of size " + (headerLength + datalen) + " from place " + source);
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReader.java

private void decodeHeader(BufferedInputStream stream) throws IOException {
    dbgLog.fine("***** decodeHeader(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }/*from  ww  w  .  j  a  v a  2 s. c  o m*/

    dbgLog.fine("reading the header segument 1: 4 byte\n");
    byte[] magic_number = new byte[DTA_MAGIC_NUMBER_LENGTH];

    int nbytes = stream.read(magic_number, 0, DTA_MAGIC_NUMBER_LENGTH);

    if (nbytes == 0) {
        throw new IOException();
    }

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(magic_number)) + "<-");

    if (magic_number[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        throw new IllegalArgumentException("given file is not stata-dta type");
    } else if ((magic_number[1] != 1) && (magic_number[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        throw new IllegalArgumentException("given file is not stata-dta type");
    } else if (!STATA_RELEASE_NUMBER.containsKey((int) magic_number[0])) {
        dbgLog.fine("1st byte (" + magic_number[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "we cannot ingest this Stata file.");
        throw new IllegalArgumentException("given file is not stata-dta type");
    } else {
        releaseNumber = (int) magic_number[0];
        smd.getFileInformation().put("releaseNumber", releaseNumber);
        smd.getFileInformation().put("byteOrder", (int) magic_number[1]);
        smd.getFileInformation().put("OSByteOrder", ByteOrder.nativeOrder().toString());

        smd.getFileInformation().put("mimeType", MIME_TYPE[0]);
        smd.getFileInformation().put("fileFormat", MIME_TYPE[0]);
        init();

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("this file is stata-dta type: " + STATA_RELEASE_NUMBER.get((int) magic_number[0])
                    + "(Number=" + magic_number[0] + ")");
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("Endian(file)(Big: 1; Little:2)=" + magic_number[1]);

        if ((int) magic_number[1] == 2) {
            isLittleEndian = true;
            dbgLog.fine("Reveral of the bytes is necessary to decode " + "multi-byte fields");
        }
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("Endian of this platform:" + ByteOrder.nativeOrder().toString());
    }

    dbgLog.fine("reading the remaining header segument 2: 60 or 109-byte");

    byte[] header = new byte[headerLength];
    nbytes = stream.read(header, 0, headerLength);
    //printHexDump(header, "header:\n");

    // 1. number of variables: short (2 bytes)
    ByteBuffer bbnvar = ByteBuffer.wrap(header, 0, NVAR_FIELD_LENGTH);
    ByteBuffer dupnvar = bbnvar.duplicate();
    short short_nvar = dupnvar.getShort();

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("get original short view(nvar)=" + short_nvar);
    if (isLittleEndian) {
        bbnvar.order(ByteOrder.LITTLE_ENDIAN);

    }

    short shrt_nvar = bbnvar.getShort();
    smd.getFileInformation().put("varQnty", new Integer(shrt_nvar));

    // setup variableTypeList
    int nvar = shrt_nvar;
    variableTypelList = new String[nvar];

    // 2. number of observations: int (4 bytes)
    ByteBuffer nobs = ByteBuffer.wrap(header, NVAR_FIELD_LENGTH, NOBS_FIELD_LENGTH);
    ByteBuffer dupnobs = nobs.duplicate();
    int int_dupnobs = dupnobs.getInt();
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("raw nobs=" + int_dupnobs);
    if (isLittleEndian) {
        nobs.order(ByteOrder.LITTLE_ENDIAN);
    }
    int int_nobs = nobs.getInt();
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("reversed nobs=" + int_nobs);

    smd.getFileInformation().put("caseQnty", new Integer(int_nobs));

    // 3. data_label: 32 or 81 bytes
    int dl_offset = NVAR_FIELD_LENGTH + NOBS_FIELD_LENGTH;
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("dl_offset=" + dl_offset);
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data_label_length=" + dataLabelLength);

    String data_label = new String(Arrays.copyOfRange(header, dl_offset, (dl_offset + dataLabelLength)),
            "ISO-8859-1");

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data_label_length=" + data_label.length());
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("loation of the null character=" + data_label.indexOf(0));

    String dataLabel = getNullStrippedString(data_label);
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data_label_length=" + dataLabel.length());
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data_label=[" + dataLabel + "]");

    smd.getFileInformation().put("dataLabel", dataLabel);

    // 4. time_stamp: ASCII String (18 bytes)
    // added after release 4
    if (releaseNumber > 104) {
        int ts_offset = dl_offset + dataLabelLength;
        String time_stamp = new String(Arrays.copyOfRange(header, ts_offset, ts_offset + TIME_STAMP_LENGTH),
                "ISO-8859-1");
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("time_stamp_length=" + time_stamp.length());
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("loation of the null character=" + time_stamp.indexOf(0));

        String timeStamp = getNullStrippedString(time_stamp);
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("timeStamp_length=" + timeStamp.length());
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("timeStamp=[" + timeStamp + "]");

        smd.getFileInformation().put("timeStamp", timeStamp);
        smd.getFileInformation().put("fileDate", timeStamp);
        smd.getFileInformation().put("fileTime", timeStamp);
        smd.getFileInformation().put("varFormat_schema", "STATA");

    }

    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("smd dump:" + smd.toString());
        dbgLog.fine("***** decodeHeader(): end *****");
    }
}

From source file:com.aimfire.gallery.cardboard.PhotoActivity.java

@Override
public void onSurfaceCreated(EGLConfig config) {
    if (BuildConfig.DEBUG)
        Log.i(TAG, "onSurfaceCreated");

    /*/*from w w  w . j  a  v  a  2 s. c o m*/
     *  Dark background so text shows up well.
     */
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f);

    ByteBuffer bbElements = ByteBuffer.allocateDirect(drawOrder.length * 2);
    bbElements.order(ByteOrder.nativeOrder());
    mPicElements = bbElements.asShortBuffer();
    mPicElements.put(drawOrder);
    mPicElements.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
    int fragmentShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

    mPicProgram = GLES20.glCreateProgram();
    GLES20.glAttachShader(mPicProgram, vertexShader);
    GLES20.glAttachShader(mPicProgram, fragmentShader);
    GLES20.glLinkProgram(mPicProgram);
    GLES20.glUseProgram(mPicProgram);

    checkGLError("Pic program");

    mDimRatioParam = GLES20.glGetUniformLocation(mPicProgram, "u_dimRatio");
    mZoomParam = GLES20.glGetUniformLocation(mPicProgram, "u_zoom");
    mParallaxParam = GLES20.glGetUniformLocation(mPicProgram, "u_parallax");

    mPicPositionParam = GLES20.glGetAttribLocation(mPicProgram, "a_position");

    GLES20.glEnableVertexAttribArray(mPicPositionParam);
    checkGLError("Pic program params");

    GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    checkGLError("onSurfaceCreated");

    /*
     * initializes a few textures (current, previous and next). we have to do this
     * here (as opposed to onCreate) as gl context is only available here
     */
    initTextures();

    /*
     * so onDrawEye will know to draw
     */
    mAssetChangedLeft = mAssetChangedRight = true;
}

From source file:ffx.xray.MTZFilter.java

public boolean readFcs(File mtzFile, ReflectionList reflectionlist, DiffractionRefinementData fcdata,
        CompositeConfiguration properties) {
    int nread, nignore, nres, nfriedel, ncut;
    ByteOrder b = ByteOrder.nativeOrder();
    FileInputStream fis;//  www. ja v a2  s . c  o  m
    DataInputStream dis;

    StringBuilder sb = new StringBuilder();
    try {
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

        byte headeroffset[] = new byte[4];
        byte bytes[] = new byte[80];
        int offset = 0;

        // eat "MTZ" title
        dis.read(bytes, offset, 4);
        String mtzstr = new String(bytes);

        // header offset
        dis.read(headeroffset, offset, 4);

        // machine stamp
        dis.read(bytes, offset, 4);
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        int stamp = bb.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampstr = Integer.toHexString(stamp);
        switch (stampstr.charAt(0)) {
        case '1':
        case '3':
            if (b.equals(ByteOrder.LITTLE_ENDIAN)) {
                b = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (b.equals(ByteOrder.BIG_ENDIAN)) {
                b = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        bb = ByteBuffer.wrap(headeroffset);
        int headeroffseti = bb.order(b).getInt();

        // skip to header and parse
        dis.skipBytes((headeroffseti - 4) * 4);

        for (Boolean parsing = true; parsing; dis.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }

        // column identifiers
        fc = phic = fs = phis = -1;
        boolean print = true;
        parseFcColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = "Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // reopen to start at beginning
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

        // skip initial header
        dis.skipBytes(80);

        float data[] = new float[nColumns];
        HKL mate = new HKL();

        // read in data
        ComplexNumber c = new ComplexNumber();
        nread = nignore = nres = nfriedel = ncut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dis.read(bytes, offset, 4);
                bb = ByteBuffer.wrap(bytes);
                data[j] = bb.order(b).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionlist.findSymHKL(ih, ik, il, mate, false);
            HKL hkl = reflectionlist.getHKL(mate);

            if (hkl != null) {
                if (fc > 0 && phic > 0) {
                    c.re(data[fc] * cos(toRadians(data[phic])));
                    c.im(data[fc] * sin(toRadians(data[phic])));
                    fcdata.setFc(hkl.index(), c);
                }
                if (fs > 0 && phis > 0) {
                    c.re(data[fs] * cos(toRadians(data[phis])));
                    c.im(data[fs] * sin(toRadians(data[phis])));
                    fcdata.setFs(hkl.index(), c);
                }
                nread++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionlist.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionlist.crystal, tmp))) {
                    nres++;
                } else {
                    nignore++;
                }
            }
        }

        sb.append(String.format(" MTZ file type (machine stamp): %s\n", stampstr));
        sb.append(String.format(" Fc HKL read in:                             %d\n", nread));
        sb.append(String.format(" Fc HKL read as friedel mates:               %d\n", nfriedel));
        sb.append(String.format(" Fc HKL NOT read in (too high resolution):   %d\n", nres));
        sb.append(String.format(" Fc HKL NOT read in (not in internal list?): %d\n", nignore));
        sb.append(String.format(" Fc HKL NOT read in (F/sigF cutoff):         %d\n", ncut));
        sb.append(String.format(" HKL in internal list:                       %d\n",
                reflectionlist.hkllist.size()));
        if (logger.isLoggable(Level.INFO)) {
            logger.info(sb.toString());
        }
    } catch (EOFException eof) {
        System.out.println("EOF reached ");
        return false;
    } catch (IOException ioe) {
        System.out.println("IO Exception: " + ioe.getMessage());
        return false;
    }

    return true;
}

From source file:ffx.xray.parsers.MTZFilter.java

/**
 * Read the structure factors./*from w  w  w. j  a va 2 s. c  o  m*/
 *
 * @param mtzFile
 * @param reflectionList
 * @param fcData
 * @param properties
 * @return
 */
public boolean readFcs(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData fcData,
        CompositeConfiguration properties) {

    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;

    StringBuilder sb = new StringBuilder();
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        byte headerOffset[] = new byte[4];
        byte bytes[] = new byte[80];
        int offset = 0;

        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzString = null;

        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);

        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampString = Integer.toHexString(stamp);
        switch (stampString.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();

        // Skip to header and parse.
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);

        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzString = new String(bytes);
            parsing = parseHeader(mtzString);
        }

        // Column identifiers.
        fc = phiC = fs = phiS = -1;
        boolean print = true;
        parseFcColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = " Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // Reopen to start at beginning.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // Skip initial header.
        dataInputStream.skipBytes(80);

        float data[] = new float[nColumns];
        HKL mate = new HKL();

        // Read in data.
        ComplexNumber complexNumber = new ComplexNumber();
        nRead = nIgnore = nRes = nFriedel = nCut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, false);
            HKL hkl = reflectionList.getHKL(mate);

            if (hkl != null) {
                if (fc > 0 && phiC > 0) {
                    complexNumber.re(data[fc] * cos(toRadians(data[phiC])));
                    complexNumber.im(data[fc] * sin(toRadians(data[phiC])));
                    fcData.setFc(hkl.index(), complexNumber);
                }
                if (fs > 0 && phiS > 0) {
                    complexNumber.re(data[fs] * cos(toRadians(data[phiS])));
                    complexNumber.im(data[fs] * sin(toRadians(data[phiS])));
                    fcData.setFs(hkl.index(), complexNumber);
                }
                nRead++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionList.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionList.crystal, tmp))) {
                    nRes++;
                } else {
                    nIgnore++;
                }
            }
        }

        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" Fc HKL read in:                             %d\n", nRead));
            sb.append(format(" Fc HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" Fc HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" Fc HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" Fc HKL NOT read in (F/sigF cutoff):         %d\n", nCut));
            sb.append(
                    format(" HKL in internal list:                       %d\n", reflectionList.hkllist.size()));
            logger.info(sb.toString());
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return false;
    } catch (IOException e) {
        String message = " MTZ IO Exception.";
        logger.log(Level.WARNING, message, e);
        return false;
    }

    return true;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java

private void decodeHeader(BufferedInputStream stream) throws IOException {
    dbgLog.fine("***** decodeHeader(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }/*from   w w  w  .j  a va  2 s . co  m*/

    dbgLog.fine("reading the header segument 1: 4 byte\n");
    byte[] magic_number = new byte[DTA_MAGIC_NUMBER_LENGTH];

    int nbytes = stream.read(magic_number, 0, DTA_MAGIC_NUMBER_LENGTH);

    if (nbytes == 0) {
        throw new IOException();
    }

    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(magic_number)) + "<-");
    }

    if (magic_number[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        throw new IllegalArgumentException("The file is not in a STATA format that we can read or support.");
    } else if ((magic_number[1] != 1) && (magic_number[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        throw new IllegalArgumentException("given file is not stata-dta type");
    } else if (!STATA_RELEASE_NUMBER.containsKey((int) magic_number[0])) {
        dbgLog.fine("1st byte (" + magic_number[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "we cannot ingest this Stata file.");
        throw new IllegalArgumentException("given file is not stata-dta type");
    } else {
        releaseNumber = magic_number[0];
        init();

        dataTable.setOriginalFileFormat(MIME_TYPE[0]);
        /* 
         * releaseNumber: 
         * for storing in the datatable, we are converting the numeric Stata
         * release number into a more user friendly "version number"; 
         * e.g., "release number 115" = "Stata v. 12"
         * -- L.A. 4.0 
         */
        dataTable.setOriginalFormatVersion(STATA_RELEASE_NUMBER.get(releaseNumber));
        dataTable.setUnf("UNF:6:FILEFILEFILEFILE");

        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("this file is stata-dta type: " + STATA_RELEASE_NUMBER.get(releaseNumber)
                    + " (that means Stata version " + releaseNumber + ")");
        }
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("Endian(file)(Big: 1; Little:2)=" + magic_number[1]);
        }

        /* 
         * byte order: defined in the second byte of the "magic number": 
         */
        if (magic_number[1] == 2) {
            isLittleEndian = true;
            dbgLog.fine("Reversal of the bytes is necessary to decode " + "multi-byte fields");
        }
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("Endian of this platform:" + ByteOrder.nativeOrder().toString());
        }
    }

    dbgLog.fine("reading the remaining header segument 2: 60 or 109-byte");

    byte[] header = new byte[headerLength];
    nbytes = stream.read(header, 0, headerLength);

    // 1. number of variables: short (2 bytes)
    ByteBuffer bbnvar = ByteBuffer.wrap(header, 0, NVAR_FIELD_LENGTH);
    ByteBuffer dupnvar = bbnvar.duplicate();
    short short_nvar = dupnvar.getShort();

    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("get original short view(nvar)=" + short_nvar);
    }
    if (isLittleEndian) {
        bbnvar.order(ByteOrder.LITTLE_ENDIAN);

    }

    short shrt_nvar = bbnvar.getShort();
    dataTable.setVarQuantity(new Long(shrt_nvar));
    int nvar = shrt_nvar;

    if (dbgLog.isLoggable(Level.INFO)) {
        dbgLog.info("number of variables(nvar)=" + nvar);
    }

    // 4.0 Initialize dataverse variable objects: 
    List<DataVariable> variableList = new ArrayList<>();

    for (int i = 0; i < nvar; i++) {
        DataVariable dv = new DataVariable();
        dv.setInvalidRanges(new ArrayList<>());
        dv.setSummaryStatistics(new ArrayList<>());
        dv.setUnf("UNF:6:XXX");
        dv.setCategories(new ArrayList<>());
        variableList.add(dv);

        dv.setFileOrder(i);

        dv.setDataTable(dataTable);
    }

    dataTable.setDataVariables(variableList);

    // setup variableTypeList
    variableTypes = new String[nvar];
    // and the date/time format list:
    dateVariableFormats = new String[nvar];

    // 2. number of observations: int (4 bytes)
    ByteBuffer nobs = ByteBuffer.wrap(header, NVAR_FIELD_LENGTH, NOBS_FIELD_LENGTH);
    ByteBuffer dupnobs = nobs.duplicate();
    int int_dupnobs = dupnobs.getInt();
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("raw nobs=" + int_dupnobs);
    }
    if (isLittleEndian) {
        nobs.order(ByteOrder.LITTLE_ENDIAN);
    }
    int int_nobs = nobs.getInt();
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("reversed nobs=" + int_nobs);
    }

    // smd.getFileInformation().put("caseQnty", new Integer(int_nobs));
    dataTable.setCaseQuantity(new Long(int_nobs));

    /* 
     the "data label" - 
     note that we are not using this label for anything 
     (wonder what it is though? can we use it somewhere?)
     but we still need to extract it from the byte stream, 
     since the offsets of the objects stored further up
     are calculated relative to it. -- L.A., 4.0
     */
    // 3. data_label: 32 or 81 bytes
    int dl_offset = NVAR_FIELD_LENGTH + NOBS_FIELD_LENGTH;
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("dl_offset=" + dl_offset);
    }
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("data_label_length=" + dataLabelLength);
    }

    String data_label = new String(Arrays.copyOfRange(header, dl_offset, (dl_offset + dataLabelLength)),
            "ISO-8859-1");

    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("data_label_length=" + data_label.length());
    }
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("loation of the null character=" + data_label.indexOf(0));
    }

    String dataLabel = getNullStrippedString(data_label);
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("data_label_length=" + dataLabel.length());
    }
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("data_label=[" + dataLabel + "]");
    }

    // smd.getFileInformation().put("dataLabel", dataLabel);

    /* end of "data label" */
    // 4. time_stamp: ASCII String (18 bytes)
    // added after release 4
    if (releaseNumber > 104) {
        int ts_offset = dl_offset + dataLabelLength;
        String time_stamp = new String(Arrays.copyOfRange(header, ts_offset, ts_offset + TIME_STAMP_LENGTH),
                "ISO-8859-1");
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("time_stamp_length=" + time_stamp.length());
        }
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("loation of the null character=" + time_stamp.indexOf(0));
        }

        String timeStamp = getNullStrippedString(time_stamp);
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("timeStamp_length=" + timeStamp.length());
        }
        if (dbgLog.isLoggable(Level.FINE)) {
            dbgLog.fine("timeStamp=[" + timeStamp + "]");
        }

    }
}

From source file:com.mobilyzer.util.PhoneUtils.java

public String getWifiIpAddress() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo != null) {
        int ip = wifiInfo.getIpAddress();
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            ip = Integer.reverseBytes(ip);
        }//from  w  w w  .ja  va2 s  .co  m
        byte[] bytes = BigInteger.valueOf(ip).toByteArray();
        String address;
        try {
            address = InetAddress.getByAddress(bytes).getHostAddress();
            return address;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
    return null;
}