Example usage for java.io ObjectOutputStream close

List of usage examples for java.io ObjectOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the stream.

Usage

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Put a collection of captchas with his locale
 *
 * @param captchas The captchas to add//w w  w  .  j av a 2 s  .co m
 * @param locale   The locale of the captchas
 */
public void putAllCaptcha(Collection captchas, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;

    if (captchas != null && captchas.size() > 0) {
        Iterator captIt = captchas.iterator();
        if (log.isDebugEnabled()) {
            log.debug("try to insert " + captchas.size() + " captchas");
        }

        try {
            con = datasource.getConnection();
            con.setAutoCommit(false);
            ps = con.prepareStatement("insert into " + table + "(" + timeMillisColumn + "," + hashCodeColumn
                    + "," + localeColumn + "," + captchaColumn + ") values (?,?,?,?)");

            while (captIt.hasNext()) {

                Captcha captcha = (Captcha) captIt.next();
                try {
                    long currenttime = System.currentTimeMillis();
                    long hash = captcha.hashCode();

                    ps.setLong(1, currenttime);
                    ps.setLong(2, hash);
                    ps.setString(3, locale.toString());
                    // Serialise the entry
                    final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
                    final ObjectOutputStream objstr = new ObjectOutputStream(outstr);
                    objstr.writeObject(captcha);
                    objstr.close();
                    final ByteArrayInputStream inpstream = new ByteArrayInputStream(outstr.toByteArray());

                    ps.setBinaryStream(4, inpstream, outstr.size());

                    ps.addBatch();

                    if (log.isDebugEnabled()) {
                        log.debug("insert captcha added to batch : " + currenttime + ";" + hash);
                    }

                } catch (IOException e) {
                    log.warn("error during captcha serialization, "
                            + "check your class versions. removing row from database", e);
                }
            }
            //exexute batch and commit()

            ps.executeBatch();
            log.debug("batch executed");

            con.commit();
            log.debug("batch commited");

        } catch (SQLException e) {
            log.error(DB_ERROR, e);

        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                }
            }
        }
    }

}

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

@RequestMapping(value = "/{ecID}/encounters", method = RequestMethod.GET)
@ResponseBody/*from  ww  w  .jav  a  2  s  .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.bskyb.cg.environments.hash.PersistentHash.java

private synchronized void writeHash(String newdirname) throws IOException {

    FileOutputStream fos;//from  w  w w. j  av  a2 s  .  c o m

    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.orange.matosweb.MatosCampaign.java

/**
 * Backup the steps.//from ww w  .j a  va2  s  .  co  m
 */
