List of usage examples for java.nio ByteOrder BIG_ENDIAN
ByteOrder BIG_ENDIAN
To view the source code for java.nio ByteOrder BIG_ENDIAN.
Click Source Link
From source file:com.easemob.dataexport.utils.ConversionUtils.java
/** * @param val//from www .ja v a 2s . c om * @return */ public static byte[] bytes(Long val) { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(val); return buf.array(); }
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java
public static boolean isMMMultipageTiff(String directory) throws IOException { File dir = new File(directory); File[] children = dir.listFiles(); File testFile = null;// ww w. ja v a 2 s. com for (File child : children) { if (child.isDirectory()) { File[] grandchildren = child.listFiles(); for (File grandchild : grandchildren) { if (grandchild.getName().endsWith(".tif")) { testFile = grandchild; break; } } } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) { testFile = child; break; } } if (testFile == null) { throw new IOException("Unexpected file structure: is this an MM dataset?"); } RandomAccessFile ra; try { ra = new RandomAccessFile(testFile, "r"); } catch (FileNotFoundException ex) { ReportingUtils.logError(ex); return false; } FileChannel channel = ra.getChannel(); ByteBuffer tiffHeader = ByteBuffer.allocate(36); ByteOrder bo; channel.read(tiffHeader, 0); char zeroOne = tiffHeader.getChar(0); if (zeroOne == 0x4949) { bo = ByteOrder.LITTLE_ENDIAN; } else if (zeroOne == 0x4d4d) { bo = ByteOrder.BIG_ENDIAN; } else { throw new IOException("Error reading Tiff header"); } tiffHeader.order(bo); int summaryMDHeader = tiffHeader.getInt(32); channel.close(); ra.close(); if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) { return true; } return false; }
From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueServices.java
static Pair<byte[], Long> decompose(ByteBuffer composite) { composite = composite.slice().order(ByteOrder.BIG_ENDIAN); short len = composite.getShort(); byte[] colName = new byte[len]; composite.get(colName);//from w w w . ja v a2s. c om short shouldBeZero = composite.getShort(); Validate.isTrue(shouldBeZero == 0); byte shouldBe8 = composite.get(); Validate.isTrue(shouldBe8 == 8); long ts = composite.getLong(); return Pair.create(colName, (~ts)); }
From source file:com.easemob.dataexport.utils.ConversionUtils.java
public static ByteBuffer bytebuffer(Long val) { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(val); return (ByteBuffer) buf.rewind(); }
From source file:org.openhab.io.transport.modbus.ModbusBitUtilities.java
/** * Read data from registers and convert the result to DecimalType * Interpretation of <tt>index</tt> goes as follows depending on type * * BIT://ww w.j a v a 2 s . co m * - a single bit is read from the registers * - indices between 0...15 (inclusive) represent bits of the first register * - indices between 16...31 (inclusive) represent bits of the second register, etc. * - index 0 refers to the least significant bit of the first register * - index 1 refers to the second least significant bit of the first register, etc. * INT8: * - a byte (8 bits) from the registers is interpreted as signed integer * - index 0 refers to low byte of the first register, 1 high byte of first register * - index 2 refers to low byte of the second register, 3 high byte of second register, etc. * - it is assumed that each high and low byte is encoded in most significant bit first order * UINT8: * - same as INT8 except value is interpreted as unsigned integer * INT16: * - register with index (counting from zero) is interpreted as 16 bit signed integer. * - it is assumed that each register is encoded in most significant bit first order * UINT16: * - same as INT16 except value is interpreted as unsigned integer * INT32: * - registers (index) and (index + 1) are interpreted as signed 32bit integer. * - it assumed that the first register contains the most significant 16 bits * - it is assumed that each register is encoded in most significant bit first order * INT32_SWAP: * - Same as INT32 but registers swapped * UINT32: * - same as INT32 except value is interpreted as unsigned integer * UINT32_SWAP: * - same as INT32_SWAP except value is interpreted as unsigned integer * FLOAT32: * - registers (index) and (index + 1) are interpreted as signed 32bit floating point number. * - it assumed that the first register contains the most significant 16 bits * - it is assumed that each register is encoded in most significant bit first order * - floating point NaN and infinity will return as empty optional * FLOAT32_SWAP: * - Same as FLOAT32 but registers swapped * INT64: * - registers (index), (index + 1), (index + 2), (index + 3) are interpreted as signed 64bit integer. * - it assumed that the first register contains the most significant 16 bits * - it is assumed that each register is encoded in most significant bit first order * INT64_SWAP: * - same as INT64 but registers swapped, that is, registers (index + 3), (index + 2), (index + 1), (index + 1) are * interpreted as signed 64bit integer * UINT64: * - same as INT64 except value is interpreted as unsigned integer * UINT64_SWAP: * - same as INT64_SWAP except value is interpreted as unsigned integer * * @param registers list of registers, each register represent 16bit of data * @param index zero based item index. Interpretation of this depends on type, see examples above. * With type larger or equal to 16 bits, the index tells the register index to start reading * from. * With type less than 16 bits, the index tells the N'th item to read from the registers. * @param type item type, e.g. unsigned 16bit integer (<tt>ModbusBindingProvider.ValueType.UINT16</tt>) * @return number representation queried value, <tt>DecimalType</tt>. Empty optional is returned * with NaN and infinity floating point values * @throws NotImplementedException in cases where implementation is lacking for the type. This can be considered a * bug * @throws IllegalArgumentException when <tt>index</tt> is out of bounds of registers * */ public static Optional<DecimalType> extractStateFromRegisters(ModbusRegisterArray registers, int index, ModbusConstants.ValueType type) { int endBitIndex = (type.getBits() >= 16 ? 16 * index : type.getBits() * index) + type.getBits() - 1; // each register has 16 bits int lastValidIndex = registers.size() * 16 - 1; if (endBitIndex > lastValidIndex || index < 0) { throw new IllegalArgumentException( String.format("Index=%d with type=%s is out-of-bounds given registers of size %d", index, type, registers.size())); } switch (type) { case BIT: return Optional .of(new DecimalType((registers.getRegister(index / 16).toUnsignedShort() >> (index % 16)) & 1)); case INT8: return Optional.of(new DecimalType(registers.getRegister(index / 2).getBytes()[1 - (index % 2)])); case UINT8: return Optional.of(new DecimalType( (registers.getRegister(index / 2).toUnsignedShort() >> (8 * (index % 2))) & 0xff)); case INT16: { ByteBuffer buff = ByteBuffer.allocate(2); buff.put(registers.getRegister(index).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getShort(0))); } case UINT16: return Optional.of(new DecimalType(registers.getRegister(index).toUnsignedShort())); case INT32: { ByteBuffer buff = ByteBuffer.allocate(4); buff.put(registers.getRegister(index).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0))); } case UINT32: { ByteBuffer buff = ByteBuffer.allocate(8); buff.position(4); buff.put(registers.getRegister(index).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0))); } case FLOAT32: { ByteBuffer buff = ByteBuffer.allocate(4); buff.put(registers.getRegister(index).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); try { return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0))); } catch (NumberFormatException e) { // floating point NaN or infinity encountered return Optional.empty(); } } case INT64: { ByteBuffer buff = ByteBuffer.allocate(8); buff.put(registers.getRegister(index).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index + 2).getBytes()); buff.put(registers.getRegister(index + 3).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0))); } case UINT64: { ByteBuffer buff = ByteBuffer.allocate(8); buff.put(registers.getRegister(index).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index + 2).getBytes()); buff.put(registers.getRegister(index + 3).getBytes()); return Optional.of( new DecimalType(new BigDecimal(new BigInteger(1, buff.order(ByteOrder.BIG_ENDIAN).array())))); } case INT32_SWAP: { ByteBuffer buff = ByteBuffer.allocate(4); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0))); } case UINT32_SWAP: { ByteBuffer buff = ByteBuffer.allocate(8); buff.position(4); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0))); } case FLOAT32_SWAP: { ByteBuffer buff = ByteBuffer.allocate(4); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index).getBytes()); try { return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0))); } catch (NumberFormatException e) { // floating point NaN or infinity encountered return Optional.empty(); } } case INT64_SWAP: { ByteBuffer buff = ByteBuffer.allocate(8); buff.put(registers.getRegister(index + 3).getBytes()); buff.put(registers.getRegister(index + 2).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index).getBytes()); return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0))); } case UINT64_SWAP: { ByteBuffer buff = ByteBuffer.allocate(8); buff.put(registers.getRegister(index + 3).getBytes()); buff.put(registers.getRegister(index + 2).getBytes()); buff.put(registers.getRegister(index + 1).getBytes()); buff.put(registers.getRegister(index).getBytes()); return Optional.of( new DecimalType(new BigDecimal(new BigInteger(1, buff.order(ByteOrder.BIG_ENDIAN).array())))); } default: throw new IllegalArgumentException(type.getConfigValue()); } }
From source file:net.pms.util.AudioUtils.java
/** * Parses the old RealAudio 1.0 and 2.0 formats that's not supported by * neither {@link org.jaudiotagger} nor MediaInfo. Returns {@code false} if * {@code channel} isn't one of these formats or the parsing fails. * <p>//from ww w . j a va 2 s. com * Primary references: * <ul> * <li><a href="https://wiki.multimedia.cx/index.php/RealMedia">RealAudio on * MultimediaWiki</a></li> * <li><a * href="https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/rmdec.c" * >FFmpeg rmdec.c</a></li> * </ul> * * @param channel the {@link Channel} containing the input. Size will only * be parsed if {@code channel} is a {@link FileChannel} * instance. * @param media the {@link DLNAMediaInfo} instance to write the parsing * results to. * @return {@code true} if the {@code channel} input is in RealAudio 1.0 or * 2.0 format and the parsing succeeds; false otherwise */ public static boolean parseRealAudio(ReadableByteChannel channel, DLNAMediaInfo media) { final byte[] magicBytes = { 0x2E, 0x72, 0x61, (byte) 0xFD }; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.BIG_ENDIAN); DLNAMediaAudio audio = new DLNAMediaAudio(); try { int count = channel.read(buffer); if (count < 4) { LOGGER.trace("Input is too short to be RealAudio"); return false; } buffer.flip(); byte[] signature = new byte[4]; buffer.get(signature); if (!Arrays.equals(magicBytes, signature)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Input signature ({}) mismatches RealAudio version 1.0 or 2.0", new String(signature, StandardCharsets.US_ASCII)); } return false; } media.setContainer(FormatConfiguration.RA); short version = buffer.getShort(); int reportedHeaderSize = 0; int reportedDataSize = 0; if (version == 3) { audio.setCodecA(FormatConfiguration.REALAUDIO_14_4); audio.getAudioProperties().setNumberOfChannels(1); audio.getAudioProperties().setSampleFrequency(8000); short headerSize = buffer.getShort(); buffer = ByteBuffer.allocate(headerSize); channel.read(buffer); buffer.flip(); buffer.position(8); int bytesPerMinute = buffer.getShort() & 0xFFFF; reportedDataSize = buffer.getInt(); byte b = buffer.get(); if (b != 0) { byte[] title = new byte[b & 0xFF]; buffer.get(title); String titleString = new String(title, StandardCharsets.US_ASCII); audio.setSongname(titleString); audio.setAudioTrackTitleFromMetadata(titleString); } b = buffer.get(); if (b != 0) { byte[] artist = new byte[b & 0xFF]; buffer.get(artist); audio.setArtist(new String(artist, StandardCharsets.US_ASCII)); } audio.setBitRate(bytesPerMinute * 8 / 60); media.setBitrate(bytesPerMinute * 8 / 60); } else if (version == 4 || version == 5) { buffer = ByteBuffer.allocate(14); channel.read(buffer); buffer.flip(); buffer.get(signature); if (!".ra4".equals(new String(signature, StandardCharsets.US_ASCII))) { LOGGER.debug("Invalid RealAudio 2.0 signature \"{}\"", new String(signature, StandardCharsets.US_ASCII)); return false; } reportedDataSize = buffer.getInt(); buffer.getShort(); //skip version repeated reportedHeaderSize = buffer.getInt(); buffer = ByteBuffer.allocate(reportedHeaderSize); channel.read(buffer); buffer.flip(); buffer.getShort(); // skip codec flavor buffer.getInt(); // skip coded frame size buffer.getInt(); // skip unknown long bytesPerMinute = buffer.getInt() & 0xFFFFFFFFL; buffer.getInt(); // skip unknown buffer.getShort(); // skip sub packet buffer.getShort(); // skip frame size buffer.getShort(); // skip sub packet size buffer.getShort(); // skip unknown if (version == 5) { buffer.position(buffer.position() + 6); // skip unknown } short sampleRate = buffer.getShort(); buffer.getShort(); // skip unknown short sampleSize = buffer.getShort(); short nrChannels = buffer.getShort(); byte[] fourCC; if (version == 4) { buffer.position(buffer.get() + buffer.position()); // skip interleaver id fourCC = new byte[buffer.get()]; buffer.get(fourCC); } else { buffer.getFloat(); // skip deinterlace id fourCC = new byte[4]; buffer.get(fourCC); } String fourCCString = new String(fourCC, StandardCharsets.US_ASCII).toLowerCase(Locale.ROOT); switch (fourCCString) { case "lpcJ": audio.setCodecA(FormatConfiguration.REALAUDIO_14_4); break; case "28_8": audio.setCodecA(FormatConfiguration.REALAUDIO_28_8); break; case "dnet": audio.setCodecA(FormatConfiguration.AC3); break; case "sipr": audio.setCodecA(FormatConfiguration.SIPRO); break; case "cook": audio.setCodecA(FormatConfiguration.COOK); case "atrc": audio.setCodecA(FormatConfiguration.ATRAC); case "ralf": audio.setCodecA(FormatConfiguration.RALF); case "raac": audio.setCodecA(FormatConfiguration.AAC_LC); case "racp": audio.setCodecA(FormatConfiguration.HE_AAC); default: LOGGER.debug("Unknown RealMedia codec FourCC \"{}\" - parsing failed", fourCCString); return false; } if (buffer.hasRemaining()) { parseRealAudioMetaData(buffer, audio, version); } audio.setBitRate((int) (bytesPerMinute * 8 / 60)); media.setBitrate((int) (bytesPerMinute * 8 / 60)); audio.setBitsperSample(sampleSize); audio.getAudioProperties().setNumberOfChannels(nrChannels); audio.getAudioProperties().setSampleFrequency(sampleRate); } else { LOGGER.error("Could not parse RealAudio format - unknown format version {}", version); return false; } media.getAudioTracksList().add(audio); long fileSize = 0; if (channel instanceof FileChannel) { fileSize = ((FileChannel) channel).size(); media.setSize(fileSize); } // Duration is estimated based on bitrate and might not be accurate if (audio.getBitRate() > 0) { int dataSize; if (fileSize > 0 && reportedHeaderSize > 0) { int fullHeaderSize = reportedHeaderSize + (version == 3 ? 8 : 16); if (reportedDataSize > 0) { dataSize = (int) Math.min(reportedDataSize, fileSize - fullHeaderSize); } else { dataSize = (int) (fileSize - fullHeaderSize); } } else { dataSize = reportedDataSize; } media.setDuration((double) dataSize / audio.getBitRate() * 8); } } catch (IOException e) { LOGGER.debug("Error while trying to parse RealAudio version 1 or 2: {}", e.getMessage()); LOGGER.trace("", e); return false; } if (PMS.getConfiguration() != null && !PMS.getConfiguration().getAudioThumbnailMethod().equals(CoverSupplier.NONE) && (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname()) || StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist()))) { ID3v1Tag tag = new ID3v1Tag(); if (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())) { tag.setTitle(media.getFirstAudioTrack().getSongname()); } if (StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist())) { tag.setArtist(media.getFirstAudioTrack().getArtist()); } try { media.setThumb(DLNAThumbnail.toThumbnail(CoverUtil.get().getThumbnail(tag), 640, 480, ScaleType.MAX, ImageFormat.SOURCE, false)); } catch (IOException e) { LOGGER.error("An error occurred while generating thumbnail for RealAudio source: [\"{}\", \"{}\"]", tag.getFirstTitle(), tag.getFirstArtist()); } } media.setThumbready(true); media.setMediaparsed(true); return true; }
From source file:io.warp10.quasar.trl.QuasarTokenRevocationListLoader.java
public void loadTrl() { try {/* w ww . j av a 2 s . co m*/ QuasarTRL quasarTRL = null; // // Sensision metrics thread heart beat // Sensision.event(QuasarTokenFilterSensisionConstants.SENSISION_CLASS_QUASAR_FILTER_TRL_COUNT, labels, 1); // // get all files in the directory // String[] files = getFolderFiles(path); // // extract the most recent files per warp.type // Map<String, JavaTRLLoaded> latest = latestFilesToRead(files); boolean update = updateTRL(read, latest); if (update) { long now = System.currentTimeMillis(); // sum files size int size = getSipHashesSize(latest.values()); // load the selected files for (Map.Entry<String, JavaTRLLoaded> entry : latest.entrySet()) { if (null == quasarTRL) { quasarTRL = new QuasarTRL(size); } // // Read the token revocation list // BufferedReader br = null; try { br = new BufferedReader(new FileReader(new File(path, entry.getValue().fileName))); while (true) { String line = br.readLine(); if (null == line) { break; } line = line.trim(); // application if (line.startsWith(QuasarConfiguration.WARP_APPLICATION_PREFIX)) { // compute the sip hash with the app name long appSipHash = getApplicationHash(line.substring(1)); quasarTRL.revokeApplication(appSipHash); } else { // token sip hash hex encoded convert it into long byte[] bytes = Hex.decodeHex(line.toCharArray()); long tokenRevoked = ByteBuffer.wrap(bytes, 0, 8).order(ByteOrder.BIG_ENDIAN) .getLong(); // add it to the future trl list quasarTRL.revokeToken(tokenRevoked); } } // mark as readed read.put(entry.getKey(), entry.getValue()); } catch (Exception exp) { exp.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { } } } } // end for all files if (0 != quasarTRLLoadedHandler.size() && null != quasarTRL) { // // sort and switch the new trl // quasarTRL.sortTokens(); // // call all the handlers // for (QuasarTRLLoadedHandler handler : quasarTRLLoadedHandler) { handler.onQuasarTRL(quasarTRL); } currentTrl = quasarTRL; // // Sensision trl loaded // long timeElapsed = System.currentTimeMillis() - now; Sensision.event(QuasarTokenFilterSensisionConstants.SENSISION_CLASS_QUASAR_FILTER_TRL_LOAD_TIME, labels, timeElapsed); Sensision.event( QuasarTokenFilterSensisionConstants.SENSISION_CLASS_QUASAR_FILTER_TRL_TOKENS_COUNT, labels, quasarTRL.getTrlSize()); } } // end if update } catch (Exception exp) { // thread error Sensision.update(QuasarTokenFilterSensisionConstants.SENSISION_CLASS_QUASAR_FILTER_TRL_ERROR_COUNT, labels, 1); } }
From source file:com.slytechs.capture.FileFactory.java
public FileCapture<? extends FilePacket> newFile(final FormatType type, final File file) throws IOException { final FileCapture<? extends FilePacket> f; if (type == FormatType.Pcap) { f = PcapFileCapture.createFile(file, FileMode.ReadWrite, ByteOrder.BIG_ENDIAN, null); } else if (type == FormatType.Snoop) { f = SnoopFileCapture.createFile(file, FileMode.ReadWrite, null); } else {//from w w w.j a v a 2 s . c o m throw new IllegalArgumentException("Unknown file format type [" + type + "] specified"); } return f; }
From source file:org.xenei.bloomgraph.SerializableNode.java
/** * Get the byte buffer for this node.//from w w w . j a v a 2 s .c o m * * @return the byte buffer for this node. */ public ByteBuffer getByteBuffer() { if (buffer == null) { buffer = ByteBuffer.wrap(value).order(ByteOrder.BIG_ENDIAN); } return buffer; }
From source file:io.fabric8.maven.docker.access.log.LogRequestor.java
private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException { // Read the header, which is composed of eight bytes. The first byte is an integer // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown // out, and the final four are the size of the remaining stream as an integer. ByteBuffer headerBuffer = ByteBuffer.allocate(8); headerBuffer.order(ByteOrder.BIG_ENDIAN); try {/*w ww.j a v a 2 s . c o m*/ this.readFully(is, headerBuffer.array()); } catch (NoBytesReadException e) { // Not bytes read for stream. Return false to stop consuming stream. return false; } catch (EOFException e) { throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e); } // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes. int type = headerBuffer.get(); // Skip three bytes, then read size from remaining four bytes. int size = headerBuffer.getInt(4); // Ignore empty messages and keep reading. if (size <= 0) { return true; } // Read the actual message ByteBuffer payload = ByteBuffer.allocate(size); try { ByteStreams.readFully(is, payload.array()); } catch (EOFException e) { throw new IOException("Failed to read log message. Could not read all " + size + " bytes. " + e.getMessage() + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e); } String message = Charsets.UTF_8.newDecoder().decode(payload).toString(); callLogCallback(type, message); return true; }