Example usage for java.io ObjectInputStream close

List of usage examples for java.io ObjectInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the input stream.

Usage

From source file:com.servoy.extensions.plugins.http.AllowedCertTrustStrategy.java

/**
 * @return the holder/*  w  w  w.  ja  v a 2s .  co m*/
 */
public CertificatesHolder getCertificatesHolder() {
    if (holder == null) {
        File file = new File(System.getProperty("user.home"), J2DBGlobals.CLIENT_LOCAL_DIR + "servoy.ks"); //$NON-NLS-1$//$NON-NLS-2$
        if (file.exists()) {
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
                holder = (CertificatesHolder) ois.readObject();
            } catch (Exception e) {
                Debug.error(e);
            } finally {
                try {
                    if (ois != null)
                        ois.close();
                } catch (Exception e) {
                }
            }
        }
        if (holder == null)
            holder = new CertificatesHolder();
    }
    return holder;
}

From source file:cn.guoyukun.spring.jpa.repository.hibernate.type.ObjectSerializeUserType.java

/**
 * JDBC ResultSet??,??//from   w ww. jav a  2  s.  co m
 * (?null?)
 * names????
 *
 * @param names
 * @param owner
 * @return
 * @throws HibernateException
 * @throws SQLException
 */
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    ObjectInputStream ois = null;
    try {
        String hexStr = rs.getString(names[0]);
        ois = new ObjectInputStream(new ByteArrayInputStream(Hex.decodeHex(hexStr.toCharArray())));
        return ois.readObject();
    } catch (Exception e) {
        throw new HibernateException(e);
    } finally {
        try {
            ois.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.nebhale.jsonpath.JsonPathTest.java

@Test
public void serializable() throws IOException, ClassNotFoundException {
    assertTrue(Serializable.class.isAssignableFrom(JsonPath.class));

    JsonPath jsonPath = JsonPath.compile("$.store.book[0].title");
    assertEquals("Sayings of the Century", jsonPath.read(STRING_VALID, String.class));

    byte[] serialized;
    ObjectOutputStream out = null;
    try {//  w  ww .  j a v a  2  s. c  o  m
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bytes);

        out.writeObject(jsonPath);
        out.flush();

        serialized = bytes.toByteArray();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    JsonPath newJsonPath;
    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new ByteArrayInputStream(serialized));

        newJsonPath = (JsonPath) in.readObject();
    } finally {
        if (in != null) {
            in.close();
        }
    }

    assertEquals("Sayings of the Century", newJsonPath.read(STRING_VALID, String.class));
}

From source file:com.joliciel.lefff.LefffMemoryLoader.java

public LefffMemoryBase deserializeMemoryBase(File memoryBaseFile) {
    LOG.debug("deserializeMemoryBase");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/* w  w  w.  jav a 2  s.  com*/

    LefffMemoryBase memoryBase = null;
    ZipInputStream zis = null;
    FileInputStream fis = null;
    ObjectInputStream in = null;

    try {
        fis = new FileInputStream(memoryBaseFile);
        if (isZip) {
            zis = new ZipInputStream(fis);
            memoryBase = this.deserializeMemoryBase(zis);
        } else {
            in = new ObjectInputStream(fis);
            memoryBase = (LefffMemoryBase) in.readObject();
            in.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }

    return memoryBase;
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Zip the selected files and send the zip to the server.
 * @param p_filesToBeZipped - A list of selected files to be uploaded.
 * @param p_targetURL - The target URL representing server URL.
 * @param p_targetLocation - A string representing the link to the next page.
 *//*  w  w  w.  ja  v  a  2 s  . c  o m*/
public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation)
        throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("GS_");
    sb.append(System.currentTimeMillis());
    sb.append(".zip");

    File targetFile = getFile(sb.toString());
    ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped);
    m_progressBar.setValue(30);

    PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true");
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.setDoAuthentication(true);
    try {
        Part[] parts = { new FilePart(targetFile.getName(), targetFile) };

        m_progressBar.setValue(40);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        setUpClientForProxy(client);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        m_progressBar.setValue(50);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            //no need to ask for auth again since the first upload was fine
            s_authPrompter.setAskForAuthentication(false);

            m_progressBar.setValue(60);
            InputStream is = filePost.getResponseBodyAsStream();
            m_progressBar.setValue(70);
            ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is);
            Vector incomingData = (Vector) inputStreamFromServlet.readObject();

            inputStreamFromServlet.close();
            if (incomingData != null) {
                if (incomingData.elementAt(0) instanceof ExceptionMessage) {
                    resetProgressBar();
                    AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this);
                }
            } else {
                boolean deleted = targetFile.delete();
                m_progressBar.setValue(100);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                // now move to some other page...
                goToTargetPage(p_targetLocation);
            }
        } else {
            //authentication may have failed, reset the need to ask
            s_authPrompter.setAskForAuthentication(true);
            resetProgressBar();
            String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status);
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try.";
            }
            AppletHelper.getErrorDlg(errorMessage, null);
        }
    } catch (Exception ex) {
        //authentication may have failed, reset the need to ask
        s_authPrompter.setAskForAuthentication(true);

        resetProgressBar();
        System.err.println(ex);
        AppletHelper.getErrorDlg(ex.getMessage(), null);
    } finally {
        filePost.releaseConnection();
    }

}

