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.jmangos.sniffer.handler.PKTLogHandler.java

/**
 * (non-Javadoc)/*w  ww. j  a va  2 s  .  c o  m*/
 * 
 * @see org.jmangos.sniffer.handler.PacketLogHandler#onDecodePacket(org.jmangos
 *      .sniffer.network.model.NetworkChannel,
 *      org.jmangos.sniffer.enums.Direction, java.lang.Integer,
 *      java.lang.Integer, byte[], int)
 */
@Override
public void onDecodePacket(final NetworkChannel channel, final Direction direction, final Integer size,
        final Integer opcode, final byte[] data, final int frame) {
    if (!isInit()) {
        init();
    }
    try {
        final ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + 4 + 4 + data.length + 4);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(direction.getValue());
        buffer.putInt(channel.hashCode());
        buffer.putInt(frame);
        buffer.putInt(0);
        buffer.putInt(data.length + 4);
        buffer.putInt(opcode);
        buffer.put(data);
        this.fous.write(buffer.array());
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

From source file:ee.ioc.phon.android.speak.Utils.java

/**
 * <p>Returns a bitmap that visualizes the given waveform (byte array),
 * i.e. a sequence of 16-bit integers.</p>
 *
 * TODO: show to high/low points in other color
 * TODO: show end pause data with another color
 *///from w ww  .j  a v a  2  s.c  o  m
public static Bitmap drawWaveform(byte[] waveBuffer, int w, int h, int start, int end) {
    final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    final Canvas c = new Canvas(b);
    final Paint paint = new Paint();
    paint.setColor(0xFFFFFFFF); // 0xRRGGBBAA
    paint.setAntiAlias(true);
    paint.setStrokeWidth(0);

    final Paint redPaint = new Paint();
    redPaint.setColor(0xFF000080);
    redPaint.setAntiAlias(true);
    redPaint.setStrokeWidth(0);

    final ShortBuffer buf = ByteBuffer.wrap(waveBuffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    buf.position(0);

    final int numSamples = waveBuffer.length / 2;
    //final int delay = (SAMPLING_RATE * 100 / 1000);
    final int delay = 0;
    int endIndex = end / 2 + delay;
    if (end == 0 || endIndex >= numSamples) {
        endIndex = numSamples;
    }
    int index = start / 2 - delay;
    if (index < 0) {
        index = 0;
    }
    final int size = endIndex - index;
    int numSamplePerPixel = 32;
    int delta = size / (numSamplePerPixel * w);
    if (delta == 0) {
        numSamplePerPixel = size / w;
        delta = 1;
    }

    final float scale = 3.5f / 65536.0f;
    // do one less column to make sure we won't read past
    // the buffer.
    try {
        for (int i = 0; i < w - 1; i++) {
            final float x = i;
            for (int j = 0; j < numSamplePerPixel; j++) {
                final short s = buf.get(index);
                final float y = (h / 2) - (s * h * scale);
                if (s > Short.MAX_VALUE - 10 || s < Short.MIN_VALUE + 10) {
                    // TODO: make it work
                    c.drawPoint(x, y, redPaint);
                } else {
                    c.drawPoint(x, y, paint);
                }
                index += delta;
            }
        }
    } catch (IndexOutOfBoundsException e) {
        // this can happen, but we don't care
    }

    return b;
}

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

private void startSeriesMetadata(JSONObject firstImageTags, int seriesIndex, String baseFileName)
        throws JSONException, MMScriptException {
    series_.put(seriesIndex, new Indices());
    //Last one is samples per pixel
    JSONObject summaryMD = mptStorage_.getSummaryMetadata();
    MetadataTools.populateMetadata(metadata_, seriesIndex, baseFileName,
            MultipageTiffWriter.BYTE_ORDER.equals(ByteOrder.LITTLE_ENDIAN),
            mptStorage_.slicesFirst() ? "XYZCT" : "XYCZT", "uint" + (MDUtils.isGRAY8(summaryMD) ? "8" : "16"),
            MDUtils.getWidth(summaryMD), MDUtils.getHeight(summaryMD), MDUtils.getNumSlices(summaryMD),
            MDUtils.getNumChannels(summaryMD), MDUtils.getNumFrames(summaryMD), 1);

    if (summaryMD.has("PixelSize_um") && !summaryMD.isNull("PixelSize_um")) {
        double pixelSize = summaryMD.getDouble("PixelSize_um");
        if (pixelSize > 0) {
            metadata_.setPixelsPhysicalSizeX(new PositiveFloat(pixelSize), seriesIndex);
            metadata_.setPixelsPhysicalSizeY(new PositiveFloat(pixelSize), seriesIndex);
        }//from  w  w  w  .ja  v  a2  s.  co m
    }
    if (summaryMD.has("z-step_um") && !summaryMD.isNull("z-step_um")) {
        double zStep = summaryMD.getDouble("z-step_um");
        if (zStep > 0) {
            metadata_.setPixelsPhysicalSizeZ(new PositiveFloat(zStep), seriesIndex);
        }
    }

    String positionName;
    try {
        positionName = MDUtils.getPositionName(firstImageTags);
    } catch (JSONException ex) {
        ReportingUtils.logError("Couldn't find position name in image metadata");
        positionName = "pos" + MDUtils.getPositionIndex(firstImageTags);
    }
    metadata_.setStageLabelName(positionName, seriesIndex);

    String instrumentID = MetadataTools.createLSID("Microscope");
    metadata_.setInstrumentID(instrumentID, 0);
    // link Instrument and Image
    metadata_.setImageInstrumentRef(instrumentID, seriesIndex);

    JSONObject comments = mptStorage_.getDisplayAndComments().getJSONObject("Comments");
    if (comments.has("Summary") && !comments.isNull("Summary")) {
        metadata_.setImageDescription(comments.getString("Summary"), seriesIndex);
    }

    JSONArray channels = mptStorage_.getDisplayAndComments().getJSONArray("Channels");
    for (int channelIndex = 0; channelIndex < channels.length(); channelIndex++) {
        JSONObject channel = channels.getJSONObject(channelIndex);
        metadata_.setChannelColor(new Color(channel.getInt("Color")), seriesIndex, channelIndex);
        metadata_.setChannelName(channel.getString("Name"), seriesIndex, channelIndex);
    }
    //used to estimate the final length of the OME xml string
    if (omeXMLBaseLength_ == -1) {
        try {
            OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
            omeXMLBaseLength_ = service.getOMEXML(metadata_).length();
        } catch (Exception ex) {
            ReportingUtils.logError("Unable to calculate OME XML Base length");
        }
    }
}

From source file:org.mcisb.util.math.MathUtils.java

/**
 * /*  www .j ava  2 s .c om*/
 * @param values
 * @param bigEndian
 * @return String
 */
public static byte[] getBytes(final double[] values, final boolean bigEndian) {
    final byte[] byteArray = new byte[values.length * DOUBLE_LENGTH];
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    buffer = buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < values.length; i++) {
        buffer.putDouble(values[i]);
    }

    return buffer.array();
}

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);/*from  w  ww  . ja  v a2s  .  c  o m*/

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

