List of usage examples for java.io DataInputStream readInt
public final int readInt() throws IOException
readInt
method of DataInput
. From source file:org.apache.pulsar.testclient.LoadSimulationClient.java
private void handle(final byte command, final DataInputStream inputStream, final DataOutputStream outputStream) throws Exception { final TradeConfiguration tradeConf = new TradeConfiguration(); tradeConf.command = command;/*from ww w.ja v a 2s. c om*/ switch (command) { case CHANGE_COMMAND: // Change the topic's settings if it exists. decodeProducerOptions(tradeConf, inputStream); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { topicsToTradeUnits.get(tradeConf.topic).change(tradeConf); } break; case STOP_COMMAND: // Stop the topic if it exists. tradeConf.topic = inputStream.readUTF(); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { topicsToTradeUnits.get(tradeConf.topic).stop.set(true); } break; case TRADE_COMMAND: // Create the topic. It is assumed that the topic does not already exist. decodeProducerOptions(tradeConf, inputStream); final TradeUnit tradeUnit = new TradeUnit(tradeConf, client, producerConf, consumerConf, payloadCache); topicsToTradeUnits.put(tradeConf.topic, tradeUnit); executor.submit(() -> { try { final String topic = tradeConf.topic; final String namespace = topic.substring("persistent://".length(), topic.lastIndexOf('/')); try { admin.namespaces().createNamespace(namespace); } catch (PulsarAdminException.ConflictException e) { // Ignore, already created namespace. } tradeUnit.start(); } catch (Exception ex) { throw new RuntimeException(ex); } }); break; case CHANGE_GROUP_COMMAND: // Change the settings of all topics belonging to a group. decodeGroupOptions(tradeConf, inputStream); tradeConf.size = inputStream.readInt(); tradeConf.rate = inputStream.readDouble(); // See if a topic belongs to this tenant and group using this regex. final String groupRegex = ".*://" + tradeConf.tenant + "/.*/" + tradeConf.group + "-.*/.*"; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(groupRegex)) { unit.change(tradeConf); } } break; case STOP_GROUP_COMMAND: // Stop all topics belonging to a group. decodeGroupOptions(tradeConf, inputStream); // See if a topic belongs to this tenant and group using this regex. final String regex = ".*://" + tradeConf.tenant + "/.*/" + tradeConf.group + "-.*/.*"; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(regex)) { unit.stop.set(true); } } break; case FIND_COMMAND: // Write a single boolean indicating if the topic was found. outputStream.writeBoolean(topicsToTradeUnits.containsKey(inputStream.readUTF())); outputStream.flush(); break; default: throw new IllegalArgumentException("Unrecognized command code received: " + command); } }
From source file:se.llbit.chunky.renderer.scene.Scene.java
public synchronized void loadDump(RenderContext context, RenderStatusListener renderListener) { String fileName = name + ".dump"; DataInputStream in = null; try {/* w ww. j a v a 2 s. c o m*/ in = new DataInputStream(new GZIPInputStream(context.getSceneFileInputStream(fileName))); String task = "Loading render dump"; renderListener.setProgress(task, 1, 0, 2); Log.info("Loading render dump " + fileName); int dumpWidth = in.readInt(); int dumpHeight = in.readInt(); if (dumpWidth != width || dumpHeight != height) { Log.warn("Render dump discarded: incorrect width or height!"); in.close(); return; } spp = in.readInt(); renderTime = in.readLong(); // Update render status renderListener.setSPP(spp); renderListener.setRenderTime(renderTime); long totalSamples = spp * ((long) (width * height)); renderListener.setSamplesPerSecond((int) (totalSamples / (renderTime / 1000.0))); for (int x = 0; x < width; ++x) { renderListener.setProgress(task, x + 1, 0, width); for (int y = 0; y < height; ++y) { samples[(y * width + x) * 3 + 0] = in.readDouble(); samples[(y * width + x) * 3 + 1] = in.readDouble(); samples[(y * width + x) * 3 + 2] = in.readDouble(); finalizePixel(x, y); } } Log.info("Render dump loaded"); } catch (IOException e) { Log.info("Render dump not loaded"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
From source file:se.llbit.chunky.renderer.scene.Scene.java
/** * Merge a render dump into this scene/*from ww w. j ava2 s.c o m*/ * @param dumpFile * @param renderListener */ public void mergeDump(File dumpFile, RenderStatusListener renderListener) { int dumpSpp; long dumpTime; DataInputStream in = null; try { in = new DataInputStream(new GZIPInputStream(new FileInputStream(dumpFile))); String task = "Merging render dump"; renderListener.setProgress(task, 1, 0, 2); Log.info("Loading render dump " + dumpFile.getAbsolutePath()); int dumpWidth = in.readInt(); int dumpHeight = in.readInt(); if (dumpWidth != width || dumpHeight != height) { Log.warn("Render dump discarded: incorrect widht or height!"); in.close(); return; } dumpSpp = in.readInt(); dumpTime = in.readLong(); double sa = spp / (double) (spp + dumpSpp); double sb = 1 - sa; for (int x = 0; x < width; ++x) { renderListener.setProgress(task, x + 1, 0, width); for (int y = 0; y < height; ++y) { samples[(y * width + x) * 3 + 0] = samples[(y * width + x) * 3 + 0] * sa + in.readDouble() * sb; samples[(y * width + x) * 3 + 1] = samples[(y * width + x) * 3 + 1] * sa + in.readDouble() * sb; samples[(y * width + x) * 3 + 2] = samples[(y * width + x) * 3 + 2] * sa + in.readDouble() * sb; finalizePixel(x, y); } } Log.info("Render dump loaded"); // Update render status spp += dumpSpp; renderTime += dumpTime; renderListener.setSPP(spp); renderListener.setRenderTime(renderTime); long totalSamples = spp * ((long) (width * height)); renderListener.setSamplesPerSecond((int) (totalSamples / (renderTime / 1000.0))); } catch (IOException e) { Log.info("Render dump not loaded"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
From source file:ClassFile.java
public boolean read(DataInputStream dis) throws IOException { int len;/*from w w w .j av a2 s . co m*/ char c; type = dis.readByte(); switch (type) { case CLASS: name = "Class"; index1 = dis.readShort(); index2 = -1; break; case FIELDREF: name = "Field Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case METHODREF: name = "Method Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case INTERFACE: name = "Interface Method Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case NAMEANDTYPE: name = "Name and Type"; index1 = dis.readShort(); index2 = dis.readShort(); break; case STRING: name = "String"; index1 = dis.readShort(); index2 = -1; break; case INTEGER: name = "Integer"; intValue = dis.readInt(); break; case FLOAT: name = "Float"; floatValue = dis.readFloat(); break; case LONG: name = "Long"; longValue = dis.readLong(); break; case DOUBLE: name = "Double"; doubleValue = dis.readDouble(); break; case ASCIZ: case UNICODE: if (type == ASCIZ) name = "ASCIZ"; else name = "UNICODE"; StringBuffer xxBuf = new StringBuffer(); len = dis.readShort(); while (len > 0) { c = (char) (dis.readByte()); xxBuf.append(c); len--; } strValue = xxBuf.toString(); break; default: System.out.println("Warning bad type."); } return (true); }
From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java
private void handle(final byte command, final DataInputStream inputStream, final DataOutputStream outputStream) throws Exception { final TradeConfiguration tradeConf = new TradeConfiguration(); tradeConf.command = command;//from w ww. j av a 2 s . c o m switch (command) { case CHANGE_COMMAND: // Change the topic's settings if it exists. Report whether the // topic was found on this server. decodeProducerOptions(tradeConf, inputStream); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { topicsToTradeUnits.get(tradeConf.topic).change(tradeConf); outputStream.write(FOUND_TOPIC); } else { outputStream.write(NO_SUCH_TOPIC); } break; case STOP_COMMAND: // Stop the topic if it exists. Report whether the topic was found, // and whether it was already stopped. tradeConf.topic = inputStream.readUTF(); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { final boolean wasStopped = topicsToTradeUnits.get(tradeConf.topic).stop.getAndSet(true); outputStream.write(wasStopped ? REDUNDANT_COMMAND : FOUND_TOPIC); } else { outputStream.write(NO_SUCH_TOPIC); } break; case TRADE_COMMAND: // Create the topic. It is assumed that the topic does not already // exist. decodeProducerOptions(tradeConf, inputStream); final TradeUnit tradeUnit = new TradeUnit(tradeConf, client, producerConf, consumerConf, payloadCache); topicsToTradeUnits.put(tradeConf.topic, tradeUnit); executor.submit(() -> { try { tradeUnit.start(); } catch (Exception ex) { throw new RuntimeException(ex); } }); // Tell controller topic creation is finished. outputStream.write(NO_SUCH_TOPIC); break; case CHANGE_GROUP_COMMAND: // Change the settings of all topics belonging to a group. Report // the number of topics changed. decodeGroupOptions(tradeConf, inputStream); tradeConf.size = inputStream.readInt(); tradeConf.rate = inputStream.readDouble(); // See if a topic belongs to this tenant and group using this regex. final String groupRegex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*"; int numFound = 0; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(groupRegex)) { ++numFound; unit.change(tradeConf); } } outputStream.writeInt(numFound); break; case STOP_GROUP_COMMAND: // Stop all topics belonging to a group. Report the number of topics // stopped. decodeGroupOptions(tradeConf, inputStream); // See if a topic belongs to this tenant and group using this regex. final String regex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*"; int numStopped = 0; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(regex) && !unit.stop.getAndSet(true)) { ++numStopped; } } outputStream.writeInt(numStopped); break; default: throw new IllegalArgumentException("Unrecognized command code received: " + command); } outputStream.flush(); }
From source file:org.ramadda.repository.database.DatabaseManager.java
/** * _more_/*from ww w. j ava 2 s . co m*/ * * @param dos _more_ * * @return _more_ * * @throws Exception _more_ */ private String readString(DataInputStream dos) throws Exception { int length = dos.readInt(); if (length < 0) { return null; } byte[] bytes = new byte[length]; dos.read(bytes); return new String(bytes); }
From source file:com.android.launcher2.Launcher.java
private static void readConfiguration(Context context, LocaleConfiguration configuration) { DataInputStream in = null; try {//from w w w . j ava 2s. c om in = new DataInputStream(context.openFileInput(PREFERENCES)); configuration.locale = in.readUTF(); configuration.mcc = in.readInt(); configuration.mnc = in.readInt(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // Ignore } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } } }
From source file:com.symbian.driver.core.controller.tasks.TEFTask.java
/** * @param aVisitor// www . java 2s . co m * @param aTestExecuteScript * @param lExecuteOnDevice * @param aTask * @return The last execption raised when running UCC. * @throws JStatException */ private boolean runUCC(List<String> aArgs, Task aTask) { boolean lReturn = true; Socket lUccSocket = null; DataOutputStream lSocketOut = null; DataInputStream lSocketIn = null; int lRunNumber = 0; int lUccPort = -1; String lUccAddress = null; IDeviceComms.ISymbianProcess lProcess = null; try { String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":"); lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER); lUccAddress = lUccSplit[0]; lUccPort = Integer.parseInt(lUccSplit[1]); } catch (ParseException lParseException) { LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException); iExceptions.put(lParseException, ESeverity.ERROR); lReturn = false; } catch (NumberFormatException lNumberFormatException) { LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException); iExceptions.put(lNumberFormatException, ESeverity.ERROR); lReturn = false; } if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) { iExceptions.put( new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"), ESeverity.ERROR); return false; } // Run the test try { LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort); lUccSocket = new Socket(lUccAddress, lUccPort); lSocketOut = new DataOutputStream(lUccSocket.getOutputStream()); lSocketIn = new DataInputStream(lUccSocket.getInputStream()); LOGGER.fine("Starting UCC while still polling"); lProcess = iDeviceProxy.createSymbianProcess(); if (lProcess != null) { // run and don't wait if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) { iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR); lReturn = false; } // Tell UCC that the test has started. LOGGER.fine("Writing to UCC socket: " + lRunNumber); lSocketOut.writeInt(lRunNumber); lSocketOut.flush(); int lUCCReply = lSocketIn.readInt(); LOGGER.fine("UCC Reply: " + lUCCReply); } } catch (UnknownHostException lUnknownHostException) { LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException); iExceptions.put(lUnknownHostException, ESeverity.ERROR); return false; } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: " + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:" + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound() : "\nUcc Socket is NULL"), lIOException); iExceptions.put(lIOException, ESeverity.ERROR); return false; } finally { // Close UCC if (lSocketOut != null) { try { LOGGER.log(Level.FINE, "Closing Socket Out."); lUccSocket.shutdownInput(); lUccSocket.shutdownOutput(); lSocketOut.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lSocketIn != null) { try { LOGGER.log(Level.FINE, "Closing Socket In."); lSocketIn.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lUccSocket != null) { try { LOGGER.log(Level.FINE, "Closing Socket UCC."); lUccSocket.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (!lUccSocket.isClosed()) { LOGGER.warning("Could not close the UCC sockets properly."); } lSocketOut = null; lSocketIn = null; lUccSocket = null; // Poll TEF Test if (!lProcess.join()) { iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR); lReturn = false; } } return lReturn; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * Used by client-side CacheClientUpdater to handshake with a server in order to receive messages * generated by subscriptions (register-interest, continuous query) *///ww w .jav a 2 s .c o m public ServerQueueStatus handshakeWithSubscriptionFeed(Socket sock, boolean isPrimary) throws IOException, AuthenticationRequiredException, AuthenticationFailedException, ServerRefusedConnectionException, ClassNotFoundException { ServerQueueStatus sqs = null; try { DataOutputStream dos = new DataOutputStream(sock.getOutputStream()); final InputStream in = sock.getInputStream(); DataInputStream dis = new DataInputStream(in); DistributedMember member = getIDForSocket(sock); if (!this.multiuserSecureMode) { this.credentials = getCredentials(member); } CommunicationMode mode = isPrimary ? CommunicationMode.PrimaryServerToClient : CommunicationMode.SecondaryServerToClient; write(dos, dis, mode, REPLY_OK, 0, new ArrayList(), this.credentials, member, true); // Wait here for a reply before continuing. This ensures that the client // updater is registered with the server before continuing. byte acceptanceCode = dis.readByte(); if (acceptanceCode == (byte) 21 && !(sock instanceof SSLSocket)) { // This is likely the case of server setup with SSL and client not using // SSL throw new AuthenticationRequiredException( LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION.toLocalizedString()); } // No need to check for return value since DataInputStream already throws // EOFException in case of EOF byte qType = dis.readByte(); // read and ignore qSize flag int qSize = dis.readInt(); sqs = new ServerQueueStatus(qType, qSize, member); // Read the message (if any) readMessage(dis, dos, acceptanceCode, member); // [sumedh] nothing more to be done for older clients used in tests // there is a difference in serializer map registration for >= 6.5.1.6 // clients but that is not used in tests if (currentClientVersion.compareTo(Version.GFE_61) < 0) { return sqs; } HashMap instantiatorMap = DataSerializer.readHashMap(dis); for (Iterator itr = instantiatorMap.entrySet().iterator(); itr.hasNext();) { Map.Entry instantiator = (Map.Entry) itr.next(); Integer id = (Integer) instantiator.getKey(); ArrayList instantiatorArguments = (ArrayList) instantiator.getValue(); InternalInstantiator.register((String) instantiatorArguments.get(0), (String) instantiatorArguments.get(1), id, false); } HashMap dataSerializersMap = DataSerializer.readHashMap(dis); for (Iterator itr = dataSerializersMap.entrySet().iterator(); itr.hasNext();) { Map.Entry dataSerializer = (Map.Entry) itr.next(); Integer id = (Integer) dataSerializer.getKey(); InternalDataSerializer.register((String) dataSerializer.getValue(), false, null, null, id); } HashMap<Integer, ArrayList<String>> dsToSupportedClassNames = DataSerializer.readHashMap(dis); InternalDataSerializer.updateSupportedClassesMap(dsToSupportedClassNames); } catch (IOException ex) { CancelCriterion stopper = this.system.getCancelCriterion(); stopper.checkCancelInProgress(null); throw ex; } catch (ClassNotFoundException ex) { CancelCriterion stopper = this.system.getCancelCriterion(); stopper.checkCancelInProgress(null); throw ex; } return sqs; }
From source file:org.apache.giraph.ooc.DiskBackedPartitionStore.java
/** * Load messages for a given partition for the current superstep to memory. * * @param partitionId Id of the partition to load the messages for * @throws IOException/*ww w.j ava 2 s . c o m*/ */ private void loadMessages(int partitionId) throws IOException { // Messages for current superstep if (currentMessageStore != null && !conf.getOutgoingMessageClasses().useMessageCombiner()) { checkState(!currentMessageStore.hasMessagesForPartition(partitionId), "loadMessages: partition " + partitionId + " is on disk, " + "but its message store is in memory (impossible)"); // First, reading the message store for the partition if there is any File file = new File(getMessagesPath(partitionId, serviceWorker.getSuperstep())); if (file.exists()) { if (LOG.isDebugEnabled()) { LOG.debug("loadMessages: loading message store of partition " + partitionId); } FileInputStream filein = new FileInputStream(file); BufferedInputStream bufferin = new BufferedInputStream(filein); DataInputStream inputStream = new DataInputStream(bufferin); currentMessageStore.readFieldsForPartition(inputStream, partitionId); inputStream.close(); checkState(file.delete(), "loadMessages: failed to delete %s.", file.getAbsolutePath()); } messageBufferRWLock.writeLock().lock(); Pair<Integer, List<VertexIdMessages<I, Writable>>> pendingMessages = pendingCurrentMessages .remove(partitionId); messageBufferRWLock.writeLock().unlock(); // Second, reading message buffers (incoming messages in previous // superstep) file = new File(getPendingMessagesBufferPath(partitionId, serviceWorker.getSuperstep())); if (file.exists()) { FileInputStream filein = new FileInputStream(file); BufferedInputStream bufferin = new BufferedInputStream(filein); DataInputStream inputStream = new DataInputStream(bufferin); while (true) { int type; try { type = inputStream.readInt(); } catch (EOFException e) { // Reached end of file, so all the records are read. break; } SerializedMessageClass messageClass = SerializedMessageClass.values()[type]; VertexIdMessages<I, Writable> vim; switch (messageClass) { case BYTE_ARRAY_VERTEX_ID_MESSAGES: vim = new ByteArrayVertexIdMessages<>(conf.createOutgoingMessageValueFactory()); vim.setConf(conf); break; case BYTE_ARRAY_ONE_MESSAGE_TO_MANY_IDS: vim = new ByteArrayOneMessageToManyIds<>(conf.createOutgoingMessageValueFactory()); vim.setConf(conf); break; default: throw new IllegalStateException("loadMessages: unsupported " + "serialized message type!"); } vim.readFields(inputStream); currentMessageStore.addPartitionMessages(partitionId, vim); } inputStream.close(); checkState(!file.delete(), "loadMessages: failed to delete %s", file.getAbsolutePath()); } // Third, applying message buffers already in memory if (pendingMessages != null) { for (VertexIdMessages<I, Writable> vim : pendingMessages.getRight()) { currentMessageStore.addPartitionMessages(partitionId, vim); } } currentMessagesOnDisk.put(partitionId, false); } }