private void backup() {
    try {
        FileOutputStream fos = new FileOutputStream(new File(privateFolder, BACKUP));
        try {
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            try {
                oos.writeObject(steps);
                oos.flush();
            } finally {
                oos.close();
            }
        } finally {
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Forms.FrmPrincipal.java

private void btnEntrenarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntrenarActionPerformed
    int[] capas = new int[Integer.parseInt(this.spIntermedias.getValue().toString()) + 2];
    if (validaCapas()) {
        for (int i = 0; i < this.pnlCapas.getComponentCount(); i++) {
            JSpinner sp = (javax.swing.JSpinner) pnlCapas.getComponent(i);
            capas[i] = Integer.parseInt(sp.getValue().toString());
        }//from www.ja  va  2 s .c  o  m
        //            BackPropagation entrena = new BackPropagation(capas, matrizPatrones, 100,0.5);
        BackPropagation entrena = new BackPropagation(capas, matrizPatrones,
                Integer.parseInt(this.spEpocas.getValue().toString()),
                Double.parseDouble(this.spFactor.getValue().toString())); // TODO add your handling code here:
        NeuronResult res = entrena.entrenamiento();

        mostrar(res, capas);
        try {
            FileOutputStream fos = new FileOutputStream("back.bin");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(entrena);
            oos.close();
            System.out.println("Acabe");
        } catch (Exception e) {
        }
    }

}

From source file:tap.Tap.java

/**
 * Dumps the ballots to the server TODO more refined explanation
 *///from   w w w  .ja v a 2  s.  c om
public void uploadToServer() {

    System.out.println("Uploading Ballots to the server!");

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost("http://localhost:9000/3FF968A3B47CT34C");

    String encoded;

    try {

        System.out.println("Encoding the Supervisors' records... ");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

        /* Write the record to the stream */
        objectOutputStream.writeObject(supervisorRecord);
        objectOutputStream.close();

        /* Encode the record as a string */
        encoded = new String(Base64.encodeBase64(byteArrayOutputStream.toByteArray()));

        try {
            PrintWriter out = new PrintWriter("testdata.txt");
            out.print(encoded);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<BasicNameValuePair> bnvp = new ArrayList();

        bnvp.add(new BasicNameValuePair("record", encoded));
        bnvp.add(new BasicNameValuePair("precinctID", Integer.toString((new Random()).nextInt())));

        /* Set entities for each of the url encoded forms of the NVP */
        post.setEntity(new UrlEncodedFormEntity(bnvp));

        System.out.println("Executing post..." + post.getEntity());

        /* Execute the post */
        client.execute(post);

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Upload complete!");

    /* Shutdown the connection when done */
    client.getConnectionManager().shutdown();
}

From source file:org.activiti.rest.service.api.runtime.TaskVariablesCollectionResourceTest.java

/**
 * Test creating a single task variable using a binary stream. POST runtime/tasks/{taskId}/variables
 *///from  w w  w.ja va2  s.  com
public void testCreateSingleSerializableTaskVariable() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);
        TestSerializableVariable serializable = new TestSerializableVariable();
        serializable.setSomeField("some value");

        // Serialize object to readable stream for representation
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream output = new ObjectOutputStream(buffer);
        output.writeObject(serializable);
        output.close();

        InputStream binaryContent = new ByteArrayInputStream(buffer.toByteArray());

        // Add name, type and scope
        Map<String, String> additionalFields = new HashMap<String, String>();
        additionalFields.put("name", "serializableVariable");
        additionalFields.put("type", "serializable");
        additionalFields.put("scope", "local");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
        httpPost.setEntity(HttpMultipartHelper.getMultiPartEntity("value",
                "application/x-java-serialized-object", binaryContent, additionalFields));
        CloseableHttpResponse response = executeBinaryRequest(httpPost, HttpStatus.SC_CREATED);

        // Check "CREATED" status
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("serializableVariable", responseNode.get("name").asText());
        assertTrue(responseNode.get("value").isNull());
        assertEquals("local", responseNode.get("scope").asText());
        assertEquals("serializable", responseNode.get("type").asText());
        assertNotNull(responseNode.get("valueUrl").isNull());
        assertTrue(responseNode.get("valueUrl").asText().endsWith(RestUrls.createRelativeResourceUrl(
                RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "serializableVariable")));

        // Check actual value of variable in engine
        Object variableValue = taskService.getVariableLocal(task.getId(), "serializableVariable");
        assertNotNull(variableValue);
        assertTrue(variableValue instanceof TestSerializableVariable);
        assertEquals("some value", ((TestSerializableVariable) variableValue).getSomeField());
    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.fragment.BuyAndSellFragment.java

public void writeOrderToCache(List<String> list) {
    try {//from  www  .  j  a va 2 s  .c  om
        FileOutputStream fot = getActivity().openFileOutput("orders", Context.MODE_PRIVATE);
        ObjectOutputStream out = new ObjectOutputStream(fot);
        out.writeObject(list);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.crispico.flower.mp.model.codesync.impl.FeatureChangeImpl.java

/**
 * Sets the cached value and sets also <code>*valueAsString</code> by converting the 
 * value to string, using the current feature.
 * //from w  w  w  .ja v a  2 s .c o  m
 * @generated NOT
 * @author Cristi
 * @author Mariana
 */
public void setOldValue(Object newOldValue) {
    Object oldOldValue = oldValue;
    oldValue = newOldValue;

    EDataType eDataTypeOfFeature = getEDataTypeOfFeature();
    if (eDataTypeOfFeature != null && !isMany()) {
        setOldValueAsString(EcoreUtil.convertToString(eDataTypeOfFeature, oldValue));
    } else {
        if (isMany()) {
            Collection<EObject> collection = (Collection<EObject>) (newOldValue == null
                    ? Collections.emptyList()
                    : newOldValue);
            getOldValueAsContainmentList().clear();
            for (EObject value : collection) {
                getOldValueAsContainmentList().add(EcoreUtil.copy(value));
            }
            oldValue = oldValueAsContainmentList;
        } else {
            try {
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(output);
                oos.writeObject(newOldValue);
                oos.close();
                setOldValueAsString(encode(output.toByteArray()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    if (eNotificationRequired())
        eNotify(new ENotificationImpl(this, Notification.SET, CodeSyncPackage.FEATURE_CHANGE__OLD_VALUE,
                oldOldValue, oldValue));
}