From source file:ru.jts_dev.gameserver.service.GameSessionService.java

private GameSession createSession(TcpConnection connection) {
    ByteBuf encryptKey = buffer(16, 16).order(ByteOrder.LITTLE_ENDIAN);
    // randomize first 8 bytes of key
    random.nextBytes(encryptKey.array());
    encryptKey.writerIndex(8);/*from ww  w.  j ava  2  s  . c  om*/

    // and add 8 byte as static key part
    encryptKey.writeBytes(STATIC_KEY_PART);

    // then copy encrypt key to decrypt key
    ByteBuf decryptKey = copiedBuffer(encryptKey).order(ByteOrder.LITTLE_ENDIAN);

    // and pass keys to a game session object
    return new GameSession(connection, encryptKey, decryptKey);
}

From source file:services.travel.TravelService.java

@Override
public void insertOpcodes(Map<Integer, INetworkRemoteEvent> swgOpcodes,
        Map<Integer, INetworkRemoteEvent> objControllerOpcodes) {
    swgOpcodes.put(Opcodes.PlanetTravelPointListRequest, new INetworkRemoteEvent() {

        @Override//from ww  w  . j av  a 2  s  .  c  o m
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {

            data.order(ByteOrder.LITTLE_ENDIAN);

            PlanetTravelPointListRequest request = new PlanetTravelPointListRequest();
            request.deserialize(data);

            Client client = core.getClient(session);

            if (client == null || client.getSession() == null)
                return;

            SWGObject object = client.getParent();

            if (object == null)
                return;

            TravelPoint travelPoint = getNearestTravelPoint(object);

            if (travelPoint == null)
                return;

            if (travelPoint.isStarport()) {

                List<Planet> planetList = core.terrainService.getPlanetList();

                for (Planet planet : planetList) {
                    String planetString = planet.getName();

                    if (request.getPlanet().equals(planetString)) {

                        Vector<TravelPoint> correctTravelPoints = new Vector<TravelPoint>();

                        for (TravelPoint tp : travelMap.get(planet)) {
                            if (tp.isStarport()
                                    || tp.getPlanetName().equalsIgnoreCase(object.getPlanet().getName())) {
                                correctTravelPoints.add(tp);
                            }
                        }
                        PlanetTravelPointListResponse response = new PlanetTravelPointListResponse(planetString,
                                correctTravelPoints);
                        client.getSession().write(response.serialize());

                        break;

                    }
                }

            } else {

                Planet planet = object.getPlanet();

                PlanetTravelPointListResponse response = new PlanetTravelPointListResponse(planet.getName(),
                        travelMap.get(planet));
                client.getSession().write(response.serialize());

            }

        }
    });

}

