List of usage examples for java.io DataInputStream readUTF
public final String readUTF() throws IOException
readUTF
method of DataInput
. From source file:com.facebook.infrastructure.db.Column.java
/** * We know the name of the column here so just return it. * Filter is pretty much useless in this call and is ignored. *//* w w w . j a va 2 s. com*/ public IColumn deserialize(DataInputStream dis, String columnName, IFilter filter) throws IOException { if (dis.available() == 0) return null; IColumn column = null; String name = dis.readUTF(); if (name.equals(columnName)) { column = defreeze(dis, name); if (filter instanceof IdentityFilter) { /* * If this is being called with identity filter * since a column name is passed in we know * that this is a final call * Hence if the column is found set the filter to done * so that we do not look for the column in further files */ IdentityFilter f = (IdentityFilter) filter; f.setDone(); } } else { /* Skip a boolean and the timestamp */ dis.skip(DBConstants.boolSize_ + DBConstants.tsSize_); int size = dis.readInt(); dis.skip(size); } return column; }
From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .ja v a2 s . 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 { // Get our raw input and output streams InputStream input = request.getInputStream(); OutputStream output = response.getOutputStream(); // Wrap the streams for compression ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION); // Wrap the streams so we can use logical types DataInputStream dataInput = new DataInputStream(input); DataOutputStream dataOutput = new DataOutputStream(zOutput); try { // Read the common submission data from mobile phone String name = dataInput.readUTF(); String password = dataInput.readUTF(); String serializer = dataInput.readUTF(); String locale = dataInput.readUTF(); byte action = dataInput.readByte(); // TODO: add authentication, possible M6 enhancement log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer + ", locale=" + locale + ", action=" + action); EpihandyXformSerializer serObj = new EpihandyXformSerializer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Perform the action specified by the mobile phone try { if (action == ACTION_DOWNLOAD_STUDY_LIST) { serObj.serializeStudies(baos, studyService.getStudies()); } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) { serObj.serializeUsers(baos, userService.getUsers()); int studyId = dataInput.readInt(); String studyName = studyService.getStudyName(studyId); List<String> studyForms = formService.getStudyForms(studyId); serObj.serializeForms(baos, studyForms, studyId, studyName); } } catch (Exception e) { dataOutput.writeByte(RESPONSE_ERROR); throw new ServletException("failed to serialize data", e); } // Write out successful upload response dataOutput.writeByte(RESPONSE_SUCCESS); dataOutput.write(baos.toByteArray()); response.setStatus(HttpServletResponse.SC_OK); } finally { // Should always do this dataOutput.flush(); zOutput.finish(); response.flushBuffer(); } }
From source file:com.exzogeni.dk.http.cache.DiscCacheStore.java
private long readMetaFile(@NonNull File metaFile, @NonNull Map<String, List<String>> headers) throws IOException { final AtomicFile af = new AtomicFile(metaFile); final FileInputStream fis = af.openRead(); final DataInputStream dat = new DataInputStream(new BufferPoolInputStream(fis)); try {/* w w w .java2 s.c om*/ final long expireTime = dat.readLong(); int headersCount = dat.readInt(); while (headersCount-- > 0) { final String name = dat.readUTF(); int valuesCount = dat.readInt(); final List<String> values = new ArrayList<>(valuesCount); while (valuesCount-- > 0) { values.add(dat.readUTF()); } headers.put(name, values); } return expireTime; } finally { IOUtils.closeQuietly(dat); } }
From source file:org.openmrs.module.odkconnector.serialization.processor.HttpProcessor.java
/** * Process any stream connection to this module * * @param inputStream the input stream//www . ja va 2 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:com.facebook.infrastructure.db.SuperColumn.java
private SuperColumn defreezeSuperColumn(DataInputStream dis) throws IOException { String name = dis.readUTF(); SuperColumn superColumn = new SuperColumn(name); superColumn.markForDeleteAt(dis.readLong()); return superColumn; }
From source file:org.openmrs.module.odkconnector.serialization.serializer.openmrs.CohortSerializerTest.java
@Test public void serialize_shouldSerializeCohortInformation() throws Exception { CohortService cohortService = Context.getCohortService(); Cohort firstCohort = new Cohort(); firstCohort.addMember(6);/* w ww. j av a 2s . c o m*/ firstCohort.addMember(7); firstCohort.addMember(8); firstCohort.setName("First Cohort"); firstCohort.setDescription("First cohort for testing the serializer"); cohortService.saveCohort(firstCohort); Cohort secondCohort = new Cohort(); secondCohort.addMember(6); secondCohort.addMember(7); secondCohort.addMember(8); secondCohort.setName("Second Cohort"); secondCohort.setDescription("Second cohort for testing the serializer"); cohortService.saveCohort(secondCohort); File file = File.createTempFile("CohortSerialization", "Example"); GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file))); List<Cohort> cohorts = cohortService.getAllCohorts(); Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class); serializer.write(outputStream, cohorts); outputStream.close(); GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); DataInputStream dataInputStream = new DataInputStream(inputStream); Integer cohortCounts = dataInputStream.readInt(); System.out.println("Number of cohorts: " + cohortCounts); for (int i = 0; i < cohortCounts; i++) { System.out.println("Cohort ID: " + dataInputStream.readInt()); System.out.println("Cohort Name: " + dataInputStream.readUTF()); } inputStream.close(); }
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:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java
@Override public void run() { try {//w ww.j a va 2 s.c o m DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream()); DataOutputStream dataOut = new DataOutputStream(clientSocket.getOutputStream()); OutputStream out; String accion = dataIn.readUTF(); Libro lbr; String nombreUsuario = dataIn.readUTF(); System.out.println("nombreUsuario" + nombreUsuario); switch (accion) { case "bajar": String codArchivo = dataIn.readUTF(); dataOut = new DataOutputStream(clientSocket.getOutputStream()); lbr = new LibroJpaController(emf).findLibro(Integer.parseInt(codArchivo)); if (lbr == null) { dataOut.writeBoolean(false); break; } dataOut.writeBoolean(true); //File file = new File("C:\\Computacion Distribuida\\" + lbr.getNombre()); dataOut.writeUTF(lbr.getNombre()); out = clientSocket.getOutputStream(); try { byte[] bytes = new byte[64 * 1024]; InputStream in = new ByteArrayInputStream(lbr.getArchivo()); int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } Usuariolibros usrLbr = new Usuariolibros(); usrLbr.setFecha(Calendar.getInstance().getTime()); usrLbr.setAccion('B'); usrLbr.setCodigolibro(lbr); usrLbr.setNombrecuenta(new Usuario(nombreUsuario)); new UsuariolibrosJpaController(emf).create(usrLbr); in.close(); } finally { IOUtils.closeQuietly(out); } break; case "subir": dataIn = new DataInputStream(clientSocket.getInputStream()); String fileName = dataIn.readUTF(); InputStream in = clientSocket.getInputStream(); try { out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileName); byte[] bytes = new byte[64 * 1024]; int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } out.close(); lbr = new Libro(); lbr.setNombre(fileName); lbr.setArchivo( IOUtils.toByteArray(new FileInputStream("C:\\Computacion Distribuida\\" + fileName))); new LibroJpaController(emf).create(lbr); Usuariolibros usrLbr = new Usuariolibros(); usrLbr.setFecha(Calendar.getInstance().getTime()); usrLbr.setAccion('S'); usrLbr.setCodigolibro(lbr); usrLbr.setNombrecuenta(new Usuario(nombreUsuario)); new UsuariolibrosJpaController(emf).create(usrLbr); actualizarLibrosEnServidores(fileName); } finally { IOUtils.closeQuietly(in); } break; case "obtenerLista": ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream()); outToServer.writeObject(new LibroJpaController(emf).findLibroEntities()); outToServer.close(); break; case "verificarEstado": dataOut.writeUTF(String.valueOf(server.isDisponible())); break; case "actualizar": dataIn = new DataInputStream(clientSocket.getInputStream()); String fileNameFromServer = dataIn.readUTF(); in = clientSocket.getInputStream(); try { out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileNameFromServer); 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); } } dataIn.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:LCModels.MessageListener.java
public void run() { /* Keep Thread running */ while (true) { try {// w w w .j a va 2 s.c om /* Accept connection on server */ Socket serverSocket = server.accept(); /* DataInputStream to get message sent by client program */ DataInputStream in = new DataInputStream(serverSocket.getInputStream()); /* We are receiving message in JSON format from client. Parse String to JSONObject */ JSONObject clientMessage = new JSONObject(in.readUTF()); /* Flag to check chat window is opened for user that sent message */ boolean flagChatWindowOpened = false; /* Reading Message and Username from JSONObject */ String userName = clientMessage.get("Username").toString(); String message = clientMessage.getString("Message").toString(); /* Get list of Frame/Windows opened by mainFrame.java */ for (Frame frame : Frame.getFrames()) { /* Check Frame/Window is opened for user */ if (frame.getTitle().equals(userName)) { /* Frame/ Window is already opened */ flagChatWindowOpened = true; /* Get instance of ChatWindow */ ChatWindowUI chatWindow = (ChatWindowUI) frame; /* Get previous messages from TextArea */ String previousMessage = chatWindow.getMessageArea().getText(); /* Set message to TextArea with new message */ chatWindow.getMessageArea().setText(previousMessage + "\n" + userName + ": " + message); } } /* ChatWindow is not open for user sent message to server */ if (!flagChatWindowOpened) { /* Create an Object of ChatWindow */ ChatWindowUI chatWindow = new ChatWindowUI(); /** * We are setting title of window to identify user for next * message we gonna receive You can set hidden value in * ChatWindow.java file. */ chatWindow.setTitle(userName); /* Set message to TextArea */ chatWindow.getMessageArea().setText(message); /* Make ChatWindow visible */ chatWindow.setVisible(true); } /* Get DataOutputStream of client to repond */ DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream()); /* Send response message to client */ out.writeUTF("Received from " + clientMessage.get("Username").toString()); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.outerrim.snippad.ui.swt.dnd.WikiTransfer.java
/** * Reads and returns a single WikiWord from the given stream. * * @param parent/*w ww. j av a2 s .c o m*/ * Parent word * @param dataIn * Stream to read the data from * @return The WikiWord contained in the data stream * @throws IOException */ private WikiWord readWikiWord(final WikiWord parent, final DataInputStream dataIn) throws IOException { /* * Serialization format is as follows: (String) name of the word * (String) wiki text (int) number of child words (WikiWord) child 1 ... * repeat for each child */ String title = dataIn.readUTF(); String text = dataIn.readUTF(); int n = dataIn.readInt(); LOG.debug(title + " has " + n + " children"); WikiWord newParent = new WikiWord(title, text); newParent.setParent(parent); for (int i = 0; i < n; ++i) { readWikiWord(newParent, dataIn); } return newParent; }