List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:com.healthmarketscience.jackcess.impl.TableImpl.java
/** * Create a new data page/*from w ww . j a v a2 s .c om*/ * @return Page number of the new page */ private ByteBuffer newDataPage() throws IOException { ByteBuffer dataPage = _addRowBufferH.setNewPage(getPageChannel()); dataPage.put(PageTypes.DATA); //Page type dataPage.put((byte) 1); //Unknown dataPage.putShort((short) getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space in this page dataPage.putInt(_tableDefPageNumber); //Page pointer to table definition dataPage.putInt(0); //Unknown dataPage.putShort((short) 0); //Number of rows on this page int pageNumber = _addRowBufferH.getPageNumber(); getPageChannel().writePage(dataPage, pageNumber); _ownedPages.addPageNumber(pageNumber); _freeSpacePages.addPageNumber(pageNumber); return dataPage; }
From source file:com.healthmarketscience.jackcess.impl.TableImpl.java
/** * Returns a single ByteBuffer which contains the entire table definition * (which may span multiple database pages). */// w ww.j ava 2 s.co m private ByteBuffer loadCompleteTableDefinitionBuffer(ByteBuffer tableBuffer) throws IOException { int nextPage = tableBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE); ByteBuffer nextPageBuffer = null; while (nextPage != 0) { if (nextPageBuffer == null) { nextPageBuffer = getPageChannel().createPageBuffer(); } getPageChannel().readPage(nextPageBuffer, nextPage); nextPage = nextPageBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE); ByteBuffer newBuffer = PageChannel.createBuffer(tableBuffer.capacity() + getFormat().PAGE_SIZE - 8); newBuffer.put(tableBuffer); newBuffer.put(nextPageBuffer.array(), 8, getFormat().PAGE_SIZE - 8); tableBuffer = newBuffer; tableBuffer.flip(); } return tableBuffer; }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Writes a numeric value.// w ww .j a v a2 s . c o m */ private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException { Object inValue = value; try { BigDecimal decVal = toBigDecimal(value); inValue = decVal; boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0); if (negative) { decVal = decVal.negate(); } // write sign byte buffer.put(negative ? (byte) 0x80 : (byte) 0); // adjust scale according to this column type (will cause the an // ArithmeticException if number has too many decimal places) decVal = decVal.setScale(getScale()); // check precision if (decVal.precision() > getPrecision()) { throw new IOException( "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal); } // convert to unscaled BigInteger, big-endian bytes byte[] intValBytes = decVal.unscaledValue().toByteArray(); int maxByteLen = getType().getFixedSize() - 1; if (intValBytes.length > maxByteLen) { throw new IOException("Too many bytes for valid BigInteger?"); } if (intValBytes.length < maxByteLen) { byte[] tmpBytes = new byte[maxByteLen]; System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length); intValBytes = tmpBytes; } if (buffer.order() != ByteOrder.BIG_ENDIAN) { fixNumericByteOrder(intValBytes); } buffer.put(intValBytes); } catch (ArithmeticException e) { throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e); } }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Serialize an Object into a raw byte value for this column * @param obj Object to serialize/*w w w .j a va 2s . c o m*/ * @param order Order in which to serialize * @return A buffer containing the bytes * @usage _advanced_method_ */ public ByteBuffer writeFixedLengthField(Object obj, ByteOrder order) throws IOException { int size = getType().getFixedSize(_columnLength); // create buffer for data ByteBuffer buffer = getPageChannel().createBuffer(size, order); // since booleans are not written by this method, it's safe to convert any // incoming boolean into an integer. obj = booleanToInteger(obj); switch (getType()) { case BOOLEAN: //Do nothing break; case BYTE: buffer.put(toNumber(obj).byteValue()); break; case INT: buffer.putShort(toNumber(obj).shortValue()); break; case LONG: buffer.putInt(toNumber(obj).intValue()); break; case MONEY: writeCurrencyValue(buffer, obj); break; case FLOAT: buffer.putFloat(toNumber(obj).floatValue()); break; case DOUBLE: buffer.putDouble(toNumber(obj).doubleValue()); break; case SHORT_DATE_TIME: writeDateValue(buffer, obj); break; case TEXT: // apparently text numeric values are also occasionally written as fixed // length... int numChars = getLengthInUnits(); // force uncompressed encoding for fixed length text buffer.put(encodeTextValue(obj, numChars, numChars, true)); break; case GUID: writeGUIDValue(buffer, obj, order); break; case NUMERIC: // yes, that's right, occasionally numeric values are written as fixed // length... writeNumericValue(buffer, obj); break; case BINARY: case UNKNOWN_0D: case UNKNOWN_11: case COMPLEX_TYPE: buffer.putInt(toNumber(obj).intValue()); break; case UNSUPPORTED_FIXEDLEN: byte[] bytes = toByteArray(obj); if (bytes.length != getLength()) { throw new IOException( "Invalid fixed size binary data, size " + getLength() + ", got " + bytes.length); } buffer.put(bytes); break; default: throw new IOException("Unsupported data type: " + getType()); } buffer.flip(); return buffer; }
From source file:au.org.ala.layers.intersect.Grid.java
public void mergeMissingValues(Grid sourceOfMissingValues, boolean hideMissing) { float[] cells = sourceOfMissingValues.getGrid(); float[] actual = getGrid(); int length = actual.length; int i;//from w w w . ja v a 2s.com RandomAccessFile afile = null; File f2 = new File(filename + ".GRI"); try { //read of random access file can throw an exception if (!f2.exists()) { afile = new RandomAccessFile(filename + ".gri", "rw"); } else { afile = new RandomAccessFile(filename + ".GRI", "rw"); } byte[] b = new byte[(int) afile.length()]; ByteBuffer bb = ByteBuffer.wrap(b); if (byteorderLSB) { bb.order(ByteOrder.LITTLE_ENDIAN); } afile.seek(0); if (datatype.equalsIgnoreCase("UBYTE")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { if (nodatavalue >= 128) { bb.put((byte) (nodatavalue - 256)); } else { bb.put((byte) nodatavalue); } } else { if (actual[i] >= 128) { bb.put((byte) (actual[i] - 256)); } else { bb.put((byte) actual[i]); } } } } else if (datatype.equalsIgnoreCase("BYTE")) { for (i = 0; i < length; i++) { bb.put((byte) actual[i]); } } else if (datatype.equalsIgnoreCase("SHORT")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { bb.putShort((short) nodatavalue); } else { bb.putShort((short) actual[i]); } } } else if (datatype.equalsIgnoreCase("INT")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { bb.putInt((int) nodatavalue); } else { bb.putInt((int) actual[i]); } } } else if (datatype.equalsIgnoreCase("LONG")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { bb.putLong((long) nodatavalue); } else { bb.putLong((long) actual[i]); } } } else if (datatype.equalsIgnoreCase("FLOAT")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { bb.putFloat((float) nodatavalue); } else { bb.putFloat(actual[i]); } } } else if (datatype.equalsIgnoreCase("DOUBLE")) { for (i = 0; i < length; i++) { if (hideMissing == Float.isNaN(cells[i])) { bb.putDouble((double) nodatavalue); } else { bb.putDouble((double) actual[i]); } } } else { // should not happen logger.error("unsupported grid data type: " + datatype); } afile.write(bb.array()); } catch (Exception e) { logger.error("error getting grid file values", e); } finally { if (afile != null) { try { afile.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Write an LVAL column into a ByteBuffer inline if it fits, otherwise in * other data page(s).//from w ww .j ava 2 s.com * @param value Value of the LVAL column * @return A buffer containing the LVAL definition and (possibly) the column * value (unless written to other pages) * @usage _advanced_method_ */ public ByteBuffer writeLongValue(byte[] value, int remainingRowLength) throws IOException { if (value.length > getType().getMaxSize()) { throw new IOException( "value too big for column, max " + getType().getMaxSize() + ", got " + value.length); } // determine which type to write byte type = 0; int lvalDefLen = getFormat().SIZE_LONG_VALUE_DEF; if (((getFormat().SIZE_LONG_VALUE_DEF + value.length) <= remainingRowLength) && (value.length <= getFormat().MAX_INLINE_LONG_VALUE_SIZE)) { type = LONG_VALUE_TYPE_THIS_PAGE; lvalDefLen += value.length; } else if (value.length <= getFormat().MAX_LONG_VALUE_ROW_SIZE) { type = LONG_VALUE_TYPE_OTHER_PAGE; } else { type = LONG_VALUE_TYPE_OTHER_PAGES; } ByteBuffer def = getPageChannel().createBuffer(lvalDefLen); // take length and apply type to first byte int lengthWithFlags = value.length | (type << 24); def.putInt(lengthWithFlags); if (type == LONG_VALUE_TYPE_THIS_PAGE) { // write long value inline def.putInt(0); def.putInt(0); //Unknown def.put(value); } else { TempPageHolder lvalBufferH = getTable().getLongValueBuffer(); ByteBuffer lvalPage = null; int firstLvalPageNum = PageChannel.INVALID_PAGE_NUMBER; byte firstLvalRow = 0; // write other page(s) switch (type) { case LONG_VALUE_TYPE_OTHER_PAGE: lvalPage = getLongValuePage(value.length, lvalBufferH); firstLvalPageNum = lvalBufferH.getPageNumber(); firstLvalRow = (byte) Table.addDataPageRow(lvalPage, value.length, getFormat(), 0); lvalPage.put(value); getPageChannel().writePage(lvalPage, firstLvalPageNum); break; case LONG_VALUE_TYPE_OTHER_PAGES: ByteBuffer buffer = ByteBuffer.wrap(value); int remainingLen = buffer.remaining(); buffer.limit(0); lvalPage = getLongValuePage(getFormat().MAX_LONG_VALUE_ROW_SIZE, lvalBufferH); firstLvalPageNum = lvalBufferH.getPageNumber(); int lvalPageNum = firstLvalPageNum; ByteBuffer nextLvalPage = null; int nextLvalPageNum = 0; while (remainingLen > 0) { lvalPage.clear(); // figure out how much we will put in this page (we need 4 bytes for // the next page pointer) int chunkLength = Math.min(getFormat().MAX_LONG_VALUE_ROW_SIZE - 4, remainingLen); // figure out if we will need another page, and if so, allocate it if (chunkLength < remainingLen) { // force a new page to be allocated lvalBufferH.clear(); nextLvalPage = getLongValuePage(getFormat().MAX_LONG_VALUE_ROW_SIZE, lvalBufferH); nextLvalPageNum = lvalBufferH.getPageNumber(); } else { nextLvalPage = null; nextLvalPageNum = 0; } // add row to this page byte lvalRow = (byte) Table.addDataPageRow(lvalPage, chunkLength + 4, getFormat(), 0); // write next page info (we'll always be writing into row 0 for // newly created pages) lvalPage.put((byte) 0); // row number ByteUtil.put3ByteInt(lvalPage, nextLvalPageNum); // page number // write this page's chunk of data buffer.limit(buffer.limit() + chunkLength); lvalPage.put(buffer); remainingLen -= chunkLength; // write new page to database getPageChannel().writePage(lvalPage, lvalPageNum); if (lvalPageNum == firstLvalPageNum) { // save initial row info firstLvalRow = lvalRow; } else { // check assertion that we wrote to row 0 for all subsequent pages if (lvalRow != (byte) 0) { throw new IllegalStateException("Expected row 0, but was " + lvalRow); } } // move to next page lvalPage = nextLvalPage; lvalPageNum = nextLvalPageNum; } break; default: throw new IOException("Unrecognized long value type: " + type); } // update def def.put(firstLvalRow); ByteUtil.put3ByteInt(def, firstLvalPageNum); def.putInt(0); //Unknown } def.flip(); return def; }
From source file:edu.hawaii.soest.hioos.storx.StorXParser.java
/** * Parses the binary STOR-X file. The binary file format is a sequence of * 'frames' that all begin with 'SAT'. The parser creates a list with the * individual frames. Some frames are StorX frames (SATSTX), some are from * external sensors (ISUS: 'SATNLB', 'SATNDB'; SBE CTD: 'SATSBE') * * @param fileBuffer - the binary data file as a ByteBuffer *///from w ww .ja v a 2 s . com public void parse(ByteBuffer fileBuffer) throws Exception { logger.debug("StorXParser.parse() called."); this.fileBuffer = fileBuffer; //logger.debug(this.fileBuffer.toString()); try { // Create a buffer that will store a single frame of the file ByteBuffer frameBuffer = ByteBuffer.allocate(1024); // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // --------------------------- // in ---> | Four | Three | Two | One | ---> out // --------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; int frameByteCount = 0; // keep track of bytes per frame int frameCount = 0; // keep track of frames this.fileBuffer.position(0); this.fileBuffer.limit(this.fileBuffer.capacity()); while (this.fileBuffer.hasRemaining()) { // load the next byte into the FIFO window byteOne = fileBuffer.get(); // show the byte stream coming in //logger.debug("b1: " + new String(Hex.encodeHex(new byte[]{byteOne})) + "\t" + // "b2: " + new String(Hex.encodeHex(new byte[]{byteTwo})) + "\t" + // "b3: " + new String(Hex.encodeHex(new byte[]{byteThree})) + "\t" + // "b4: " + new String(Hex.encodeHex(new byte[]{byteFour})) + "\t" + // "st: " + Integer.toString(this.state) + "\t" + // "po: " + this.fileBuffer.position() + "\t" + // "cp: " + this.fileBuffer.capacity() // ); // evaluate the bytes, separate the file frame by frame (SAT ...) switch (this.state) { case 0: // find a frame beginning (SAT) 53 41 54 if (byteOne == 0x54 && byteTwo == 0x41 && byteThree == 0x53) { // found a line, add the beginning to the line buffer frameBuffer.put(byteThree); frameBuffer.put(byteTwo); frameBuffer.put(byteOne); frameByteCount = frameByteCount + 3; this.state = 1; break; } else { break; } case 1: // find the next frame beginning (SAT) 53 41 54 if ((byteOne == 0x54 && byteTwo == 0x41 && byteThree == 0x53) || fileBuffer.position() == fileBuffer.capacity()) { // we have a line ending. store the line in the arrayList frameBuffer.put(byteOne); frameByteCount++; frameBuffer.flip(); byte[] frameArray = frameBuffer.array(); ByteBuffer currentFrameBuffer; if (fileBuffer.position() == fileBuffer.capacity()) { // create a true copy of the byte array subset (no trailing 'SAT') byte[] frameCopy = new byte[frameByteCount]; System.arraycopy(frameArray, 0, frameCopy, 0, frameByteCount); currentFrameBuffer = ByteBuffer.wrap(frameCopy); } else { // create a true copy of the byte array subset (less the 'SAT') byte[] frameCopy = new byte[frameByteCount - 3]; System.arraycopy(frameArray, 0, frameCopy, 0, frameByteCount - 3); currentFrameBuffer = ByteBuffer.wrap(frameCopy); } // parse the current frame and add it to the frameMap frameCount++; // create a map to store frames as they are encountered BasicHierarchicalMap frameMap = new BasicHierarchicalMap(); // peek at the first six header bytes as a string byte[] sixBytes = new byte[6]; currentFrameBuffer.get(sixBytes); currentFrameBuffer.position(0); String frameHeader = new String(sixBytes, "US-ASCII"); // determine the frame type based on the header if (frameHeader.matches(this.STOR_X_HEADER_ID)) { frameMap.put("rawFrame", currentFrameBuffer); frameMap.put("id", frameHeader); frameMap.put("type", frameHeader.substring(3, 6)); frameMap.put("serialNumber", null); frameMap.put("date", null); String headerString = new String(currentFrameBuffer.array()); // trim trailing null characters and line endings int nullIndex = headerString.indexOf(0); headerString = headerString.substring(0, nullIndex).trim(); frameMap.put("parsedFrameObject", headerString); // Add the frame to the frames map this.framesMap.add("/frames/frame", (BasicHierarchicalMap) frameMap.clone()); frameMap.removeAll("frame"); currentFrameBuffer.clear(); } else if (frameHeader.matches(this.STOR_X_FRAME_ID)) { // test if the frame is complete if (currentFrameBuffer.capacity() == this.STOR_X_FRAME_SIZE) { // convert the frame buffer to a StorXFrame StorXFrame storXFrame = new StorXFrame(currentFrameBuffer); frameMap.put("rawFrame", currentFrameBuffer); frameMap.put("id", frameHeader); frameMap.put("type", frameHeader.substring(3, 6)); frameMap.put("serialNumber", storXFrame.getSerialNumber()); frameMap.put("date", parseTimestamp(storXFrame.getTimestamp())); frameMap.put("parsedFrameObject", storXFrame); // Add the frame to the frames map this.framesMap.add("/frames/frame", (BasicHierarchicalMap) frameMap.clone()); frameMap.removeAll("frame"); currentFrameBuffer.clear(); } else { logger.debug(frameHeader + " frame " + frameCount + " length is " + currentFrameBuffer.capacity() + " not " + this.STOR_X_FRAME_SIZE); } } else if (frameHeader.matches(this.SBE_CTD_FRAME_ID)) { // convert the frame buffer to a CTDFrame CTDFrame ctdFrame = new CTDFrame(currentFrameBuffer); // add in a sample if it matches a general data sample pattern if (ctdFrame.getSample().matches(" [0-9].*[0-9]\r\n")) { // extract the sample bytes from the frame frameMap.put("rawFrame", currentFrameBuffer); frameMap.put("id", frameHeader); frameMap.put("type", frameHeader.substring(3, 6)); frameMap.put("serialNumber", ctdFrame.getSerialNumber()); frameMap.put("date", parseTimestamp(ctdFrame.getTimestamp())); frameMap.put("parsedFrameObject", ctdFrame); // Add the frame to the frames map this.framesMap.add("/frames/frame", (BasicHierarchicalMap) frameMap.clone()); } else { logger.debug("This CTD frame is not a data sample." + " Skipping it. The string is: " + ctdFrame.getSample()); } frameMap.removeAll("frame"); currentFrameBuffer.clear(); } else if (frameHeader.matches(this.ISUS_DARK_FRAME_ID)) { // test if the frame is complete if (currentFrameBuffer.capacity() == this.ISUS_FRAME_SIZE) { // convert the frame buffer to a ISUSFrame ISUSFrame isusFrame = new ISUSFrame(currentFrameBuffer); frameMap.put("rawFrame", currentFrameBuffer); frameMap.put("id", frameHeader); frameMap.put("type", frameHeader.substring(3, 6)); frameMap.put("serialNumber", isusFrame.getSerialNumber()); frameMap.put("date", parseTimestamp(isusFrame.getTimestamp())); frameMap.put("parsedFrameObject", isusFrame); // Add the frame to the frames map this.framesMap.add("/frames/frame", (BasicHierarchicalMap) frameMap.clone()); frameMap.removeAll("frame"); currentFrameBuffer.clear(); } else { logger.debug(frameHeader + " frame " + frameCount + " length is " + currentFrameBuffer.capacity() + " not " + this.ISUS_FRAME_SIZE); } currentFrameBuffer.clear(); } else if (frameHeader.matches(this.ISUS_LIGHT_FRAME_ID)) { // test if the frame is complete if (currentFrameBuffer.capacity() == this.ISUS_FRAME_SIZE) { // convert the frame buffer to a ISUSFrame ISUSFrame isusFrame = new ISUSFrame(currentFrameBuffer); frameMap.put("rawFrame", currentFrameBuffer); frameMap.put("id", frameHeader); frameMap.put("type", frameHeader.substring(3, 6)); frameMap.put("serialNumber", isusFrame.getSerialNumber()); frameMap.put("date", parseTimestamp(isusFrame.getTimestamp())); frameMap.put("parsedFrameObject", isusFrame); // Add the frame to the frames map this.framesMap.add("/frames/frame", (BasicHierarchicalMap) frameMap.clone()); frameMap.removeAll("frame"); currentFrameBuffer.clear(); } else { logger.debug(frameHeader + " frame " + frameCount + " length is " + currentFrameBuffer.capacity() + " not " + this.ISUS_FRAME_SIZE); } currentFrameBuffer.clear(); } else { logger.info("The current frame type is not recognized. " + "Discarding it. The header was: " + frameHeader); currentFrameBuffer.clear(); } // reset the frame buffer for the next frame, but add the 'SAT' // bytes already encountered frameBuffer.clear(); frameByteCount = 0; this.fileBuffer.position(this.fileBuffer.position() - 3); this.state = 0; break; } else { // no full line yet, keep adding bytes frameBuffer.put(byteOne); frameByteCount++; break; } } // end switch() // shift the bytes in the FIFO window byteFour = byteThree; byteThree = byteTwo; byteTwo = byteOne; } // end while() logger.debug(this.framesMap.toXMLString(1000)); } catch (Exception e) { logger.debug("Failed to parse the data file. The error message was:" + e.getMessage()); e.printStackTrace(); } }
From source file:eu.abc4trust.smartcard.HardwareSmartcard.java
public SmartcardStatusCode setWorkingMode() { ByteBuffer buf = ByteBuffer.allocate(4); buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setWorkingMode, 0, 0 }); buf.position(0);//from w ww .j a v a 2 s .c o m try { System.out.println("Input for setWorkingMode: " + Arrays.toString(buf.array())); ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf)); System.out.println("response from setWorkingMode: " + response); return this.evaluateStatus(response); } catch (CardException e) { return SmartcardStatusCode.NOT_FOUND; } }
From source file:eu.abc4trust.smartcard.HardwareSmartcard.java
public SmartcardStatusCode setRootMode(byte[] accesscode) { try {//from ww w .ja v a2s.co m ByteBuffer buf = ByteBuffer.allocate(13); buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setRootMode, 0, 0, 8 }); buf.put(accesscode); buf.position(0); System.out.println("Input to setRootMode: " + Arrays.toString(buf.array())); ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf)); System.out.println("response from setRootMode: " + response); return this.evaluateStatus(response); } catch (CardException e) { return SmartcardStatusCode.NOT_FOUND; } }
From source file:eu.abc4trust.smartcard.HardwareSmartcard.java
public int getMode() { try {//from ww w.j a v a 2 s . c om ByteBuffer buf = ByteBuffer.allocate(5); buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.getMode, 0, 0, 1 }); buf.position(0); System.out.println("Input to GetMode: " + Arrays.toString(buf.array())); ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf)); System.out.println("Reponse from getMode: " + response); if (this.evaluateStatus(response) == SmartcardStatusCode.OK) { return response.getData()[0]; } } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; }