List of usage examples for java.io DataInputStream readBoolean
public final boolean readBoolean() throws IOException
readBoolean
method of DataInput
. From source file:org.apache.nifi.distributed.cache.client.DistributedMapCacheClientService.java
@Override public <K, V> boolean putIfAbsent(final K key, final V value, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws IOException { return withCommsSession(new CommsAction<Boolean>() { @Override/*from ww w . j a va 2s. c o m*/ public Boolean execute(final CommsSession session) throws IOException { final DataOutputStream dos = new DataOutputStream(session.getOutputStream()); dos.writeUTF("putIfAbsent"); serialize(key, keySerializer, dos); serialize(value, valueSerializer, dos); dos.flush(); final DataInputStream dis = new DataInputStream(session.getInputStream()); return dis.readBoolean(); } }); }
From source file:epn.edu.ec.bibliotecadigital.cliente.Client.java
@Override public void run() { try {//from w w w . j ava2 s . co m clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer); DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream()); DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream()); dataOut.writeUTF((String) params[0]);//nombre de usuario String ipServer = dataInBalancer.readUTF(); int portServer = dataInBalancer.readInt(); clientSocketBalancer.close(); Socket clientSocket = new Socket(ipServer, portServer); dataOut = new DataOutputStream(clientSocket.getOutputStream()); dataOut.writeUTF(accion); dataOut.writeUTF((String) params[0]);//nombre de usuario InputStream in; DataInputStream dataIn; switch (accion) { case "bajar": dataOut = new DataOutputStream(clientSocket.getOutputStream()); dataOut.writeUTF((String) params[1]); dataIn = new DataInputStream(clientSocket.getInputStream()); boolean encontrado = dataIn.readBoolean(); if (!encontrado) { System.out.println("Libro con el cdigo: " + params[1] + " no encontrado"); break; } String fileName = dataIn.readUTF(); System.out.println( "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads"); String home = System.getProperty("user.home"); in = clientSocket.getInputStream(); try { FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName)); byte[] bytes = new byte[64 * 1024]; int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } out.close(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(in); } break; case "subir": dataOut = new DataOutputStream(clientSocket.getOutputStream()); dataOut.writeUTF(((File) params[1]).getName()); OutputStream out = clientSocket.getOutputStream(); try { byte[] bytes = new byte[64 * 1024]; in = new FileInputStream((File) params[1]); int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } in.close(); } finally { IOUtils.closeQuietly(out); } break; case "obtenerLista": ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream()); System.out.println("Libros disponibles: \n"); List<Libro> libros = (List<Libro>) inFromClient.readObject(); System.out.println("\tCdigo\tNommbre\n"); for (Libro lbr : libros) { System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre()); } inFromClient.close(); break; case "verificar": break; } dataOut.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:WriteReadMixedDataTypesExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*www . j av a 2 s . co m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString = "First Record"; int outputInteger = 15; boolean outputBoolean = true; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); outputDataStream.writeUTF(outputString); outputDataStream.writeBoolean(outputBoolean); outputDataStream.writeInt(outputInteger); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { String inputString = null; int inputInteger = 0; boolean inputBoolean = false; byte[] byteInputData = new byte[100]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); for (int x = 1; x <= recordstore.getNumRecords(); x++) { recordstore.getRecord(x, byteInputData, 0); inputString = inputDataStream.readUTF(); inputBoolean = inputDataStream.readBoolean(); inputInteger = inputDataStream.readInt(); inputStream.reset(); } inputStream.close(); inputDataStream.close(); alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }
From source file:org.apache.nifi.distributed.cache.client.DistributedMapCacheClientService.java
@Override public <K, V> void put(final K key, final V value, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws IOException { withCommsSession(new CommsAction<Object>() { @Override//w w w .ja v a2s . c o m public Object execute(final CommsSession session) throws IOException { final DataOutputStream dos = new DataOutputStream(session.getOutputStream()); dos.writeUTF("put"); serialize(key, keySerializer, dos); serialize(value, valueSerializer, dos); dos.flush(); final DataInputStream dis = new DataInputStream(session.getInputStream()); final boolean success = dis.readBoolean(); if (!success) { throw new IOException( "Expected to receive confirmation of 'put' request but received unexpected response"); } return null; } }); }
From source file:org.apache.cassandra.db.ReadCommand.java
public ReadCommand deserialize(DataInputStream dis) throws IOException { String table = dis.readUTF(); String key = dis.readUTF();/*from ww w.ja v a 2 s. c om*/ String columnFamily_column = dis.readUTF(); int start = dis.readInt(); int count = dis.readInt(); long sinceTimestamp = dis.readLong(); boolean isDigest = dis.readBoolean(); int size = dis.readInt(); List<String> columns = new ArrayList<String>(); for (int i = 0; i < size; ++i) { byte[] bytes = new byte[dis.readInt()]; dis.readFully(bytes); columns.add(new String(bytes)); } ReadCommand rm = null; if (columns.size() > 0) { rm = new ReadCommand(table, key, columnFamily_column, columns); } else if (sinceTimestamp > 0) { rm = new ReadCommand(table, key, columnFamily_column, sinceTimestamp); } else { rm = new ReadCommand(table, key, columnFamily_column, start, count); } rm.setDigestQuery(isDigest); return rm; }
From source file:com.ryan.ryanreader.cache.PersistentCookieStore.java
public PersistentCookieStore(final byte[] data) throws IOException { final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); final int len = dis.readInt(); for (int i = 0; i < len; i++) { final String name = dis.readUTF(); final String value = dis.readUTF(); final String domain = dis.readUTF(); final String path = dis.readUTF(); final boolean isSecure = dis.readBoolean(); final BasicClientCookie cookie = new BasicClientCookie(name, value); cookie.setDomain(domain);/*from w ww. jav a 2 s . co m*/ cookie.setPath(path); cookie.setSecure(isSecure); cookies.add(cookie); } }
From source file:org.openmrs.module.odkconnector.serialization.processor.HttpProcessor.java
/** * Process any stream connection to this module * * @param inputStream the input stream/*from w ww.java2 s .c o m*/ * @param outputStream the output stream * @throws Exception when the stream processing failed */ @Override public void process(final InputStream inputStream, final OutputStream outputStream) throws Exception { GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(inputStream)); DataInputStream dataInputStream = new DataInputStream(gzipInputStream); String username = dataInputStream.readUTF(); String password = dataInputStream.readUTF(); Boolean savedSearch = dataInputStream.readBoolean(); Integer cohortId = 0; Integer programId = 0; if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) { cohortId = dataInputStream.readInt(); programId = dataInputStream.readInt(); } dataInputStream.close(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new BufferedOutputStream(outputStream)); DataOutputStream dataOutputStream = new DataOutputStream(gzipOutputStream); try { Context.openSession(); Context.authenticate(username, password); dataOutputStream.writeInt(HttpURLConnection.HTTP_OK); dataOutputStream.flush(); if (log.isDebugEnabled()) { log.debug("Saved Search Value: " + savedSearch); log.debug("Cohort ID: " + cohortId); log.debug("Program ID: " + programId); } Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class); if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) { ConnectorService connectorService = Context.getService(ConnectorService.class); Cohort cohort = new Cohort(); if (savedSearch) { CohortSearchHistory history = new CohortSearchHistory(); PatientSearchReportObject patientSearchReportObject = (PatientSearchReportObject) Context .getReportObjectService().getReportObject(cohortId); if (patientSearchReportObject != null) { if (log.isDebugEnabled()) { log.debug("Object Class: " + patientSearchReportObject.getClass()); log.debug("Object Name: " + patientSearchReportObject.getName()); log.debug("Object Subtype: " + patientSearchReportObject.getSubType()); log.debug("Object Type: " + patientSearchReportObject.getType()); } history.addSearchItem(PatientSearch.createSavedSearchReference(cohortId)); cohort = history.getPatientSet(0, null); } } else { cohort = Context.getCohortService().getCohort(cohortId); } if (log.isDebugEnabled()) log.debug("Cohort data: " + cohort.getMemberIds()); log.info("Streaming patients information!"); serializer.write(dataOutputStream, connectorService.getCohortPatients(cohort)); // check the concept list Collection<Concept> concepts = null; ConceptConfiguration conceptConfiguration = connectorService.getConceptConfiguration(programId); if (conceptConfiguration != null) { if (log.isDebugEnabled()) log.debug("Printing concept configuration information: " + conceptConfiguration); concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts()); } log.info("Streaming observations information!"); serializer.write(dataOutputStream, connectorService.getCohortObservations(cohort, concepts)); // evaluate and get the applicable form for the patients CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class); ReportingConnectorService reportingService = Context.getService(ReportingConnectorService.class); List<ExtendedDefinition> definitions = reportingService.getAllExtendedDefinition(); EvaluationContext context = new EvaluationContext(); context.setBaseCohort(cohort); Collection intersectedMemberIds = Collections.emptyList(); List<SerializedForm> serializedForms = new ArrayList<SerializedForm>(); for (ExtendedDefinition definition : definitions) { if (definition.containsProperty(ExtendedDefinition.DEFINITION_PROPERTY_FORM)) { if (log.isDebugEnabled()) log.debug("Evaluating: " + definition.getCohortDefinition().getName()); EvaluatedCohort evaluatedCohort = cohortDefinitionService .evaluate(definition.getCohortDefinition(), context); // the cohort could be null, so we don't want to get exception during the intersection process if (cohort != null) intersectedMemberIds = CollectionUtils.intersection(cohort.getMemberIds(), evaluatedCohort.getMemberIds()); if (log.isDebugEnabled()) log.debug("Cohort data after intersection: " + intersectedMemberIds); for (DefinitionProperty definitionProperty : definition.getProperties()) { // skip retired definition property if (definitionProperty.isRetired()) continue; Integer formId = NumberUtils.toInt(definitionProperty.getPropertyValue()); for (Object patientId : intersectedMemberIds) serializedForms.add( new SerializedForm(NumberUtils.toInt(String.valueOf(patientId)), formId)); } } } if (log.isDebugEnabled()) log.debug("Serialized form informations:" + serializedForms); log.info("Streaming forms information!"); serializer.write(dataOutputStream, serializedForms); } else { if (savedSearch) { List<SerializedCohort> serializedCohorts = new ArrayList<SerializedCohort>(); List<AbstractReportObject> objects = Context.getReportObjectService() .getReportObjectsByType(OpenmrsConstants.REPORT_OBJECT_TYPE_PATIENTSEARCH); for (AbstractReportObject object : objects) { SerializedCohort serializedCohort = new SerializedCohort(); serializedCohort.setId(object.getReportObjectId()); serializedCohort.setName(object.getName()); serializedCohorts.add(serializedCohort); } serializer.write(dataOutputStream, serializedCohorts); } else { serializer.write(dataOutputStream, Context.getCohortService().getAllCohorts()); } } dataOutputStream.close(); } catch (Exception e) { log.error("Processing stream failed!", e); dataOutputStream.writeInt(HttpURLConnection.HTTP_UNAUTHORIZED); dataOutputStream.close(); } finally { Context.closeSession(); } }
From source file:J2MEMixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);//from www . j ava 2 s .c o m notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:ReadWriteStreams.java
public void readStream() { try {/*from w ww . ja v a 2 s. c o m*/ // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); for (int i = 1; i <= rs.getNumRecords(); i++) { // Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i); System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } }
From source file:MixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*from w ww. ja v a 2 s .c om*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); recordEnumeration.destroy(); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }