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:github.daneren2005.serverproxy.ServerProxy.java

public String getPublicAddress(String request) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();

    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }/*  w  ww .  j a va 2 s . co m*/

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
    String ipAddressString = null;
    try {
        ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
        Log.e(TAG, "Unable to get host address.");
    }

    return getAddress(ipAddressString, request);
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPAuthenticateV10MessageMessage.java

public static void write(ByteBuf out, String userName, String userPassword, String salt, Charset charset,
        int mysqlCharsetID, int capabilitiesFlag) {
    ByteBuf leBuf = out.order(ByteOrder.LITTLE_ENDIAN);

    int payloadSizeIndex = leBuf.writerIndex();
    leBuf.writeMedium(0);// w w w . ja va  2  s.  com
    leBuf.writeByte(1);
    int payloadStartIndex = leBuf.writerIndex();
    leBuf.writeInt(capabilitiesFlag);
    leBuf.writeInt(MAX_PACKET_SIZE);
    //      leBuf.writeByte(serverGreeting.getServerCharsetId());
    leBuf.writeByte(mysqlCharsetID);
    leBuf.writeZero(23);
    leBuf.writeBytes(userName.getBytes(charset));
    leBuf.writeZero(1);

    if ((capabilitiesFlag & ClientCapabilities.CLIENT_SECURE_CONNECTION) > 0) {

        byte[] securePassword = computeSecurePassword(userPassword, salt);
        leBuf.writeByte(securePassword.length);
        leBuf.writeBytes(securePassword);
    } else {
        leBuf.writeBytes(userPassword.getBytes(charset));
        leBuf.writeZero(1);
    }

    leBuf.setMedium(payloadSizeIndex, leBuf.writerIndex() - payloadStartIndex);
}

From source file:com.talent.balance.backend.BackendStarter.java

/**
 * /*w ww . j a  v a 2s . c  o m*/
 * @param remoteIp
 * @param remotePort
 * @param bindIp
 * @param bindPort
 * @param frontendChannelContext
 * @param wait true: ??
 * @return
 */
public static ChannelContext addConnection(BackendServerConf backendServer, String bindIp, int bindPort,
        ChannelContext frontendChannelContext, BackendConf backendConf, boolean wait, int timeout) {
    RemoteNode remoteNode = new RemoteNode(backendServer.getIp(), backendServer.getPort());

    DecoderIntf decoder = new BackendResponseDecoder();
    PacketHandlerIntf packetHandler = new BackendPacketHandler();

    final ChannelContext backendChannelContext = new ChannelContext(bindIp, bindPort, remoteNode,
            BackendConf.getInstance().getProtocol(), decoder, packetHandler,
            new BackendConnectionStateListener());

    if (backendConf.getByteOrder() == 0) {
        backendChannelContext.setByteOrder(ByteOrder.LITTLE_ENDIAN);
    }

    BackendExt.setBackendServer(backendChannelContext, backendServer);

    if (frontendChannelContext != null) {
        BackendExt.setFrontend(backendChannelContext, frontendChannelContext);
    }

    if (StringUtils.isNotBlank(bindIp)) {
        backendChannelContext.setBindIp(bindIp);
        backendChannelContext.setBindPort(bindPort);
    }

    backendChannelContext.setWriteIOErrorHandler(BackendIOErrorHandler.getInstance());
    backendChannelContext.setReadIOErrorHandler(BackendIOErrorHandler.getInstance());

    if (wait) {
        synchronized (backendChannelContext) {
            try {
                Nio.getInstance().addConnection(backendChannelContext);
                backendChannelContext.wait(timeout);
            } catch (InterruptedException e) {
                log.error("", e);
            }
        }
    } else {
        Nio.getInstance().addConnection(backendChannelContext);
    }

    return backendChannelContext;
}

From source file:org.onlab.util.ImmutableByteSequence.java

/**
 * Creates a new immutable byte sequence copying bytes from the given
 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
 * bytes will be copied in reverse order.
 *
 * @param original a byte buffer//from w  ww  .  jav a  2 s  . c  o m
 * @return a new byte buffer object
 */
public static ImmutableByteSequence copyFrom(ByteBuffer original) {
    checkArgument(original != null && original.capacity() > 0, "Cannot copy from an empty or null byte buffer");

    byte[] bytes = new byte[original.capacity()];

    // copy bytes from original buffer
    original.rewind();
    original.get(bytes);

    if (original.order() == ByteOrder.LITTLE_ENDIAN) {
        // FIXME: this can be improved, e.g. read bytes in reverse order from original
        reverse(bytes);
    }

    return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
}

From source file:org.ros.internal.transport.tcp.TcpRosServer.java

public void start() {
    Preconditions.checkState(outgoingChannel == null);
    channelFactory = new NioServerSocketChannelFactory(executorService, executorService);
    bootstrap = new ServerBootstrap(channelFactory);
    bootstrap.setOption("child.bufferFactory", new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN));
    bootstrap.setOption("child.keepAlive", true);
    incomingChannelGroup = new DefaultChannelGroup();
    bootstrap.setPipelineFactory(/*w ww  . j a v  a2 s . c  om*/
            new TcpRosServerPipelineFactory(incomingChannelGroup, topicParticipantManager, serviceManager));

    outgoingChannel = bootstrap.bind(bindAddress.toInetSocketAddress());
    advertiseAddress.setPortCallable(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return ((InetSocketAddress) outgoingChannel.getLocalAddress()).getPort();
        }
    });
    if (log.isDebugEnabled()) {
        log.debug(String.format("Bound to: %s, Advertising: %s", bindAddress, advertiseAddress));
    }
}

From source file:io.github.dsheirer.record.wave.MonoWaveReader.java