From source file:com.stgmastek.core.logic.ExecutionOrder.java

/**
 * Reads the saved state of the batch for revision runs 
 * If the current batch number it 1000 and revision is 5, 
 * then this method would look for saved state of batch 1000 
 * with revision (5 - 1) i.e. '1000_4.savepoint' 
 * /* ww  w .  j a v  a2 s . c  om*/
 * @param batchContext
 *         The context for the batch 
 * @throws BatchException
 *          Any exception thrown during reading of the serialized file 
 */
public static synchronized void updateBatchState(BatchContext batchContext) throws BatchException {
    BatchInfo newBatchInfo = batchContext.getBatchInfo();
    String savepointFilePath = Configurations.getConfigurations().getConfigurations("CORE", "SAVEPOINT",
            "DIRECTORY");
    String savePointFile = FilenameUtils.concat(savepointFilePath,
            newBatchInfo.getBatchNo() + "_" + (newBatchInfo.getBatchRevNo() - 1) + ".savepoint");
    if (logger.isDebugEnabled()) {
        logger.debug("Reading the saved state from file : " + savePointFile);
    }
    FileInputStream fis = null;
    try {

        //Check whether the file exists
        File f = new File(savePointFile);
        if (!f.exists())
            throw new BatchException("Cannot locate the the save point file named :" + savePointFile);

        fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        BatchInfo savedBatchInfo = (BatchInfo) ois.readObject();
        newBatchInfo.setOrderedMap(savedBatchInfo.getOrderedMap());
        newBatchInfo.setProgressLevelAtLastSavePoint(
                (ProgressLevel) savedBatchInfo.getProgressLevelAtLastSavePoint()); //This object is different but still cloned.
        newBatchInfo.setBatchRunDate(savedBatchInfo.getBatchRunDate());
        newBatchInfo.setDateRun(savedBatchInfo.isDateRun());

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Last batch saved state is " + savedBatchInfo.getProgressLevelAtLastSavePoint().toString());
        }
        //Set the ExecutionStatus in the ProgressLevel
        ExecutionStatus savedExecutionStatus = newBatchInfo.getProgressLevelAtLastSavePoint()
                .getExecutionStatus();
        ProgressLevel.getProgressLevel(newBatchInfo.getBatchNo())
                .setExecutionStatus(savedExecutionStatus.getEntity(), savedExecutionStatus.getStageCode());
        fis.close();
        fis = null;
        ois.close();
        ois = null;
    } catch (FileNotFoundException e) {
        logger.error(e);
        throw new BatchException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e);
        throw new BatchException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        logger.error(e);
        throw new BatchException(e.getMessage(), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.fullmetalgalaxy.server.AdminServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    ModelFmpInit modelInit = null;/*from  w w  w. j av a 2 s.c  o m*/

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            } else if (item.getFieldName().equalsIgnoreCase("gamefile")) {
                ObjectInputStream in = new ObjectInputStream(item.openStream());
                modelInit = ModelFmpInit.class.cast(in.readObject());
                in.close();
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    } catch (ClassNotFoundException e2) {
        log.error(e2);
    }

    // import game from file
    if (modelInit != null) {
        // set transient to avoid override data
        modelInit.getGame().setTrancient();

        // search all accounts in database to correct ID
        for (EbRegistration registration : modelInit.getGame().getSetRegistration()) {
            if (registration.haveAccount()) {
                EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId());
                if (account == null) {
                    // corresponding account from this player doesn't exist in database
                    try {
                        // try to find corresponding pseudo
                        account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==",
                                ServerUtil.compactTag(registration.getAccount().getPseudo())).get();
                    } catch (Exception e) {
                    }
                }
                registration.setAccount(account);
            }
        }

        // then save game
        FmgDataStore dataStore = new FmgDataStore(false);
        dataStore.put(modelInit.getGame());
        dataStore.close();

    }

}

