List of usage examples for java.nio ByteBuffer get
public abstract byte get(int index);
From source file:de.fhg.fokus.diameter.DiameterPeer.transport.Communicator.java
public void run() { MessageInfo messageInfo = null;//from www . j ava 2 s .c o m ByteBuffer receiveByteBuffer = ByteBuffer.allocateDirect(MAX_MESSAGE_LENGTH); DiameterMessage msg = null; byte[] buffer = null; int len = 0; //handler to keep track of association setup and termination AssociationHandler assocHandler = new AssociationHandler(); try { while (this.running) { messageInfo = sctpChannel.receive(receiveByteBuffer, System.out, assocHandler); log.debug("Received msg from communicator:" + this + " and sctpChannel:" + sctpChannel); log.debug("Received msg's length:" + messageInfo.bytes()); log.error("Received msg's length:" + messageInfo.bytes()); receiveByteBuffer.flip(); if (receiveByteBuffer.remaining() > 0) { buffer = new byte[messageInfo.bytes()]; receiveByteBuffer.get(buffer); receiveByteBuffer.clear(); // log.debug("The origin message stream is:\n" + CommonMethod.byteToHex(buffer)); //first we check the version if (buffer[0] != 1) { log.error("Expecting diameter version 1, received version " + buffer[0]); continue; } //then we check the length of the message len = ((int) buffer[1] & 0xFF) << 16 | ((int) buffer[2] & 0xFF) << 8 | ((int) buffer[3] & 0xFF); if (len > MAX_MESSAGE_LENGTH) { log.error("Message too long (msg length:" + len + " > max buffer length:" + MAX_MESSAGE_LENGTH + ")."); continue; } //now we can decode the message try { msg = Codec.decodeDiameterMessage(buffer, 0); } catch (DiameterMessageDecodeException e) { log.error("Error decoding diameter message !"); log.error(e, e); msg = null; continue; } msg.networkTime = System.currentTimeMillis(); log.debug("Received message is:\n" + msg); if (this.peer != null) { this.peer.refreshTimer(); } processMessage(msg); } msg = null; } } catch (Exception e1) { log.error("Exception:" + e1.getCause() + " catched in communicator:" + this + " and running flag=" + running); if (this.running) { if (this.peer != null) { if (this.peer.I_comm == this) { StateMachine.process(this.peer, StateMachine.I_Peer_Disc); } if (this.peer.R_comm == this) { log.error("Now closing the peer:" + this.peer); StateMachine.process(this.peer, StateMachine.R_Peer_Disc); } } log.error("Error reading from sctpChannel:" + sctpChannel + ", the channel might be colsed."); } /* else it was a shutdown request, it's normal */ } log.debug("Now closing communicator:" + this + ", and it's sctpChannel:" + sctpChannel); this.running = false; try { sctpChannel.close(); } catch (IOException e) { log.error("Error closing sctpChannel !"); log.error(e, e); } }
From source file:edu.northwestern.jcr.adapter.fedora.persistence.FedoraConnectorREST.java
/** * Wrapper of getDatastreamDissemination in REST. * * @param pid pid of the object/*from w ww . j av a2 s . c om*/ * @param dsID id of the datastream * @return byte content of the data stream */ public byte[] getDataStream(String pid, String dsID) { HttpInputStream inputStream; ReadableByteChannel channel; ByteBuffer buf; byte[] bytes; int numRead = 0; int length = 0; try { inputStream = fc.get( String.format("/objects/%s/datastreams/%s/content", URLEncoder.encode(pid, "UTF-8"), dsID), true, false); } catch (Exception e) { return null; } channel = Channels.newChannel(inputStream); // Create a direct ByteBuffer buf = ByteBuffer.allocateDirect(10 * 1024 * 1024); while (numRead >= 0) { // Read bytes from the channel try { numRead = channel.read(buf); } catch (Exception e) { return null; } if (numRead > 0) { length += numRead; } } bytes = new byte[length]; // reset the position of the buffer to zero buf.rewind(); buf.get(bytes); return bytes; }
From source file:automenta.knowtention.channel.LineFileChannel.java
@Override public void run() { FileInputStream fileInputStream = null; FileChannel channel = null;//w ww . ja va2s.c o m ByteBuffer buffer = null; LinkedList<String> lines = new LinkedList(); StringBuilder builder = new StringBuilder(); long lastSize = -1, lastLastModified = -1; while (running) { try { Thread.sleep(delayPeriodMS); } catch (InterruptedException ex) { } lines.clear(); try { fileInputStream = new FileInputStream(file); channel = fileInputStream.getChannel(); long lastModified = file.lastModified(); long csize = channel.size(); if ((lastModified == lastLastModified) && (csize == lastSize)) { //also check file update time? fileInputStream.close(); continue; } int currentPos = (int) csize; buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, csize); buffer.position(currentPos); lastSize = csize; lastLastModified = lastModified; int count = 0; for (long i = csize - 1; i >= 0; i--) { char c = (char) buffer.get((int) i); if (c == '\n') { count++; builder.reverse(); lines.addFirst(builder.toString()); if (count == numLines) { break; } builder.setLength(0); } else builder.append(c); } update(lines); lines.clear(); buffer.clear(); channel.close(); fileInputStream.close(); fileInputStream = null; } catch (Exception ex) { Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex); } } try { channel.close(); } catch (IOException ex) { Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Reads the sort order info from the given buffer from the given position. *///from w w w . j a v a2 s . c om static SortOrder readSortOrder(ByteBuffer buffer, int position, JetFormat format) { short value = buffer.getShort(position); byte version = 0; if (format.SIZE_SORT_ORDER == 4) { version = buffer.get(position + 3); } if (value == 0) { // probably a file we wrote, before handling sort order return format.DEFAULT_SORT_ORDER; } if (value == GENERAL_SORT_ORDER_VALUE) { if (version == GENERAL_LEGACY_SORT_ORDER.getVersion()) { return GENERAL_LEGACY_SORT_ORDER; } if (version == GENERAL_SORT_ORDER.getVersion()) { return GENERAL_SORT_ORDER; } } return new SortOrder(value, version); }
From source file:com.healthmarketscience.jackcess.impl.IndexData.java
/** * Determines if the given index page is a leaf or node page. *//* w w w .j ava 2 s . c o m*/ private static boolean isLeafPage(ByteBuffer buffer) throws IOException { byte pageType = buffer.get(0); if (pageType == PageTypes.INDEX_LEAF) { return true; } else if (pageType == PageTypes.INDEX_NODE) { return false; } throw new IOException("Unexpected page type " + pageType); }
From source file:de.spqrinfo.cups4j.operations.IppOperation.java
/** * Sends a request to the provided url//from w w w.ja v a2 s .c o m * * @param url * @param ippBuf * * @param documentStream * @return result * @throws Exception */ private IppResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream) throws Exception { IppResult ippResult = null; if (ippBuf == null) { return null; } if (url == null) { return null; } HttpClient client = new DefaultHttpClient(); // will not work with older versions of CUPS! client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); client.getParams().setParameter("http.socket.timeout", new Integer(10000)); client.getParams().setParameter("http.connection.timeout", new Integer(10000)); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092)); // probabaly not working with older CUPS versions client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true)); HttpPost httpPost = new HttpPost(new URI("http://" + url.getHost() + ":" + ippPort) + url.getPath()); httpPost.getParams().setParameter("http.socket.timeout", new Integer(10000)); byte[] bytes = new byte[ippBuf.limit()]; ippBuf.get(bytes); ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes); // If we need to send a document, concatenate InputStreams InputStream inputStream = headerStream; if (documentStream != null) { inputStream = new SequenceInputStream(headerStream, documentStream); } // set length to -1 to advice the entity to read until EOF InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1); requestEntity.setContentType(IPP_MIME_TYPE); httpPost.setEntity(requestEntity); httpStatusLine = null; ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); httpStatusLine = response.getStatusLine().toString(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] result = client.execute(httpPost, handler); IppResponse ippResponse = new IppResponse(); ippResult = ippResponse.getResponse(ByteBuffer.wrap(result)); ippResult.setHttpStatusResponse(httpStatusLine); // IppResultPrinter.print(ippResult); client.getConnectionManager().shutdown(); return ippResult; }
From source file:com.esri.geoevent.solutions.adapter.cap.CAPInboundAdapter.java
@Override public void receive(ByteBuffer buffer, String channelId) { //System.out.println("Processing..."); String data;/*from w w w.jav a2 s. c om*/ while (buffer.hasRemaining()) { buffer.mark(); try { byte[] bytearray = new byte[buffer.remaining()]; buffer.get(bytearray); data = new String(bytearray); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(data))); NodeList alerts = doc.getElementsByTagName("alert"); System.out.println(); System.out.println(new Date().toString() + ": Processing " + alerts.getLength() + " alerts."); int procAlerts = 0; for (int a = 0; a < alerts.getLength(); a++) { Element alert = (Element) alerts.item(a); NodeList nodeList = alert.getElementsByTagName("identifier"); Element line = (Element) nodeList.item(0); String identifier = getCharacterDataFromElement(line); if (MAP.containsKey(identifier)) { System.out.println( " Alert: " + identifier + " was processed previously. Skipping to next alert."); continue; } //System.out.println(" Alert "+ a + ": " + identifier + ". Processing now."); MAP.put(identifier, identifier); procAlerts++; GeoEvent alertMsg = parseAlert(alert, identifier); if (alertMsg != null) { geoEventListener.receive(alertMsg); System.out.println(" Alert " + a + ": " + identifier); System.out.println(" " + alertMsg.toString()); NodeList codes = alert.getElementsByTagName("code"); for (int c = 0; c < codes.getLength(); c++) { Element code = (Element) codes.item(c); GeoEvent codeMsg = parseAlertCode(code, identifier); if (codeMsg != null) { geoEventListener.receive(codeMsg); System.out.println(" Code: " + codeMsg.toString()); } } NodeList infos = alert.getElementsByTagName("info"); for (int i = 0; i < infos.getLength(); i++) { Element info = (Element) infos.item(i); String infoID = identifier + "_" + i; GeoEvent infoMsg = parseAlertInfo(info, identifier, infoID); if (infoMsg != null) { geoEventListener.receive(infoMsg); System.out.println(" Info " + i + ": " + infoID); System.out.println(" " + infoMsg.toString()); NodeList categories = info.getElementsByTagName("category"); for (int cat = 0; cat < categories.getLength(); cat++) { Element category = (Element) categories.item(cat); GeoEvent catMsg = parseInfoCategory(category, identifier, infoID); if (catMsg != null) { geoEventListener.receive(catMsg); System.out.println(" Category: " + catMsg.toString()); } } NodeList eventCodes = info.getElementsByTagName("eventCode"); for (int e = 0; e < eventCodes.getLength(); e++) { Element eventCode = (Element) eventCodes.item(e); GeoEvent eMsg = parseInfoEventCode(eventCode, identifier, infoID); if (eMsg != null) { geoEventListener.receive(eMsg); System.out.println(" Event code: " + eMsg.toString()); } } NodeList responseTypes = info.getElementsByTagName("responseType"); for (int rt = 0; rt < responseTypes.getLength(); rt++) { Element responseType = (Element) responseTypes.item(rt); GeoEvent rtMsg = parseInfoResponseType(responseType, identifier, infoID); if (rtMsg != null) { geoEventListener.receive(rtMsg); System.out.println(" Response type: " + rtMsg.toString()); } } NodeList parameters = info.getElementsByTagName("parameter"); for (int p = 0; p < parameters.getLength(); p++) { Element parameter = (Element) parameters.item(p); GeoEvent pMsg = parseInfoParameter(parameter, identifier, infoID); if (pMsg != null) { geoEventListener.receive(pMsg); System.out.println(" Parameter: " + pMsg.toString()); } } NodeList resources = info.getElementsByTagName("resource"); for (int r = 0; r < resources.getLength(); r++) { Element resource = (Element) resources.item(r); GeoEvent rMsg = parseInfoResource(resource, identifier, infoID); if (rMsg != null) { geoEventListener.receive(rMsg); System.out.println(" Resource " + r + ": "); System.out.println(" " + rMsg.toString()); } } NodeList areas = info.getElementsByTagName("area"); for (int ar = 0; ar < areas.getLength(); ar++) { Element area = (Element) areas.item(ar); String areaID = infoID + "_" + ar; GeoEvent areaMsg = parseInfoArea(area, identifier, infoID, areaID); if (areaMsg != null) { geoEventListener.receive(areaMsg); System.out.println(" Area " + ar + ": "); System.out.println(" " + areaMsg.toString()); NodeList polygons = info.getElementsByTagName("polygon"); for (int pg = 0; pg < polygons.getLength(); pg++) { Element polygon = (Element) polygons.item(pg); System.out.println(" Polygon " + pg + ": "); GeoEvent areaGeomMsg = parseInfoAreaGeom(polygon, null, null, identifier, infoID, areaID); if (areaGeomMsg != null) { geoEventListener.receive(areaGeomMsg); System.out.println(" " + areaGeomMsg.toString()); } else { System.out.println(" " + getCharacterDataFromElement(polygon)); } } NodeList circles = info.getElementsByTagName("circle"); for (int c = 0; c < circles.getLength(); c++) { Element circle = (Element) circles.item(c); System.out.println(" Circle " + c + ": "); GeoEvent areaGeomMsg = parseInfoAreaGeom(null, circle, null, identifier, infoID, areaID); if (areaGeomMsg != null) { geoEventListener.receive(areaGeomMsg); System.out.println(" " + areaGeomMsg.toString()); } else { System.out.println(" " + getCharacterDataFromElement(circle)); } } NodeList geocodes = info.getElementsByTagName("geocode"); for (int g = 0; g < geocodes.getLength(); g++) { Element geocode = (Element) geocodes.item(g); GeoEvent areaGeomMsg = parseInfoAreaGeom(null, null, geocode, identifier, infoID, areaID); if (areaGeomMsg != null) { geoEventListener.receive(areaGeomMsg); System.out.println(" Geocode " + g + ": "); System.out.println(" " + areaGeomMsg.toString()); } } } } } } } } //System.out.println("Processed " + procAlerts + " of " + alerts.getLength() + " alerts."); } catch (Exception e) { String msg = e.getMessage(); System.out.println(msg); e.printStackTrace(); } return; } }
From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java
/** * Construct data table from byte array. (broker side) *///from w ww.j ava 2s .c om public DataTableImplV2(@Nonnull ByteBuffer byteBuffer) throws IOException { // Read header. _numRows = byteBuffer.getInt(); _numColumns = byteBuffer.getInt(); int dictionaryMapStart = byteBuffer.getInt(); int dictionaryMapLength = byteBuffer.getInt(); int metadataStart = byteBuffer.getInt(); int metadataLength = byteBuffer.getInt(); int dataSchemaStart = byteBuffer.getInt(); int dataSchemaLength = byteBuffer.getInt(); int fixedSizeDataStart = byteBuffer.getInt(); int fixedSizeDataLength = byteBuffer.getInt(); int variableSizeDataStart = byteBuffer.getInt(); int variableSizeDataLength = byteBuffer.getInt(); // Read dictionary. if (dictionaryMapLength != 0) { byte[] dictionaryMapBytes = new byte[dictionaryMapLength]; byteBuffer.position(dictionaryMapStart); byteBuffer.get(dictionaryMapBytes); _dictionaryMap = deserializeDictionaryMap(dictionaryMapBytes); } else { _dictionaryMap = null; } // Read metadata. byte[] metadataBytes = new byte[metadataLength]; byteBuffer.position(metadataStart); byteBuffer.get(metadataBytes); _metadata = deserializeMetadata(metadataBytes); // Read data schema. if (dataSchemaLength != 0) { byte[] schemaBytes = new byte[dataSchemaLength]; byteBuffer.position(dataSchemaStart); byteBuffer.get(schemaBytes); _dataSchema = DataSchema.fromBytes(schemaBytes); _columnOffsets = new int[_dataSchema.size()]; _rowSizeInBytes = DataTableUtils.computeColumnOffsets(_dataSchema, _columnOffsets); } else { _dataSchema = null; _columnOffsets = null; _rowSizeInBytes = 0; } // Read fixed size data. if (fixedSizeDataLength != 0) { _fixedSizeDataBytes = new byte[fixedSizeDataLength]; byteBuffer.position(fixedSizeDataStart); byteBuffer.get(_fixedSizeDataBytes); _fixedSizeData = ByteBuffer.wrap(_fixedSizeDataBytes); } else { _fixedSizeDataBytes = null; _fixedSizeData = null; } // Read variable size data. if (variableSizeDataLength != 0) { _variableSizeDataBytes = new byte[variableSizeDataLength]; byteBuffer.position(variableSizeDataStart); byteBuffer.get(_variableSizeDataBytes); _variableSizeData = ByteBuffer.wrap(_variableSizeDataBytes); } else { _variableSizeDataBytes = null; _variableSizeData = null; } }
From source file:com.healthmarketscience.jackcess.impl.TableImpl.java
/** * Returns the row count for the current page. If the page is invalid * ({@code null}) or the page is not a DATA page, 0 is returned. *///from w w w. ja v a 2s. co m static int getRowsOnDataPage(ByteBuffer rowBuffer, JetFormat format) throws IOException { int rowsOnPage = 0; if ((rowBuffer != null) && (rowBuffer.get(0) == PageTypes.DATA)) { rowsOnPage = rowBuffer.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE); } return rowsOnPage; }
From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java
/** * Parse mp4 chunk/segment that contains one moof and one mdat. * * @param content//from w w w . ja v a 2 s. c o m * @return double[] mdat payload length, time sequence */ private Integer[] parsePayload(byte[] content) { byte[] buf = new byte[4]; int mdatSize = 0; ByteBuffer bbc = ByteBuffer.wrap(content); // get moof size double moofSize = bbc.getInt(); bbc.get(buf); String moofName = new String(buf); int timeSequence = 0; if (moofName.equals("moof")) { // skip past mfhd double mfhdSize = bbc.getInt(); bbc.get(buf); String mfhdName = new String(buf); if (mfhdName.equals("mfhd")) { bbc.position((int) mfhdSize + bbc.position() - 8); // parse into traf // double trafSize = bbc.getInt(); // skip over bbc.get(buf); String trafName = new String(buf); if (trafName.equals("traf")) { // skip tfhd double tfhdSize = bbc.getInt(); bbc.get(buf); String tfhdName = new String(buf); if (tfhdName.equals("tfhd")) { // skip past this atom bbc.position((int) tfhdSize + bbc.position() - 8); } // parse tfdt // double tfdtSize = bbc.getInt(); // skip over bbc.get(buf); String tfdtName = new String(buf); if (tfdtName.equals("tfdt")) { bbc.getInt(); // skip over always 16k bbc.getInt(); // skip over always 0 timeSequence = bbc.getInt(); } } } } else { return new Integer[] { 0, 0 }; } // parse mdat bbc.position((int) moofSize); mdatSize = bbc.getInt(); bbc.get(buf, 0, 4); String mdatName = new String(buf); if (mdatName.equals("mdat")) { mdatSize -= 8; } else { mdatSize = 0; } return new Integer[] { mdatSize, timeSequence }; }