Example usage for java.nio ByteOrder LITTLE_ENDIAN

List of usage examples for java.nio ByteOrder LITTLE_ENDIAN

Introduction

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

Prototype

ByteOrder LITTLE_ENDIAN

To view the source code for java.nio ByteOrder LITTLE_ENDIAN.

Click Source Link

Document

This constant represents little endian.

Usage

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

private void setGeometry(PrintWriter out, IfcProduct ifcProductObject, String material)
        throws RenderEngineException, SerializerException {
    // Mostly just skips IfcOpeningElements which one would probably not want to end up in the Collada file.
    if (ifcProductObject instanceof IfcFeatureElementSubtraction)
        return;/*w w  w  .j av  a 2  s.com*/
    //
    GeometryInfo geometryInfo = ifcProductObject.getGeometry();
    if (geometryInfo != null && geometryInfo.getTransformation() != null) {
        GeometryData geometryData = geometryInfo.getData();
        ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
        indicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // TODO: In Blender (3d modeling tool) and Three.js, normals are ignored in favor of vertex order. The incoming geometry seems to be in order 0 1 2 when it needs to be in 1 0 2. Need more test cases.
        // Failing order: (0, 1050, 2800), (0, 1050, 3100), (3580, 1050, 3100)
        // Successful order: (0, 1050, 3100), (0, 1050, 2800), (3580, 1050, 3100)
        List<Integer> list = new ArrayList<Integer>();
        while (indicesBuffer.hasRemaining())
            list.add(indicesBuffer.getInt());
        indicesBuffer.rewind();
        for (int i = 0; i < list.size(); i += 3) {
            Integer first = list.get(i);
            Integer next = list.get(i + 1);
            list.set(i, next);
            list.set(i + 1, first);
        }
        // Positions the X or the Y or the Z of (X, Y, Z).
        ByteBuffer positionsBuffer = ByteBuffer.wrap(geometryData.getVertices());
        positionsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Do pass to find highest Z for considered objects.
        while (positionsBuffer.hasRemaining()) {
            float x = positionsBuffer.getFloat();
            float y = positionsBuffer.getFloat();
            float z = positionsBuffer.getFloat();
            // X
            if (x > highestObserved.x())
                highestObserved.x(x);
            else if (x < lowestObserved.x())
                lowestObserved.x(x);
            // Y
            if (y > highestObserved.y())
                highestObserved.y(y);
            else if (y < lowestObserved.y())
                lowestObserved.y(y);
            // Z
            if (z > highestObserved.z())
                highestObserved.z(z);
            else if (z < lowestObserved.z())
                lowestObserved.z(z);
        }
        positionsBuffer.rewind();
        //
        ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
        normalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Create a geometry identification number in the form of: geom-320450
        long oid = ifcProductObject.getOid();
        String id = String.format("geom-%d", oid);
        // If the material doesn't exist in the converted map, add it.
        if (!converted.containsKey(material))
            converted.put(material, new HashSet<IfcProduct>());
        // Add the current IfcProduct to the appropriate entry in the material map.
        converted.get(material).add(ifcProductObject);
        // Name for geometry.
        String name = (ifcProductObject.getGlobalId() == null) ? "[NO_GUID]" : ifcProductObject.getGlobalId();
        // Counts.
        int vertexComponentsTotal = positionsBuffer.capacity() / 4,
                normalComponentsTotal = normalsBuffer.capacity() / 4;
        int verticesCount = positionsBuffer.capacity() / 12, normalsCount = normalsBuffer.capacity() / 12,
                triangleCount = indicesBuffer.capacity() / 12;
        // Vertex scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringPositionScalars = byteBufferToFloatingPointSpaceDelimitedString(positionsBuffer);
        // Normal scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringNormalScalars = byteBufferToFloatingPointSpaceDelimitedString(normalsBuffer); //doubleBufferToFloatingPointSpaceDelimitedString(flippedNormalsBuffer);
        // Vertex indices as one long string: 1 0 2 0 3 2 5 4 6
        String stringIndexScalars = listToSpaceDelimitedString(list, intFormat);
        // Write geometry block for this IfcProduct (i.e. IfcRoof, IfcSlab, etc).
        out.println(" <geometry id=\"" + id + "\" name=\"" + name + "\">");
        out.println("  <mesh>");
        out.println("   <source id=\"positions-" + oid + "\" name=\"positions-" + oid + "\">");
        out.println("    <float_array id=\"positions-array-" + oid + "\" count=\"" + vertexComponentsTotal
                + "\">" + stringPositionScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + verticesCount + "\" offset=\"0\" source=\"#positions-array-"
                + oid + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <source id=\"normals-" + oid + "\" name=\"normals-" + oid + "\">");
        out.println("    <float_array id=\"normals-array-" + oid + "\" count=\"" + normalComponentsTotal + "\">"
                + stringNormalScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + normalsCount + "\" offset=\"0\" source=\"#normals-array-" + oid
                + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <vertices id=\"vertices-" + oid + "\">");
        out.println("    <input semantic=\"POSITION\" source=\"#positions-" + oid + "\"/>");
        out.println("    <input semantic=\"NORMAL\" source=\"#normals-" + oid + "\"/>");
        out.println("   </vertices>");
        out.println("   <triangles count=\"" + triangleCount + "\" material=\"Material-" + oid + "\">");
        out.println("    <input offset=\"0\" semantic=\"VERTEX\" source=\"#vertices-" + oid + "\"/>");
        out.println("    <p>" + stringIndexScalars + "</p>");
        out.println("   </triangles>");
        out.println("  </mesh>");
        out.println(" </geometry>");
    }
}

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

