public static Object readData(String filePath) { Object result = null; try { filePath = StringUtil.checkFullPathLength(filePath); FileLockManager.startFileRead(filePath); if (isValid(filePath)) { FileInputStream os = new FileInputStream(filePath); XMLDecoder decoder = new XMLDecoder(os); decoder.setExceptionListener( new ExceptionListener() { public void exceptionThrown(Exception exception) { log.error("readData(): error", exception); } }); result = decoder.readObject(); decoder.close(); } } catch (java.io.FileNotFoundException fnfe) { log.trace("readData(): file not found exception, filePath=" + filePath); } catch (Error e) { log.error("readData(): error, filePath=" + filePath, e); } catch (Exception e) { log.error("readData(): exception, filePath=" + filePath, e); } finally { FileLockManager.endFileRead(filePath); } return result; }
/** @return */ public static final Map<String, List<String>> getHashMap() { File file = null; FileInputStream fis = null; XMLDecoder decode = null; Map<String, List<String>> dataMap = new HashMap<String, List<String>>(); try { file = new File(BuildConstants.propFile); fis = new FileInputStream(file); decode = new XMLDecoder(fis); dataMap = (ConcurrentHashMap<String, List<String>>) decode.readObject(); Set<String> mKeySet = dataMap.keySet(); for (String se : mKeySet) { List<String> valList = dataMap.get(se); for (String val : valList) { log.info("Elements in the Map->List are : Cluster -" + se + " Server - " + val); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (decode != null) { decode.close(); } if (fis != null) { fis.close(); } } catch (Exception e) { e.printStackTrace(); } } return dataMap; }
/** * Ctor that gets the properties from the XML files and set them to the server If properties does * not exist then it will take default values */ public MyModel() { this.clinetHandler = new MyClientHandler(); this.clientsHandled = 0; this.killServer = false; this.serverOpen = false; File serverProp = new File("./resources/propServer.xml"); // check if server Properties xml file exists if (!serverProp.exists()) // if the file does not exists { try { // create the xml file XMLEncoder xml = new XMLEncoder(new FileOutputStream("./resources/propServer.xml")); xml.writeObject(new ServerProperties(1234, 10)); xml.close(); } catch (FileNotFoundException e) { setChanged(); notifyObservers(new String[] {"error", e.getMessage()}); } } try { // get the server properties from the xml file XMLDecoder xml = new XMLDecoder(new FileInputStream("./resources/propServer.xml")); ServerProperties properties = (ServerProperties) xml.readObject(); this.port = properties.getPort(); this.numOfClients = properties.getNumClients(); xml.close(); } catch (Exception e) { setChanged(); notifyObservers(new String[] {"error", e.getMessage()}); } }
/** * Creates an instance of the given bean. The bean is first search as a class. If not found as * class, it is searched as a resource. There isn't a lazy initialization. * * @param beanName name of the bean (for now is also the file name, without .ser, into which the * bean has been serialized) NOT NULL * @return a new instance of the serialized bean * @throws BeanInstantiationException if the bean cannot be istantiated * @throws BeanInitializationException if an initialization error occurred * @throws BeanNotFoundException if the bean does not exist */ public static Object getNoInitBeanInstance(File beanName) throws BeanInstantiationException, BeanInitializationException, BeanNotFoundException { Object bean = null; InputStream is = null; try { is = new FileInputStream(beanName); } catch (FileNotFoundException ex) { throw new BeanNotFoundException(beanName.getAbsolutePath()); } BeanExceptionListener exceptionListener = new BeanExceptionListener(); XMLDecoder d = new XMLDecoder(is, null, exceptionListener); bean = d.readObject(); d.close(); if (exceptionListener.exceptionThrown()) { Throwable t = exceptionListener.getException(); if (t.getCause() != null) { t = t.getCause(); } throw new BeanInstantiationException("Error instantiating " + beanName, t); } return bean; }
@Override public ArrayList<User> loadAllUsers(String Identifier) { String file_name = BoardConfiguration.COMMON_STORAGE_PATH + Identifier + BoardConfiguration.USER_STORAGE_PATH; XMLDecoder dec = null; ArrayList<User> usr_list = null; try { dec = new XMLDecoder(new FileInputStream(file_name)); usr_list = (ArrayList<User>) dec.readObject(); } catch (FileNotFoundException ex) { usr_list = new ArrayList<>(); } catch (ArrayIndexOutOfBoundsException ex) { usr_list = new ArrayList<>(); } if (usr_list == null) { usr_list = new ArrayList<>(); } if (dec != null) { dec.close(); } return usr_list; }
@Test public void testAccountSerialization() throws Exception { Account a = ModelFactory.createAccount("Foo", ModelFactory.createAccountType("Cash", false)); a.setInterestRate(1234); a.setNotes("Foo bar notes"); a.setOverdraftCreditLimit(123); a.setStartingBalance(10000); ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(os); encoder.writeObject(a); encoder.flush(); encoder.close(); InputStream is = new ByteArrayInputStream(os.toByteArray()); XMLDecoder decoder = new XMLDecoder(is); Object o = decoder.readObject(); decoder.close(); if (!(o instanceof Account)) { throw new Exception("Deserialized object is not an account!"); } Account newAccount = (Account) o; assertEquals(a.getName(), newAccount.getName()); assertEquals(a.getAccountType(), newAccount.getAccountType()); assertEquals(a.getInterestRate(), newAccount.getInterestRate()); assertEquals(a.getNotes(), newAccount.getNotes()); assertEquals(a.getOverdraftCreditLimit(), newAccount.getOverdraftCreditLimit()); assertEquals(a.getStartingBalance(), newAccount.getStartingBalance()); }
private static Object loadObject(String path) throws IOException { Object rv = null; XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(path))); try { rv = d.readObject(); } catch (Exception e) { String error = "Error loading file: " + e; d.close(); throw new IOException(error); } d.close(); return rv; }
@SuppressWarnings("unchecked") protected void loadConfiguration() { String configFileName = getConfigurationFileName(); boolean debugGlobalConfiguration = Boolean.parseBoolean(defaultValues.get(G_PROPERTIES.DEBUG_GLOBALCONFIGURATION)); XMLDecoder decoder = null; if (configFileName != null && new File(configFileName).canRead()) try { if (debugGlobalConfiguration) System.out.println("Loaded configuration file " + configFileName); decoder = new XMLDecoder(new FileInputStream(configFileName)); properties = (Properties) decoder.readObject(); windowCoords = (HashMap<Integer, WindowPosition>) decoder.readObject(); decoder.close(); } catch (Exception e) { // failed loading, (almost) ignore this. System.err.println("Failed to load " + configFileName); e.printStackTrace(); if (debugGlobalConfiguration) { System.err.println("Failed to load " + configFileName); e.printStackTrace(); } } finally { if (decoder != null) decoder.close(); } if (windowCoords == null) windowCoords = new HashMap<Integer, WindowPosition>(); if (properties == null) properties = new Properties(); boolean valuesSet = false, firstValue = true; for (G_PROPERTIES prop : G_PROPERTIES.values()) { String name = prop.name(), value = null; try { value = System.getProperty(name); } catch (Exception ex) { } // ignore exception if cannot extract a value if (value != null) { // new value set via command-line if (debugGlobalConfiguration) { if (firstValue) firstValue = false; else System.out.print(','); System.out.print(name + "=" + value); } properties.setProperty(name, value); valuesSet = true; } } if (valuesSet && debugGlobalConfiguration) System.out.println(); }
public Set<String> getPreviousISNodeMethodsNames() throws FileNotFoundException, IOException { FileInputStream stream = new FileInputStream( PathManager.getHomePath() + "/testbench/modules/testRead/SNodeContract.xml"); XMLDecoder xmlDecoder = new XMLDecoder(stream); Set<String> set = (Set<String>) xmlDecoder.readObject(); xmlDecoder.close(); stream.close(); return set; }
/** * Unmarshals the given serialized object into the corresponding instance using * <i>java.beans.XMLDecoder</i>. * * @param classLoader the class loader to use (null for the standard one) * @param xml XML serialized form * @return the unmarshalled instance * @throws BeanException in case of unmarshalling errors */ public static Object unmarshal(ClassLoader classLoader, String xml) throws BeanException { XMLDecoder dec = null; ClassLoader oldClassLoader = null; if (classLoader != null) { oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); } BeanExceptionListener exceptionListener = new BeanExceptionListener(); try { ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); Object ret = null; dec = new XMLDecoder(is); dec.setExceptionListener(exceptionListener); ret = dec.readObject(); dec.close(); dec = null; if (exceptionListener.exceptionThrown()) { Throwable t = exceptionListener.getException(); if (t.getCause() != null) { t = t.getCause(); } throw new BeanInstantiationException("Error creating bean", t); } return ret; } finally { if (dec != null) { dec.close(); } if (classLoader != null) { Thread.currentThread().setContextClassLoader(oldClassLoader); } } }
public static Object readBytes(byte[] bytes) { Object result = null; try { ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes); XMLDecoder decoder = new XMLDecoder(byteIn); result = decoder.readObject(); decoder.close(); } catch (Exception e) { log.error("readData(): exception", e); } return result; }
/** * Create a new <code>PanelModel</code> from an object serialized using <code>XMLEncoder</code>. * For example, * * <pre> * PanelModel pModel; * Page page = new Page(); * try { * pModel = PanelModel.loadFromXML(new BufferedInputStream( * new FileInputStream(outpath))); * page.setPanelModel(pModel); * } catch (FileNotFoundException fnfe) { * JOptionPane.showMessageDialog(this, "Error openning file", * "File Open Error", JOptionPane.ERROR_MESSAGE); * } catch (InvalidObjectException ioe) { * JOptionPane.showMessageDialog(this, "File does not contain a PanelModel", * "PanelModel Not Found", * JOptionPane.ERROR_MESSAGE); * } * * </pre> * * @param is InputStream * @return PanelModel object * @throws InvalidObjectException * @see java.beans.XMLEncoder */ public static PanelModel loadFromXML(InputStream is) throws InvalidObjectException { PanelModel pModel = null; XMLDecoder xd = new XMLDecoder(is); Object obj = xd.readObject(); xd.close(); if (obj instanceof PanelModel) { pModel = (PanelModel) obj; pModel.repair(); } else { throw new InvalidObjectException("XML file does not contain a PanelModel"); } return pModel; }
private void loadDefaultConfig() { InputStream fs; // 必須加上"/"才能找到檔案 fs = ClassLoader.class.getResourceAsStream("/" + beanXml); if (fs != null) { XMLDecoder decoder = new XMLDecoder(fs); bean = decoder.readObject(); decoder.close(); } if (bean == null) { throw new IllegalStateException("No default config loaded!"); } }
/** * Encodes an object as XML and then decodes it. * * @param <T> the type to operate on * @param object the object to encode/decode * @return a copy of the original object that was encoded and decoded * @see XMLEncoder * @see XMLDecoder */ @SuppressWarnings("unchecked") public static <T> T encode(T object) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(baos); encoder.writeObject(object); encoder.close(); XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(baos.toByteArray())); T copy = (T) decoder.readObject(); decoder.close(); return copy; }
public static <T> T fromStream(boolean isXml, InputStream is, Class<T> tType) { if (isXml) { XMLDecoder decoder = null; try { decoder = new XMLDecoder(new BufferedInputStream(is)); return (T) decoder.readObject(); } catch (Exception e) { if (e instanceof java.io.InvalidClassException) { log.info("got type mismatch"); } else { e.printStackTrace(); } } finally { if (decoder != null) { decoder.close(); decoder = null; System.gc(); } } } else { ObjectInputStream decoder = null; try { decoder = new ObjectInputStream(new BufferedInputStream(is)); return (T) decoder.readObject(); } catch (Exception e) { if (e instanceof java.io.InvalidClassException) { log.info("got type mismatch"); } else { e.printStackTrace(); } } finally { if (decoder != null) { try { decoder.close(); } catch (Exception e) { } decoder = null; System.gc(); } } } return (T) (List.class.isAssignableFrom(tType) ? Collections.<T>emptyList() : Set.class.isAssignableFrom(tType) ? Collections.<T>emptySet() : Map.class.isAssignableFrom(tType) ? Collections.emptyMap() : null); }
/** * Generates a visibility map for data grid columns based on the XML encoded map stored in the * database. * * @return Map containing mappings between actions and a set of visible columns. */ @SuppressWarnings("unchecked") public Map<String, Set<String>> getColumnVisibilityMap() { if (columnVisibilityMap == null) { if (this.serializedVisibilityMap != null && this.serializedVisibilityMap.length() > 0) { XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(this.serializedVisibilityMap.getBytes())); this.columnVisibilityMap = (Map<String, Set<String>>) xmlDecoder.readObject(); xmlDecoder.close(); } else { columnVisibilityMap = new HashMap<String, Set<String>>(); } } return columnVisibilityMap; }
/** * Return an object from the specified array of bytes * * @param data an object */ public static Object unmarshallObject(byte[] data) { if (data == null) { return null; } XMLDecoder decoder = null; try { ByteArrayInputStream baIn = new ByteArrayInputStream(data); decoder = new XMLDecoder(baIn); return decoder.readObject(); } finally { if (decoder != null) { decoder.close(); } } }
public void load() { // show file chooser dialog int r = chooser.showOpenDialog(null); // if file selected, open if (r == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); XMLDecoder decoder = new XMLDecoder(new FileInputStream(file)); decoder.readObject(); decoder.close(); } catch (IOException e) { JOptionPane.showMessageDialog(null, e); } } }
public static Serializable loadBeanFromXML(InputStream in) { Serializable obj; XMLDecoder decoder = null; try { decoder = new XMLDecoder(in, ResourceHelper.class.getClassLoader()); obj = (Serializable) decoder.readObject(); return obj; } catch (Exception e) { e.printStackTrace(); } finally { if (decoder != null) { decoder.close(); } } return null; }
/** * 从XML中读取对象 Reads serialized object from the XML file. * * @param <T> * @param source XML文件 * @return 对象 * @throws IOException */ @SuppressWarnings("unchecked") public static <T> T readObjectFromXml(File source) throws IOException { Object result = null; FileInputStream fis = null; XMLDecoder xmldec = null; try { fis = new FileInputStream(source); xmldec = new XMLDecoder(new BufferedInputStream(fis)); result = xmldec.readObject(); } finally { FileUtil.close(fis); if (xmldec != null) { xmldec.close(); } } return (T) result; }
/** * Opens an XML file and returns it as an object making use of the {@link java.io.Serializable * serializable interface}. * * @param filename The filename (with extension) to be opened * @return The object contained within the XML code of the file */ public static Object openFromXML(String filename) { // System.out.print("opening \""+filename+"\" . . . "); // first open file and update to latest gem version: UpdateFileToLatestGemVersion(filename); XMLDecoder xmlIn = null; try { xmlIn = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename))); } catch (FileNotFoundException e) { e.printStackTrace(); } Object O = xmlIn.readObject(); xmlIn.close(); // System.out.print("done\n"); return O; }
public static Serializable loadBeanFromXML(String xml, ClassLoader cl) { Serializable obj; InputStream in; XMLDecoder decoder = null; try { in = new ByteArrayInputStream(xml.getBytes(ContentContext.CHARACTER_ENCODING)); decoder = new XMLDecoder(in, cl); obj = (Serializable) decoder.readObject(); return obj; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { if (decoder != null) { decoder.close(); } } return null; }
public void loadFromFile(String path) { InitData initData; try { XMLDecoder dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(path))); initData = (InitData) dec.readObject(); dec.close(); int initMRUlength = initData.MRUFiles.length; int length = (maxSize < initMRUlength) ? maxSize : initMRUlength; for (int i = 0; i < length; i++) { if (initData.MRUFiles[i] != null && !initData.MRUFiles[i].equals("")) { mostRecentlyUsedHistory.add(initData.MRUFiles[i]); } } } catch (Exception e) { } }
/** Reads in all the dots from the file and set the panel to show them. */ public void open(File file) { ManModel[] dotArray = null; try { XMLDecoder xmlIn = new XMLDecoder(new BufferedInputStream(new FileInputStream(file))); dotArray = (ManModel[]) xmlIn.readObject(); xmlIn.close(); // now we have the data, so go ahead and wipe out the old state // and put in the new. Goes through the same doAdd() bottleneck // used by the UI to add dots. // Note that we do this after the operations that might throw. clear(); for (ManModel dm : dotArray) { doAdd(dm); } setDirty(false); } catch (IOException e) { e.printStackTrace(); } }
private void obtenerExpediente(String fichero) { try { XMLDecoder dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(fichero))); FichaCliente ficha = (FichaCliente) dec.readObject(); dec.close(); cifjTextField2.setText(ficha.getCif()); direccionCompnanyia.setText(ficha.getDireccion()); nombreCompanyiajTextField1.setText(ficha.getNombre()); ciudadjTextField.setText(ficha.getCiudad()); codigoPostaljTextField.setText(ficha.getCodigoPostal()); telefonojTextField.setText(ficha.getTelefono()); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } catch (java.util.NoSuchElementException e) { JOptionPane.showMessageDialog( null, String.format("El fichero %s no es un fichero de Ficha de cliente", fichero)); } }
/** Read an InputStream that contains a list of servers to restore. */ protected boolean restoreServers(InputStream inputStream) throws SplatException { XMLDecoder decoder = new XMLDecoder(inputStream); boolean ok = true; SSAPRegResource server = null; while (true) { try { server = (SSAPRegResource) decoder.readObject(); String name = server.getShortName(); if (name == null || name.length() == 0) name = "<>"; serverList.put(name, server); selectionList.put(name, true); } catch (ArrayIndexOutOfBoundsException e) { break; // End of list. } catch (NoSuchElementException e) { System.out.println( "Failed to read server list " + " (old-style or invalid): '" + e.getMessage() + "'"); ok = false; break; } } decoder.close(); return ok; }
/** * Sets the directory in which to look for templates. Calling this method adds any new templates * found in the specified directory to the templates already registered. * * @param dir The new directory in which to look for templates. * @return The new number of templates in this template manager, or <code>-1</code> if the * specified directory does not exist. */ public int setTemplateDirectory(File dir) { if (dir != null && dir.isDirectory()) { this.directory = dir; File[] files = dir.listFiles(new XMLFileFilter()); int newCount = files == null ? 0 : files.length; int oldCount = templates.size(); List temp = new ArrayList(oldCount + newCount); temp.addAll(templates); for (int i = 0; i < newCount; i++) { try { XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(files[i]))); Object obj = d.readObject(); if (!(obj instanceof CodeTemplate)) { throw new IOException("Not a CodeTemplate: " + files[i].getAbsolutePath()); } temp.add((CodeTemplate) obj); d.close(); } catch (/*IO, NoSuchElement*/ Exception e) { // NoSuchElementException can be thrown when reading // an XML file not in the format expected by XMLDecoder. // (e.g. CodeTemplates in an old format). e.printStackTrace(); } } templates = temp; sortTemplates(); return getTemplateCount(); } return -1; }
public static Properties read(String filename) throws Exception { XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename))); Properties properties = (Properties) decoder.readObject(); decoder.close(); return properties; }
@Override public void actionPerformed(ActionEvent ae) { if (ae.getSource() == entityInfoMenuItem) { MapNode mNode = pane.getRenderer().getNextNode(x, y); if (mNode != null) pane.showMapEntityInfoDialog(mNode, pane.isDebugModeEnabled()); } else if (ae.getSource() == clearMenuItem) { pane.getMap().clearMarkersAndTracks(); } else if (ae.getSource() == createMarkerMenuItem) { PositionPanel panel = new PositionPanel(); int res = JOptionPane.showConfirmDialog( pane, panel, "Specify a Position", JOptionPane.OK_CANCEL_OPTION); if (res == JOptionPane.OK_OPTION) { float lat = panel.getLat(); float lon = panel.getLon(); if (!Float.isNaN(lat) && !Float.isNaN(lon)) { pane.getMap().addMarker(lat, lon); pane.adjustToCenter(lat, lon); } } } else if (ae.getSource() == removeMarkerMenuItem) { pane.removeNearestMarker(x, y); } else if (ae.getSource() == loadMarkersMenuItem) { XMLDecoder decoder = null; try { File xmlFile = null; if (getFileChooser().showDialog(pane, "Load Markers") == JFileChooser.APPROVE_OPTION) { xmlFile = getFileChooser().getSelectedFile(); if (!xmlFile.getPath().contains(".")) xmlFile = new File(xmlFile.getPath() + ".xml"); } if (xmlFile != null && xmlFile.exists()) { pane.getMap().clearMarkersAndTracks(); decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(xmlFile))); int size = (Integer) decoder.readObject(); for (int i = 0; i < size; i++) { WritablePosition pos = (WritablePosition) decoder.readObject(); pane.getMap().addMarker(pos.getLat(), pos.getLon()); } pane.fireMapViewEvent(new MapViewEvent(pane, MapViewEvent.Type.MARKER_ADDED)); } } catch (IOException e) { e.printStackTrace(); } finally { if (decoder != null) decoder.close(); } } else if (ae.getSource() == saveMarkersMenuItem) { XMLEncoder encoder = null; try { File xmlFile = null; if (getFileChooser().showDialog(pane, "Save Markers") == JFileChooser.APPROVE_OPTION) { xmlFile = getFileChooser().getSelectedFile(); if (!xmlFile.getPath().contains(".")) xmlFile = new File(xmlFile.getPath() + ".xml"); encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(xmlFile))); encoder.writeObject(pane.getMap().getMarkers().size()); for (MapNode node : pane.getMap().getMarkers()) encoder.writeObject(new WritablePosition(node)); } } catch (IOException e) { e.printStackTrace(); } finally { if (encoder != null) encoder.close(); } } else if (ae.getSource() == functionsMenuItem) { JOptionPane.showMessageDialog( pane, MapViewPane.FUNCTION_DESCRIPTION.split("\\|"), "Function Description", JOptionPane.INFORMATION_MESSAGE); } else if (ae.getSource() == debugMenuItem) { pane.enableDebugMode(debugMenuItem.isSelected()); } }
public static Quiz readXML(String filename) throws IOException { XMLDecoder dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename))); Quiz q = (Quiz) dec.readObject(); dec.close(); return q; }