List of usage examples for java.nio ByteBuffer order
Endianness order
To view the source code for java.nio ByteBuffer order.
Click Source Link
From source file:com.google.vrtoolkit.cardboard.samples.treasurehunt.MainActivity.java
/** * Creates the buffers we use to store information about the 3D world. * * <p>OpenGL doesn't use Java arrays, but rather needs data in a format it can understand. * Hence we use ByteBuffers./*from ww w. jav a2 s.c o m*/ * * @param config The EGL configuration used when creating the surface. */ @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 bbVertices = ByteBuffer.allocateDirect(WorldLayoutData.CUBE_COORDS.length * 4); bbVertices.order(ByteOrder.nativeOrder()); cubeVertices = bbVertices.asFloatBuffer(); cubeVertices.put(WorldLayoutData.CUBE_COORDS); cubeVertices.position(0); ByteBuffer bbColors = ByteBuffer.allocateDirect(WorldLayoutData.CUBE_COLORS.length * 4); bbColors.order(ByteOrder.nativeOrder()); cubeColors = bbColors.asFloatBuffer(); cubeColors.put(WorldLayoutData.CUBE_COLORS); cubeColors.position(0); ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(WorldLayoutData.CUBE_FOUND_COLORS.length * 4); bbFoundColors.order(ByteOrder.nativeOrder()); cubeFoundColors = bbFoundColors.asFloatBuffer(); cubeFoundColors.put(WorldLayoutData.CUBE_FOUND_COLORS); cubeFoundColors.position(0); ByteBuffer bbNormals = ByteBuffer.allocateDirect(WorldLayoutData.CUBE_NORMALS.length * 4); bbNormals.order(ByteOrder.nativeOrder()); cubeNormals = bbNormals.asFloatBuffer(); cubeNormals.put(WorldLayoutData.CUBE_NORMALS); cubeNormals.position(0); ByteBuffer mcbbVertices = ByteBuffer.allocateDirect(WorldLayoutData.MINI_CUBE_COORDS.length * 4); mcbbVertices.order(ByteOrder.nativeOrder()); miniCubeVertices = mcbbVertices.asFloatBuffer(); miniCubeVertices.put(WorldLayoutData.MINI_CUBE_COORDS); miniCubeVertices.position(0); ByteBuffer mcbbColors = ByteBuffer.allocateDirect(WorldLayoutData.MINI_CUBE_COLORS.length * 4); mcbbColors.order(ByteOrder.nativeOrder()); miniCubeColors = mcbbColors.asFloatBuffer(); miniCubeColors.put(WorldLayoutData.MINI_CUBE_COLORS); miniCubeColors.position(0); ByteBuffer mcbbNormals = ByteBuffer.allocateDirect(WorldLayoutData.CUBE_NORMALS.length * 4); mcbbNormals.order(ByteOrder.nativeOrder()); miniCubeNormals = mcbbNormals.asFloatBuffer(); miniCubeNormals.put(WorldLayoutData.CUBE_NORMALS); miniCubeNormals.position(0); // make a floor ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COORDS.length * 4); bbFloorVertices.order(ByteOrder.nativeOrder()); floorVertices = bbFloorVertices.asFloatBuffer(); floorVertices.put(WorldLayoutData.FLOOR_COORDS); floorVertices.position(0); ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_NORMALS.length * 4); bbFloorNormals.order(ByteOrder.nativeOrder()); floorNormals = bbFloorNormals.asFloatBuffer(); floorNormals.put(WorldLayoutData.FLOOR_NORMALS); floorNormals.position(0); ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COLORS.length * 4); bbFloorColors.order(ByteOrder.nativeOrder()); floorColors = bbFloorColors.asFloatBuffer(); floorColors.put(WorldLayoutData.FLOOR_COLORS); floorColors.position(0); int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, R.raw.light_vertex); int gridShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.grid_fragment); int passthroughShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.passthrough_fragment); cubeProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(cubeProgram, vertexShader); GLES20.glAttachShader(cubeProgram, passthroughShader); GLES20.glLinkProgram(cubeProgram); GLES20.glUseProgram(cubeProgram); checkGLError("Cube program"); cubePositionParam = GLES20.glGetAttribLocation(cubeProgram, "a_Position"); cubeNormalParam = GLES20.glGetAttribLocation(cubeProgram, "a_Normal"); cubeColorParam = GLES20.glGetAttribLocation(cubeProgram, "a_Color"); cubeModelParam = GLES20.glGetUniformLocation(cubeProgram, "u_Model"); cubeModelViewParam = GLES20.glGetUniformLocation(cubeProgram, "u_MVMatrix"); cubeModelViewProjectionParam = GLES20.glGetUniformLocation(cubeProgram, "u_MVP"); cubeLightPosParam = GLES20.glGetUniformLocation(cubeProgram, "u_LightPos"); GLES20.glEnableVertexAttribArray(cubePositionParam); GLES20.glEnableVertexAttribArray(cubeNormalParam); GLES20.glEnableVertexAttribArray(cubeColorParam); checkGLError("Cube program params"); //Minicube miniCubeProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(miniCubeProgram, vertexShader); GLES20.glAttachShader(miniCubeProgram, passthroughShader); GLES20.glLinkProgram(miniCubeProgram); GLES20.glUseProgram(miniCubeProgram); checkGLError("Cube program"); miniCubePositionParam = GLES20.glGetAttribLocation(miniCubeProgram, "a_Position"); miniCubeNormalParam = GLES20.glGetAttribLocation(miniCubeProgram, "a_Normal"); miniCubeColorParam = GLES20.glGetAttribLocation(miniCubeProgram, "a_Color"); miniCubeModelParam = GLES20.glGetUniformLocation(miniCubeProgram, "u_Model"); miniCubeModelViewParam = GLES20.glGetUniformLocation(miniCubeProgram, "u_MVMatrix"); miniCubeModelViewProjectionParam = GLES20.glGetUniformLocation(miniCubeProgram, "u_MVP"); miniCubeLightPosParam = GLES20.glGetUniformLocation(miniCubeProgram, "u_LightPos"); GLES20.glEnableVertexAttribArray(miniCubePositionParam); GLES20.glEnableVertexAttribArray(miniCubeNormalParam); GLES20.glEnableVertexAttribArray(miniCubeColorParam); checkGLError("Cube program params"); floorProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(floorProgram, vertexShader); GLES20.glAttachShader(floorProgram, gridShader); GLES20.glLinkProgram(floorProgram); GLES20.glUseProgram(floorProgram); checkGLError("Floor program"); floorModelParam = GLES20.glGetUniformLocation(floorProgram, "u_Model"); floorModelViewParam = GLES20.glGetUniformLocation(floorProgram, "u_MVMatrix"); floorModelViewProjectionParam = GLES20.glGetUniformLocation(floorProgram, "u_MVP"); floorLightPosParam = GLES20.glGetUniformLocation(floorProgram, "u_LightPos"); floorPositionParam = GLES20.glGetAttribLocation(floorProgram, "a_Position"); floorNormalParam = GLES20.glGetAttribLocation(floorProgram, "a_Normal"); floorColorParam = GLES20.glGetAttribLocation(floorProgram, "a_Color"); GLES20.glEnableVertexAttribArray(floorPositionParam); GLES20.glEnableVertexAttribArray(floorNormalParam); GLES20.glEnableVertexAttribArray(floorColorParam); checkGLError("Floor program params"); Matrix.setIdentityM(modelFloor, 0); Matrix.translateM(modelFloor, 0, 0, -floorDepth, 0); // Floor appears below user. // Avoid any delays during start-up due to decoding of sound files. new Thread(new Runnable() { public void run() { // Start spatial audio playback of SOUND_FILE at the model postion. The returned //soundId handle is stored and allows for repositioning the sound object whenever // the cube position changes. cardboardAudioEngine.preloadSoundFile(SOUND_FILE); soundId = cardboardAudioEngine.createSoundObject(SOUND_FILE); cardboardAudioEngine.setSoundObjectPosition(soundId, modelPosition[0], modelPosition[1], modelPosition[2]); cardboardAudioEngine.playSound(soundId, true /* looped playback */); } }).start(); updateModelPosition(); checkGLError("onSurfaceCreated"); }
From source file:ffx.xray.MTZFilter.java
/** * {@inheritDoc}/*from ww w .java 2 s . c o m*/ */ @Override public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) { ByteOrder b = ByteOrder.nativeOrder(); FileInputStream fis; DataInputStream dis; 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); } } catch (EOFException eof) { System.out.println("EOF reached "); } catch (IOException ioe) { System.out.println("IO Exception: " + ioe.getMessage()); return null; } // column identifiers foString = sigfoString = rfreeString = null; if (properties != null) { foString = properties.getString("fostring", null); sigfoString = properties.getString("sigfostring", null); rfreeString = properties.getString("rfreestring", null); } h = k = l = fo = sigfo = rfree = -1; fplus = sigfplus = fminus = sigfminus = rfreeplus = rfreeminus = -1; fc = phic = -1; boolean print = false; parseColumns(print); parseFcColumns(print); if (fo < 0 && fplus < 0 && sigfo < 0 && sigfplus < 0 && fc < 0 && phic < 0) { logger.info( " The MTZ header contains insufficient information to generate the reflection list.\n For non-default column labels set fostring/sigfostring in the properties file."); return null; } Column c; if (fo > 0) { c = (Column) columns.get(fo); } else if (fplus > 0) { c = (Column) columns.get(fplus); } else { c = (Column) columns.get(fc); } Dataset d = (Dataset) datasets.get(c.id - dsetoffset); if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format("\n Reading %s\n\n", mtzFile.getName())); sb.append(String.format(" Setting up reflection list based on MTZ file.\n")); sb.append(String.format(" Space group number: %d (name: %s)\n", sgnum, SpaceGroup.spaceGroupNames[sgnum - 1])); sb.append(String.format(" Resolution: %8.3f\n", 0.999999 * resHigh)); sb.append(String.format(" Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", d.cell[0], d.cell[1], d.cell[2], d.cell[3], d.cell[4], d.cell[5])); logger.info(sb.toString()); } Crystal crystal = new Crystal(d.cell[0], d.cell[1], d.cell[2], d.cell[3], d.cell[4], d.cell[5], SpaceGroup.spaceGroupNames[sgnum - 1]); double sampling = 0.6; if (properties != null) { sampling = properties.getDouble("sampling", 0.6); } Resolution resolution = new Resolution(0.999999 * resHigh, sampling); return new ReflectionList(crystal, resolution, properties); }
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;/*from w ww. j av a2 s . co 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:com.healthmarketscience.jackcess.impl.ColumnImpl.java
/** * Writes a GUID value.//from w w w .j av a 2 s . c om */ private static void writeGUIDValue(ByteBuffer buffer, Object value) throws IOException { Matcher m = GUID_PATTERN.matcher(toCharSequence(value)); if (!m.matches()) { throw new IOException("Invalid GUID: " + value); } ByteBuffer origBuffer = null; byte[] tmpBuf = null; if (buffer.order() != ByteOrder.BIG_ENDIAN) { // write to a temp buf so we can do some swapping below origBuffer = buffer; tmpBuf = new byte[16]; buffer = ByteBuffer.wrap(tmpBuf); } ByteUtil.writeHexString(buffer, m.group(1)); ByteUtil.writeHexString(buffer, m.group(2)); ByteUtil.writeHexString(buffer, m.group(3)); ByteUtil.writeHexString(buffer, m.group(4)); ByteUtil.writeHexString(buffer, m.group(5)); if (tmpBuf != null) { // the first 3 guid components are integer components which need to // respect endianness, so swap 4-byte int, 2-byte int, 2-byte int ByteUtil.swap4Bytes(tmpBuf, 0); ByteUtil.swap2Bytes(tmpBuf, 4); ByteUtil.swap2Bytes(tmpBuf, 6); origBuffer.put(tmpBuf); } }
From source file:org.openpilot_nonag.uavtalk.UAVTalk.java
/** * Send an object through the telemetry link. * @throws IOException/*w w w . j ava 2 s .c o m*/ * @param[in] obj Object handle to send * @param[in] type Transaction type \return Success (true), Failure (false) */ private boolean transmitSingleObject(int type, long objId, long instId, UAVObject obj) throws IOException { int length = 0; assert (objMngr != null && outStream != null); // IMPORTANT : obj can be null (when type is NACK for example) // Determine data length if (type == TYPE_OBJ_REQ || type == TYPE_ACK || type == TYPE_NACK) { length = 0; } else { length = obj.getNumBytes(); } ByteBuffer bbuf = ByteBuffer.allocate(MAX_PACKET_LENGTH); bbuf.order(ByteOrder.LITTLE_ENDIAN); // Setup type and object id fields bbuf.put((byte) (SYNC_VAL & 0xff)); bbuf.put((byte) (type & 0xff)); bbuf.putShort((short) (length + HEADER_LENGTH)); bbuf.putInt((int) objId); bbuf.putShort((short) (instId & 0xffff)); // Check length if (length >= MAX_PAYLOAD_LENGTH) { ++stats.txErrors; return false; } // Copy data (if any) if (length > 0) try { if (obj.pack(bbuf) == 0) { ++stats.txErrors; return false; } } catch (Exception e) { ++stats.txErrors; // TODO Auto-generated catch block e.printStackTrace(); return false; } // Calculate checksum bbuf.put((byte) (updateCRC(0, bbuf.array(), bbuf.position()) & 0xff)); int packlen = bbuf.position(); bbuf.position(0); byte[] dst = new byte[packlen]; bbuf.get(dst, 0, packlen); outStream.write(dst); // Update stats ++stats.txObjects; stats.txBytes += bbuf.position(); stats.txObjectBytes += length; // Done return true; }
From source file:ffx.xray.parsers.MTZFilter.java
/** * {@inheritDoc}//w w w. j a va2s . com */ @Override public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) { ByteOrder byteOrder = ByteOrder.nativeOrder(); FileInputStream fileInputStream; DataInputStream dataInputStream; 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 mtzstr = new String(bytes); // 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 stampstr = Integer.toHexString(stamp); switch (stampstr.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)) { mtzstr = new String(bytes); parsing = parseHeader(mtzstr); } } catch (EOFException e) { String message = " MTZ end of file reached."; logger.log(Level.WARNING, message, e); return null; } catch (IOException e) { String message = " MTZ IO exception."; logger.log(Level.WARNING, message, e); return null; } // column identifiers foString = sigFoString = rFreeString = null; if (properties != null) { foString = properties.getString("fostring", null); sigFoString = properties.getString("sigfostring", null); rFreeString = properties.getString("rfreestring", null); } h = k = l = fo = sigFo = rFree = -1; fPlus = sigFPlus = fMinus = sigFMinus = rFreePlus = rFreeMinus = -1; fc = phiC = -1; boolean print = false; parseColumns(print); parseFcColumns(print); if (fo < 0 && fPlus < 0 && sigFo < 0 && sigFPlus < 0 && fc < 0 && phiC < 0) { logger.info(" The MTZ header contains insufficient information to generate the reflection list."); logger.info(" For non-default column labels set fostring/sigfostring in the properties file."); return null; } Column column; if (fo > 0) { column = (Column) columns.get(fo); } else if (fPlus > 0) { column = (Column) columns.get(fPlus); } else { column = (Column) columns.get(fc); } Dataset dataSet = (Dataset) dataSets.get(column.id - dsetOffset); if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(format("\n Reading %s\n\n", mtzFile.getName())); sb.append(format(" Setting up reflection list based on MTZ file.\n")); sb.append(format(" Space group number: %d (name: %s)\n", spaceGroupNum, SpaceGroup.spaceGroupNames[spaceGroupNum - 1])); sb.append(format(" Resolution: %8.3f\n", 0.999999 * resHigh)); sb.append(format(" Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5])); logger.info(sb.toString()); } Crystal crystal = new Crystal(dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5], SpaceGroup.spaceGroupNames[spaceGroupNum - 1]); double sampling = 0.6; if (properties != null) { sampling = properties.getDouble("sampling", 0.6); } Resolution resolution = new Resolution(0.999999 * resHigh, sampling); return new ReflectionList(crystal, resolution, properties); }
From source file:ffx.xray.parsers.MTZFilter.java
/** * Read the structure factors.// w w w . jav a2 s .c om * * @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:org.dkf.jmule.activities.MainActivity.java
@Override protected void onNewIntent(Intent intent) { log.info("[main activity] on new intent {}", intent); if (intent == null) { return;// w w w . jav a 2s. c o m } if (isShutdown(intent)) { return; } String action = intent.getAction(); // view action here - check type of link and load data if (action != null && action.equals("android.intent.action.VIEW")) { try { final String uri = intent.getDataString(); if (uri != null && uri.startsWith("content")) { List<EMuleLink> links = parseCollectionContent(this, Uri.parse(uri)); log.info("link size {}", links.size()); if (!Engine.instance().isStarted()) { UIUtils.showInformationDialog(this, R.string.add_collection_session_stopped_body, R.string.add_collection_session_stopped_title, false, null); return; } if (!links.isEmpty()) { controller.showTransfers(TransferStatus.ALL); HandpickedCollectionDownloadDialog dialog = HandpickedCollectionDownloadDialog .newInstance(this, links); dialog.show(getFragmentManager()); } else { UIUtils.showInformationDialog(this, R.string.add_collection_empty, R.string.add_collection_session_stopped_title, false, null); } return; } EMuleLink link = EMuleLink.fromString(uri); if (link.getType().equals(EMuleLink.LinkType.SERVER)) { ServerMet sm = new ServerMet(); ConfigurationManager.instance().getSerializable(Constants.PREF_KEY_SERVERS_LIST, sm); try { sm.addServer(ServerMet.ServerMetEntry.create(link.getStringValue(), (int) link.getNumberValue(), "[" + link.getStringValue() + "]", "")); ConfigurationManager.instance().setSerializable(Constants.PREF_KEY_SERVERS_LIST, sm); servers.setupAdapter(); controller.showServers(); } catch (JED2KException e) { e.printStackTrace(); } } else if (link.getType().equals(EMuleLink.LinkType.SERVERS)) { final String serversLink = link.getStringValue(); final MainActivity main = this; AsyncTask<Void, Void, ServerMet> task = new AsyncTask<Void, Void, ServerMet>() { @Override protected ServerMet doInBackground(Void... voids) { try { byte[] data = IOUtils.toByteArray(new URI(serversLink)); ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); ServerMet sm = new ServerMet(); sm.get(buffer); return sm; } catch (Exception e) { log.error("unable to load servers {}", e); } return null; } @Override protected void onPostExecute(ServerMet result) { if (result != null) { lastLoadedServers = result; UIUtils.showYesNoDialog(main, R.string.add_servers_list_text, R.string.add_servers_list_title, main); } else { UIUtils.showInformationDialog(main, R.string.link_download_failed, R.string.link_download_failed, true, null); } } }; task.execute(); } else if (link.getType().equals(EMuleLink.LinkType.NODES)) { final String serversLink = link.getStringValue(); final MainActivity main = this; AsyncTask<Void, Void, KadNodesDat> task = new AsyncTask<Void, Void, KadNodesDat>() { @Override protected KadNodesDat doInBackground(Void... voids) { try { byte[] data = IOUtils.toByteArray(new URI(serversLink)); ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); KadNodesDat sm = new KadNodesDat(); sm.get(buffer); return sm; } catch (Exception e) { log.error("unable to load nodes dat {}", e); } return null; } @Override protected void onPostExecute(KadNodesDat result) { if (result != null) { if (!Engine.instance().addDhtNodes(result)) { UIUtils.showInformationDialog(main, R.string.nodes_link_open_error_text, R.string.nodes_link_open_error_title, false, null); } } else { UIUtils.showInformationDialog(main, R.string.link_download_failed, R.string.link_download_failed, true, null); } } }; task.execute(); } else if (link.getType().equals(EMuleLink.LinkType.FILE)) { transfers.startTransferFromLink(intent.getDataString()); controller.showTransfers(TransferStatus.ALL); } else { log.error("wtf? link unrecognized {}", intent.getDataString()); } } catch (JED2KException e) { log.error("intent get data parse error {}", e.toString()); UIUtils.showInformationDialog(this, R.string.intent_link_parse_error, R.string.add_servers_list_title, true, null); } } if (action != null) { if (action.equals(ED2KService.ACTION_SHOW_TRANSFERS)) { intent.setAction(null); controller.showTransfers(TransferStatus.ALL); } else if (action.equals(ED2KService.ACTION_REQUEST_SHUTDOWN)) { showShutdownDialog(); } } if (intent.hasExtra(ED2KService.EXTRA_DOWNLOAD_COMPLETE_NOTIFICATION)) { controller.showTransfers(TransferStatus.COMPLETED); try { ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)) .cancel(Constants.NOTIFICATION_DOWNLOAD_TRANSFER_FINISHED); Bundle extras = intent.getExtras(); if (extras.containsKey(Constants.EXTRA_DOWNLOAD_COMPLETE_PATH)) { File file = new File(extras.getString(Constants.EXTRA_DOWNLOAD_COMPLETE_PATH)); if (file.isFile()) { //UIUtils.openFile(this, file.getAbsoluteFile()); } } } catch (Exception e) { log.warn("Error handling download complete notification", e); } } if (intent.hasExtra(Constants.EXTRA_FINISH_MAIN_ACTIVITY)) { finish(); } }
From source file:ffx.xray.MTZFilter.java
/** * {@inheritDoc}//from w w w .jav a2 s. c o m */ @Override public boolean readFile(File mtzFile, ReflectionList reflectionlist, DiffractionRefinementData refinementdata, CompositeConfiguration properties) { int nread, nignore, nres, nfriedel, ncut; ByteOrder b = ByteOrder.nativeOrder(); FileInputStream fis; DataInputStream dis; boolean transpose = false; StringBuilder sb = new StringBuilder(); //sb.append(String.format("\n Opening %s\n", mtzFile.getName())); 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 foString = sigfoString = rfreeString = null; if (properties != null) { foString = properties.getString("fostring", null); sigfoString = properties.getString("sigfostring", null); rfreeString = properties.getString("rfreestring", null); } h = k = l = fo = sigfo = rfree = -1; fplus = sigfplus = fminus = sigfminus = rfreeplus = rfreeminus = -1; boolean print = true; parseColumns(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); // check if HKLs need to be transposed or not float data[] = new float[nColumns]; HKL mate = new HKL(); int nposignore = 0; int ntransignore = 0; int nzero = 0; int none = 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 hklpos = reflectionlist.getHKL(mate); if (hklpos == null) { nposignore++; } friedel = reflectionlist.findSymHKL(ih, ik, il, mate, true); HKL hkltrans = reflectionlist.getHKL(mate); if (hkltrans == null) { ntransignore++; } if (rfree > 0) { if (((int) data[rfree]) == 0) { nzero++; } else if (((int) data[rfree]) == 1) { none++; } } if (rfreeplus > 0) { if (((int) data[rfreeplus]) == 0) { nzero++; } else if (((int) data[rfreeplus]) == 1) { none++; } } if (rfreeminus > 0) { if (((int) data[rfreeminus]) == 0) { nzero++; } else if (((int) data[rfreeminus]) == 1) { none++; } } } if (nposignore > ntransignore) { transpose = true; } if (none > (nzero * 2) && refinementdata.rfreeflag < 0) { refinementdata.setFreeRFlag(0); sb.append(String.format(" Setting R free flag to %d based on MTZ file data.\n", refinementdata.rfreeflag)); } else if (nzero > (none * 2) && refinementdata.rfreeflag < 0) { refinementdata.setFreeRFlag(1); sb.append(String.format(" Setting R free flag to %d based on MTZ file data.\n", refinementdata.rfreeflag)); } else if (refinementdata.rfreeflag < 0) { refinementdata.setFreeRFlag(0); sb.append(String.format(" Setting R free flag to MTZ default: %d\n", refinementdata.rfreeflag)); } // reopen to start at beginning fis = new FileInputStream(mtzFile); dis = new DataInputStream(fis); // skip initial header dis.skipBytes(80); // read in data double anofsigf[][] = new double[refinementdata.n][4]; for (int i = 0; i < refinementdata.n; i++) { anofsigf[i][0] = anofsigf[i][1] = anofsigf[i][2] = anofsigf[i][3] = Double.NaN; } 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, transpose); HKL hkl = reflectionlist.getHKL(mate); if (hkl != null) { if (fo > 0 && sigfo > 0) { if (refinementdata.fsigfcutoff > 0.0) { if ((data[fo] / data[sigfo]) < refinementdata.fsigfcutoff) { ncut++; continue; } } if (friedel) { anofsigf[hkl.index()][2] = data[fo]; anofsigf[hkl.index()][3] = data[sigfo]; nfriedel++; } else { anofsigf[hkl.index()][0] = data[fo]; anofsigf[hkl.index()][1] = data[sigfo]; } } else { if (fplus > 0 && sigfplus > 0) { if (refinementdata.fsigfcutoff > 0.0) { if ((data[fplus] / data[sigfplus]) < refinementdata.fsigfcutoff) { ncut++; continue; } } anofsigf[hkl.index()][0] = data[fplus]; anofsigf[hkl.index()][1] = data[sigfplus]; } if (fminus > 0 && sigfminus > 0) { if (refinementdata.fsigfcutoff > 0.0) { if ((data[fminus] / data[sigfminus]) < refinementdata.fsigfcutoff) { ncut++; continue; } } anofsigf[hkl.index()][2] = data[fminus]; anofsigf[hkl.index()][3] = data[sigfminus]; } } if (rfree > 0) { refinementdata.setFreeR(hkl.index(), (int) data[rfree]); } else { if (rfreeplus > 0 && rfreeminus > 0) { // not sure what the correct thing to do here is? refinementdata.setFreeR(hkl.index(), (int) data[rfreeplus]); } else if (rfreeplus > 0) { refinementdata.setFreeR(hkl.index(), (int) data[rfreeplus]); } else if (rfreeminus > 0) { refinementdata.setFreeR(hkl.index(), (int) data[rfreeminus]); } } nread++; } else { HKL tmp = new HKL(ih, ik, il); if (!reflectionlist.resolution .inInverseResSqRange(Crystal.invressq(reflectionlist.crystal, tmp))) { nres++; } else { nignore++; } } } // set up fsigf from F+ and F- refinementdata.generate_fsigf_from_anofsigf(anofsigf); sb.append(String.format(" MTZ file type (machine stamp): %s\n", stampstr)); sb.append(String.format(" HKL data is %s\n", transpose ? "transposed" : "not transposed")); sb.append(String.format(" HKL read in: %d\n", nread)); sb.append(String.format(" HKL read as friedel mates: %d\n", nfriedel)); sb.append(String.format(" HKL NOT read in (too high resolution): %d\n", nres)); sb.append(String.format(" HKL NOT read in (not in internal list?): %d\n", nignore)); sb.append(String.format(" 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()); } if (rfree < 0 && rfreeplus < 0 && rfreeminus < 0) { refinementdata.generateRFree(); } } 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:com.yobidrive.diskmap.buckets.BucketTableManager.java
private void initializeBucketTableFromLastCommittedBucketFile() throws BucketTableManagerException { FileInputStream tableStream = null; FileChannel fileChannel = null; try {/*from www . ja v a2 s . co m*/ File latestCommittedFile = getLatestCommitedFile(); if (latestCommittedFile != null) { tableStream = new FileInputStream(latestCommittedFile); fileChannel = tableStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(HEADERSIZE); fileChannel.position(0L); int read = fileChannel.read(buffer); if (read < HEADERSIZE) { fileChannel.close(); throw new BucketTableManagerException( "Wrong bucket table header size: " + read + "/" + HEADERSIZE); } // Check content of header. Start with Big Endian (default for Java) buffer.rewind(); byteOrder = ByteOrder.BIG_ENDIAN; buffer.order(byteOrder); int magic = buffer.getInt(); if (magic == MAGICSTART_BADENDIAN) { byteOrder = ByteOrder.LITTLE_ENDIAN; buffer.order(byteOrder); } else if (magic != MAGICSTART) { fileChannel.close(); throw new BucketTableManagerException("Bad header in bucket table file"); } // Read number of buckets long headerMapSize = buffer.getLong(); // Read checkPoint NeedlePointer includedCheckpoint = new NeedlePointer(); includedCheckpoint.getNeedlePointerFromBuffer(buffer); // Read second magic number magic = buffer.getInt(); if (magic != MAGICEND) { fileChannel.close(); throw new BucketTableManagerException("Bad header in bucket table file"); } // Check number of buckets against requested map size if (headerMapSize != mapSize) { // Map size does not match fileChannel.close(); throw new BucketTableManagerException( "Requested map size " + mapSize + " does not match header map size " + headerMapSize); } // Sets initial checkpoint bucketTable.setInitialCheckPoint(includedCheckpoint); // Now reads all entries logger.info("Hot start: loading buckets..."); for (int i = 0; i < nbBuffers; i++) { bucketTable.prepareBufferForReading(i); read = fileChannel.read(bucketTable.getBuffer(i)); if (read < bucketTable.getBuffer(i).limit()) throw new BucketTableManagerException("Incomplete bucket table file " + latestCommittedFile.getName() + ", expected " + mapSize + HEADERSIZE); //else // logger.info("Hot start: loaded "+(i+1)*entriesPerBuffer+" buckets"+((i<(nbBuffers-1))?"...":"")) ; } // Checks second magic marker buffer = ByteBuffer.allocate(NeedleLogInfo.INFOSIZE); buffer.rewind(); buffer.limit(INTSIZE); if (fileChannel.read(buffer) < INTSIZE) throw new BucketTableManagerException( "Incomplete bucket table file, missing secong magic number " + latestCommittedFile.getName()); buffer.rewind(); magic = buffer.getInt(); if (magic != MAGICSTART) { fileChannel.close(); throw new BucketTableManagerException("Bad header in bucket table file"); } // Now reads clean counters while (true) { buffer.rewind(); buffer.limit(NeedleLogInfo.INFOSIZE); read = fileChannel.read(buffer); if (read > 0 && read < NeedleLogInfo.INFOSIZE) throw new BucketTableManagerException("Incomplete bucket table file, log info too short " + latestCommittedFile.getName() + ", expected " + mapSize + HEADERSIZE); if (read <= 0) break; else { NeedleLogInfo nli = new NeedleLogInfo(useAverage); buffer.rewind(); nli.getNeedleLogInfo(buffer); logInfoPerLogNumber.put(new Integer(nli.getNeedleFileNumber()), nli); } } logger.info("Hot start: loaded " + (nbBuffers * entriesPerBuffer) + " buckets"); } else { // Empty file bucketTable.setInitialCheckPoint(new NeedlePointer()); bucketTable.format(); } } catch (IOException ie) { throw new BucketTableManagerException("Failed initializing bucket table", ie); } catch (BufferUnderflowException bue) { throw new BucketTableManagerException("Bucket table too short", bue); } finally { if (fileChannel != null) { try { fileChannel.close(); } catch (IOException ex) { throw new BucketTableManagerException("Error while closing file channel", ex); } } } }