List of usage examples for java.nio ByteBuffer getShort
public abstract short getShort();
From source file:org.energy_home.jemma.osgi.ah.io.flexgateway.FlexGatewayButtons.java
public void run() { long tv_sec;//from w w w .ja v a2s . c o m long tv_usec; short type; short code; int value; while (true) { buttonFile = new File(flexGatewayButtonsDevice); ByteBuffer buffer = ByteBuffer.allocate(100); buffer.order(ByteOrder.nativeOrder()); try { fis = new FileInputStream(buttonFile); channel = fis.getChannel(); while (true) { buffer.clear(); int size = channel.read(buffer); buffer.rewind(); while (size > 0) { tv_sec = buffer.getInt(); tv_usec = buffer.getInt(); long tv = tv_sec * 1000000 + tv_usec; type = buffer.getShort(); code = buffer.getShort(); value = buffer.getInt(); size -= 16; if (type == 0 && code == 0 && value == 0) continue; // Code 3 -> front button // Code 2 -> back button // Value > 0 -> button pressed // Value > 0 -> button released // send event log.debug("Button: ms " + tv + " type " + (type & 0xffff) + " code " + (code & 0xffff) + " value " + (value & 0xffffffff)); Hashtable props = new Hashtable(); props.put("timestamp", new Long(tv)); if (value > 0) this.postEvent("button/" + code + "/UP", props); else this.postEvent("button/" + code + "/DOWN", props); } } } catch (ClosedByInterruptException e) { break; } catch (IOException e) { // TODO Auto-generated catch block log.error("exception", e); break; } finally { try { if (channel != null) channel.close(); } catch (IOException e) { log.error("exception", e); break; } } } log.debug("exiting"); }
From source file:org.apache.hadoop.hbase.io.encoding.EncodedDataBlock.java
/** * Do the encoding, but do not cache the encoded data. * @return encoded data block with header and checksum *//*from w w w .j a v a2s . c o m*/ public byte[] encodeData() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(HConstants.HFILEBLOCK_DUMMY_HEADER); DataOutputStream out = new DataOutputStream(baos); this.dataBlockEncoder.startBlockEncoding(encodingCtx, out); ByteBuffer in = getUncompressedBuffer(); in.rewind(); int klength, vlength; short tagsLength = 0; long memstoreTS = 0L; KeyValue kv = null; while (in.hasRemaining()) { int kvOffset = in.position(); klength = in.getInt(); vlength = in.getInt(); ByteBufferUtils.skip(in, klength + vlength); if (this.meta.isIncludesTags()) { tagsLength = in.getShort(); ByteBufferUtils.skip(in, tagsLength); } if (this.meta.isIncludesMvcc()) { memstoreTS = ByteBufferUtils.readVLong(in); } kv = new KeyValue(in.array(), kvOffset, (int) KeyValue.getKeyValueDataStructureSize(klength, vlength, tagsLength)); kv.setMvccVersion(memstoreTS); this.dataBlockEncoder.encode(kv, encodingCtx, out); } BufferGrabbingByteArrayOutputStream stream = new BufferGrabbingByteArrayOutputStream(); baos.writeTo(stream); this.dataBlockEncoder.endBlockEncoding(encodingCtx, out, stream.buf); } catch (IOException e) { throw new RuntimeException(String.format("Bug in encoding part of algorithm %s. " + "Probably it requested more bytes than are available.", toString()), e); } return baos.toByteArray(); }
From source file:tor.TorCircuit.java
public boolean handleCell(Cell c) throws IOException { boolean handled = false; if (receiveWindow < 900) { //System.out.println("sent SENDME (CIRCUIT): " + receiveWindow); send(null, RELAY_SENDME, false, (short) 0); receiveWindow += 100;/*from www . j a va2 s.co m*/ } if (state == STATES.DESTROYED) { log.error("Trying to use destroyed circuit"); throw new RuntimeException("Trying to use destroyed circuit"); } if (c.cmdId == Cell.CREATED) // create { handleCreated(c.payload); if (!circuitToBuild.isEmpty()) {// more? boolean block = blocking; setBlocking(false); extend(circuitToBuild.removeFirst()); setBlocking(block); } handled = true; } else if (c.cmdId == Cell.RELAY_EARLY || c.cmdId == Cell.PADDING || c.cmdId == Cell.VPADDING) { // these are used in deanon attacks log.error("WARNING**** cell CMD " + c.cmdId + " received in - Possible DEANON attack!!: Route: " + hops.toArray()); } else if (c.cmdId == Cell.RELAY) // relay cell { // cell decrypt logic - decrypt from each hop in turn checking recognised and digest until success // remember, we can receive cells from intermediate hops, so it's an iterative decrypt and check if successful // for each hop. int cellFromHop = -1; for (int di = 0; di < hops.size(); di++) { // loop through circuit hops TorHop hop = hops.get(di); c.payload = hop.decrypt(c.payload); // decrypt for this hop if (c.payload[1] == 0 && c.payload[2] == 0) { // are recognised bytes set to zero? byte nodgrl[] = relayCellRemoveDigest(c.payload); // remove digest from cell byte hash[] = Arrays.copyOfRange(c.payload, 5, 9); // put digest from cell into hash byte[] digest; try { // calculate the digest that we thing it should be // must clone here to stop clobbering original digest = ((MessageDigest) hop.db_md.clone()).digest(nodgrl); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } // compare our calculations with digest in cell - if right, we've decrypted correctly if (Arrays.equals(hash, Arrays.copyOfRange(digest, 0, 4))) { hop.db_md.update(nodgrl); // update digest for hop for future cells cellFromHop = di; // hop number this cell is from break; } } } if (cellFromHop == -1) { log.warn("unrecognised cell - didn't decrypt"); return false; } // successfully decrypted - now let's proceed // decode relay header ByteBuffer buf = ByteBuffer.wrap(c.payload); int cmd = buf.get(); if (buf.getShort() != 0) { log.warn("invalid relay cell"); return false; } int streamid = buf.getShort(); int digest = buf.getInt(); int length = buf.getShort(); byte data[] = Arrays.copyOfRange(c.payload, 1 + 2 + 2 + 4 + 2, 1 + 2 + 2 + 4 + 2 + length); // now pass cell off to handler function below handled = handleRelayCell(cmd, streamid, cellFromHop, data); } else if (c.cmdId == Cell.DESTROY) { log.info("Circuit destroyed " + circId); log.info("Reason: " + DESTROY_ERRORS[c.payload[0]]); for (TorStream s : streams.values()) { s.notifyDisconnect(); } setState(STATES.DESTROYED); handled = true; } return handled; }
From source file:org.opendaylight.lispflowmapping.lisp.serializer.MappingRecordSerializer.java
public MappingRecordBuilder deserializeToBuilder(ByteBuffer buffer) { MappingRecordBuilder builder = new MappingRecordBuilder(); builder.setRecordTtl(buffer.getInt()); byte locatorCount = (byte) ByteUtil.getUnsignedByte(buffer); builder.setMaskLength((short) ByteUtil.getUnsignedByte(buffer)); byte actionAndAuthoritative = buffer.get(); Action act = Action.forValue(actionAndAuthoritative >> 5); if (act == null) { act = Action.NoAction;/*from w ww.j av a2 s .c o m*/ } builder.setAction(act); builder.setAuthoritative(ByteUtil.extractBit(actionAndAuthoritative, Flags.AUTHORITATIVE)); buffer.position(buffer.position() + Length.RESERVED); builder.setMapVersion(buffer.getShort()); LispAddressSerializerContext ctx = new LispAddressSerializerContext(builder.getMaskLength()); builder.setEid(LispAddressSerializer.getInstance().deserializeEid(buffer, ctx)); builder.setLocatorRecord(new ArrayList<LocatorRecord>()); for (int i = 0; i < locatorCount; i++) { builder.getLocatorRecord().add(LocatorRecordSerializer.getInstance().deserialize(buffer)); } builder.setTimestamp(System.currentTimeMillis()); return builder; }
From source file:org.opendaylight.lispflowmapping.implementation.serializer.EidToLocatorRecordSerializer.java
public EidToLocatorRecord deserialize(ByteBuffer buffer) { EidToLocatorRecordBuilder builder = new EidToLocatorRecordBuilder(); builder.setRecordTtl(buffer.getInt()); byte locatorCount = (byte) ByteUtil.getUnsignedByte(buffer); builder.setMaskLength((short) ByteUtil.getUnsignedByte(buffer)); byte actionAndAuthoritative = buffer.get(); Action act = Action.forValue(actionAndAuthoritative >> 5); if (act == null) { act = Action.NoAction;/*from ww w . j ava 2 s . co m*/ } builder.setAction(act); builder.setAuthoritative(ByteUtil.extractBit(actionAndAuthoritative, Flags.AUTHORITATIVE)); buffer.position(buffer.position() + Length.RESERVED); builder.setMapVersion(buffer.getShort()); LispAFIAddress afiAddress = LispAddressSerializer.getInstance().deserialize(buffer); LispAddressContainer container = LispAFIConvertor.toContainer(afiAddress); builder.setLispAddressContainer(container); builder.setLocatorRecord(new ArrayList<LocatorRecord>()); for (int i = 0; i < locatorCount; i++) { builder.getLocatorRecord().add(LocatorRecordSerializer.getInstance().deserialize(buffer)); } return builder.build(); }
From source file:org.apache.hadoop.hbase.io.hfile.TestHFileWriterV3.java
private void writeDataAndReadFromHFile(Path hfilePath, Algorithm compressAlgo, int entryCount, boolean findMidKey, boolean useTags) throws IOException { HFileContext context = new HFileContextBuilder().withBlockSize(4096).withIncludesTags(useTags) .withCompression(compressAlgo).build(); HFileWriterV3 writer = (HFileWriterV3) new HFileWriterV3.WriterFactoryV3(conf, new CacheConfig(conf)) .withPath(fs, hfilePath).withFileContext(context).withComparator(KeyValue.COMPARATOR).create(); Random rand = new Random(9713312); // Just a fixed seed. List<KeyValue> keyValues = new ArrayList<KeyValue>(entryCount); for (int i = 0; i < entryCount; ++i) { byte[] keyBytes = TestHFileWriterV2.randomOrderedKey(rand, i); // A random-length random value. byte[] valueBytes = TestHFileWriterV2.randomValue(rand); KeyValue keyValue = null; if (useTags) { ArrayList<Tag> tags = new ArrayList<Tag>(); for (int j = 0; j < 1 + rand.nextInt(4); j++) { byte[] tagBytes = new byte[16]; rand.nextBytes(tagBytes); tags.add(new Tag((byte) 1, tagBytes)); }//ww w .j a va2s. c o m keyValue = new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes, tags); } else { keyValue = new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes); } writer.append(keyValue); keyValues.add(keyValue); } // Add in an arbitrary order. They will be sorted lexicographically by // the key. writer.appendMetaBlock("CAPITAL_OF_USA", new Text("Washington, D.C.")); writer.appendMetaBlock("CAPITAL_OF_RUSSIA", new Text("Moscow")); writer.appendMetaBlock("CAPITAL_OF_FRANCE", new Text("Paris")); writer.close(); FSDataInputStream fsdis = fs.open(hfilePath); long fileSize = fs.getFileStatus(hfilePath).getLen(); FixedFileTrailer trailer = FixedFileTrailer.readFromStream(fsdis, fileSize); assertEquals(3, trailer.getMajorVersion()); assertEquals(entryCount, trailer.getEntryCount()); HFileContext meta = new HFileContextBuilder().withCompression(compressAlgo).withIncludesMvcc(false) .withIncludesTags(useTags).withHBaseCheckSum(true).build(); HFileBlock.FSReader blockReader = new HFileBlock.FSReaderV2(fsdis, fileSize, meta); // Comparator class name is stored in the trailer in version 2. KVComparator comparator = trailer.createComparator(); HFileBlockIndex.BlockIndexReader dataBlockIndexReader = new HFileBlockIndex.BlockIndexReader(comparator, trailer.getNumDataIndexLevels()); HFileBlockIndex.BlockIndexReader metaBlockIndexReader = new HFileBlockIndex.BlockIndexReader( KeyValue.RAW_COMPARATOR, 1); HFileBlock.BlockIterator blockIter = blockReader.blockRange(trailer.getLoadOnOpenDataOffset(), fileSize - trailer.getTrailerSize()); // Data index. We also read statistics about the block index written after // the root level. dataBlockIndexReader.readMultiLevelIndexRoot(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount()); if (findMidKey) { byte[] midkey = dataBlockIndexReader.midkey(); assertNotNull("Midkey should not be null", midkey); } // Meta index. metaBlockIndexReader.readRootIndex(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX).getByteStream(), trailer.getMetaIndexCount()); // File info FileInfo fileInfo = new FileInfo(); fileInfo.read(blockIter.nextBlockWithBlockType(BlockType.FILE_INFO).getByteStream()); byte[] keyValueFormatVersion = fileInfo.get(HFileWriterV3.KEY_VALUE_VERSION); boolean includeMemstoreTS = keyValueFormatVersion != null && Bytes.toInt(keyValueFormatVersion) > 0; // Counters for the number of key/value pairs and the number of blocks int entriesRead = 0; int blocksRead = 0; long memstoreTS = 0; // Scan blocks the way the reader would scan them fsdis.seek(0); long curBlockPos = 0; while (curBlockPos <= trailer.getLastDataBlockOffset()) { HFileBlock block = blockReader.readBlockData(curBlockPos, -1, -1, false); assertEquals(BlockType.DATA, block.getBlockType()); ByteBuffer buf = block.getBufferWithoutHeader(); int keyLen = -1; while (buf.hasRemaining()) { keyLen = buf.getInt(); int valueLen = buf.getInt(); byte[] key = new byte[keyLen]; buf.get(key); byte[] value = new byte[valueLen]; buf.get(value); byte[] tagValue = null; if (useTags) { int tagLen = buf.getShort(); tagValue = new byte[tagLen]; buf.get(tagValue); } if (includeMemstoreTS) { ByteArrayInputStream byte_input = new ByteArrayInputStream(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); DataInputStream data_input = new DataInputStream(byte_input); memstoreTS = WritableUtils.readVLong(data_input); buf.position(buf.position() + WritableUtils.getVIntSize(memstoreTS)); } // A brute-force check to see that all keys and values are correct. assertTrue(Bytes.compareTo(key, keyValues.get(entriesRead).getKey()) == 0); assertTrue(Bytes.compareTo(value, keyValues.get(entriesRead).getValue()) == 0); if (useTags) { assertNotNull(tagValue); KeyValue tkv = keyValues.get(entriesRead); assertEquals(tagValue.length, tkv.getTagsLength()); assertTrue(Bytes.compareTo(tagValue, 0, tagValue.length, tkv.getTagsArray(), tkv.getTagsOffset(), tkv.getTagsLength()) == 0); } ++entriesRead; } ++blocksRead; curBlockPos += block.getOnDiskSizeWithHeader(); } LOG.info("Finished reading: entries=" + entriesRead + ", blocksRead=" + blocksRead); assertEquals(entryCount, entriesRead); // Meta blocks. We can scan until the load-on-open data offset (which is // the root block index offset in version 2) because we are not testing // intermediate-level index blocks here. int metaCounter = 0; while (fsdis.getPos() < trailer.getLoadOnOpenDataOffset()) { LOG.info("Current offset: " + fsdis.getPos() + ", scanning until " + trailer.getLoadOnOpenDataOffset()); HFileBlock block = blockReader.readBlockData(curBlockPos, -1, -1, false); assertEquals(BlockType.META, block.getBlockType()); Text t = new Text(); ByteBuffer buf = block.getBufferWithoutHeader(); if (Writables.getWritable(buf.array(), buf.arrayOffset(), buf.limit(), t) == null) { throw new IOException( "Failed to deserialize block " + this + " into a " + t.getClass().getSimpleName()); } Text expectedText = (metaCounter == 0 ? new Text("Paris") : metaCounter == 1 ? new Text("Moscow") : new Text("Washington, D.C.")); assertEquals(expectedText, t); LOG.info("Read meta block data: " + t); ++metaCounter; curBlockPos += block.getOnDiskSizeWithHeader(); } fsdis.close(); }
From source file:guru.benson.pinch.Pinch.java
/** * Parses the ZIP central directory from a byte buffer. * * @param data//from w ww . j a v a2s .c om * The byte buffer to be parsed. * * @return {@code true} if central directory was parsed, otherwise {@code false} */ private boolean parseEndOfCentralDirectory(byte[] data) { byte[] zipEndSignature = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN) .putInt((int) ZipConstants.ENDSIG).array(); // find start of ZIP archive signature. int index = KMPMatch.indexOf(data, zipEndSignature); if (index < 0) { return false; } // wrap our head around a part of the buffer starting with index. ByteBuffer buf = ByteBuffer.wrap(data, index, data.length - index); buf.order(ByteOrder.LITTLE_ENDIAN); /* * For ZIP header descriptions, see * http://en.wikipedia.org/wiki/ZIP_(file_format)#File_headers */ // skip signature buf.getInt(); // skip numberOfThisDisk buf.getShort(); // skip diskWhereCentralDirectoryStarts = buf.getShort(); // skip numberOfCentralDirectoriesOnThisDisk buf.getShort(); entriesCount = buf.getShort(); centralDirectorySize = buf.getInt(); centralDirectoryOffset = buf.getInt(); zipFileCommentLength = buf.getShort(); return true; }
From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java
public com.alliander.osgp.dto.valueobjects.smartmetering.CosemDateTime fromDateTimeValue( final byte[] dateTimeValue) throws ProtocolAdapterException { final ByteBuffer bb = ByteBuffer.wrap(dateTimeValue); final int year = bb.getShort() & 0xFFFF; final int monthOfYear = bb.get() & 0xFF; final int dayOfMonth = bb.get() & 0xFF; final int dayOfWeek = bb.get() & 0xFF; final int hourOfDay = bb.get() & 0xFF; final int minuteOfHour = bb.get() & 0xFF; final int secondOfMinute = bb.get() & 0xFF; final int hundredthsOfSecond = bb.get() & 0xFF; final int deviation = bb.getShort(); final byte clockStatusValue = bb.get(); final com.alliander.osgp.dto.valueobjects.smartmetering.CosemDate date = new com.alliander.osgp.dto.valueobjects.smartmetering.CosemDate( year, monthOfYear, dayOfMonth, dayOfWeek); final com.alliander.osgp.dto.valueobjects.smartmetering.CosemTime time = new com.alliander.osgp.dto.valueobjects.smartmetering.CosemTime( hourOfDay, minuteOfHour, secondOfMinute, hundredthsOfSecond); final com.alliander.osgp.dto.valueobjects.smartmetering.ClockStatus clockStatus = new com.alliander.osgp.dto.valueobjects.smartmetering.ClockStatus( clockStatusValue);/*w ww . j ava 2 s.c o m*/ return new com.alliander.osgp.dto.valueobjects.smartmetering.CosemDateTime(date, time, deviation, clockStatus); }
From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java
public String getDebugInfoDateTimeBytes(final byte[] dateTimeValue) { if (dateTimeValue.length != 12) { throw new IllegalArgumentException("DateTime values should be 12 bytes long: " + dateTimeValue.length); }// w w w .j av a2 s . c om final StringBuilder sb = new StringBuilder(); final ByteBuffer bb = ByteBuffer.wrap(dateTimeValue); final int year = bb.getShort(); final int monthOfYear = bb.get(); final int dayOfMonth = bb.get(); final int dayOfWeek = bb.get(); final int hourOfDay = bb.get(); final int minuteOfHour = bb.get(); final int secondOfMinute = bb.get(); final int hundredthsOfSecond = bb.get(); final int deviation = bb.getShort(); final int clockStatus = bb.get(); sb.append("year=").append(year).append(", month=").append(monthOfYear).append(", day=").append(dayOfMonth) .append(", weekday=").append(dayOfWeek).append(", hour=").append(hourOfDay).append(", minute=") .append(minuteOfHour).append(", second=").append(secondOfMinute).append(", hundredths=") .append(hundredthsOfSecond).append(", deviation=").append(deviation).append(", clockstatus=") .append(clockStatus); return sb.toString(); }
From source file:org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer.java
public MapNotify deserialize(ByteBuffer notifyBuffer) { try {//from ww w. ja v a 2 s .c o m MapNotifyBuilder builder = new MapNotifyBuilder(); builder.setMappingRecordItem(new ArrayList<MappingRecordItem>()); byte typeAndFlags = notifyBuffer.get(); boolean xtrSiteIdPresent = ByteUtil.extractBit(typeAndFlags, Flags.XTRSITEID); builder.setXtrSiteIdPresent(xtrSiteIdPresent); notifyBuffer.position(notifyBuffer.position() + Length.RES); builder.setMergeEnabled(ByteUtil.extractBit(notifyBuffer.get(), Flags.MERGE_ENABLED)); byte recordCount = (byte) ByteUtil.getUnsignedByte(notifyBuffer); builder.setNonce(notifyBuffer.getLong()); builder.setKeyId(notifyBuffer.getShort()); short authenticationLength = notifyBuffer.getShort(); byte[] authenticationData = new byte[authenticationLength]; notifyBuffer.get(authenticationData); builder.setAuthenticationData(authenticationData); if (xtrSiteIdPresent) { List<MappingRecordBuilder> mrbs = new ArrayList<MappingRecordBuilder>(); for (int i = 0; i < recordCount; i++) { mrbs.add(MappingRecordSerializer.getInstance().deserializeToBuilder(notifyBuffer)); } byte[] xtrIdBuf = new byte[MapRegisterSerializer.Length.XTRID_SIZE]; notifyBuffer.get(xtrIdBuf); XtrId xtrId = new XtrId(xtrIdBuf); byte[] siteIdBuf = new byte[MapRegisterSerializer.Length.SITEID_SIZE]; notifyBuffer.get(siteIdBuf); SiteId siteId = new SiteId(siteIdBuf); builder.setXtrId(xtrId); builder.setSiteId(siteId); for (MappingRecordBuilder mrb : mrbs) { mrb.setXtrId(xtrId); mrb.setSiteId(siteId); builder.getMappingRecordItem() .add(new MappingRecordItemBuilder().setMappingRecord(mrb.build()).build()); } } else { for (int i = 0; i < recordCount; i++) { builder.getMappingRecordItem() .add(new MappingRecordItemBuilder() .setMappingRecord( MappingRecordSerializer.getInstance().deserialize(notifyBuffer)) .build()); } } notifyBuffer.limit(notifyBuffer.position()); return builder.build(); } catch (RuntimeException re) { throw new LispSerializationException( "Couldn't deserialize Map-Notify (len=" + notifyBuffer.capacity() + ")", re); } }