/**
 * {@inheritDoc}/* w w w .ja va2s.c o m*/
 */
@Override
public boolean readFile(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData refinementData,
        CompositeConfiguration properties) {
    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    boolean transpose = false;

    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 mtzstr = 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)) {
            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.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // Skip initial header.
        dataInputStream.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++) {
                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 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(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(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(format(" Setting R free flag to MTZ default: %d\n", refinementData.rfreeflag));
        }

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

        // skip initial header
        dataInputStream.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++) {
                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, 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);

        // Log results.
        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" HKL data is %s\n", transpose ? "transposed" : "not transposed"));
            sb.append(format(" HKL read in:                             %d\n", nRead));
            sb.append(format(" HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" 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());
        }
        if (rFree < 0 && rFreePlus < 0 && rFreeMinus < 0) {
            refinementData.generateRFree();
        }
    } 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.apache.fop.fonts.type1.Type1SubsetFile.java

ByteArrayOutputStream updateSectionSize(int size) throws IOException {
    //Update the size in the header for the previous section
    ByteArrayOutputStream boas = new ByteArrayOutputStream();
    byte[] lowOrderSize = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array();
    boas.write(lowOrderSize);//from w ww  .j a v  a  2s . c  om
    return boas;
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

private static String bigEndian2LittleEndian(String fileName) throws FileNotFoundException, IOException {

    //import java.nio.ByteBuffer;
    //import java.nio.ByteOrder;
    //import java.nio.channels.FileChannel;
    //import java.io.FileOutputStream;

    byte[] imgData = loadFileToByteArray(fileName);
    String newFileName = fileName + ".be2le.tif";

    ByteBuffer buffer = ByteBuffer.allocate(imgData.length);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(imgData);//www  . j  av a 2 s.  c om
    FileChannel out = new FileOutputStream(newFileName).getChannel();
    out.write(buffer);
    out.close();

    return newFileName;
}

From source file:com.github.nlloyd.hornofmongo.util.BSONizer.java

@SuppressWarnings("deprecation")
private static Object convertScriptableMongoToBSON(ScriptableMongoObject jsMongoObj, boolean isJsObj,
        String dateFormat) {/*from  w  w  w .j a v  a  2  s .c o  m*/
    Object bsonObject = null;
    if (jsMongoObj instanceof ObjectId) {
        bsonObject = ((ObjectId) jsMongoObj).getRealObjectId();
    } else if (jsMongoObj instanceof BinData) {
        BinData binData = (BinData) jsMongoObj;
        byte type = new Integer(binData.getType()).byteValue();
        byte[] data = binData.getDataBytes();
        if (type == BSON.B_UUID) {
            ByteBuffer dataBuffer = ByteBuffer.wrap(data);
            // mongodb wire protocol is little endian
            dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
            long mostSigBits = dataBuffer.getLong();
            long leastSigBits = dataBuffer.getLong();
            bsonObject = new UUID(mostSigBits, leastSigBits);
        } else
            bsonObject = new org.bson.types.Binary(type, data);
    } else if (jsMongoObj instanceof MinKey) {
        bsonObject = new org.bson.types.MinKey();
    } else if (jsMongoObj instanceof MaxKey) {
        bsonObject = new org.bson.types.MaxKey();
    } else if (jsMongoObj instanceof NumberInt) {
        bsonObject = Integer.valueOf(((NumberInt) jsMongoObj).getRealInt());
    } else if (jsMongoObj instanceof NumberLong) {
        bsonObject = Long.valueOf(((NumberLong) jsMongoObj).getRealLong());
    } else if (jsMongoObj instanceof DBRef) {
        DBRef jsRef = (DBRef) jsMongoObj;
        Object id = convertJStoBSON(jsRef.getId(), isJsObj, dateFormat);
        bsonObject = new com.mongodb.DBRef(jsRef.getNs(), id);
    } else if (jsMongoObj instanceof Timestamp) {
        bsonObject = convertTimestampToBSONTimestamp((Timestamp) jsMongoObj);
    }
    return bsonObject;
}

From source file:nl.salp.warcraft4j.casc.cdn.EncodingFileParser.java

private EncodingFileSegment parseSegment(DataReader reader)
        throws DataReadingException, DataParsingException, CascParsingException {
    long segmentStart = reader.position();
    byte[] segmentChecksum = MD5.hash(reader.readNext(DataTypeFactory.getByteArray(SEGMENT_SIZE)));
    LOGGER.trace(//from  w  w w. j  av  a  2 s. co  m
            "Calculated checksum {} over {} byte segment from position {} to {}, reading entries from position {}",
            byteArrayToHexString(segmentChecksum), SEGMENT_SIZE, segmentStart, reader.position(), segmentStart);
    reader.position(segmentStart);
    List<EncodingEntry> entries = new ArrayList<>();

    int keyCount;

    while ((keyCount = reader.readNext(DataTypeFactory.getUnsignedShort(), ByteOrder.LITTLE_ENDIAN)) != 0) {
        long fileSize = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.BIG_ENDIAN);
        byte[] checksum = reader.readNext(DataTypeFactory.getByteArray(CHECKSUM_SIZE));

        List<FileKey> keys = new ArrayList<>();
        for (int keyIndex = 0; keyIndex < keyCount; keyIndex++) {
            byte[] key = reader.readNext(DataTypeFactory.getByteArray(CHECKSUM_SIZE));
            keys.add(new FileKey(key));
        }
        EncodingEntry entry = new CascEncodingEntry(fileSize, new ContentChecksum(checksum), keys);
        entries.add(entry);
    }
    while (reader.hasRemaining() && reader.peek(DataTypeFactory.getByte()) == 0) {
        reader.skip(1);
    }
    return new EncodingFileSegment(entries, segmentChecksum);
}

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;/*from www .j  av  a2 s . com*/
    }

    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:burstcoin.observer.service.ATService.java