From source file:nl.salp.warcraft4j.casc.cdn.local.LocalIndexFileParser.java

/**
 * Read and parse a {@link LocalIndexFile}.
 *
 * @param reader The reader for the file.
 *
 * @return The parsed index file./*from  w  w  w  . j ava  2  s . c o  m*/
 *
 * @throws CascParsingException When the file is invalid.
 * @throws DataReadingException When reading the entry data failed.
 * @throws DataParsingException When parsing the entry data failed.
 */
public LocalIndexFile parse(DataReader reader) throws DataReadingException, DataParsingException {
    LOGGER.trace("Parsing index file {}", file);
    validateHeader(reader);
    int dataHeaderLength = reader.readNext(DataTypeFactory.getInteger(), ByteOrder.LITTLE_ENDIAN);
    Checksum dataHeaderChecksum = new Checksum(reader.readNext(DataTypeFactory.getByteArray(4))); // ByteOrder.LITTLE_ENDIAN
    // TODO Validate header based on the checksum.
    IndexHeaderV2 header = parseHeader(reader);
    LOGGER.trace("Parsed header {}", header);
    reader.position((8 + dataHeaderLength + 0x0F) & 0xFFFFFFF0);

    int dataLength = reader.readNext(DataTypeFactory.getInteger(), ByteOrder.LITTLE_ENDIAN);
    Checksum dataChecksum = new Checksum(reader.readNext(DataTypeFactory.getByteArray(4))); // ByteOrder.LITTLE_ENDIAN
    // TODO Validate data based on the checksum.
    int entryCount = (dataLength / ENTRY_SIZE);
    LOGGER.trace("Parsing {} index file entries from {} bytes at position {}", entryCount, dataLength,
            reader.position());
    List<IndexEntry> entries = parseEntries(reader, entryCount);

    int fileNumber = fileNumberFunction.apply(file);
    int fileVersion = fileVersionFunction.apply(file);
    LOGGER.trace("Parsed index file {}, version {} with {} entries, expecting {} entries", fileNumber,
            fileVersion, entries.size(), entryCount);
    return new LocalIndexFile(file, fileNumber, fileVersion, entries);
}

From source file:xbird.server.services.RemotePagingService.java

public RemotePagingService() {
    super(SRV_NAME);
    this._fdCacheMap = new FinalizableSoftValueReferenceMap<String, FileChannel>(
            new ReferentFinalizer<FileChannel>() {
                public void finalize(FileChannel reclaimed) {
                    IOUtils.closeQuietly(reclaimed);
                }//from  w ww.  ja  v  a  2s . c o m
            });
    this._directoryCache = new ReferenceMap<String, IDescriptor>(ReferenceType.STRONG, ReferenceType.SOFT);
    if (SystemUtils.isSendfileSupported()) {
        this._sndBufSegm = null;
        this._sndBufDTM = null;
    } else {
        this._sndBufSegm = ByteBuffer.allocateDirect(SND_BUFSIZE);
        _sndBufSegm.order(ByteOrder.BIG_ENDIAN);
        this._sndBufDTM = ByteBuffer.allocateDirect(SND_BUFSIZE);
        _sndBufDTM.order(ByteOrder.LITTLE_ENDIAN);
    }
}

From source file:org.jmangos.realm.network.packet.wow.client.CMSG_AUTH_SESSION.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    this.ClientBuild = readD();
    skip(4);//from  ww  w . java2s  . com
    this.accountName = readS();
    skip(4);
    this.clientSeed = readB(4);
    skip(20);
    this.digest = readB(20);

    if (getAvaliableBytes() < 4) {
        return;
    }

    final int UncopressedSize = readD();
    final byte[] compressedData = readB(getAvaliableBytes());
    final Inflater decompressor = new Inflater();
    decompressor.setInput(compressedData);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

    final byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        try {
            final int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        } catch (final DataFormatException e) {
        }
    }
    try {
        bos.close();
    } catch (final IOException e) {
    }

    final byte[] decompressedData = bos.toByteArray();
    if (UncopressedSize != decompressedData.length) {
        logger.warn("Somesing wrong with compressed addonInfo");
        return;
    }
    final ChannelBuffer addonInfo = ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN, decompressedData);

    final int addonsCount = addonInfo.readInt();

    this.addonLists = new ArrayList<AddonInfo>(addonsCount);
    for (int i = 0; i < addonsCount; i++) {
        final TextBuilder tb = TextBuilder.newInstance();
        for (byte c; (c = addonInfo.readByte()) != 0;) {
            tb.append((char) c);
        }
        final String addonName = tb.toString();
        TextBuilder.recycle(tb);
        final byte enabled = addonInfo.readByte();
        final int crc = addonInfo.readInt();
        /* int unk1 = */addonInfo.readInt();
        this.addonLists.add(new AddonInfo(addonName, enabled, crc));
    }

    /* int unk2 = */addonInfo.readInt();
}