From source file:com.izforge.izpack.event.AntActionUninstallerListener.java

/**
 * Initialises the listener.// www  .ja v  a  2  s.  co m
 *
 * @throws IzPackException for any error
 */
@Override
public void initialise() {
    String buildResource = getBuildResource();
    List<AntAction> allActions;
    try {
        // Load the defined actions.
        InputStream in = getClass().getResourceAsStream("/antActions");
        if (in == null) { // No actions, nothing todo.
            return;
        }
        ObjectInputStream objIn = new ObjectInputStream(in);
        // The actions are stored at installation time as list of AntAction
        // objects.
        // See AntActionInstallerListener.afterPacks.
        allActions = (List<AntAction>) objIn.readObject();
        objIn.close();
        in.close();
    } catch (Exception exception) {
        throw new IzPackException(exception);
    }
    // There are two possible orders; before and after deletion.
    // Now we assign the actions to two different lists, the
    // local "before" list which we perform after the scan and
    // the class member "antActions" which should contain the
    // "afterdeletion" actions. Additionally we should save needed
    // files like the properties file for this order because if they're
    // part of the pack the'll be lost after the deletion has been
    // performed.
    for (AntAction action : allActions) {
        // See if we need to set the action with the build_resource that
        //  we extracted
        if (null != buildResource) {
            // We do
            action.setBuildFile(new File(buildResource));
        }
        //
        if (action.getUninstallOrder().equals(ActionBase.BEFOREDELETION)) {
            befDel.add(action);
        } else {// We need the build and the properties file(s) outside the
                // install dir.
            if (null == buildResource) {
                // We have not copied a build_resource to a temporary file
                //  so now copy the local build file to a temporary file
                //  and set it as the build file for the action
                File tmpFile;
                try {
                    tmpFile = IoHelper.copyToTempFile(action.getBuildFile(), ".xml");
                } catch (IOException exception) {
                    throw new IzPackException(exception);
                }
                action.setBuildFile(tmpFile);
            }
            List<String> props = action.getPropertyFiles();
            if (props != null) {
                ArrayList<String> newProps = new ArrayList<String>();
                for (String propName : props) {
                    File propFile;
                    try {
                        propFile = IoHelper.copyToTempFile(propName, ".properties");
                        newProps.add(propFile.getCanonicalPath());
                    } catch (IOException exception) {
                        throw new IzPackException(exception);
                    }
                }
                action.setPropertyFiles(newProps);
            }
            antActions.add(action);
        }
    }
}

From source file:com.adaptris.core.services.metadata.CheckUniqueMetadataValueService.java

private void loadPreviouslyReceivedValues() throws CoreException {
    if (store != null) {
        try {/* ww w.ja  v  a2s .co  m*/
            if (store.exists()) {
                ObjectInputStream o = new ObjectInputStream(new FileInputStream(store));

                previousValuesStore = (ArrayList<Object>) o.readObject();
                o.close();
            }
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }
}

From source file:com.fratello.longevity.smooth.catalog.CompareFilter.java

public boolean loadObject() {
    try {/*from   w ww  .jav  a2 s. c om*/
        FileInputStream door = new FileInputStream(
                new File(new File(FileUtils.getTempDirectoryPath() + "NicksProgram"), "defaultsettings.ser"));
        ObjectInputStream reader = new ObjectInputStream(door);
        CompareFilter x = new CompareFilter();
        try {
            x = (CompareFilter) reader.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        reader.close();
        if (x == null)
            return false;
        setCompareFilter(x);
    } catch (IOException e) {
    }
    return true;
}