public static String getATLong(String hex) {
    ByteBuffer bf = ByteBuffer.allocate(8);
    bf.order(ByteOrder.LITTLE_ENDIAN);
    bf.put(parseHexString(hex));//w w  w  . j  a  v a 2s  .  c om
    return toUnsignedLong(bf.getLong(0));
}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java

/**
 * internal test switch/*from   ww  w.j  a v a  2  s . com*/
 * 
 * @param data DOCUMENT ME!
 * @return DOCUMENT ME!
 */
private boolean testInternal(byte[] data) {
    log.debug("testInternal(byte[])");

    if (data.length == 0) {
        return false;
    }

    String type = match.getType();
    String test = new String(match.getTest().array());
    String mimeType = match.getMimeType();
    String description = match.getDescription();

    ByteBuffer buffer = ByteBuffer.allocate(data.length);

    if ((type != null) && (test != null) && (test.length() > 0)) {
        if (type.equals("string")) {
            buffer = buffer.put(data);

            return testString(buffer);
        } else if (type.equals("byte")) {
            buffer = buffer.put(data);

            return testByte(buffer);
        } else if (type.equals("short")) {
            buffer = buffer.put(data);

            return testShort(buffer);
        } else if (type.equals("leshort")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.LITTLE_ENDIAN);

            return testShort(buffer);
        } else if (type.equals("beshort")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.BIG_ENDIAN);

            return testShort(buffer);
        } else if (type.equals("long")) {
            buffer = buffer.put(data);

            return testLong(buffer);
        } else if (type.equals("lelong")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.LITTLE_ENDIAN);

            return testLong(buffer);
        } else if (type.equals("belong")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.BIG_ENDIAN);

            return testLong(buffer);
        } else if (type.equals("regex")) {
            return testRegex(new String(data));
        } else if (type.equals("detector")) {
            buffer = buffer.put(data);

            return testDetector(buffer);

            //         } else if (type.equals("date")) {
            //            return testDate(data, BIG_ENDIAN);
            //         } else if (type.equals("ledate")) {
            //            return testDate(data, LITTLE_ENDIAN);
            //         } else if (type.equals("bedate")) {
            //            return testDate(data, BIG_ENDIAN);
        } else {
            log.error("testInternal(byte[]): invalid test type '" + type + "'");
        }
    } else {
        log.error("testInternal(byte[]): type or test is empty for '" + mimeType + " - " + description + "'");
    }

    return false;
}

