List of usage examples for java.io ObjectInputStream close
public void close() throws IOException
From source file:com.sumzerotrading.broker.ib.InteractiveBrokersBroker.java
protected void loadOrderMaps() throws Exception { tradeFileSemaphore.acquire();// w ww.jav a2 s . c om try { createDir(); File file = new File(getDirName() + "orders.ser"); if (file.exists()) { ObjectInputStream input = new ObjectInputStream(new FileInputStream(file)); completedOrderMap = (HashMap) input.readObject(); orderMap = (HashMap) input.readObject(); input.close(); } } finally { tradeFileSemaphore.release(); } }
From source file:net.geant.edugain.filter.EduGAINFilter.java
private void loadDatabase() { this.requestDBName = (String) this.config.getProperty("net.geant.edugain.filter.requestDB"); File f = null;//w w w .j a va 2s . c om FileInputStream requestFile; try { f = new File(this.requestDBName); requestFile = new FileInputStream(f); ObjectInputStream requestInputStream = new ObjectInputStream(requestFile); this.requests = (HashMap<String, HashMap<String, String>>) requestInputStream.readObject();//savedRequest; requestInputStream.close(); requestFile.close(); } catch (FileNotFoundException e) { this.log.error("File " + requestDBName + " not found."); } catch (IOException e) { this.log.error("Exception while reading file " + requestDBName); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { f.createNewFile(); this.requests = new HashMap<String, HashMap<String, String>>(); } catch (IOException e) { this.log.error( "Fatal error while loading request file. Please fix this and restart the application"); } } }
From source file:com.inmobi.grill.server.GrillServices.java
private void setupPersistedState() throws IOException, ClassNotFoundException { if (conf.getBoolean(GrillConfConstants.GRILL_SERVER_RECOVER_ON_RESTART, GrillConfConstants.DEFAULT_GRILL_SERVER_RECOVER_ON_RESTART)) { FileSystem fs = persistDir.getFileSystem(conf); for (GrillService service : grillServices) { ObjectInputStream in = null; try { try { in = new ObjectInputStream(fs.open(getServicePersistPath(service))); } catch (FileNotFoundException fe) { LOG.warn("No persist path available for service:" + service.getName()); continue; }/* w ww . jav a 2s .c om*/ service.readExternal(in); LOG.info("Recovered service " + service.getName() + " from persisted state"); } finally { if (in != null) { in.close(); } } } } }
From source file:com.octo.captcha.engine.bufferedengine.buffer.DiskCaptchaBuffer.java
/** * Gets an entry from the Disk Store.//from w w w .ja v a 2 s . c o m * * @return The element */ protected synchronized Collection remove(int number, Locale locale) throws IOException { if (!isInitalized) return new ArrayList(0); DiskElement diskElement = null; int index = 0; boolean diskEmpty = false; Collection collection = new UnboundedFifoBuffer(); //if no locale if (!diskElements.containsKey(locale)) { return collection; } try { while (!diskEmpty && index < number) { // Check if the element is on disk try { diskElement = (DiskElement) ((LinkedList) diskElements.get(locale)).removeFirst(); // Load the element randomAccessFile.seek(diskElement.position); byte[] buffer = new byte[diskElement.payloadSize]; randomAccessFile.readFully(buffer); ByteArrayInputStream instr = new ByteArrayInputStream(buffer); ObjectInputStream objstr = new ObjectInputStream(instr); collection.add(objstr.readObject()); instr.close(); objstr.close(); freeBlock(diskElement); index++; } catch (NoSuchElementException e) { diskEmpty = true; log.debug("disk is empty for locale : " + locale.toString()); } } } catch (Exception e) { log.error("Error while reading on disk ", e); } if (log.isDebugEnabled()) { log.debug("removed " + collection.size() + " from disk buffer with locale " + locale.toString()); } return collection; }
From source file:com.ibm.jaggr.core.impl.cache.CacheManagerImpl.java
/** * Starts up the cache. Attempts to de-serialize a previously serialized * cache from disk and starts the periodic serializer task. * * @param aggregator//from w w w .j a v a2s.co m * the aggregator instance this cache manager belongs to * @param stamp * a time stamp used to determine if the cache should be cleared. * The cache should be cleared if the time stamp is later than * the one associated with the cached resources. * @throws IOException */ public CacheManagerImpl(IAggregator aggregator, long stamp) throws IOException { _directory = new File(aggregator.getWorkingDirectory(), CACHEDIR_NAME); _aggregator = aggregator; // Make sure the cache directory exists if (!_directory.exists()) { if (!_directory.mkdirs()) { throw new IOException(MessageFormat.format(Messages.CacheManagerImpl_0, new Object[] { _directory.getAbsoluteFile() })); } } // Attempt to de-serialize the cache from disk CacheImpl cache = null; try { File file = new File(_directory, CACHE_META_FILENAME); ObjectInputStream is = new ObjectInputStream(new FileInputStream(file)); try { cache = (CacheImpl) is.readObject(); } finally { try { is.close(); } catch (Exception ignore) { } } } catch (FileNotFoundException e) { if (log.isLoggable(Level.INFO)) log.log(Level.INFO, Messages.CacheManagerImpl_1); } catch (InvalidClassException e) { if (log.isLoggable(Level.INFO)) log.log(Level.INFO, Messages.CacheManagerImpl_2); // one or more of the serializable classes has changed. Delete the stale // cache files } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); } if (cache != null) { _control = (CacheControl) cache.getControlObj(); } if (_control != null) { // stamp == 0 means no overrides. Need to check for this explicitly // in case the overrides directory has been removed. if (stamp == 0 && _control.initStamp == 0 || stamp != 0 && stamp <= _control.initStamp) { // Use AggregatorProxy so that getCacheManager will return non-null // if called from within setAggregator. Need to do this because // IAggregator.getCacheManager() is unable to return this object // since it is still being constructed. cache.setAggregator(AggregatorProxy.newInstance(_aggregator, this)); _cache.set(cache); } } else { _control = new CacheControl(); _control.initStamp = stamp; } // Start up the periodic serializer task. Serializes the cache every 10 minutes. // This is done so that we can recover from an unexpected shutdown aggregator.getExecutors().getScheduledExecutor().scheduleAtFixedRate(new Runnable() { public void run() { try { File file = new File(_directory, CACHE_META_FILENAME); // Synchronize on the cache object to keep the scheduled cache sync thread and // the thread processing servlet destroy from colliding. synchronized (cacheSerializerSyncObj) { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file)); try { os.writeObject(_cache.get()); } finally { try { os.close(); } catch (Exception ignore) { } } } } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); } } }, 10, 10, TimeUnit.MINUTES); Dictionary<String, String> dict; if (_aggregator.getPlatformServices() != null) { dict = new Hashtable<String, String>(); dict.put("name", aggregator.getName()); //$NON-NLS-1$ _serviceRegistrations.add(_aggregator.getPlatformServices() .registerService(IShutdownListener.class.getName(), this, dict)); dict = new Hashtable<String, String>(); dict.put("name", aggregator.getName()); //$NON-NLS-1$ _serviceRegistrations.add( _aggregator.getPlatformServices().registerService(IConfigListener.class.getName(), this, dict)); dict = new Hashtable<String, String>(); dict.put("name", aggregator.getName()); //$NON-NLS-1$ _serviceRegistrations.add(_aggregator.getPlatformServices() .registerService(IDependenciesListener.class.getName(), this, dict)); dict = new Hashtable<String, String>(); dict.put("name", aggregator.getName()); //$NON-NLS-1$ _serviceRegistrations.add(_aggregator.getPlatformServices() .registerService(IOptionsListener.class.getName(), this, dict)); } optionsUpdated(aggregator.getOptions(), 1); configLoaded(aggregator.getConfig(), 1); dependenciesLoaded(aggregator.getDependencies(), 1); // Now invoke the listeners for objects that have already been initialized IOptions options = _aggregator.getOptions(); if (options != null) { optionsUpdated(options, 1); } IConfig config = _aggregator.getConfig(); if (config != null) { configLoaded(config, 1); } IDependencies deps = _aggregator.getDependencies(); if (deps != null) { dependenciesLoaded(deps, 1); } }
From source file:com.kynetx.api.java
protected CookieStore fetchCookies() { CookieStore toReturn = null;/* w ww.j av a2 s. c o m*/ int size = 0; if (isReadable() || isWritable()) { try { File path = new File(context.getExternalFilesDir(null), "cookies"); FileInputStream fin = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fin); size = ois.readInt(); toReturn = new BasicCookieStore(); for (int i = 0; i < size; i++) { BasicClientCookie cookie = new BasicClientCookie((String) ois.readObject(), (String) ois.readObject()); cookie.setDomain((String) ois.readObject()); cookie.setPath((String) ois.readObject()); cookie.setVersion(ois.readInt()); toReturn.addCookie((Cookie) cookie); } ois.close(); } catch (Exception e) { return null; } } if (size > 0) { return toReturn; } else { return null; } }
From source file:com.runwaysdk.session.FileSessionCache.java
@Override protected Session getSession(String sessionId) { sessionCacheLock.lock();//from www. j av a2 s . c o m try { if (sessions.containsKey(sessionId)) { return sessions.get(sessionId); } String dir = this.getDirectory(sessionId); File file = new File(dir + sessionId); try { ObjectInputStream stream = new ResolvedObjectInputStream(new FileInputStream(file)); Session session = (Session) stream.readObject(); stream.close(); // Check that the session has not expired long currentTime = System.currentTimeMillis(); if (session.isExpired(currentTime)) { // Session has expired: delete it from the file // system and throw an exception FileIO.deleteFile(file); String error = "Session [" + sessionId + "] does not exist or has expired."; throw new InvalidSessionException(error); } return session; } catch (FileNotFoundException e) { String error = "Session [" + sessionId + "] does not exist or has expired."; throw new InvalidSessionException(error); } catch (IOException e) { throw new FileReadException(file, e); } catch (ClassNotFoundException e) { throw new ProgrammingErrorException(e); } } finally { sessionCacheLock.unlock(); } }
From source file:com.uberspot.storageutils.StorageUtils.java
/** Loads the object stored in the given fileName * @param fileName the name of the file to load * @return the object loaded from the file *///from w ww.j a v a2 s .c o m public Object loadObjectFromInternalStorage(String fileName) { Object obj = null; ObjectInputStream input = null; try { if (fileExists(fileName)) { input = new ObjectInputStream(new BufferedInputStream(openFileInput(fileName))); obj = input.readObject(); } } catch (Exception e) { e.printStackTrace(System.out); } finally { if (input != null) try { input.close(); } catch (IOException e) { e.printStackTrace(System.out); } } return obj; }
From source file:hudson.console.AnnotatedLargeText.java
private ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException { try {/*from ww w .ja va 2 s . c om*/ String base64 = req != null ? req.getHeader("X-ConsoleAnnotator") : null; if (base64 != null) { Cipher sym = PASSING_ANNOTATOR.decrypt(); ObjectInputStream ois = new ObjectInputStreamEx( new GZIPInputStream(new CipherInputStream( new ByteArrayInputStream(Base64.decode(base64.toCharArray())), sym)), Jenkins.getInstance().pluginManager.uberClassLoader); try { long timestamp = ois.readLong(); if (TimeUnit2.HOURS.toMillis(1) > abs(System.currentTimeMillis() - timestamp)) // don't deserialize something too old to prevent a replay attack return (ConsoleAnnotator) ois.readObject(); } finally { ois.close(); } } } catch (ClassNotFoundException e) { throw new IOException(e); } // start from scratch return ConsoleAnnotator.initial(context == null ? null : context.getClass()); }
From source file:com.frostwire.gui.updates.InstallerUpdater.java
private final InstallerMetaData getLastInstallerMetaData() { InstallerMetaData result = null;// ww w . ja v a 2 s .c om try { File installerDatFile = new File(getInstallerDatPath()); if (!installerDatFile.exists()) { return null; } FileInputStream fis = new FileInputStream(installerDatFile); ObjectInputStream ois = new ObjectInputStream(fis); try { result = (InstallerMetaData) ois.readObject(); if (result == null) { return null; } } finally { fis.close(); ois.close(); } return result; } catch (Throwable e) { // processMessage will deal with us returning null LOG.info("Can't read installer meta data"); return null; } }