private static Media readMedia(DataInputStream in) throws IOException { String uri = in.readUTF(); String title = readMaybeString(in); int width = in.readInt(); int height = in.readInt(); String format = in.readUTF(); long duration = in.readLong(); long size = in.readLong(); boolean hasBitrate = in.readBoolean(); int bitrate = 0; if (hasBitrate) bitrate = in.readInt(); int numPersons = in.readInt(); ArrayList<String> persons = new ArrayList<String>(numPersons); for (int i = 0; i < numPersons; i++) { persons.add(in.readUTF()); } Media.Player player = Media.Player.values()[in.readByte()]; String copyright = readMaybeString(in); return new Media( uri, title, width, height, format, duration, size, bitrate, hasBitrate, persons, player, copyright); }
/** * Create a FreenetURI from the binary form of the key, read from a stream, with no length. * * @throws MalformedURLException If there was a format error in the data. * @throws IOException If a read error occurred */ public static FreenetURI readFullBinaryKey(DataInputStream dis) throws IOException { byte type = dis.readByte(); String keyType; if (type == CHK) keyType = "CHK"; else if (type == SSK) keyType = "SSK"; else if (type == KSK) keyType = "KSK"; else throw new MalformedURLException("Unrecognized type " + type); byte[] routingKey = null; byte[] cryptoKey = null; byte[] extra = null; if ((type == CHK) || (type == SSK)) { // routingKey is a hash, so is exactly 32 bytes routingKey = new byte[32]; dis.readFully(routingKey); // cryptoKey is a 256 bit AES key, so likewise cryptoKey = new byte[32]; dis.readFully(cryptoKey); // Number of bytes of extra depends on key type int extraLen; extraLen = (type == CHK ? Constants.CLIENT_CHK_EXTRA_LENGTH : Constants.CLIENT_SSK_EXTRA_LENGTH); extra = new byte[extraLen]; dis.readFully(extra); } String docName = null; if (type != CHK) docName = dis.readUTF(); int count = dis.readInt(); String[] metaStrings = new String[count]; for (int i = 0; i < metaStrings.length; i++) metaStrings[i] = dis.readUTF(); return new FreenetURI(keyType, docName, metaStrings, routingKey, cryptoKey, extra); }
public void read(InputStream is) throws IOException { DataInputStream oin = new DataInputStream(is); byte[] magic = new byte[MAGIC_NUMBER.length]; oin.read(magic, 0, magic.length); if (Arrays.equals(MAGIC_NUMBER_OFH_20040908, magic)) { // Old format requires us to read the OModel to get the type and guid. this.format = oin.readShort(); this.compileTime = oin.readLong(); oin.readInt(); ObjectInputStream ois = new CustomObjectInputStream(_inputStream); OProcess oprocess; try { oprocess = (OProcess) ois.readObject(); } catch (ClassNotFoundException e) { throw new IOException("DataStream Error"); } this.type = new QName(oprocess.targetNamespace, oprocess.processName); this.guid = "OLD-FORMAT-NO-GUID"; return; } // The current (most recent) scheme if (Arrays.equals(MAGIC_NUMBER, magic)) { this.format = oin.readShort(); this.compileTime = oin.readLong(); this.guid = oin.readUTF(); String tns = oin.readUTF(); String name = oin.readUTF(); this.type = new QName(tns, name); return; } throw new IOException("Unrecognized file format (bad magic number)."); }
/** * Method declaration * * @return */ private Session init() { try { mSocket.setTcpNoDelay(true); mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream())); mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream())); user = mInput.readUTF(); String password = mInput.readUTF(); Session c; try { mServer.trace(mThread + ":trying to connect user " + user); return mServer.mDatabase.connect(user, password); } catch (SQLException e) { write(new Result(e.getMessage(), e.getErrorCode()).getBytes()); } } catch (Exception e) { mServer.trace(mThread + ":couldn't connect " + user); } close(); return null; }
/** Dumps a snapshot to the log. Useful for debugging. */ public static void logSnapshot(byte[] snapshot) { DataInputStream in = new DataInputStream(new ByteArrayInputStream(snapshot)); try { int version = in.readUnsignedShort(); int classCount = in.readUnsignedShort(); StringBuilder sb = new StringBuilder(); sb.append("version=") .append(version) .append(' ') .append("classes=") .append(classCount) .append('\n'); logger.info(sb.toString()); for (int i = 0; i < classCount; i++) { sb = new StringBuilder(); sb.append("class ").append(in.readUTF()).append('\n'); int methodCount = in.readUnsignedShort(); for (int m = 0; m < methodCount; m++) { sb.append(" ").append(in.readUTF()).append(":\n"); sb.append(" event:\n"); appendCounts(in, sb); sb.append(" other:\n"); appendCounts(in, sb); } logger.info(sb.toString()); } } catch (IOException e) { logger.warning(e.toString()); } }
private void deserialize0(ParameterTable.Builder builder, DataInputStream data) throws IOException { int magic = data.readInt(); if (magic != MAGIC) { throw new IOException("parameter table is broken: invalid magic number"); } int version = data.readInt(); if (version != VERSION) { throw new IOException( MessageFormat.format( "inconsistent parameter table version: required={0}, actual={1}", VERSION, version)); } INTERPRETER: while (true) { byte op = data.readByte(); switch (op) { case OP_ROW: builder.next(); break; case OP_CELL: String name = data.readUTF(); String value = data.readUTF(); builder.put(name, value); break; case OP_END: break INTERPRETER; default: throw new IOException(MessageFormat.format("unknown op: {0}", op)); } } }
private void processSetStartupCmd(DataInputStream params, IOTACommandHelper helper) throws IOException { ConfigPage configPage = spot.getConfigPage(); configPage.setStartup(params.readUTF(), params.readUTF(), params.readUTF()); spot.flashConfigPage(configPage); helper.sendPrompt(); }
/** * this method defines the job of the client thread. the client connects to the server to see if * there is message for it in every other interval. */ @Override public void run() { while (true) { Socket socket; try { Thread.sleep(INTERVAL); socket = new Socket(serverUrl, serverPost); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(clientId); DataInputStream in = new DataInputStream(socket.getInputStream()); String hasMessage = in.readUTF(); // check to see if there is unread message if (hasMessage != null && hasMessage.equals("yes")) { boolean done = false; while (!done) { String messageString = in.readUTF(); if (messageString != null) { if (messageString.equals("done!")) break; else { Message message = getMessage(messageString); unReadMessage.add(message); } } } } socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
@Override public void run() { try { msg = dis.readUTF(); System.out.println("메세지 받음"); System.out.println(msg); if (msg.equals("using")) { cMain.loginFrame.UsingMessage(); return; } else { } while (dis != null) { msg = dis.readUTF(); System.out.println(msg); if (msg.equals("stopCom")) { dao_User.UserStop(seatNum); cMain.usingFrame.user.setRun(false); cMain.ShowLogin(cMain.usingFrame); return; } else { chat.receiveMsg(msg); } System.out.println(msg); // cGui.receiveMsg(msg); } } catch (IOException e) { e.printStackTrace(); } // catch(ClassNotFoundException ce){ce.printStackTrace();} }
@Override public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.data)); try { if ("ModConfig".equals(packet.channel)) { int mode = dis.readInt(); if (mode == 0) { String modid = dis.readUTF(); int entryCount = dis.readInt(); int pos = 0; ConfigMod.dbg("modconfig packet, size: " + entryCount); // require a full resync of data, make sure other side sends it all if (!GuiConfigEditor.clientMode || ConfigMod.configLookup.get(modid).configData.size() == 0) { ConfigMod.configLookup.get(modid).configData.clear(); for (int i = 0; i < entryCount; i++) { String str1 = dis.readUTF(); String str2 = dis.readUTF(); String str3 = ""; // dis.readUTF(); ConfigMod.configLookup .get(modid) .configData .add(new ConfigEntryInfo(pos++, str1, str2, str3)); } } } else { openConfigGui(); } } } catch (Exception ex) { // HostileWorlds.dbg("ERROR HANDLING HW PACKETS"); ex.printStackTrace(); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger.getLogger(getClass()).debug("LOGIN device J2ME"); final UserWorkerLocal userWorkerLocal = ServiceLocator.lookupLocal(UserWorkerLocal.JNDI_NAME); final SubjectWorkerLocal subjectWorkerLocal = ServiceLocator.lookupLocal(SubjectWorkerLocal.JNDI_NAME); DataInputStream dis = null; try { dis = new DataInputStream(request.getInputStream()); final String login = dis.readUTF(); final String password = dis.readUTF(); final User user = userWorkerLocal.login(login, password); final String deviceId = subjectWorkerLocal.loginDevice(user); final byte[] resultBytes = deviceId.getBytes("utf-8"); response.setContentLength(resultBytes.length); response.getOutputStream().write(resultBytes); } catch (LoginFailedException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } finally { if (dis != null) { dis.close(); } } }
private static Binder load(byte[] buffer) throws IOException { Binder b; try { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buffer)); String fileName = dis.readUTF(); b = new Binder(fileName); int numberOfNotes = dis.readInt(); String title; String body; for (int i = 0; i < numberOfNotes; i++) { title = dis.readUTF(); body = dis.readUTF(); b.addNote(new Note(title, body)); } dis.close(); } catch (IOException ioe) { ioe.printStackTrace(); throw ioe; } return b; }
public static Member load(String number) throws IOException { Member member; try (DataInputStream input = new DataInputStream(new FileInputStream(number))) { member = new Member(input.readUTF(), input.readUTF(), input.readInt()); } return member; }
public void load(DataInputStream dis) throws IOException { dis.readInt(); // name length this.name = dis.readUTF(); dis.readInt(); // map_kdLength this.map_kd = dis.readUTF(); if (parent.hasTexcoords() && map_kd.length() > 0) { parent.loadTexture(map_kd); } this.ka[0] = dis.readFloat(); this.ka[1] = dis.readFloat(); this.ka[2] = dis.readFloat(); this.ka[3] = dis.readFloat(); this.kd[0] = dis.readFloat(); this.kd[1] = dis.readFloat(); this.kd[2] = dis.readFloat(); this.kd[3] = dis.readFloat(); this.ks[0] = dis.readFloat(); this.ks[1] = dis.readFloat(); this.ks[2] = dis.readFloat(); this.ks[3] = dis.readFloat(); this.ns = dis.readFloat(); this.illum = dis.readInt(); this.d = dis.readFloat(); }
/** * Keep calling this till you get a {@link EOFException} for getting logs of all types for a * single container. * * @param valueStream * @param out * @throws IOException */ public static void readAContainerLogsForALogType(DataInputStream valueStream, PrintStream out) throws IOException { byte[] buf = new byte[65535]; String fileType = valueStream.readUTF(); String fileLengthStr = valueStream.readUTF(); long fileLength = Long.parseLong(fileLengthStr); out.print("LogType: "); out.println(fileType); out.print("LogLength: "); out.println(fileLengthStr); out.println("Log Contents:"); int curRead = 0; long pendingRead = fileLength - curRead; int toRead = pendingRead > buf.length ? buf.length : (int) pendingRead; int len = valueStream.read(buf, 0, toRead); while (len != -1 && curRead < fileLength) { out.write(buf, 0, len); curRead += len; pendingRead = fileLength - curRead; toRead = pendingRead > buf.length ? buf.length : (int) pendingRead; len = valueStream.read(buf, 0, toRead); } out.println(""); }
public String nextLog() throws IOException { if (currentLogData != null && currentLogLength > 0) { // seek to the end of the current log, relying on BoundedInputStream // to prevent seeking past the end of the current log do { if (currentLogData.skip(currentLogLength) < 0) { break; } } while (currentLogData.read() != -1); } currentLogType = null; currentLogLength = 0; currentLogData = null; currentLogISR = null; try { String logType = valueStream.readUTF(); String logLengthStr = valueStream.readUTF(); currentLogLength = Long.parseLong(logLengthStr); currentLogData = new BoundedInputStream(valueStream, currentLogLength); currentLogData.setPropagateClose(false); currentLogISR = new InputStreamReader(currentLogData); currentLogType = logType; } catch (EOFException e) { } return currentLogType; }
/** * Returns ACLs for the application. An empty map is returned if no ACLs are found. * * @return a map of the Application ACLs. * @throws IOException */ public Map<ApplicationAccessType, String> getApplicationAcls() throws IOException { // TODO Seek directly to the key once a comparator is specified. TFile.Reader.Scanner aclScanner = reader.createScanner(); LogKey key = new LogKey(); Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(); while (!aclScanner.atEnd()) { TFile.Reader.Scanner.Entry entry = aclScanner.entry(); key.readFields(entry.getKeyStream()); if (key.toString().equals(APPLICATION_ACL_KEY.toString())) { DataInputStream valueStream = entry.getValueStream(); while (true) { String appAccessOp = null; String aclString = null; try { appAccessOp = valueStream.readUTF(); } catch (EOFException e) { // Valid end of stream. break; } try { aclString = valueStream.readUTF(); } catch (EOFException e) { throw new YarnRuntimeException("Error reading ACLs", e); } acls.put(ApplicationAccessType.valueOf(appAccessOp), aclString); } } aclScanner.advance(); } return acls; }
/** * Writes all logs for a single container to the provided writer. * * @param valueStream * @param writer * @throws IOException */ public static void readAcontainerLogs(DataInputStream valueStream, Writer writer) throws IOException { int bufferSize = 65536; char[] cbuf = new char[bufferSize]; String fileType; String fileLengthStr; long fileLength; while (true) { try { fileType = valueStream.readUTF(); } catch (EOFException e) { // EndOfFile return; } fileLengthStr = valueStream.readUTF(); fileLength = Long.parseLong(fileLengthStr); writer.write("\n\nLogType:"); writer.write(fileType); writer.write("\nLogLength:"); writer.write(fileLengthStr); writer.write("\nLog Contents:\n"); // ByteLevel BoundedInputStream bis = new BoundedInputStream(valueStream, fileLength); InputStreamReader reader = new InputStreamReader(bis); int currentRead = 0; int totalRead = 0; while ((currentRead = reader.read(cbuf, 0, bufferSize)) != -1) { writer.write(cbuf, 0, currentRead); totalRead += currentRead; } } }
@Test public void dataRoundTrip() throws IOException { dos.writeUTF("Hello, world!"); dos.writeInt(0xCAFEBABE); dos.writeUTF("Over & out."); dos.close(); // aos.close(); // important? byte[] bs = bos.toByteArray(); if (verbose) { for (int i = 0; i < bs.length; i++) { System.out.printf("%02x ", bs[i]); if (i % 16 == 15) System.out.println(); } System.out.println(); } PPMModel pi = new PPMModel(4); ByteArrayInputStream bis = new ByteArrayInputStream(bs); ArithCodeInputStream ais = new ArithCodeInputStream(bis, pi); DataInputStream dis = new DataInputStream(ais); String s1 = dis.readUTF(); assert s1.equals("Hello, world!") : s1; int i1 = dis.readInt(); assert 0xCAFEBABE == i1 : i1; String s2 = dis.readUTF(); assert s2.equals("Over & out.") : s2; int i2 = dis.read(); assert -1 == i2 : i2; }
public static ArrayList<Patient> getPatientList(Socket socket, ArrayList<Patient> patientList) { int id; String ic; String fname; String lname; int age; int cnumber; try { OutputStream output = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(output); InputStream input = socket.getInputStream(); DataInputStream dis = new DataInputStream(input); dos.writeInt(2); int numberOfPatients = dis.readInt(); for (int i = 0; i < numberOfPatients; i++) { id = dis.readInt(); ic = dis.readUTF(); fname = dis.readUTF(); lname = dis.readUTF(); age = dis.readInt(); cnumber = dis.readInt(); patientList.add(new Patient(id, ic, fname, lname, age, cnumber)); } } catch (IOException e) { System.out.println("Cannot get IO streams."); } return patientList; }
void ReceiveFile() throws Exception { String fileName; fileName = din.readUTF(); if (fileName != null && !fileName.equals("NOFILE")) { System.out.println("Receiving File"); File f = new File( System.getProperty("user.home") + "/Desktop" + "/" + fileName.substring(fileName.lastIndexOf("/") + 1)); System.out.println(f.toString()); f.createNewFile(); FileOutputStream fout = new FileOutputStream(f); int ch; String temp; do { temp = din.readUTF(); ch = Integer.parseInt(temp); if (ch != -1) { fout.write(ch); } } while (ch != -1); System.out.println("Received File : " + fileName); fout.close(); } else { } }
@Override public void run() { try { while (true) { clientMessage = this.nodeInput.readUTF(); if (clientMessage.equals("chatClient-hello")) { this.nodeOutput.writeUTF("chat-request_name_id"); this.nodeName = nodeInput.readUTF(); this.nodeID = nodeInput.readInt(); System.out.println("ChatClient: " + this.nodeName + " with ID: " + this.nodeID); } else if (clientMessage.equals("chatClient-sending_message")) { nodes = ChatServer.getNodes(); messageToBeSent = nodeInput.readUTF(); for (int i = 0; i < 4; i++) { this.nodes.get(i).nodeOutput.writeUTF("chat-sending_message"); this.nodes.get(i).nodeOutput.writeUTF(this.nodeName + " says: " + messageToBeSent); } System.out.println("Message has been sent: " + messageToBeSent); } } // while } catch (IOException ex) { System.err.println("Error in ChatNode"); ex.printStackTrace(); } } // run()
/** Reinstantiate a StateEngine from the stream. */ public void deserializeFrom(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); if (dis.readInt() != STATE_ENGINE_SERIALIZATION_FORMAT_VERSION) { throw new RuntimeException( "Refusing to reinstantiate FastBlobStateEngine due to serialized version mismatch."); } latestVersion = dis.readUTF(); int numHeaderTagEntries = dis.readShort(); headerTags.clear(); headerTags = new HashMap<String, String>(); for (int i = 0; i < numHeaderTagEntries; i++) { headerTags.put(dis.readUTF(), dis.readUTF()); } int numConfigs = VarInt.readVInt(dis); int numStates = VarInt.readVInt(dis); for (int i = 0; i < numStates; i++) { String typeName = dis.readUTF(); FastBlobTypeSerializationState<?> typeState = serializationTypeStates.get(typeName); if (typeState != null) { typeState.deserializeFrom(dis, numConfigs); } else { FastBlobTypeSerializationState.discardSerializedTypeSerializationState(dis, numConfigs); } } }
public VoldemortOperation(byte[] bytes) { if (bytes == null || bytes.length <= 1) throw new SerializationException("Not enough bytes to serialize"); DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(bytes)); try { this.opCode = inputStream.readByte(); switch (opCode) { case VoldemortOpCode.GET_OP_CODE: this.version = null; this.key = inputStream.readUTF(); this.value = null; break; case VoldemortOpCode.PUT_OP_CODE: this.version = new VectorClock(bytes, 1); this.key = inputStream.readUTF(); int valueSize = inputStream.readInt(); this.value = new byte[valueSize]; ByteUtils.read(inputStream, this.value); break; case VoldemortOpCode.DELETE_OP_CODE: this.version = new VectorClock(bytes, 1); this.key = inputStream.readUTF(); this.value = null; break; default: throw new SerializationException("Unknown opcode: " + bytes[0]); } } catch (IOException e) { throw new SerializationException(e); } }
public static void main(String[] args) throws IOException { FileReader in = new FileReader("frog.txt"); FileWriter out = new FileWriter("prince.txt"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); // Read file name from stdin BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a valid filename: "); String fileName = stdin.readLine(); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName))); outStream.writeDouble(3.14); outStream.writeUTF("That is pi"); outStream.writeDouble(1.41413); outStream.writeUTF("Square root of 2"); outStream.close(); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); System.out.println(inStream.readDouble()); System.out.println(inStream.readUTF()); System.out.println(inStream.readDouble()); System.out.println(inStream.readUTF()); }
public static Client getClientInfo(DataInputStream in) { try { return new Client(in.readUTF(), in.readUTF(), in.readUTF(), in.readBoolean()); } catch (Exception e) { e.printStackTrace(); return null; } }
protected void read(DataInputStream s) { try { ref = new WeakReference<DataBuffer>(this, Nd4j.bufferRefQueue()); referencing = Collections.synchronizedSet(new HashSet<String>()); dirty = new AtomicBoolean(false); allocationMode = AllocationMode.valueOf(s.readUTF()); length = s.readInt(); Type t = Type.valueOf(s.readUTF()); if (t == Type.DOUBLE) { if (allocationMode == AllocationMode.HEAP) { if (this.dataType() == Type.FLOAT) { // DataBuffer type // double -> float floatData = new float[length()]; } else if (this.dataType() == Type.DOUBLE) { // double -> double doubleData = new double[length()]; } else { // double -> int intData = new int[length()]; } for (int i = 0; i < length(); i++) { put(i, s.readDouble()); } } else { wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize()); wrappedBuffer.order(ByteOrder.nativeOrder()); for (int i = 0; i < length(); i++) { put(i, s.readDouble()); } } } else { if (allocationMode == AllocationMode.HEAP) { if (this.dataType() == Type.FLOAT) { // DataBuffer type // float -> float floatData = new float[length()]; } else if (this.dataType() == Type.DOUBLE) { // float -> double doubleData = new double[length()]; } else { // float-> int intData = new int[length()]; } for (int i = 0; i < length(); i++) { put(i, s.readFloat()); } } else { wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize()); wrappedBuffer.order(ByteOrder.nativeOrder()); for (int i = 0; i < length(); i++) { put(i, s.readFloat()); } } } } catch (Exception e) { throw new RuntimeException(e); } }
private void getuserinfo(String name) throws IOException { ToServer.writeUTF("iserinfo"); ToServer.writeUTF(name); txaddname.setText(FromServer.readUTF()); txaddpass.setText(FromServer.readUTF()); txgroupname.setText(FromServer.readUTF()); if (FromServer.readUTF().equals("1")) cboxadmin.setSelected(true); else cboxadmin.setSelected(false); }
public NameVersion(DataInputStream dis) throws IOException { String n = dis.readUTF(); String v = dis.readUTF(); String l = dis.readUTF(); if (l.length() == 0) { l = null; } init(n, v, l); }
/** * Read the form-lemma mapping not read by operations * * @param dis */ public void readMap(DataInputStream dis) { try { int size = dis.readInt(); for (int i = 0; i < size; i++) { opse.put(dis.readUTF(), dis.readUTF()); } } catch (IOException e1) { e1.printStackTrace(); } }