From source file:org.mycontroller.standalone.mysensors.ProcessRawMessage.java

private void procressFirmwareRequest(RawMessage rawMessage) {
    FirmwareRequest firmwareRequest = new FirmwareRequest();
    try {/*from   w w w  .  j  a va2s  . c o m*/
        firmwareRequest.setByteBuffer(ByteBuffer.wrap(Hex.decodeHex(rawMessage.getPayload().toCharArray()))
                .order(ByteOrder.LITTLE_ENDIAN), 0);
        _logger.debug("Firmware Request:[Type:{},Version:{},Block:{}]", firmwareRequest.getType(),
                firmwareRequest.getVersion(), firmwareRequest.getBlock());

        boolean requestFirmwareReload = false;
        if (firmware == null) {
            requestFirmwareReload = true;
        } else if (firmware != null) {
            if (firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
                requestFirmwareReload = true;
            } else if (firmwareRequest.getType() == firmware.getType().getId()
                    && firmwareRequest.getVersion() == firmware.getVersion().getId()) {
                //Nothing to do just continue
            } else {
                requestFirmwareReload = true;
            }
        } else {
            requestFirmwareReload = true;
        }

        if (requestFirmwareReload) {
            firmware = DaoUtils.getFirmwareDao().get(firmwareRequest.getType(), firmwareRequest.getVersion());
            _logger.debug("Firmware reloaded...");
        }

        if (firmware == null) {
            _logger.debug("selected firmware type/version not available");
            return;
        }

        FirmwareResponse firmwareResponse = new FirmwareResponse();
        firmwareResponse.setByteBufferPosition(0);
        firmwareResponse.setBlock(firmwareRequest.getBlock());
        firmwareResponse.setVersion(firmwareRequest.getVersion());
        firmwareResponse.setType(firmwareRequest.getType());
        StringBuilder builder = new StringBuilder();
        int fromIndex = firmwareRequest.getBlock() * FirmwareUtils.FIRMWARE_BLOCK_SIZE;
        for (int index = fromIndex; index < fromIndex + FirmwareUtils.FIRMWARE_BLOCK_SIZE; index++) {
            builder.append(String.format("%02X", firmware.getData().get(index)));
        }
        if (firmwareRequest.getBlock() == 0) {
            firmware = null;
            _logger.debug("Firmware unloaded...");
        }

        // Print firmware status in sensor logs
        if (firmwareRequest.getBlock() % FIRMWARE_PRINT_LOG == 0
                || firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
            SensorLogUtils.setSensorStreamData(MESSAGE_TYPE_STREAM.ST_FIRMWARE_REQUEST,
                    "Block No: " + firmwareRequest.getBlock(), rawMessage, null);
        }

        rawMessage.setTxMessage(true);
        rawMessage.setSubType(MESSAGE_TYPE_STREAM.ST_FIRMWARE_RESPONSE.ordinal());
        rawMessage
                .setPayload(Hex.encodeHexString(firmwareResponse.getByteBuffer().array()) + builder.toString());
        ObjectFactory.getRawMessageQueue().putMessage(rawMessage);
        _logger.debug("FirmwareRespone:[Type:{},Version:{},Block:{}]", firmwareResponse.getType(),
                firmwareResponse.getVersion(), firmwareResponse.getBlock());

        // Print firmware status in sensor logs
        if (firmwareRequest.getBlock() % FIRMWARE_PRINT_LOG == 0
                || firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
            SensorLogUtils.setSensorStreamData(MESSAGE_TYPE_STREAM.ST_FIRMWARE_RESPONSE,
                    "Block No:" + firmwareRequest.getBlock(), rawMessage, null);
        }

    } catch (DecoderException ex) {
        _logger.error("Exception, ", ex);
    }
}