Example usage for java.io ObjectOutputStream flush

List of usage examples for java.io ObjectOutputStream flush

Introduction

In this page you can find the example usage for java.io ObjectOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.jcs.auxiliary.lateral.http.server.LateralCacheServletReciever.java

/** SERVICE THE REQUEST */
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (log.isDebugEnabled()) {
        log.debug("The LateralCacheServlet has been called.\n");
    }/*from  w  w w . j a  v  a 2  s  .  c o m*/

    ICacheElement item = null;

    try {

        // Create the ObjectInputStream with
        // the Request InputStream.
        ObjectInputStream ois = new ObjectInputStream(request.getInputStream());

        if (log.isDebugEnabled()) {
            log.debug("after getting input stream and before reading it");
        }

        // READ POLLOBJ
        item = (ICacheElement) ois.readObject();
        ois.close();

    } catch (Exception e) {
        log.error(e);
    }

    if (item == null) {
        if (log.isDebugEnabled()) {
            log.debug("item is null in LateralCacheServlet");
        }
    } else {
        String hashtableName = item.getCacheName();
        Serializable key = item.getKey();
        Serializable val = item.getVal();

        log.debug("item read in = " + item);
        log.debug("item.getKey = " + item.getKey());

        CompositeCache cache = (CompositeCache) cacheMgr.getCache(hashtableName);
        try {
            // need to set as from lateral
            cache.localUpdate(item);
        } catch (Exception e) {
            log.error("Problem putting item in cache " + item, e);
        }
    }

    try {

        // BEGIN RESPONSE
        response.setContentType("application/octet-stream");

        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());

        if (log.isDebugEnabled()) {
            log.debug("Opened output stream.\n");
        }

        String result = "Completed transfer";

        // echo a message to the client
        oos.writeObject(result);

        if (log.isDebugEnabled()) {
            log.debug("Wrote object to output stream");
        }

        oos.flush();

        if (log.isDebugEnabled()) {
            log.debug("Flushed output stream.\n");
        }

        oos.close();

        if (log.isDebugEnabled()) {
            log.debug("Closed output stream.\n");
        }
    } catch (Exception e) {
        log.error("Problem writing response.", e);
    }
}

From source file:com.talis.storage.s3.ExternalizableS3ObjectTest.java

@Test
public void roundTripS3ObjectSerialization() throws Exception {
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(tmp);

    byte[] bytes = ("When replying to any emails you have prior to migration "
            + "(ie any in your inbox before you have been migrated) "
            + "you will need to change the way you reply to them").getBytes();

    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);/*from   w  ww .  j a  v  a2s  .  c  o  m*/

    S3ObjectFactory factory = new S3ObjectFactory("bucket");
    S3Object original = factory.newObject("foo", 0, MediaType.TEXT_PLAIN_TYPE, buffer);

    out.writeObject(original);
    out.flush();
    out.close();

    byte[] serialized = tmp.toByteArray();

    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized));
    S3Object clone = (S3Object) in.readObject();

    assertObjectsEqual(original, clone);
}

From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java

public static ByteString fromObject(Object snapshot) throws Exception {
    ByteArrayOutputStream b = null;
    ObjectOutputStream o = null;
    try {/* ww  w  . j a  v a  2  s.  c o  m*/
        b = new ByteArrayOutputStream();
        o = new ObjectOutputStream(b);
        o.writeObject(snapshot);
        byte[] snapshotBytes = b.toByteArray();
        return ByteString.copyFrom(snapshotBytes);
    } finally {
        if (o != null) {
            o.flush();
            o.close();
        }
        if (b != null) {
            b.close();
        }
    }
}

From source file:org.intermine.api.lucene.KeywordSearch.java

private static void writeObjectToDB(ObjectStore os, String key, Object object)
        throws IOException, SQLException {
    LOG.debug("Saving stream to database...");
    Database db = ((ObjectStoreInterMineImpl) os).getDatabase();

    LargeObjectOutputStream streamOut = null;
    GZIPOutputStream gzipStream = null;
    ObjectOutputStream objectStream = null;

    try {/*from w ww  .j av a  2 s .  com*/
        streamOut = MetadataManager.storeLargeBinary(db, key);
        gzipStream = new GZIPOutputStream(new BufferedOutputStream(streamOut));
        objectStream = new ObjectOutputStream(gzipStream);

        LOG.debug("GZipping and serializing object...");
        objectStream.writeObject(object);
    } finally {
        if (objectStream != null) {
            objectStream.flush();
            objectStream.close();
        }
        if (gzipStream != null) {
            gzipStream.finish();
            gzipStream.flush();
            gzipStream.close();
        }
        if (streamOut != null) {
            streamOut.close();
        }
    }

}

From source file:org.openmrs.module.hl7output.web.controller.RHEApatientController.java

