List of usage examples for java.io StringReader StringReader
public StringReader(String s)
From source file:MainClass.java
public static void main(String args[]) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = null;/*w ww .ja v a 2 s. co m*/ spf.setNamespaceAware(true); spf.setValidating(true); try { spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true); parser = spf.newSAXParser(); System.out.println("Parser object is: " + parser); } catch (Exception e) { e.printStackTrace(System.err); } MySAXHandler handler = new MySAXHandler(); parser.parse(new InputSource(new StringReader(xmlString)), handler); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = null;/*from ww w . jav a2 s .co m*/ spf.setNamespaceAware(true); spf.setValidating(true); try { spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true); parser = spf.newSAXParser(); System.out.println("Parser object is: " + parser); } catch (SAXException e) { e.printStackTrace(System.err); System.exit(1); } catch (ParserConfigurationException e) { e.printStackTrace(System.err); System.exit(1); } MySAXHandler handler = new MySAXHandler(); parser.parse(new InputSource(new StringReader(xmlString)), handler); }
From source file:Main.java
public static void main(String[] args) throws Exception { List<Element> elementList = new ArrayList<Element>(); List<Item> itemList = new ArrayList<Item>(); Element element1 = new Element(); Element element2 = new Element(); Item item1 = new Item(); Item item2 = new Item(); Elements elements = new Elements(); item1.setId(1);//from w w w. j a v a 2s . c om item1.setName("Test1"); item2.setId(2); item2.setName("Test2"); itemList.add(item1); itemList.add(item2); element1.setProperty1("prop1"); element1.setProperty2("prop2"); element1.setType(2); element1.setItems(itemList); element2.setProperty1("prop11"); element2.setProperty2("prop22"); element2.setType(22); element2.setItems(itemList); elementList.add(element1); elementList.add(element2); elements.setElements(elementList); System.out.println("------- Object to XML -----------\n"); JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(elements, System.out); System.out.println("\n------- XML to Object -----------\n"); String xml = "<elements><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop1</property1><property2>prop2</property2><type>2</type></element><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop11</property1><property2>prop22</property2><type>22</type></element></elements>"; StringReader reader = new StringReader(xml); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Elements elementsOut = (Elements) jaxbUnmarshaller.unmarshal(reader); System.out.println(elementsOut); }
From source file:de.zib.gndms.gritserv.tests.EncTest.java
public static void main(String[] args) throws Exception { // String delfac = "https://130.73.72.106:8443/wsrf/services/DelegationFactoryService"; // GlobusCredential cred = DelegationAux.findCredential( null ); // EndpointReferenceType epr = DelegationAux.createProxy( delfac, cred ); String eprs = "<DelegatedEPR xsi:type=\"ns1:EndpointReferenceType\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://schemas.xmlsoap.org/ws/2004/03/addressing\">" + "<ns1:Address xsi:type=\"ns1:AttributedURI\">https://130.73.72.106:8443/wsrf/services/DelegationService</ns1:Address>" + "<ns1:ReferenceProperties xsi:type=\"ns1:ReferencePropertiesType\">" + "<ns1:DelegationKey xmlns:ns1=\"http://www.globus.org/08/2004/delegationService\">e54cb3e0-f834-11dd-93ce-a15e7f2269a5</ns1:DelegationKey>" + "</ns1:ReferenceProperties>" + "<ns1:ReferenceParameters xsi:type=\"ns1:ReferenceParametersType\"/>" + "</DelegatedEPR>"; InputSource is = new InputSource(new StringReader(eprs)); EndpointReferenceType epr = (EndpointReferenceType) ObjectDeserializer.deserialize(is, EndpointReferenceType.class); fieldTest(epr);/*from ww w .j av a 2 s . co m*/ }
From source file:ProcessorDemo.java
public static void main(String args[]) { try {//www.ja v a 2 s .c o m System.setProperty("sen.home", "../Sen1221/senhome-ipadic"); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "FATAL"); if (args.length != 2) { System.err.println("usage: java ProcessorDemo <filename> <encoding>"); System.exit(1); } BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), args[1])); String confPath = System.getProperty("sen.home") + System.getProperty("file.separator") + "conf/sen-processor.xml"; StreamTagger tagger = new StreamTagger((Reader) br, confPath); readConfig(confPath); if (!isCompound) { CompoundWordPostProcessor cwProcessor = new CompoundWordPostProcessor(compoundFile); tagger.addPostProcessor(cwProcessor); } if (compositRule != null && !compositRule.equals("")) { CompositPostProcessor processor = new CompositPostProcessor(); processor.readRules(new BufferedReader(new StringReader(compositRule))); tagger.addPostProcessor(processor); } if (remarkRule != null && !remarkRule.equals("")) { RemarkPreProcessor processor = new RemarkPreProcessor(); processor.readRules(new BufferedReader(new StringReader(remarkRule))); tagger.addPreProcessor(processor); RemarkPostProcessor p2 = new RemarkPostProcessor(); tagger.addPostProcessor(p2); } // BufferedReader is = new BufferedReader(System.in); while (tagger.hasNext()) { Token token = tagger.next(); System.out.println(token.getSurface() + "\t" + token.getPos() + "\t" + token.start() + "\t" + token.end() + "\t" + token.getCost() + "\t" + token.getAddInfo()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:ExternalConnection.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { // Create a connection to the database server // Up the connection pool count for testing DefaultConnectionPool cp = new DefaultConnectionPool(); cp.setDriver("org.apache.derby.jdbc.EmbeddedDriver"); cp.setURL("jdbc:derby:sampleDB"); //cp.setUser("sa"); //cp.setPassword(""); cp.setMinConnections(10);//from w w w . j a v a 2s .c o m cp.setPoolEnabled(true); // Now let's register our connection pool so we can use // in a stylesheet ConnectionPoolManager pm = new ConnectionPoolManager(); pm.registerPool("extpool", cp); // Use the static TransformerFactory.newInstance() method to instantiate // a TransformerFactory. The javax.xml.transform.TransformerFactory // system property setting determines the actual class to instantiate -- // org.apache.xalan.transformer.TransformerImpl. TransformerFactory tFactory = TransformerFactory.newInstance(); // Grab the Name of the Stylesheet from the commad line if (args.length == 0) { System.out.println("You must provide the path and name to a stylesheet to process"); System.exit(0); } String stylesheet = args[0]; System.out.println("Transforming Stylesheet " + stylesheet); // Use the TransformerFactory to instantiate a Transformer that will work with // the stylesheet you specify. This method call also processes the stylesheet // into a compiled Templates object. Transformer transformer = tFactory.newTransformer(new StreamSource(stylesheet)); // For this transformation, all the required information is in the stylesheet, so generate // a minimal XML source document for the input. // Note: the command-line processor (org.apache.xalan.xslt.Process) uses this strategy when // the user does not provide an -IN parameter. StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); // Use the Transformer to apply the associated Templates object to an XML document // and write the output to a file. transformer.transform(new StreamSource(reader), new StreamResult(new FileOutputStream("dbtest-out.html"))); System.out.println("************* The result is in dbtest-out.html *************"); cp.setPoolEnabled(false); }
From source file:MyContentHandler.java
static public void main(String[] arg) { SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader reader = null;//from w w w. jav a 2s . c o m try { SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); } catch (Exception e) { System.err.println(e); System.exit(1); } reader.setErrorHandler(new MyErrorHandler()); reader.setContentHandler(new MyContentHandler()); try { InputSource is = new InputSource(new StringReader(getXMLData())); reader.parse(is); } catch (SAXException e) { System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } }
From source file:Anaphora_Resolution.ParseAllXMLDocuments.java
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException { // File dataFolder = new File("DataToPort"); // File[] documents; String grammar = "grammar/englishPCFG.ser.gz"; String[] options = { "-maxLength", "100", "-retainTmpSubcategories" }; //LexicalizedParser lp = new LexicalizedParser(grammar, options); LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"); ////from w ww . ja v a 2s . co m // if (dataFolder.isDirectory()) { // documents = dataFolder.listFiles(); // } else { // documents = new File[] {dataFolder}; // } // int currfile = 0; // int totfiles = documents.length; // for (File paper : documents) { // currfile++; // if (paper.getName().equals(".DS_Store")||paper.getName().equals(".xml")) { // currfile--; // totfiles--; // continue; // } // System.out.println("Working on "+paper.getName()+" (file "+currfile+" out of "+totfiles+")."); // // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // This is for XML // DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Document doc = docBuilder.parse(paper.getAbsolutePath()); // // NodeList textlist = doc.getElementsByTagName("text"); // for(int i=0; i < textlist.getLength(); i++) { // Node currentnode = textlist.item(i); // String wholetext = textlist.item(i).getTextContent(); String wholetext = "How about other changes for example the ways of doing the work and \n" + "\n" + "Iwould say security has , there 's more pressure put on people now than there used to be because obviously , especially after Locherbie , they tightened up on security and there 's a lot more pressure now especially from the ETR and stuff like that \n" + "People do n't feel valued any more , they feel I do n't know I think they feel that nobody cares about them really anyway \n"; //System.out.println(wholetext); //Iterable<List<? extends HasWord>> sentences; ArrayList<Tree> parseTrees = new ArrayList<Tree>(); String asd = ""; int j = 0; StringReader stringreader = new StringReader(wholetext); DocumentPreprocessor dp = new DocumentPreprocessor(stringreader); @SuppressWarnings("rawtypes") ArrayList<List> sentences = preprocess(dp); for (List sentence : sentences) { parseTrees.add(lp.apply(sentence)); // Parsing a new sentence and adding it to the parsed tree ArrayList<Tree> PronounsList = findPronouns(parseTrees.get(j)); // Locating all pronouns to resolve in the sentence Tree corefedTree; for (Tree pronounTree : PronounsList) { parseTrees.set(parseTrees.size() - 1, HobbsResolve(pronounTree, parseTrees)); // Resolving the coref and modifying the tree for each pronoun } StringWriter strwr = new StringWriter(); PrintWriter prwr = new PrintWriter(strwr); TreePrint tp = new TreePrint("penn"); tp.printTree(parseTrees.get(j), prwr); prwr.flush(); asd += strwr.toString(); j++; } String armando = ""; for (Tree sentence : parseTrees) { for (Tree leaf : Trees.leaves(sentence)) armando += leaf + " "; } System.out.println(wholetext); System.out.println(); System.out.println("......"); System.out.println(armando); System.out.println("All done."); // currentnode.setTextContent(asd); // } // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(paper); // transformer.transform(source, result); // // System.out.println("Done"); // } }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;/*from w w w . ja v a2 s .c o m*/ } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }
From source file:kishida.cnn.NeuralNetwork.java
public static void main(String[] args) throws IOException { NeuralNetwork nn = new NeuralNetwork(); nn.getLayers()//from www.ja va 2s. co m .addAll(Arrays.asList(new InputLayer(20, 20), new ConvolutionLayer("conv1", 3, 7, 2, 1, true), new MaxPoolingLayer("pool", 3, 2), new MultiNormalizeLayer("norm1", 5, .0001f, true), new FullyConnect("test", 3, 0, 1, new LogisticFunction(), true))); nn.init(); nn.random.nextInt(); StringWriter sw = new StringWriter(); nn.writeAsJson(sw); System.out.println(sw); // ?????????????? StringReader sr0 = new StringReader(sw.toString()); NeuralNetwork nn0 = nn.readFromJson(sr0); nn0.init(); ConvolutionLayer conv1o = (ConvolutionLayer) nn.findLayerByName("conv1").get(); ConvolutionLayer conv1r = (ConvolutionLayer) nn0.findLayerByName("conv1").get(); System.out.println("org:" + Arrays.toString(conv1o.getFilter())); System.out.println("red:" + Arrays.toString(conv1r.getFilter())); double loss = IntStream.range(0, conv1o.getFilter().length) .mapToDouble(i -> (conv1o.getFilter()[i] - conv1r.getFilter()[i]) * (conv1o.getFilter()[i] - conv1r.getFilter()[i])) .sum(); System.out.println(Math.sqrt(loss)); NeuralNetwork v = NeuralNetwork.readFromJson(new StringReader("{\n" + " \"weightDecay\" : 5.0E-4,\n" + " \"miniBatch\" : 128,\n" + " \"random\" : \"c3EAfgAAAT/wWGBKFyCXAAATnQ6sF654\",\n" + " \"imageRandom\" : \"c3EAfgAAAAAAAAAAAAAAAAAABd7s70R4\",\n" + " \"momentam\" : 0.9,\n" + " \"layers\" : [ {\n" + " \"InputLayer\" : {\n" + " \"width\" : 250,\n" + " \"height\" : 220,\n" + " \"name\" : \"input\"\n" + " }\n" + " }, {\n" + " \"ConvolutionLayer\" : {\n" + " \"name\" : \"conv1\",\n" + " \"filter\" : null,\n" + " \"bias\" : [ 1.0, 1.0, 1.0 ],\n" + " \"filterDelta\" : null,\n" + " \"biasDelta\" : [ 0.0, 0.0, 0.0 ],\n" + " \"stride\" : 2,\n" + " \"filterSize\" : 7,\n" + " \"useGpu\" : true\n" + " }\n" + " }, {\n" + " \"MaxPoolingLayer\" : {\n" + " \"name\" : \"pool\",\n" + " \"size\" : 3,\n" + " \"stride\" : 2\n" + " }\n" + " }, {\n" + " \"MultiNormalizeLayer\" : {\n" + " \"name\" : \"norm1\",\n" + " \"size\" : 5,\n" + " \"threshold\" : 1.0E-4,\n" + " \"useGpu\" : true\n" + " }\n" + " }, {\n" + " \"FullyConnect\" : {\n" + " \"name\" : \"test\",\n" + " \"outputSize\" : 3,\n" + " \"weight\" : [ 0.0014115907, 0.0043465886, 0.01138472, -0.0013297468, " + "-0.0060525155, -0.0109255025, -0.015493984, 0.011872963, -0.0015145391 ],\n" + " \"initBias\" : 0.5, " + " \"bias\" : [ 0.0, 0.2, 0.4 ],\n" + " \"weightDelta\" : [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ],\n" + " \"biasDelta\" : [ 0.0, 0.0, 0.0 ],\n" + " \"dropoutRate\" : 1.0,\n" + " \"activation\" : \"LogisticFunction\",\n" + " \"useGpu\" : true\n" + " }\n" + " } ],\n" + " \"learningRate\" : 0.01\n" + "}")); System.out.println(nn.random.nextInt()); System.out.println(v.random.nextInt()); v.findLayerByName("test").ifPresent(layer -> { FullyConnect f = (FullyConnect) layer; System.out.println(f.getActivation().getClass()); System.out.println(Arrays.toString(f.getBias())); }); v.init(); v.findLayerByName("test").ifPresent(layer -> { FullyConnect f = (FullyConnect) layer; System.out.println(f.getActivation().getClass()); System.out.println(Arrays.toString(f.getBias())); }); }