List of usage examples for java.io DataOutputStream writeUTF
public final void writeUTF(String str) throws IOException
From source file:org.apache.jackrabbit.core.persistence.util.Serializer.java
/** * Serializes the specified <code>NodeState</code> object to the given * binary <code>stream</code>. * * @param state <code>state</code> to serialize * @param stream the stream where the <code>state</code> should be * serialized to/*w w w .ja va 2 s . co m*/ * @throws Exception if an error occurs during the serialization * @see #deserialize(NodeState, InputStream) */ public static void serialize(NodeState state, OutputStream stream) throws Exception { DataOutputStream out = new DataOutputStream(stream); // primaryType out.writeUTF(state.getNodeTypeName().toString()); // parentUUID if (state.getParentId() == null) { out.write(NULL_UUID_PLACEHOLDER_BYTES); } else { out.write(state.getParentId().getRawBytes()); } // definitionId out.writeUTF(""); // mixin types Collection<Name> c = state.getMixinTypeNames(); out.writeInt(c.size()); // count for (Iterator<Name> iter = c.iterator(); iter.hasNext();) { out.writeUTF(iter.next().toString()); // name } // modCount out.writeShort(state.getModCount()); // properties (names) c = state.getPropertyNames(); out.writeInt(c.size()); // count for (Iterator<Name> iter = c.iterator(); iter.hasNext();) { Name propName = iter.next(); out.writeUTF(propName.toString()); // name } // child nodes (list of name/uuid pairs) Collection<ChildNodeEntry> collChildren = state.getChildNodeEntries(); out.writeInt(collChildren.size()); // count for (Iterator<ChildNodeEntry> iter = collChildren.iterator(); iter.hasNext();) { ChildNodeEntry entry = iter.next(); out.writeUTF(entry.getName().toString()); // name out.write(entry.getId().getRawBytes()); // uuid } }
From source file:ml.shifu.shifu.core.dtrain.dt.BinaryDTSerializer.java
public static void save(ModelConfig modelConfig, List<ColumnConfig> columnConfigList, List<List<TreeNode>> baggingTrees, String loss, int inputCount, OutputStream output) throws IOException { DataOutputStream fos = null; try {/*from ww w.ja v a 2 s.c o m*/ fos = new DataOutputStream(new GZIPOutputStream(output)); // version fos.writeInt(CommonConstants.TREE_FORMAT_VERSION); fos.writeUTF(modelConfig.getAlgorithm()); fos.writeUTF(loss); fos.writeBoolean(modelConfig.isClassification()); fos.writeBoolean(modelConfig.getTrain().isOneVsAll()); fos.writeInt(inputCount); Map<Integer, String> columnIndexNameMapping = new HashMap<Integer, String>(); Map<Integer, List<String>> columnIndexCategoricalListMapping = new HashMap<Integer, List<String>>(); Map<Integer, Double> numericalMeanMapping = new HashMap<Integer, Double>(); for (ColumnConfig columnConfig : columnConfigList) { if (columnConfig.isFinalSelect()) { columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName()); } if (columnConfig.isCategorical() && CollectionUtils.isNotEmpty(columnConfig.getBinCategory())) { columnIndexCategoricalListMapping.put(columnConfig.getColumnNum(), columnConfig.getBinCategory()); } if (columnConfig.isNumerical() && columnConfig.getMean() != null) { numericalMeanMapping.put(columnConfig.getColumnNum(), columnConfig.getMean()); } } if (columnIndexNameMapping.size() == 0) { boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList); for (ColumnConfig columnConfig : columnConfigList) { if (CommonUtils.isGoodCandidate(columnConfig, hasCandidates)) { columnIndexNameMapping.put(columnConfig.getColumnNum(), columnConfig.getColumnName()); } } } // serialize numericalMeanMapping fos.writeInt(numericalMeanMapping.size()); for (Entry<Integer, Double> entry : numericalMeanMapping.entrySet()) { fos.writeInt(entry.getKey()); // for some feature, it is null mean value, it is not selected, just set to 0d to avoid NPE fos.writeDouble(entry.getValue() == null ? 0d : entry.getValue()); } // serialize columnIndexNameMapping fos.writeInt(columnIndexNameMapping.size()); for (Entry<Integer, String> entry : columnIndexNameMapping.entrySet()) { fos.writeInt(entry.getKey()); fos.writeUTF(entry.getValue()); } // serialize columnIndexCategoricalListMapping fos.writeInt(columnIndexCategoricalListMapping.size()); for (Entry<Integer, List<String>> entry : columnIndexCategoricalListMapping.entrySet()) { List<String> categories = entry.getValue(); if (categories != null) { fos.writeInt(entry.getKey()); fos.writeInt(categories.size()); for (String category : categories) { // There is 16k limitation when using writeUTF() function. // if the category value is larger than 10k, write a marker -1 and write bytes instead of // writeUTF; // in read part logic should be changed also to readByte not readUTF according to the marker if (category.length() < Constants.MAX_CATEGORICAL_VAL_LEN) { fos.writeUTF(category); } else { fos.writeShort(UTF_BYTES_MARKER); // marker here byte[] bytes = category.getBytes("UTF-8"); fos.writeInt(bytes.length); for (int i = 0; i < bytes.length; i++) { fos.writeByte(bytes[i]); } } } } } Map<Integer, Integer> columnMapping = getColumnMapping(columnConfigList); fos.writeInt(columnMapping.size()); for (Entry<Integer, Integer> entry : columnMapping.entrySet()) { fos.writeInt(entry.getKey()); fos.writeInt(entry.getValue()); } // after model version 4 (>=4), IndependentTreeModel support bagging, here write a default RF/GBT size 1 fos.writeInt(baggingTrees.size()); for (int i = 0; i < baggingTrees.size(); i++) { List<TreeNode> trees = baggingTrees.get(i); int treeLength = trees.size(); fos.writeInt(treeLength); for (TreeNode treeNode : trees) { treeNode.write(fos); } } } catch (IOException e) { LOG.error("Error in writing output.", e); } finally { IOUtils.closeStream(fos); } }
From source file:org.apache.jackrabbit.core.persistence.util.Serializer.java
/** * Serializes the specified <code>PropertyState</code> object to the given * binary <code>stream</code>. Binary values are stored in the specified * <code>BLOBStore</code>.//from ww w.j a v a2 s . c o m * * @param state <code>state</code> to serialize * @param stream the stream where the <code>state</code> should be * serialized to * @param blobStore handler for BLOB data * @throws Exception if an error occurs during the serialization * @see #deserialize(PropertyState, InputStream,BLOBStore) */ public static void serialize(PropertyState state, OutputStream stream, BLOBStore blobStore) throws Exception { DataOutputStream out = new DataOutputStream(stream); // type out.writeInt(state.getType()); // multiValued out.writeBoolean(state.isMultiValued()); // definitionId out.writeUTF(""); // modCount out.writeShort(state.getModCount()); // values InternalValue[] values = state.getValues(); out.writeInt(values.length); // count for (int i = 0; i < values.length; i++) { InternalValue val = values[i]; if (state.getType() == PropertyType.BINARY) { // special handling required for binary value: // put binary value in BLOB store InputStream in = val.getStream(); String blobId = blobStore.createId(state.getPropertyId(), i); try { blobStore.put(blobId, in, val.getLength()); } finally { IOUtils.closeQuietly(in); } // store id of BLOB as property value out.writeUTF(blobId); // value // replace value instance with value backed by resource // in BLOB store and discard old value instance (e.g. temp file) if (blobStore instanceof ResourceBasedBLOBStore) { // optimization: if the BLOB store is resource-based // retrieve the resource directly rather than having // to read the BLOB from an input stream FileSystemResource fsRes = ((ResourceBasedBLOBStore) blobStore).getResource(blobId); values[i] = InternalValue.create(fsRes); } else { in = blobStore.get(blobId); try { values[i] = InternalValue.create(in); } finally { IOUtils.closeQuietly(in); } } val.discard(); } else { /** * because writeUTF(String) has a size limit of 65k, * Strings are serialized as <length><byte[]> */ //out.writeUTF(val.toString()); // value byte[] bytes = val.toString().getBytes(ENCODING); out.writeInt(bytes.length); // lenght of byte[] out.write(bytes); // byte[] } } }
From source file:Main.java
public static void writeSettings(String file, Object... objs) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file), 1024)); try {// w w w.j a v a2s. com out.writeInt(objs.length); for (Object obj : objs) { char cl; if (obj instanceof Byte) { cl = 'Y'; } else { cl = obj.getClass().getSimpleName().charAt(0); } out.writeChar(cl); if (obj instanceof String) { out.writeUTF((String) obj); } else if (obj instanceof Float) { out.writeFloat((Float) obj); } else if (obj instanceof Double) { out.writeDouble((Double) obj); } else if (obj instanceof Integer) { out.writeInt((Integer) obj); } else if (obj instanceof Long) { out.writeLong((Long) obj); } else if (obj instanceof Boolean) { out.writeBoolean((Boolean) obj); } else { throw new IllegalStateException("Unsupported type"); } } } finally { out.close(); } }
From source file:EZShare.SubscribeCommandConnection.java
public static void establishPersistentConnection(Boolean secure, int port, String ip, int id, JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description, String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay, String servers) throws URISyntaxException { //secure = false; try {/*from w w w . j a va 2s . c o m*/ System.out.print(port + ip); Socket socket = null; if (secure) { SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = (SSLSocket) sslsocketfactory.createSocket(ip, port); } else { socket = new Socket(ip, port); } BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream output = new DataOutputStream(socket.getOutputStream()); DataInputStream input = new DataInputStream(socket.getInputStream()); JSONObject command = new JSONObject(); Resource resource = new Resource(); command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver, secret, relay, servers); output.writeUTF(command.toJSONString()); Client.debug("SEND", command.toJSONString()); //output.writeUTF(command.toJSONString()); new Thread(new Runnable() { @Override public void run() { String string = null; try { while (true/*(string = input.readUTF()) != null*/) { String serverResponse = input.readUTF(); JSONParser parser = new JSONParser(); JSONObject response = (JSONObject) parser.parse(serverResponse); Client.debug("RECEIVE", response.toJSONString()); //System.out.println(serverResponse); // if((string = Reader.readLine()) != null){ // if(onKeyPressed(output,string,unsubscribJsonObject)) break; // } if (flag == 1) { break; } } } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { String string = null; try { while ((string = Reader.readLine()) != null) { flag = 1; if (onKeyPressed(output, string, unsubscribJsonObject)) break; } } catch (IOException e) { e.printStackTrace(); } } }).start(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.apache.jackrabbit.core.persistence.util.Serializer.java
/** * Serializes the specified <code>NodeReferences</code> object to the given * binary <code>stream</code>. * * @param refs object to serialize//from w w w .jav a2 s . c om * @param stream the stream where the object should be serialized to * @throws Exception if an error occurs during the serialization * @see #deserialize(NodeReferences, InputStream) */ public static void serialize(NodeReferences refs, OutputStream stream) throws Exception { DataOutputStream out = new DataOutputStream(stream); // references Collection<PropertyId> c = refs.getReferences(); out.writeInt(c.size()); // count for (Iterator<PropertyId> iter = c.iterator(); iter.hasNext();) { PropertyId propId = iter.next(); out.writeUTF(propId.toString()); // propertyId } }
From source file:com.appassit.common.Utils.java
/** * <p>//from w w w.java 2s . c o m * Get UTF8 bytes from a string * </p> * * @param string * String * @return UTF8 byte array, or null if failed to get UTF8 byte array */ public static byte[] getUTF8Bytes(String string) { if (string == null) return new byte[0]; try { return string.getBytes(ENCODING_UTF8); } catch (UnsupportedEncodingException e) { /* * If system doesn't support UTF-8, use another way */ try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeUTF(string); byte[] jdata = bos.toByteArray(); bos.close(); dos.close(); byte[] buff = new byte[jdata.length - 2]; System.arraycopy(jdata, 2, buff, 0, buff.length); return buff; } catch (IOException ex) { return new byte[0]; } } }
From source file:uk.ac.ebi.mdk.io.ReactionMatrixIO.java
public static void writeCompressedBasicStoichiometricMatrix(StoichiometricMatrix<?, ?> s, OutputStream writer) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(writer, 2048)); int n = s.getMoleculeCount(); int m = s.getReactionCount(); out.writeInt(n);//from ww w .j ava 2s .c o m out.writeInt(m); for (int j = 0; j < m; j++) { out.writeUTF(s.getReaction(j).toString()); } for (int i = 0; i < n; i++) { out.writeUTF(s.getMolecule(i).toString()); } out.writeBoolean(convertDoubles); out.writeInt(s.getNonNullCount()); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // if the value is null if (convertDoubles) { int value = s.get(i, j).intValue(); if (value != 0) { out.writeInt(i); out.writeInt(j); out.writeInt(value); } } else { double value = s.get(i, j); if (value != 0d) { out.writeInt(i); out.writeInt(j); out.writeDouble(value); } } } } out.close(); }
From source file:com.google.gwt.dev.javac.CachedCompilationUnit.java
public static void save(SourceFileCompilationUnit unit, OutputStream outputStream) throws Exception { DataOutputStream dos = null; try {/*from ww w . j a va 2 s.c o m*/ dos = new DataOutputStream(new BufferedOutputStream(outputStream)); // version dos.writeLong(CompilationUnitDiskCache.CACHE_VERSION); // simple stuff dos.writeLong(unit.getLastModified()); dos.writeUTF(unit.getDisplayLocation()); dos.writeUTF(unit.getTypeName()); dos.writeUTF(unit.getContentId().get()); dos.writeBoolean(unit.isSuperSource()); // compiled classes { Collection<CompiledClass> compiledClasses = unit.getCompiledClasses(); int size = compiledClasses.size(); dos.writeInt(size); if (size > 0) { // sort in enclosing order to be able to restore enclosing classes by name CompiledClass[] compiledClassesArray = compiledClasses .toArray(new CompiledClass[compiledClasses.size()]); Arrays.sort(compiledClassesArray, new Comparator<CompiledClass>() { public int compare(CompiledClass o1, CompiledClass o2) { int o1count = countMatches(o1.getInternalName(), Signature.C_DOLLAR); int o2count = countMatches(o2.getInternalName(), Signature.C_DOLLAR); return o1count - o2count; } }); // store for (CompiledClass compiledClass : compiledClassesArray) { // internal name dos.writeUTF(compiledClass.getInternalName()); // is local dos.writeBoolean(compiledClass.isLocal()); // bytes byte[] bytes = compiledClass.getBytes(); dos.writeInt(bytes.length); dos.write(bytes); // enclosing class, write the name only CompiledClass enclosingClass = compiledClass.getEnclosingClass(); String enclosingClassName = enclosingClass != null ? enclosingClass.getInternalName() : ""; dos.writeUTF(enclosingClassName); } } } // dependencies { Set<ContentId> dependencies = unit.getDependencies(); int size = dependencies.size(); dos.writeInt(size); if (size > 0) { for (ContentId contentId : dependencies) { dos.writeUTF(contentId.get()); } } } // JSNI methods { List<JsniMethod> jsniMethods = unit.getJsniMethods(); int size = jsniMethods.size(); dos.writeInt(size); if (size > 0) { for (JsniMethod jsniMethod : jsniMethods) { dos.writeUTF(jsniMethod.name()); JsFunction function = jsniMethod.function(); SourceInfo sourceInfo = function.getSourceInfo(); dos.writeInt(sourceInfo.getStartPos()); dos.writeInt(sourceInfo.getEndPos()); dos.writeInt(sourceInfo.getStartLine()); dos.writeUTF(function.toSource()); } } } // Method lookup { MethodArgNamesLookup methodArgs = unit.getMethodArgs(); MethodArgNamesLookup.save(methodArgs, dos); } } finally { IOUtils.closeQuietly(dos); } }
From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.Krb5ConfServerSetupTask.java
/** * Creates a keytab file for given principal. * //from w ww. j a va 2s . c o m * @param principalName * @param passPhrase * @param keytabFile * @throws IOException */ public static void createKeytab(final String principalName, final String passPhrase, final File keytabFile) throws IOException { LOGGER.info("Principal name: " + principalName); final KerberosTime timeStamp = new KerberosTime(); DataOutputStream dos = null; try { dos = new DataOutputStream(new FileOutputStream(keytabFile)); dos.write(Keytab.VERSION_0X502_BYTES); for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory .getKerberosKeys(principalName, passPhrase).entrySet()) { final EncryptionKey key = keyEntry.getValue(); final byte keyVersion = (byte) key.getKeyVersion(); // entries.add(new KeytabEntry(principalName, principalType, timeStamp, keyVersion, key)); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream entryDos = new DataOutputStream(baos); // handle principal name String[] spnSplit = principalName.split("@"); String nameComponent = spnSplit[0]; String realm = spnSplit[1]; String[] nameComponents = nameComponent.split("/"); try { // increment for v1 entryDos.writeShort((short) nameComponents.length); entryDos.writeUTF(realm); // write components for (String component : nameComponents) { entryDos.writeUTF(component); } entryDos.writeInt(1); // principal type: KRB5_NT_PRINCIPAL entryDos.writeInt((int) (timeStamp.getTime() / 1000)); entryDos.write(keyVersion); entryDos.writeShort((short) key.getKeyType().getValue()); byte[] data = key.getKeyValue(); entryDos.writeShort((short) data.length); entryDos.write(data); } finally { IOUtils.closeQuietly(entryDos); } final byte[] entryBytes = baos.toByteArray(); dos.writeInt(entryBytes.length); dos.write(entryBytes); } // } catch (IOException ioe) { } finally { IOUtils.closeQuietly(dos); } }