@RequestMapping(value = "/{ecID}/encounters", method = RequestMethod.GET)
@ResponseBody//from  ww w . j  a v a2s .  c o m
public Object getEncounters(@PathVariable("ecID") String enterpriseId,
        @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId,
        @RequestParam(value = "dateStart", required = false) String dateStart,
        @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request,
        HttpServletResponse response) throws ResponseException {

    LogEncounterService service = Context.getService(LogEncounterService.class);

    Date fromDate = null;
    Date toDate = null;
    Patient p = null;
    ORU_R01 r01 = null;

    log.info("RHEA Controller call detected...");
    log.info("Enterprise Patient Id is :" + enterpriseId);
    log.info("encounterUniqueId is :" + encounterUniqueId);
    log.info("dateStart is :" + dateStart);

    GetEncounterLog getEncounterLog = new GetEncounterLog();
    getEncounterLog.setEncounterUniqueId(encounterUniqueId);

    // first, we create from and to data objects out of the String
    // parameters

    if (enterpriseId == null) {
        log.info("Error : missing enterpriseId");
        getEncounterLog.setResult("Error, missing enterpriseId");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    getEncounterLog.setEnterpriseId(enterpriseId);

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    try {
        if (dateStart != null)
            fromDate = format.parse(dateStart);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied start date : " + dateStart);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("fromDate is :" + fromDate);

    try {
        if (dateEnd != null)
            toDate = format.parse(dateEnd);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied end date : " + dateEnd);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("toDate is :" + toDate);

    getEncounterLog.setDateEnd(toDate);
    getEncounterLog.setDateStart(fromDate);

    // Next, we try to retrieve the matching patient object
    if (enterpriseId != null) {
        PatientIdentifierType patientIdentifierType = Context.getPatientService()
                .getPatientIdentifierTypeByName("ECID");
        List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>();
        identifierTypeList.add(patientIdentifierType);

        List<Patient> patients = Context.getPatientService().getPatients(null, enterpriseId, identifierTypeList,
                false);
        //I am not checking the identifier type here. Need to come back and add a check for this
        if (patients.size() == 1) {
            p = patients.get(0);
        }
    }

    // if the patient doesn't exist, we need to return 400-BAD REQUEST
    // because the parameters are malformed
    if (p == null) {
        log.info("Error : failed to retreive patient for the given uuid : " + enterpriseId);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } else {
        log.info("Patient id : " + p.getPatientId() + "was retreived...");

        if (p != null) {
            //get all the encounters for this patient
            List<Encounter> encounterList = Context.getEncounterService().getEncountersByPatient(p);
            //if the enconteruniqueId is not null, we can isolate the given encounter

            if (encounterUniqueId != null) {
                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {
                    if (!i.next().getUuid().equals(encounterUniqueId))
                        i.remove();
                }
            }

            //If the encounterUniqueId was not given, we will try to filter encounters based on from and to dates
            List<Encounter> filteredEncounterList = new ArrayList<Encounter>();

            if (fromDate != null || toDate != null) {
                for (Encounter encounter : encounterList) {
                    if (fromDate != null && toDate != null) {
                        if ((encounter.getEncounterDatetime().after(fromDate))
                                && (encounter.getEncounterDatetime().before(toDate))) {
                            filteredEncounterList.add(encounter);
                        }

                    } else if (fromDate == null) {
                        if (encounter.getEncounterDatetime().before(toDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    } else {
                        if (encounter.getEncounterDatetime().after(fromDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    }
                }

                log.info("The number of matching encounters are :" + filteredEncounterList.size());
                encounterList = filteredEncounterList;
            }
            log.info("Calling the ORU_R01 parser...");

            SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>();

            for (Encounter e : encounterList) {
                MatchingEncounters matchingEncounters = new MatchingEncounters();
                matchingEncounters.setGetEncounterLog(getEncounterLog);
                matchingEncounters.setEncounterId(e.getEncounterId());

                encounterSet.add(matchingEncounters);
            }

            getEncounterLog.setLogTime(new Date());
            if (encounterList.size() > 0)
                getEncounterLog.setResult("Results Retrived");
            if (encounterList.size() == 0)
                getEncounterLog.setResult("No Results Retrived");

            //Now we will generate the HL7 message

            GenerateORU_R01 R01Util = new GenerateORU_R01();
            try {
                r01 = R01Util.generateORU_R01Message(p, encounterList);
            } catch (Exception e) {
                getEncounterLog.setResult("Error : Processing hl7 message failed");
                service.saveGetEncounterLog(getEncounterLog);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            getEncounterLog.getMatchingEncounters().clear();
            getEncounterLog.setMatchingEncounters(encounterSet);

            service.saveGetEncounterLog(getEncounterLog);

        }

        try {
            // Convert the ORU_R01 object into a byte stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(r01);
            oos.flush();
            oos.close();
            bos.close();
            byte[] data = bos.toByteArray();

            // Write the bytestream into the HttpServletResponse
            ServletOutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();

            response.getWriter().flush();
            response.getWriter().close();

            //NOTE : Im returning the ORU_R01 object as a bytestream AND a session object. Why both ? remove one later !
            request.getSession().setAttribute("oru_r01", r01);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Return null for now
    return null;
}

From source file:com.uberspot.storageutils.StorageUtils.java

/** Saves the given object in the internal storage
 * @param obj the object to save/*  ww  w .j a va2  s.c  o m*/
 * @param fileName the name of the file in which it will be saved
 * @return true if it's saved successfully, false otherwise
 */
public boolean saveObjectToInternalStorage(Object obj, String fileName) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(
                new BufferedOutputStream(openFileOutput(fileName, Context.MODE_PRIVATE)));
        output.writeObject(obj);
        output.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace(System.out);
            }
    }
    return false;
}

From source file:edu.stanford.muse.datacache.BlobStore.java

private synchronized void pack_to_stream(ObjectOutputStream oos) throws IOException {
    oos.writeObject(uniqueBlobs);// www. j  ava2 s .co  m
    oos.writeObject(id_map);
    oos.writeObject(views);
    oos.writeInt(next_data_id);
    oos.flush();
}

From source file:com.bskyb.cg.environments.hash.PersistentHash.java

private synchronized void writeHash(String newdirname) throws IOException {

    FileOutputStream fos;//from   www  . j av  a2  s .  com

    Enumeration<String> e = hash.keys();
    if (e == null)
        return;
    Message message;
    ObjectOutputStream oos = null;
    BufferedOutputStream bos = null;
    createEmptyStore(newdirname);
    String key;
    while (e.hasMoreElements()) {
        key = (String) e.nextElement();
        message = hash.get(key);
        File outFile = new File(newdirname, key);
        fos = new FileOutputStream(outFile);
        bos = new BufferedOutputStream(fos);
        oos = new ObjectOutputStream(bos);
        oos.writeObject(message);
        oos.flush();
        oos.close();
        fos.flush();
        fos.close();

    }

}

From source file:com.sec.ose.osi.ui.cache.UICache.java

private void save() {

    log.debug("save cache");
    ObjectOutputStream dos = null;

    try {//  w ww . jav a2s .  c o  m
        File file = new File(CACHE_FILE_NAME);
        if (file.exists() == false)
            file.createNewFile(); // IOException

        dos = new ObjectOutputStream(new FileOutputStream(file)); // FileNotFoundException
        dos.writeObject(mMap);

    } catch (FileNotFoundException e) {
        log.warn(e);
    } catch (IOException e) {
        log.warn(e);
    } finally {
        if (dos != null) {
            try {
                dos.flush();

            } catch (IOException e) {
                log.warn(e);
            }
            try {
                dos.close();
            } catch (IOException e) {
                log.warn(e);
            }

            dos = null;
        }
    }
    log.debug("save done");
}

From source file:ubic.gemma.analysis.report.WhatsNewServiceImpl.java

/**
 * @param wn/*from   ww  w  . j  av a  2s .  com*/
 * @return
 */
private boolean saveFile(WhatsNew wn) {
    try {
        // remove file first
        File newOutput = new File(
                HOME_DIR + File.separatorChar + WHATS_NEW_DIR + File.separatorChar + WHATS_NEW_FILE + ".new");
        File updatedOutput = new File(HOME_DIR + File.separatorChar + WHATS_NEW_DIR + File.separatorChar
                + WHATS_NEW_FILE + ".updated");
        if (newOutput.exists()) {
            newOutput.delete();
        }
        if (updatedOutput.exists()) {
            updatedOutput.delete();
        }
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();

        Collection<ArrayDesign> ads = wn.getNewArrayDesigns();
        Collection<ExpressionExperiment> ees = wn.getNewExpressionExperiments();
        // save the IDs for new Auditables
        Collection<AuditableObject> newObjects = new ArrayList<AuditableObject>();
        for (ArrayDesign ad : ads) {
            AuditableObject ao = new AuditableObject();
            ao.date = date;
            ao.type = "ArrayDesign";
            ao.id = ad.getId();
            newObjects.add(ao);
        }
        for (ExpressionExperiment ee : ees) {
            AuditableObject ao = new AuditableObject();
            ao.date = date;
            ao.type = "ExpressionExperiment";
            ao.id = ee.getId();
            newObjects.add(ao);
        }

        // save the ids for updated Auditables
        ads = wn.getUpdatedArrayDesigns();
        ees = wn.getUpdatedExpressionExperiments();
        // save the IDs for new Auditables
        Collection<AuditableObject> updatedObjects = new ArrayList<AuditableObject>();
        for (ArrayDesign ad : ads) {
            AuditableObject ao = new AuditableObject();
            ao.date = date;
            ao.type = "ArrayDesign";
            ao.id = ad.getId();
            updatedObjects.add(ao);
        }
        for (ExpressionExperiment ee : ees) {
            AuditableObject ao = new AuditableObject();
            ao.date = date;
            ao.type = "ExpressionExperiment";
            ao.id = ee.getId();
            updatedObjects.add(ao);
        }
        FileOutputStream fos = new FileOutputStream(newOutput);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(newObjects);
        oos.flush();
        oos.close();

        fos = new FileOutputStream(updatedOutput);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(updatedObjects);
        oos.flush();
        oos.close();
    } catch (Throwable e) {
        return false;
    }

    return true;
}