//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static Object deepCopy(Object paramObject) throws Exception public static object deepCopy(object paramObject) { objectOutputStream = null; objectInputStream = null; try { MemoryStream byteArrayOutputStream = new MemoryStream(); objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(paramObject); objectOutputStream.flush(); MemoryStream byteArrayInputStream = new MemoryStream(byteArrayOutputStream.toByteArray()); objectInputStream = new ObjectInputStream(byteArrayInputStream); return(objectInputStream.readObject()); } catch (Exception exception) { Console.WriteLine("Exception in ObjectCloner = " + exception); throw exception; } finally { objectOutputStream.close(); objectInputStream.close(); } }
/// <summary> /// クリップボードに格納された文字列を元に,デシリアライズされたオブジェクトを取得します /// </summary> /// <param name="s"></param> /// <returns></returns> private Object getDeserializedObjectFromText(String s) { if (s.StartsWith(CLIP_PREFIX)) { int index = s.IndexOf(":"); index = s.IndexOf(":", index + 1); Object ret = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(str.sub(s, index + 1))); ObjectInputStream ois = new ObjectInputStream(bais); ret = ois.readObject(); } catch (Exception ex) { ret = null; Logger.write(typeof(ClipboardModel) + ".getDeserializedObjectFromText; ex=" + ex + "\n"); } return(ret); } else { return(null); } }
/* * public Set<Integer> getPatterns(String sentId, Integer tokenId) throws SQLException, IOException, ClassNotFoundException { * if(useDBForTokenPatterns){ * Connection conn = SQLConnection.getConnection(); * * String query = "Select patterns from " + tableName + " where sentid=\'" + sentId + "\' and tokenid = " + tokenId; * Statement stmt = conn.createStatement(); * ResultSet rs = stmt.executeQuery(query); * Set<Integer> pats = null; * if(rs.next()){ * byte[] st = (byte[]) rs.getObject(1); * ByteArrayInputStream baip = new ByteArrayInputStream(st); * ObjectInputStream ois = new ObjectInputStream(baip); * pats = (Set<Integer>) ois.readObject(); * * } * conn.close(); * return pats; * } * else * return patternsForEachToken.get(sentId).get(tokenId); * }*/ public override IDictionary <int, ICollection <E> > GetPatternsForAllTokens(string sentId) { try { IConnection conn = SQLConnection.GetConnection(); //Map<Integer, Set<Integer>> pats = new ConcurrentHashMap<Integer, Set<Integer>>(); string query = "Select patterns from " + tableName + " where sentid=\'" + sentId + "\'"; IStatement stmt = conn.CreateStatement(); IResultSet rs = stmt.ExecuteQuery(query); IDictionary <int, ICollection <E> > patsToken = new Dictionary <int, ICollection <E> >(); if (rs.Next()) { byte[] st = (byte[])rs.GetObject(1); ByteArrayInputStream baip = new ByteArrayInputStream(st); ObjectInputStream ois = new ObjectInputStream(baip); patsToken = (IDictionary <int, ICollection <E> >)ois.ReadObject(); } //pats.put(rs.getInt("tokenid"), patsToken); conn.Close(); return(patsToken); } catch (Exception e) { throw new Exception(e); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.TypeLoadException"/> private static void DemonstrateSerializationColumnDataClassifier() { System.Console.Out.WriteLine(); System.Console.Out.WriteLine("Demonstrating working with a serialized classifier using serializeTo"); ColumnDataClassifier cdc = new ColumnDataClassifier(where + "examples/cheese2007.prop"); cdc.TrainClassifier(where + "examples/cheeseDisease.train"); // Exhibit serialization and deserialization working. Serialized to bytes in memory for simplicity System.Console.Out.WriteLine(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); cdc.SerializeClassifier(oos); oos.Close(); byte[] @object = baos.ToByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(@object); ObjectInputStream ois = new ObjectInputStream(bais); ColumnDataClassifier cdc2 = ColumnDataClassifier.GetClassifier(ois); ois.Close(); // We compare the output of the deserialized classifier cdc2 versus the original one cl // For both we use a ColumnDataClassifier to convert text lines to examples System.Console.Out.WriteLine("Making predictions with both classifiers"); foreach (string line in ObjectBank.GetLineIterator(where + "examples/cheeseDisease.test", "utf-8")) { IDatum <string, string> d = cdc.MakeDatumFromLine(line); IDatum <string, string> d2 = cdc2.MakeDatumFromLine(line); System.Console.Out.Printf("%s =origi=> %s (%.4f)%n", line, cdc.ClassOf(d), cdc.ScoresOf(d).GetCount(cdc.ClassOf(d))); System.Console.Out.Printf("%s =deser=> %s (%.4f)%n", line, cdc2.ClassOf(d2), cdc2.ScoresOf(d).GetCount(cdc2.ClassOf(d))); } }
/// <summary> /// Loads and return s neural network instance from specified file /// </summary> /// <param name="file"> neural network file </param> /// <returns> neural network instance </returns> public static NeuralNetwork createFromFile(File file) { ObjectInputStream oistream = null; try { if (!file.exists()) { throw new FileNotFoundException("Cannot find file: " + file); } oistream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))); NeuralNetwork nnet = (NeuralNetwork)oistream.readObject(); return(nnet); } catch (IOException ioe) { throw new NeurophException("Could not read neural network file!", ioe); } catch (ClassNotFoundException cnfe) { throw new NeurophException("Class not found while trying to read neural network from file!", cnfe); } finally { if (oistream != null) { try { oistream.close(); } catch (IOException) { } } } }
/// <summary> /// This method is used by Java object deserialization, to fill in the /// transient /// <see cref="trackingUriPlugins"/> /// field. /// See /// <see cref="System.IO.ObjectInputStream.DefaultReadObject()"/> /// <p> /// <I>Do not remove</I> /// <p> /// Yarn isn't currently serializing this class, but findbugs /// complains in its absence. /// </summary> /// <param name="input">source</param> /// <exception cref="System.IO.IOException">IO failure</exception> /// <exception cref="System.TypeLoadException">classloader fun</exception> private void ReadObject(ObjectInputStream input) { input.DefaultReadObject(); conf = new YarnConfiguration(); this.trackingUriPlugins = conf.GetInstances <TrackingUriPlugin>(YarnConfiguration. YarnTrackingUrlGenerator); }
/// <summary> /// Deserializes this <code>DragSource</code>. This method first performs /// default deserialization. Next, this object's <code>FlavorMap</code> is /// deserialized by using the next object in the stream. /// If the resulting <code>FlavorMap</code> is <code>null</code>, this /// object's <code>FlavorMap</code> is set to the default FlavorMap for /// this thread's <code>ClassLoader</code>. /// Next, this object's listeners are deserialized by reading a /// <code>null</code>-terminated sequence of 0 or more key/value pairs /// from the stream: /// <ul> /// <li>If a key object is a <code>String</code> equal to /// <code>dragSourceListenerK</code>, a <code>DragSourceListener</code> is /// deserialized using the corresponding value object and added to this /// <code>DragSource</code>. /// <li>If a key object is a <code>String</code> equal to /// <code>dragSourceMotionListenerK</code>, a /// <code>DragSourceMotionListener</code> is deserialized using the /// corresponding value object and added to this <code>DragSource</code>. /// <li>Otherwise, the key/value pair is skipped. /// </ul> /// </summary> /// <seealso cref= java.awt.datatransfer.SystemFlavorMap#getDefaultFlavorMap /// @since 1.4 </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException private void ReadObject(ObjectInputStream s) { s.DefaultReadObject(); // 'flavorMap' was written explicitly FlavorMap_Renamed = (FlavorMap)s.ReadObject(); // Implementation assumes 'flavorMap' is never null. if (FlavorMap_Renamed == null) { FlavorMap_Renamed = SystemFlavorMap.DefaultFlavorMap; } Object keyOrNull; while (null != (keyOrNull = s.ReadObject())) { String key = ((String)keyOrNull).intern(); if (DragSourceListenerK == key) { AddDragSourceListener((DragSourceListener)(s.ReadObject())); } else if (DragSourceMotionListenerK == key) { AddDragSourceMotionListener((DragSourceMotionListener)(s.ReadObject())); } else { // skip value for unrecognized key s.ReadObject(); } } }
/// <summary> /// Reads the default serializable fields, provides default values for objects /// in older serial versions, and initializes non-serializable fields. /// If <code>serialVersionOnStream</code> /// is less than 1, initializes <code>monetarySeparator</code> to be /// the same as <code>decimalSeparator</code> and <code>exponential</code> /// to be 'E'. /// If <code>serialVersionOnStream</code> is less than 2, /// initializes <code>locale</code>to the root locale, and initializes /// If <code>serialVersionOnStream</code> is less than 3, it initializes /// <code>exponentialSeparator</code> using <code>exponential</code>. /// Sets <code>serialVersionOnStream</code> back to the maximum allowed value so that /// default serialization will work properly if this object is streamed out again. /// Initializes the currency from the intlCurrencySymbol field. /// /// @since JDK 1.1.6 /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException private void ReadObject(ObjectInputStream stream) { stream.DefaultReadObject(); if (SerialVersionOnStream < 1) { // Didn't have monetarySeparator or exponential field; // use defaults. MonetarySeparator = DecimalSeparator_Renamed; Exponential = 'E'; } if (SerialVersionOnStream < 2) { // didn't have locale; use root locale Locale = Locale.ROOT; } if (SerialVersionOnStream < 3) { // didn't have exponentialSeparator. Create one using exponential ExponentialSeparator = char.ToString(Exponential); } SerialVersionOnStream = CurrentSerialVersion; if (IntlCurrencySymbol != null) { try { Currency_Renamed = Currency.GetInstance(IntlCurrencySymbol); } catch (IllegalArgumentException) { } } }
/// <summary> /// Reads serializable fields from stream. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException private void ReadObject(ObjectInputStream s) { ObjectInputStream.GetField f = s.ReadFields(); Hgap_Renamed = f.Get("hgap", 0); Vgap_Renamed = f.Get("vgap", 0); if (f.Defaulted("vector")) { // pre-1.4 stream Dictionary <String, Component> tab = (Hashtable)f.Get("tab", null); Vector = new List <>(); if (tab != null && tab.Count > 0) { for (IEnumerator <String> e = tab.Keys.GetEnumerator(); e.MoveNext();) { String key = (String)e.Current; Component comp = (Component)tab[key]; Vector.Add(new Card(this, key, comp)); if (comp.Visible) { CurrentCard = Vector.Count - 1; } } } } else { Vector = (ArrayList)f.Get("vector", null); CurrentCard = f.Get("currentCard", 0); } }
public static IList <Tree> ConvertToTrees(byte[] input) { try { IList <Tree> output = new List <Tree>(); ByteArrayInputStream bis = new ByteArrayInputStream(input); GZIPInputStream gis = new GZIPInputStream(bis); ObjectInputStream ois = new ObjectInputStream(gis); int size = ErasureUtils.UncheckedCast <int>(ois.ReadObject()); for (int i = 0; i < size; ++i) { string rawTree = ErasureUtils.UncheckedCast(ois.ReadObject()); Tree tree = Tree.ValueOf(rawTree, trf); tree.SetSpans(); output.Add(tree); } ois.Close(); gis.Close(); bis.Close(); return(output); } catch (IOException e) { throw new RuntimeIOException(e); } catch (TypeLoadException e) { throw new Exception(e); } }
//------------------------------------------------------------------------- /// <summary> /// Asserts that the object can be serialized and deserialized to an equal form. /// </summary> /// <param name="base"> the object to be tested </param> public static void assertSerialization(object @base) { assertNotNull(@base); try { using (MemoryStream baos = new MemoryStream()) { using (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(@base); oos.close(); using (MemoryStream bais = new MemoryStream(baos.toByteArray())) { using (ObjectInputStream ois = new ObjectInputStream(bais)) { assertEquals(ois.readObject(), @base); } } } } } catch (Exception ex) when(ex is IOException || ex is ClassNotFoundException) { throw new Exception(ex); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.TypeLoadException"/> public virtual IDictionary <string, double[]> GetEmbeddings(string cacheFilename, IList <CoNLLBenchmark.CoNLLSentence> sentences) { File f = new File(cacheFilename); IDictionary <string, double[]> trimmedSet; if (!f.Exists()) { trimmedSet = new Dictionary <string, double[]>(); IDictionary <string, double[]> massiveSet = LoadEmbeddingsFromFile("../google-300.txt"); log.Info("Got massive embedding set size " + massiveSet.Count); foreach (CoNLLBenchmark.CoNLLSentence sentence in sentences) { foreach (string token in sentence.token) { if (massiveSet.Contains(token)) { trimmedSet[token] = massiveSet[token]; } } } log.Info("Got trimmed embedding set size " + trimmedSet.Count); f.CreateNewFile(); ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(cacheFilename))); oos.WriteObject(trimmedSet); oos.Close(); log.Info("Wrote trimmed set to file"); } else { ObjectInputStream ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream(cacheFilename))); trimmedSet = (IDictionary <string, double[]>)ois.ReadObject(); ois.Close(); } return(trimmedSet); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.TypeLoadException"/> private void ReadObject(ObjectInputStream stream) { stream.DefaultReadObject(); // log.info("Before decompression:"); // log.info("arg size: " + argCounter.size() + " total: " + argCounter.totalCount()); // log.info("stop size: " + stopCounter.size() + " total: " + stopCounter.totalCount()); ClassicCounter <IntDependency> compressedArgC = argCounter; argCounter = new ClassicCounter <IntDependency>(); ClassicCounter <IntDependency> compressedStopC = stopCounter; stopCounter = new ClassicCounter <IntDependency>(); foreach (IntDependency d in compressedArgC.KeySet()) { double count = compressedArgC.GetCount(d); ExpandArg(d, d.distance, count); } foreach (IntDependency d_1 in compressedStopC.KeySet()) { double count = compressedStopC.GetCount(d_1); ExpandStop(d_1, d_1.distance, count, false); } // log.info("After decompression:"); // log.info("arg size: " + argCounter.size() + " total: " + argCounter.totalCount()); // log.info("stop size: " + stopCounter.size() + " total: " + stopCounter.totalCount()); expandDependencyMap = null; }
/// <summary> /// Reads default serializable fields to stream. </summary> /// <exception cref="HeadlessException"> if /// <code>GraphicsEnvironment.isHeadless()</code> returns /// <code>true</code> </exception> /// <seealso cref= java.awt.GraphicsEnvironment#isHeadless </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException, HeadlessException private void ReadObject(ObjectInputStream s) { GraphicsEnvironment.CheckHeadless(); // 4352819: Gotcha! Cannot use s.defaultReadObject here and // then continue with reading optional data. Use GetField instead. ObjectInputStream.GetField f = s.ReadFields(); // Old fields ScrollbarDisplayPolicy_Renamed = f.Get("scrollbarDisplayPolicy", SCROLLBARS_AS_NEEDED); HAdjustable_Renamed = (ScrollPaneAdjustable)f.Get("hAdjustable", null); VAdjustable_Renamed = (ScrollPaneAdjustable)f.Get("vAdjustable", null); // Since 1.4 WheelScrollingEnabled_Renamed = f.Get("wheelScrollingEnabled", DefaultWheelScroll); // // Note to future maintainers // if (f.defaulted("wheelScrollingEnabled")) { // // We are reading pre-1.4 stream that doesn't have // // optional data, not even the TC_ENDBLOCKDATA marker. // // Reading anything after this point is unsafe as we will // // read unrelated objects further down the stream (4352819). // } // else { // // Reading data from 1.4 or later, it's ok to try to read // // optional data as OptionalDataException with eof == true // // will be correctly reported // } }
/// <summary> /// Deserialize the {@code CertificateRevokedException} instance. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException private void ReadObject(ObjectInputStream ois) { // Read in the non-transient fields // (revocationDate, reason, authority) ois.DefaultReadObject(); // Defensively copy the revocation date RevocationDate_Renamed = new DateTime(RevocationDate_Renamed.Ticks); // Read in the size (number of mappings) of the extensions map // and create the extensions map int size = ois.ReadInt(); if (size == 0) { Extensions_Renamed = Collections.EmptyMap(); } else { Extensions_Renamed = new Dictionary <String, Extension>(size); } // Read in the extensions and put the mappings in the extensions map for (int i = 0; i < size; i++) { String oid = (String)ois.ReadObject(); bool critical = ois.ReadBoolean(); int length = ois.ReadInt(); sbyte[] extVal = new sbyte[length]; ois.ReadFully(extVal); Extension ext = sun.security.x509.Extension.newExtension(new ObjectIdentifier(oid), critical, extVal); Extensions_Renamed[oid] = ext; } }
/// <summary> /// Read the ObjectInputStream and if it isn't null, /// add a listener to receive action events fired by the /// TextField. Unrecognized keys or values will be /// ignored. /// </summary> /// <exception cref="HeadlessException"> if /// <code>GraphicsEnvironment.isHeadless()</code> returns /// <code>true</code> </exception> /// <seealso cref= #removeActionListener(ActionListener) </seealso> /// <seealso cref= #addActionListener(ActionListener) </seealso> /// <seealso cref= java.awt.GraphicsEnvironment#isHeadless </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException, HeadlessException private void ReadObject(ObjectInputStream s) { // HeadlessException will be thrown by TextComponent's readObject s.DefaultReadObject(); // Make sure the state we just read in for columns has legal values if (Columns_Renamed < 0) { Columns_Renamed = 0; } // Read in listeners, if any Object keyOrNull; while (null != (keyOrNull = s.ReadObject())) { String key = ((String)keyOrNull).intern(); if (ActionListenerK == key) { AddActionListener((ActionListener)(s.ReadObject())); } else { // skip value for unrecognized key s.ReadObject(); } } }
// package-private for testing Module deserialize(string sourcePath) { #if NEVER string cachePath = getCachePath(sourcePath); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(cachePath); ois = new ObjectInputStream(fis); return((Module)ois.readObject()); } catch (Exception e) { return(null); } finally { try { if (ois != null) { ois.close(); } else if (fis != null) { fis.close(); } } catch (Exception e) { } } }
/// <summary> /// Deserializes this <code>DropTarget</code>. This method first performs /// default deserialization for all non-<code>transient</code> fields. An /// attempt is then made to deserialize this object's /// <code>DropTargetListener</code> as well. This is first attempted by /// deserializing the field <code>dtListener</code>, because, in releases /// prior to 1.4, a non-<code>transient</code> field of this name stored the /// <code>DropTargetListener</code>. If this fails, the next object in the /// stream is used instead. /// /// @since 1.4 /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException private void ReadObject(ObjectInputStream s) { ObjectInputStream.GetField f = s.ReadFields(); try { DropTargetContext_Renamed = (DropTargetContext)f.Get("dropTargetContext", null); } catch (IllegalArgumentException) { // Pre-1.4 support. 'dropTargetContext' was previously transient } if (DropTargetContext_Renamed == null) { DropTargetContext_Renamed = CreateDropTargetContext(); } Component_Renamed = (Component)f.Get("component", null); Actions = f.Get("actions", DnDConstants.ACTION_COPY_OR_MOVE); Active_Renamed = f.Get("active", true); // Pre-1.4 support. 'dtListener' was previously non-transient try { DtListener = (DropTargetListener)f.Get("dtListener", null); } catch (IllegalArgumentException) { // 1.4-compatible byte stream. 'dtListener' was written explicitly DtListener = (DropTargetListener)s.ReadObject(); } }
public void handleStream(Socket client) { try { setClient(client); //und dat naked fields ? outputStream = new ObjectOutputStream(getClient().getOutputStream()); inputStream = new ObjectInputStream(getClient().getInputStream()); } catch (IOException e) { e.printStackTrace(); } finally { try { //try to close gracefully client.close(); } catch (IOException e) { e.printStackTrace(); } } }
public void handleStream() { try { setClient(serverSocket.accept()); //reflush the stream outputStream = new ObjectOutputStream(getClient().getOutputStream()); inputStream = new ObjectInputStream(getClient().getInputStream()); } catch (IOException e) { e.printStackTrace(); } finally { try { //try to close gracefully getClient().close(); } catch (IOException e) { e.printStackTrace(); } } }
/// <summary> /// Creates a new file-backed CacheMap or loads it in from the specified file /// if it already exists. /// </summary> /// <remarks> /// Creates a new file-backed CacheMap or loads it in from the specified file /// if it already exists. The parameters passed in are the same as the /// constructor. If useFileParams is true and the file exists, all of your /// parameters will be ignored (replaced with those stored in the file /// itself). If useFileParams is false then we override the settings in the /// file with the ones you specify (except loadFactor and accessOrder) and /// reset the stats. /// </remarks> public static Edu.Stanford.Nlp.Util.CacheMap <K, V> Create <K, V>(int numEntries, float loadFactor, bool accessOrder, string file, bool useFileParams) { try { using (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { Edu.Stanford.Nlp.Util.CacheMap <K, V> c = ErasureUtils.UncheckedCast(ois.ReadObject()); log.Info("Read cache from " + file + ", contains " + c.Count + " entries. Backing file is " + c.backingFile); if (!useFileParams) { c.backingFile = file; c.hits = c.misses = c.puts = 0; c.CacheEntries = numEntries; } return(c); } } catch (FileNotFoundException) { log.Info("Cache file " + file + " has not been created yet. Making new one."); return(new Edu.Stanford.Nlp.Util.CacheMap <K, V>(numEntries, loadFactor, accessOrder, file)); } catch (Exception) { log.Info("Error reading cache file " + file + ". Making a new cache and NOT backing to file."); return(new Edu.Stanford.Nlp.Util.CacheMap <K, V>(numEntries, loadFactor, accessOrder)); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws ClassNotFoundException, java.io.IOException private void ReadObject(ObjectInputStream s) { this.Map = new PropertyChangeListenerMap(); ObjectInputStream.GetField fields = s.ReadFields(); //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") java.util.Hashtable<String, PropertyChangeSupport> children = (java.util.Hashtable<String, PropertyChangeSupport>) fields.get("children", null); Dictionary <String, PropertyChangeSupport> children = (Dictionary <String, PropertyChangeSupport>)fields.Get("children", null); this.Source = fields.Get("source", null); fields.Get("propertyChangeSupportSerializedDataVersion", 2); Object listenerOrNull; while (null != (listenerOrNull = s.ReadObject())) { this.Map.Add(null, (PropertyChangeListener)listenerOrNull); } if (children != null) { foreach (Map_Entry <String, PropertyChangeSupport> entry in children) { foreach (PropertyChangeListener listener in entry.Value.PropertyChangeListeners) { this.Map.Add(entry.Key, listener); } } } }
/// <summary> /// Deserialize <seealso cref="#msgPatterns"/> and <seealso cref="#msgArguments"/>. /// </summary> /// <param name="in"> Stream. </param> /// <exception cref="IOException"> This should never happen. </exception> /// <exception cref="ClassNotFoundException"> This should never happen. </exception> private void DeSerializeMessages(ObjectInputStream @in) { // Step 1. //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int len = in.readInt(); int len = @in.readInt(); msgPatterns = new List <Localizable>(len); msgArguments = new List <object[]>(len); // Step 2. for (int i = 0; i < len; i++) { // Step 3. //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Localizable pat = (Localizable) in.readObject(); Localizable pat = (Localizable)@in.readObject(); msgPatterns.Add(pat); // Step 4. //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int aLen = in.readInt(); int aLen = @in.readInt(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Object[] args = new Object[aLen]; object[] args = new object[aLen]; for (int j = 0; j < aLen; j++) { // Step 5. args[j] = @in.readObject(); } msgArguments.Add(args); } }
/* * Reads in a Hashtable in which the values are Vectors of * UnresolvedPermissions and saves them in the perms field. */ //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException private void ReadObject(ObjectInputStream @in) { // Don't call defaultReadObject() // Read in serialized fields ObjectInputStream.GetField gfields = @in.ReadFields(); // Get permissions //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") Hashtable<String, Vector<UnresolvedPermission>> permissions = (Hashtable<String, Vector<UnresolvedPermission>>) gfields.get("permissions", null); Dictionary <String, Vector <UnresolvedPermission> > permissions = (Dictionary <String, Vector <UnresolvedPermission> >)gfields.Get("permissions", null); // writeObject writes a Hashtable<String, Vector<UnresolvedPermission>> // for the permissions key, so this cast is safe, unless the data is corrupt. Perms = new HashMap <String, List <UnresolvedPermission> >(permissions.Size() * 2); // Convert each entry (Vector) into a List Set <Map_Entry <String, Vector <UnresolvedPermission> > > set = permissions.EntrySet(); foreach (Map_Entry <String, Vector <UnresolvedPermission> > e in set) { // Convert Vector into ArrayList Vector <UnresolvedPermission> vec = e.Value; List <UnresolvedPermission> list = new List <UnresolvedPermission>(vec.Size()); list.AddAll(vec); // Add to Hashtable being serialized Perms.Put(e.Key, list); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException private void ReadObject(ObjectInputStream @in) { // Don't call defaultReadObject() ObjectInputStream.GetField oisFields = @in.ReadFields(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String oisHostname = (String)oisFields.get("hostname", null); String oisHostname = (String)oisFields.Get("hostname", null); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final InetAddress oisAddr = (InetAddress)oisFields.get("addr", null); InetAddress oisAddr = (InetAddress)oisFields.Get("addr", null); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int oisPort = oisFields.get("port", -1); int oisPort = oisFields.Get("port", -1); // Check that our invariants are satisfied CheckPort(oisPort); if (oisHostname == null && oisAddr == null) { throw new InvalidObjectException("hostname and addr " + "can't both be null"); } InetSocketAddressHolder h = new InetSocketAddressHolder(oisHostname, oisAddr, oisPort); UNSAFE.putObject(this, FIELDS_OFFSET, h); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public Object getConfigFileEntryObject(String fileName) throws org.maltparser.core.exception.MaltChainedException public virtual object getConfigFileEntryObject(string fileName) { object @object = null; try { ObjectInputStream input = new ObjectInputStream(getInputStreamFromConfigFileEntry(fileName)); try { @object = input.readObject(); } catch (ClassNotFoundException e) { throw new ConfigurationException("Could not load object '" + fileName + "' from mco-file", e); } catch (Exception e) { throw new ConfigurationException("Could not load object '" + fileName + "' from mco-file", e); } finally { input.close(); } } catch (IOException e) { throw new ConfigurationException("Could not load object from '" + fileName + "' in mco-file", e); } return(@object); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected org.maltparser.ml.lib.FeatureMap loadFeatureMap(java.io.InputStream is) throws org.maltparser.core.exception.MaltChainedException protected internal virtual FeatureMap loadFeatureMap(Stream @is) { FeatureMap map = new FeatureMap(); try { ObjectInputStream input = new ObjectInputStream(@is); try { map = (FeatureMap)input.readObject(); } finally { input.close(); } } catch (ClassNotFoundException e) { throw new LibException("Load feature map error", e); } catch (IOException e) { throw new LibException("Load feature map error", e); } return(map); }
public override IDictionary <int, ICollection <E> > GetPatternsForAllTokens(string sentId) { try { TermQuery query = new TermQuery(new Term("sentid", sentId)); TopDocs tp = searcher.Search(query, 1); if (tp.totalHits > 0) { foreach (ScoreDoc s in tp.scoreDocs) { int docId = s.doc; Org.Apache.Lucene.Document.Document d = searcher.Doc(docId); byte[] st = d.GetBinaryValue("patterns").bytes; ByteArrayInputStream baip = new ByteArrayInputStream(st); ObjectInputStream ois = new ObjectInputStream(baip); return((IDictionary <int, ICollection <E> >)ois.ReadObject()); } } else { throw new Exception("Why no patterns for sentid " + sentId + ". Number of documents in index are " + Size()); } } catch (IOException e) { throw new Exception(e); } catch (TypeLoadException e) { throw new Exception(e); } return(null); }
/// <summary>Returs a Tree from the server connected to at host:port.</summary> /// <exception cref="System.IO.IOException"/> public virtual Tree GetTree(string query) { Socket socket = new Socket(host, port); TextWriter @out = new OutputStreamWriter(socket.GetOutputStream(), "utf-8"); @out.Write("tree " + query + "\n"); @out.Flush(); ObjectInputStream ois = new ObjectInputStream(socket.GetInputStream()); object o; try { o = ois.ReadObject(); } catch (TypeLoadException e) { throw new Exception(e); } if (!(o is Tree)) { throw new ArgumentException("Expected a tree"); } Tree tree = (Tree)o; socket.Close(); return(tree); }
/// <summary>Loads the model from disk.</summary> /// <param name="path">The location of model that was saved to disk</param> /// <exception cref="System.InvalidCastException">if model is the wrong format</exception> /// <exception cref="System.IO.IOException"> /// if the model file doesn't exist or is otherwise /// unavailable/incomplete /// </exception> /// <exception cref="System.TypeLoadException">this would probably indicate a serious classpath problem</exception> public static Edu.Stanford.Nlp.IE.Machinereading.BasicEntityExtractor Load(string path, Type entityClassifier, bool preferDefaultGazetteer) { // load the additional arguments // try to load the extra file from the CLASSPATH first InputStream @is = typeof(Edu.Stanford.Nlp.IE.Machinereading.BasicEntityExtractor).GetClassLoader().GetResourceAsStream(path + ".extra"); // if not found in the CLASSPATH, load from the file system if (@is == null) { @is = new FileInputStream(path + ".extra"); } ObjectInputStream @in = new ObjectInputStream(@is); string gazetteerLocation = ErasureUtils.UncheckedCast <string>(@in.ReadObject()); if (preferDefaultGazetteer) { gazetteerLocation = DefaultPaths.DefaultNflGazetteer; } ICollection <string> annotationsToSkip = ErasureUtils.UncheckedCast <ICollection <string> >(@in.ReadObject()); bool useSubTypes = ErasureUtils.UncheckedCast <bool>(@in.ReadObject()); bool useBIO = ErasureUtils.UncheckedCast <bool>(@in.ReadObject()); @in.Close(); @is.Close(); Edu.Stanford.Nlp.IE.Machinereading.BasicEntityExtractor extractor = (Edu.Stanford.Nlp.IE.Machinereading.BasicEntityExtractor)MachineReading.MakeEntityExtractor(entityClassifier, gazetteerLocation); // load the CRF classifier (this works from any resource, e.g., classpath or file system) extractor.classifier = CRFClassifier.GetClassifier(path); // copy the extra arguments extractor.annotationsToSkip = annotationsToSkip; extractor.useSubTypes = useSubTypes; extractor.useBIO = useBIO; return(extractor); }
public static object load(string fname) { object r = null; try { FileInputStream fs = new FileInputStream(fname); ObjectInputStream @in = new ObjectInputStream(fs); r = @in.readObject(); @in.close(); return r; } catch(Exception ex) { ex.printStackTrace(); } return r; }
// package-private for testing Module deserialize(string sourcePath) { #if NEVER string cachePath = getCachePath(sourcePath); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(cachePath); ois = new ObjectInputStream(fis); return (Module) ois.readObject(); } catch (Exception e) { return null; } finally { try { if (ois != null) { ois.close(); } else if (fis != null) { fis.close(); } } catch (Exception e) { } } }
/** * Reads one object from the given ObjectInputStream, which is * assumed to be a LexicalizedParser. Throws a ClassCastException * if this is not true. The stream is not closed. */ public static LexicalizedParser loadModel(ObjectInputStream ois) { try { Object o = ois.readObject(); if (o instanceof LexicalizedParser) { return (LexicalizedParser) o; } throw new ClassCastException("Wanted LexicalizedParser, got " + o.getClass()); } catch (IOException e) { throw new RuntimeIOException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }