List of usage examples for java.io DataInputStream readUTF
public final String readUTF() throws IOException
readUTF
method of DataInput
. From source file:org.pentaho.di.trans.dataservice.jdbc.RemoteClientTest.java
@Test public void testQuery() throws Exception { String sql = "SELECT * FROM myService\nWHERE id = 3"; String debugTrans = "/tmp/genTrans.ktr"; int maxRows = 200; when(connection.getDebugTransFilename()).thenReturn(debugTrans); when(connection.getParameters()).thenReturn(ImmutableMap.of("PARAMETER_ECHO", "hello world")); when(httpClient.executeMethod(isA(PostMethod.class))).thenReturn(200); MockDataInput mockDataInput = new MockDataInput(); mockDataInput.writeUTF("Query Response"); when(execMethod.getResponseBodyAsStream()).thenReturn(mockDataInput.toDataInputStream()); DataInputStream queryResponse = remoteClient.query(sql, maxRows); verify(httpClient).executeMethod(httpMethodCaptor.capture()); PostMethod httpMethod = (PostMethod) httpMethodCaptor.getValue(); assertThat(httpMethod.getURI().toString(), equalTo("http://localhost:9080/pentaho-di/kettle/sql/")); assertThat(httpMethod.getRequestHeader("SQL").getValue(), equalTo("SELECT * FROM myService WHERE id = 3")); assertThat(httpMethod.getRequestHeader("MaxRows").getValue(), equalTo("200")); assertThat(httpMethod.getParameter("SQL").getValue(), equalTo("SELECT * FROM myService WHERE id = 3")); assertThat(httpMethod.getParameter("MaxRows").getValue(), equalTo("200")); assertThat(httpMethod.getParameter("debugtrans").getValue(), equalTo(debugTrans)); assertThat(httpMethod.getParameter("PARAMETER_ECHO").getValue(), equalTo("hello world")); assertThat(queryResponse.readUTF(), equalTo("Query Response")); }
From source file:SafeUTF.java
public String safeReadUTF(DataInputStream in) throws IOException { boolean isNull = in.readByte() == NULL; if (isNull) { return null; }/*from w w w . j a v a2 s . c om*/ short numChunks = in.readShort(); int bufferSize = chunkSize * numChunks; // special handling for single chunk if (numChunks == 1) { // The text size is likely to be much smaller than the chunkSize // so set bufferSize to the min of the input stream available // and the maximum buffer size. Since the input stream // available() can be <= 0 we check for that and default to // a small msg size of 256 bytes. int inSize = in.available(); if (inSize <= 0) { inSize = 256; } bufferSize = Math.min(inSize, bufferSize); lastReadBufferSize = bufferSize; } StringBuffer buff = new StringBuffer(bufferSize); for (int i = 0; i < numChunks; i++) { String s = in.readUTF(); buff.append(s); } return buff.toString(); }
From source file:org.exist.dom.ElementImpl.java
public static StoredNode deserialize(byte[] data, int start, int len, DocumentImpl doc, boolean pooled) { final int end = start + len; int pos = start; final byte idSizeType = (byte) (data[pos] & 0x03); boolean isDirty = (data[pos] & 0x8) == 0x8; final boolean hasNamespace = (data[pos] & 0x10) == 0x10; pos += StoredNode.LENGTH_SIGNATURE_LENGTH; int children = ByteConversion.byteToInt(data, pos); pos += LENGTH_ELEMENT_CHILD_COUNT;/* www. j av a 2 s . c o m*/ final int dlnLen = ByteConversion.byteToShort(data, pos); pos += NodeId.LENGTH_NODE_ID_UNITS; final NodeId dln = doc.getBrokerPool().getNodeFactory().createFromData(dlnLen, data, pos); pos += dln.size(); short attributes = ByteConversion.byteToShort(data, pos); pos += LENGTH_ATTRIBUTES_COUNT; final short id = (short) Signatures.read(idSizeType, data, pos); pos += Signatures.getLength(idSizeType); short nsId = 0; String prefix = null; if (hasNamespace) { nsId = ByteConversion.byteToShort(data, pos); pos += LENGTH_NS_ID; int prefixLen = ByteConversion.byteToShort(data, pos); pos += LENGTH_PREFIX_LENGTH; if (prefixLen > 0) { prefix = UTF8.decode(data, pos, prefixLen).toString(); } pos += prefixLen; } final String name = doc.getBrokerPool().getSymbols().getName(id); String namespace = ""; if (nsId != 0) { namespace = doc.getBrokerPool().getSymbols().getNamespace(nsId); } ElementImpl node; if (pooled) { node = (ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE); } else { node = new ElementImpl(); } node.setNodeId(dln); node.nodeName = doc.getBrokerPool().getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix); node.children = children; node.attributes = attributes; node.isDirty = isDirty; node.setOwnerDocument(doc); //TO UNDERSTAND : why is this code here ? if (end > pos) { final byte[] pfxData = new byte[end - pos]; System.arraycopy(data, pos, pfxData, 0, end - pos); final ByteArrayInputStream bin = new ByteArrayInputStream(pfxData); final DataInputStream in = new DataInputStream(bin); try { final short prefixCount = in.readShort(); for (int i = 0; i < prefixCount; i++) { prefix = in.readUTF(); nsId = in.readShort(); node.addNamespaceMapping(prefix, doc.getBrokerPool().getSymbols().getNamespace(nsId)); } } catch (final IOException e) { e.printStackTrace(); } } return node; }
From source file:org.sakaiproject.nakamura.auth.trusted.TokenStore.java
/** * *///from w ww . j av a 2 s . co m private void loadLocalSecretKeys() { FileInputStream fin = null; DataInputStream keyInputStream = null; try { fin = new FileInputStream(tokenFile); keyInputStream = new DataInputStream(fin); int newCurrentToken = keyInputStream.readInt(); long newNextUpdate = keyInputStream.readLong(); ExpiringSecretKey[] newKeys = new ExpiringSecretKey[5]; for (int i = 0; i < newKeys.length; i++) { int isNull = keyInputStream.readInt(); if (isNull == 1) { long expires = keyInputStream.readLong(); String keyServerId = keyInputStream.readUTF(); int l = keyInputStream.readInt(); byte[] b = new byte[l]; if (keyInputStream.read(b) != l) { throw new IOException( "Failed to read Key no " + i + " from Secret Keys, end of file reached "); } newKeys[i] = new ExpiringSecretKey(b, HMAC_SHA1, expires, keyServerId); getServerKeyCache().put(getCacheKey(keyServerId, i), newKeys[i].getSecretKeyData()); LOG.info("Loaded Key {} from Local Store into {} ", getCacheKey(keyServerId, i), getServerKeyCache()); } else { newKeys[i] = null; } } keyInputStream.close(); nextUpdate = newNextUpdate; secretKeyId = newCurrentToken; secretKeyRingBuffer = newKeys; } catch (IOException e) { LOG.error("Failed to load cookie keys " + e.getMessage()); } finally { try { keyInputStream.close(); } catch (Exception e) { } try { fin.close(); } catch (Exception e) { } } if (secretKeyRingBuffer == null) { secretKeyRingBuffer = new ExpiringSecretKey[5]; nextUpdate = System.currentTimeMillis(); secretKeyId = 0; } if (debugCookies) { dumpSecretKeyRingBuffer(secretKeyRingBuffer); } }
From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java
/** * Deserializes a <code>PropertyState</code> from the data input stream. * * @param in the input stream//from w ww . j a v a 2s .c o m * @param id the property id for the new property entry * @return the property entry * @throws IOException if an I/O error occurs. */ public NodePropBundle.PropertyEntry readPropertyEntry(DataInputStream in, PropertyId id) throws IOException { NodePropBundle.PropertyEntry entry = new NodePropBundle.PropertyEntry(id); // type and modcount int type = in.readInt(); entry.setModCount((short) ((type >> 16) & 0x0ffff)); type &= 0x0ffff; entry.setType(type); // multiValued entry.setMultiValued(in.readBoolean()); // definitionId in.readUTF(); // values int count = in.readInt(); // count InternalValue[] values = new InternalValue[count]; String[] blobIds = new String[count]; for (int i = 0; i < count; i++) { InternalValue val; switch (type) { case PropertyType.BINARY: int size = in.readInt(); if (size == BINARY_IN_DATA_STORE) { val = InternalValue.create(dataStore, in.readUTF()); } else if (size == BINARY_IN_BLOB_STORE) { blobIds[i] = in.readUTF(); try { if (blobStore instanceof ResourceBasedBLOBStore) { val = InternalValue .create(((ResourceBasedBLOBStore) blobStore).getResource(blobIds[i])); } else { val = InternalValue.create(blobStore.get(blobIds[i])); } } catch (IOException e) { if (errorHandling.ignoreMissingBlobs()) { log.warn("Ignoring error while reading blob-resource: " + e); val = InternalValue.create(new byte[0]); } else { throw e; } } catch (Exception e) { throw new IOException("Unable to create property value: " + e.toString()); } } else { // short values into memory byte[] data = new byte[size]; in.readFully(data); val = InternalValue.create(data); } break; case PropertyType.DOUBLE: val = InternalValue.create(in.readDouble()); break; case PropertyType.LONG: val = InternalValue.create(in.readLong()); break; case PropertyType.BOOLEAN: val = InternalValue.create(in.readBoolean()); break; case PropertyType.NAME: val = InternalValue.create(readQName(in)); break; case PropertyType.REFERENCE: val = InternalValue.create(readUUID(in)); break; default: // because writeUTF(String) has a size limit of 64k, // Strings are serialized as <length><byte[]> int len = in.readInt(); byte[] bytes = new byte[len]; in.readFully(bytes); val = InternalValue.valueOf(new String(bytes, "UTF-8"), type); } values[i] = val; } entry.setValues(values); entry.setBlobIds(blobIds); return entry; }
From source file:org.exist.dom.ElementImpl.java
public static void readNamespaceDecls(List<String[]> namespaces, Value value, DocumentImpl document, NodeId nodeId) {/*from w w w. j ava 2 s . c o m*/ final byte[] data = value.data(); int offset = value.start(); final int end = offset + value.getLength(); final byte idSizeType = (byte) (data[offset] & 0x03); final boolean hasNamespace = (data[offset] & 0x10) == 0x10; offset += StoredNode.LENGTH_SIGNATURE_LENGTH; offset += LENGTH_ELEMENT_CHILD_COUNT; offset += NodeId.LENGTH_NODE_ID_UNITS; offset += nodeId.size(); offset += LENGTH_ATTRIBUTES_COUNT; offset += Signatures.getLength(idSizeType); if (hasNamespace) { offset += LENGTH_NS_ID; int prefixLen = ByteConversion.byteToShort(data, offset); offset += LENGTH_PREFIX_LENGTH; offset += prefixLen; } if (end > offset) { final byte[] pfxData = new byte[end - offset]; System.arraycopy(data, offset, pfxData, 0, end - offset); final ByteArrayInputStream bin = new ByteArrayInputStream(pfxData); final DataInputStream in = new DataInputStream(bin); try { final short prefixCount = in.readShort(); String prefix; short nsId; for (int i = 0; i < prefixCount; i++) { prefix = in.readUTF(); nsId = in.readShort(); namespaces .add(new String[] { prefix, document.getBrokerPool().getSymbols().getNamespace(nsId) }); } } catch (final IOException e) { e.printStackTrace(); } } }
From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w .j a v a2s. c o m*/ * * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @RequestMapping(method = RequestMethod.POST) public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); IMPService impService = (IMPService) appCtx.getBean("impService"); StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor"); InputStream input = request.getInputStream(); OutputStream output = response.getOutputStream(); ZOutputStream zOutput = null; // Wrap the streams for compression // Wrap the streams so for logical types DataInputStream dataInput = null; DataOutputStream dataOutput = null; // Set the MIME type so clients don't misinterpret response.setContentType("application/octet-stream"); try { zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION); dataInput = new DataInputStream(input); dataOutput = new DataOutputStream(zOutput); if (rawUploadLog.isInfoEnabled()) { byte[] rawPayload = IOUtils.toByteArray(dataInput); String hexEncodedPayload = Hex.encodeHexString(rawPayload); rawUploadLog.info(hexEncodedPayload); // Replace the original input stream with one using read payload dataInput.close(); dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload)); } String name = dataInput.readUTF(); String password = dataInput.readUTF(); String serializer = dataInput.readUTF(); String locale = dataInput.readUTF(); byte action = dataInput.readByte(); // TODO Authentication of usename and password. Possible M6 // enhancement log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer + ", locale=" + locale + ", action=" + action); EpihandyXformSerializer serObj = new EpihandyXformSerializer(); serObj.addDeserializationListener(studyProcessor); try { Map<Integer, String> formVersionMap = formService.getXForms(); serObj.deserializeStudiesWithEvents(dataInput, formVersionMap); } catch (FormNotFoundException fne) { String msg = "failed to deserialize forms: "; log.error(msg + fne.getMessage()); dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE); response.setStatus(HttpServletResponse.SC_OK); return; } catch (Exception e) { String msg = "failed to deserialize forms"; log.error(msg, e); dataOutput.writeByte(ResponseHeader.STATUS_ERROR); response.setStatus(HttpServletResponse.SC_OK); return; } String[][] studyForms = studyProcessor.getConvertedStudies(); int numForms = studyProcessor.getNumForms(); log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms); // Starting processing here, only process until we run out of time int processedForms = 0; int faultyForms = 0; if (studyForms != null && numForms > 0) { formprocessing: for (int i = 0; i < studyForms.length; i++) { for (int j = 0; j < studyForms[i].length; j++, processedForms++) { if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime) break formprocessing; try { studyForms[i][j] = impService.processXForm(studyForms[i][j]); } catch (Exception ex) { log.error("processing form failed", ex); studyForms[i][j] = ex.getMessage(); } if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) { faultyForms++; } } } } // Write out usual upload response dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS); dataOutput.writeInt(processedForms); dataOutput.writeInt(faultyForms); for (int s = 0; s < studyForms.length; s++) { for (int f = 0; f < studyForms[s].length; f++) { if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) { dataOutput.writeByte((byte) s); dataOutput.writeShort((short) f); dataOutput.writeUTF(studyForms[s][f]); } } } response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { log.error("failure during upload", e); } finally { if (dataOutput != null) dataOutput.flush(); if (zOutput != null) zOutput.finish(); response.flushBuffer(); } }
From source file:net.sergetk.mobile.lcdui.BitmapFont.java
/** * Creates a new font from the resource. The capacity of the color cache defines maximum size of * the color cache.//from w ww. j a v a 2s . c om * * @param fontPath * the resource name * @param colorCacheCapacity * the maximum color cache size */ public BitmapFont(String fontPath, int colorCacheCapacity) { this.style = Font.STYLE_PLAIN; this.currentColor = 0; this.colorCache = new CacheEntry[colorCacheCapacity]; this.colorUsageCounts = new IntHashMap(colorCacheCapacity * 2); try { InputStream input = new Object().getClass().getResourceAsStream(fontPath); if (input == null) { throw new IOException(); } DataInputStream data = new DataInputStream(input); int streamLen = data.available(); this.fontFilePath = fontPath; this.version = data.readByte(); this.height = data.readByte(); this.baseline = data.readByte(); this.xIndent = data.readByte(); this.yIndent = data.readByte(); this.spaceWidth = data.readByte(); characterMap = data.readUTF(); int count = characterMap.length(); // read characters widthes this.widths = new int[count]; this.x = new int[count]; this.y = new int[count]; for (int i = 0; i < count; i++) { widths[i] = data.readByte(); } baseImage = null; // the original implementation supported multiple-images // in the font file, but this is not necessary. Because I do // not want to change the encoding, I am leaving this byte that // used to represent the number of PNGs in the file data.skipBytes(1); short pngLen = data.readShort(); byte[] buffer = new byte[pngLen]; data.read(buffer, 0, pngLen); this.pngOffset = (short) (streamLen - pngLen); baseImage = Image.createImage(buffer, 0, pngLen); currentImage = baseImage; // calculate characters coordinates int curX = 0, curY = 0; for (int i = 0; i < count; i++) { if (widths[i] < 0) { // negative width points to another character int sourceIndex = -widths[i]; widths[i] = widths[sourceIndex]; x[i] = x[sourceIndex]; y[i] = y[sourceIndex]; } else { x[i] = curX; y[i] = curY; curX += widths[i]; } } if (defaultFont == null) defaultFont = this; } catch (IOException e) { // Log.warn("IOException reading font: ", e); System.err.println("IOException reading font: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java
/** * Deserializes a <code>PropertyState</code> from the data input stream. * * @param in the input stream/* w ww .j av a2 s. co m*/ * @param id the property id for the new property entry * @return the property entry * @throws IOException if an I/O error occurs. */ public NodePropBundle.PropertyEntry readPropertyEntry(DataInputStream in, PropertyId id) throws IOException { NodePropBundle.PropertyEntry entry = new NodePropBundle.PropertyEntry(id); // type and modcount int type = in.readInt(); entry.setModCount((short) ((type >> 16) & 0x0ffff)); type &= 0x0ffff; entry.setType(type); // multiValued entry.setMultiValued(in.readBoolean()); // definitionId entry.setPropDefId(PropDefId.valueOf(in.readUTF())); // values int count = in.readInt(); // count InternalValue[] values = new InternalValue[count]; String[] blobIds = new String[count]; for (int i = 0; i < count; i++) { InternalValue val; switch (type) { case PropertyType.BINARY: int size = in.readInt(); if (size == BINARY_IN_DATA_STORE) { val = InternalValue.create(dataStore, in.readUTF()); } else if (size == BINARY_IN_BLOB_STORE) { blobIds[i] = in.readUTF(); try { if (blobStore instanceof ResourceBasedBLOBStore) { val = InternalValue .create(((ResourceBasedBLOBStore) blobStore).getResource(blobIds[i])); } else { val = InternalValue.create(blobStore.get(blobIds[i])); } } catch (IOException e) { if (errorHandling.ignoreMissingBlobs()) { log.warn("Ignoring error while reading blob-resource: " + e); val = InternalValue.create(new byte[0]); } else { throw e; } } catch (Exception e) { throw new IOException("Unable to create property value: " + e.toString()); } } else { // short values into memory byte[] data = new byte[size]; in.readFully(data); val = InternalValue.create(data); } break; case PropertyType.DOUBLE: val = InternalValue.create(in.readDouble()); break; case PropertyType.DECIMAL: val = InternalValue.create(readDecimal(in)); break; case PropertyType.LONG: val = InternalValue.create(in.readLong()); break; case PropertyType.BOOLEAN: val = InternalValue.create(in.readBoolean()); break; case PropertyType.NAME: val = InternalValue.create(readQName(in)); break; case PropertyType.WEAKREFERENCE: case PropertyType.REFERENCE: val = InternalValue.create(readID(in)); break; default: // because writeUTF(String) has a size limit of 64k, // Strings are serialized as <length><byte[]> int len = in.readInt(); byte[] bytes = new byte[len]; in.readFully(bytes); val = InternalValue.valueOf(new String(bytes, "UTF-8"), type); } values[i] = val; } entry.setValues(values); entry.setBlobIds(blobIds); return entry; }
From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java
/** * Deserializes a <code>PropertyState</code> from the data input stream. * * @param in the input stream//from w w w . j ava 2s . co m * @param id the property id for the new property entry * @return the property entry * @throws IOException if an I/O error occurs. */ public NodePropBundle.PropertyEntry readPropertyEntry(DataInputStream in, PropertyId id) throws IOException { NodePropBundle.PropertyEntry entry = new NodePropBundle.PropertyEntry(id); // type and modcount int type = in.readInt(); entry.setModCount((short) ((type >> 16) & 0x0ffff)); type &= 0x0ffff; entry.setType(type); // multiValued entry.setMultiValued(in.readBoolean()); // definitionId entry.setPropDefId(PropDefId.valueOf(in.readUTF())); // values int count = in.readInt(); // count InternalValue[] values = new InternalValue[count]; String[] blobIds = new String[count]; for (int i = 0; i < count; i++) { InternalValue val; switch (type) { case PropertyType.BINARY: int size = in.readInt(); if (size == BINARY_IN_DATA_STORE) { val = InternalValue.create(dataStore, in.readUTF()); } else if (size == BINARY_IN_BLOB_STORE) { blobIds[i] = in.readUTF(); try { if (blobStore instanceof ResourceBasedBLOBStore) { val = InternalValue .create(((ResourceBasedBLOBStore) blobStore).getResource(blobIds[i])); } else { val = InternalValue.create(blobStore.get(blobIds[i])); } } catch (IOException e) { if (errorHandling.ignoreMissingBlobs()) { log.warn("Ignoring error while reading blob-resource: " + e); val = InternalValue.create(new byte[0]); } else { throw e; } } catch (Exception e) { throw new IOException("Unable to create property value: " + e.toString()); } } else { // short values into memory byte[] data = new byte[size]; in.readFully(data); val = InternalValue.create(data); } break; case PropertyType.DOUBLE: val = InternalValue.create(in.readDouble()); break; case PropertyType.DECIMAL: val = InternalValue.create(readDecimal(in)); break; case PropertyType.LONG: val = InternalValue.create(in.readLong()); break; case PropertyType.BOOLEAN: val = InternalValue.create(in.readBoolean()); break; case PropertyType.NAME: val = InternalValue.create(readQName(in)); break; case PropertyType.WEAKREFERENCE: case PropertyType.REFERENCE: val = InternalValue.create(readUUID(in)); break; default: // because writeUTF(String) has a size limit of 64k, // Strings are serialized as <length><byte[]> int len = in.readInt(); byte[] bytes = new byte[len]; in.readFully(bytes); val = InternalValue.valueOf(new String(bytes, "UTF-8"), type); } values[i] = val; } entry.setValues(values); entry.setBlobIds(blobIds); return entry; }