/**
 * Opens the file// ww  w  .j  ava 2s  .  c  o  m
 */
private void open() throws IOException {
    if (!Files.exists(mPath)) {
        throw new IOException("File not found");
    }

    mInputStream = Files.newInputStream(mPath, StandardOpenOption.READ);

    //Check for RIFF header
    byte[] buffer = new byte[4];
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.RIFF_CHUNK)) {
        throw new IOException("File is not .wav format - missing RIFF chunk");
    }

    //Get file size
    mInputStream.read(buffer);
    int fileSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Check for WAVE format
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.WAV_FORMAT)) {
        throw new IOException("File is not .wav format - missing WAVE format");
    }

    //Check for format chunk
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_FORMAT)) {
        throw new IOException("File is not .wav format - missing format chunk");
    }

    //Get chunk size
    mInputStream.read(buffer);
    int chunkSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get format
    mInputStream.read(buffer);

    ShortBuffer shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short format = shortBuffer.get();
    if (format != WaveUtils.PCM_FORMAT) {
        throw new IOException("File format not supported - expecting PCM format");
    }

    //Get number of channels
    short channels = shortBuffer.get();
    if (channels != 1) {
        throw new IOException("Unsupported channel count - mono audio only");
    }

    //Get samples per second
    mInputStream.read(buffer);
    int sampleRate = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get bytes per second
    mInputStream.read(buffer);
    int bytesPerSecond = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    mInputStream.read(buffer);

    //Get frame size
    shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short frameSize = shortBuffer.get();
    if (frameSize != 2) {
        throw new IOException("PCM frame size not supported - expecting 2 bytes per frame");
    }

    //Get bits per sample
    short bitsPerSample = shortBuffer.get();
    if (bitsPerSample != 16) {
        throw new IOException("PCM sample size not supported - expecting 16 bits per sample");
    }

    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_DATA)) {
        throw new IOException("Unexpected chunk - expecting data chunk");
    }

    //Get data chunk size
    mInputStream.read(buffer);
    mDataByteSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();
}

From source file:org.onosproject.drivers.barefoot.TofinoPipelineProgrammable.java

private ByteBuffer extensionBuffer(PiPipeconf pipeconf, ExtensionType extType) {
    if (!pipeconf.extension(extType).isPresent()) {
        log.warn("Missing extension {} in pipeconf {}", extType, pipeconf.id());
        throw new ExtensionException();
    }//from   ww w  .j a va  2  s.  co m
    try {
        byte[] bytes = IOUtils.toByteArray(pipeconf.extension(extType).get());
        // Length of the extension + bytes.
        return ByteBuffer.allocate(Integer.BYTES + bytes.length).order(ByteOrder.LITTLE_ENDIAN)
                .putInt(bytes.length).put(bytes);
    } catch (IOException ex) {
        log.warn("Unable to read extension {} from pipeconf {}: {}", extType, pipeconf.id(), ex.getMessage());
        throw new ExtensionException();
    }
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyUserVarLogEvent.java

String processVariableValue(ByteBuf cb) throws PEException {
    String value = StringUtils.EMPTY;

    valueType = MyItemResultCode.fromByte(cb.readByte());
    valueCharSet = cb.readInt();/*from  w w  w . j ava  2  s .  co  m*/
    valueLen = cb.readInt();
    valueBytes = Unpooled.buffer(cb.readableBytes()).order(ByteOrder.LITTLE_ENDIAN);
    valueBytes.writeBytes(cb);

    switch (valueType) {
    case DECIMAL_RESULT:
        value = processDecimalValue(valueBytes, valueLen);
        break;
    case INT_RESULT:
        value = processIntValue(valueBytes, valueLen);
        break;
    case REAL_RESULT:
        value = Double.toString(valueBytes.readDouble());
        break;
    case STRING_RESULT:
        value = "'" + StringUtils.replace(
                MysqlAPIUtils.readBytesAsString(valueBytes, valueLen, CharsetUtil.UTF_8), "'", "''") + "'";
        break;
    case ROW_RESULT:
    default:
        throw new PEException(
                "Unsupported variable type '" + valueType + "' for variable '" + variableName + "'");
    }
    return value;
}

From source file:net.pms.util.OpenSubtitle.java

private static long computeHashForChunk(ByteBuffer buffer) {
    LongBuffer longBuffer = buffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
    long hash = 0;

    while (longBuffer.hasRemaining()) {
        hash += longBuffer.get();//from  w w  w. ja va2s. c o  m
    }

    return hash;
}

From source file:nl.salp.warcraft4j.util.Checksum.java

/**
 * Trim the checksum to a length, resizing it (using the byte order for cut-off) if the checksum is bigger then the provided length.
 *
 * @param length    The maximum length in bytes.
 * @param byteOrder The byte order to determine which side to cut off the bytes.
 *
 * @return A new checksum instance with checksum data or the current checksum instance or the current checksum instance when the current data is equal or smaller in length.
 *
 * @throws IllegalArgumentException When the length is {@code 0} or negative.
 *///from   www  . j a  v  a  2s  . c  o m
public Checksum trim(int length, ByteOrder byteOrder) throws IllegalArgumentException {
    Checksum instance;
    if (length < 1) {
        throw new IllegalArgumentException(
                format("Can't trim a %d byte checksum to %d bytes.", checksum.length, length));
    }
    if (length >= checksum.length) {
        instance = this;
    } else if (ByteOrder.LITTLE_ENDIAN.equals(byteOrder)) {
        instance = new Checksum(subarray(checksum, checksum.length - length, checksum.length));
    } else {
        instance = new Checksum(subarray(checksum, 0, length));
    }
    return instance;
}