List of usage examples for java.io StringReader close
public void close()
From source file:org.unitime.timetable.tags.Registration.java
private synchronized void init() { sLastRefresh = System.currentTimeMillis(); try {// w w w .jav a 2 s . com File regFile = new File(ApplicationProperties.getDataFolder(), "unitime.reg"); if (sKey == null && regFile.exists()) { Properties reg = new Properties(); FileInputStream in = new FileInputStream(regFile); try { reg.load(in); } finally { in.close(); } sKey = reg.getProperty("key"); } HashMap<String, String> registration = new HashMap<String, String>(); if (sKey != null) registration.put("key", sKey); else sLog.debug("No registration key found..."); registration.put("version", Constants.getVersion()); registration.put("sessions", String.valueOf(QueryLog.getNrSessions(31))); registration.put("users", String.valueOf(QueryLog.getNrActiveUsers(31))); registration.put("url", pageContext.getRequest().getScheme() + "://" + pageContext.getRequest().getServerName() + ":" + pageContext.getRequest().getServerPort() + ((HttpServletRequest) pageContext.getRequest()).getContextPath()); sLog.debug("Sending the following registration info: " + registration); Document input = DocumentHelper.createDocument(); Element regEl = input.addElement("registration"); for (Map.Entry<String, String> entry : registration.entrySet()) { regEl.addElement(entry.getKey()).setText(entry.getValue()); } sLog.debug("Contacting registration service..."); ClientResource cr = new ClientResource("http://register.unitime.org/xml"); StringWriter w = new StringWriter(); new XMLWriter(w, OutputFormat.createPrettyPrint()).write(input); w.flush(); w.close(); String result = cr.post(w.toString(), String.class); sLog.info("Registration information received."); try { cr.release(); } catch (Exception e) { } StringReader r = new StringReader(result); Document output = (new SAXReader()).read(r); r.close(); HashMap<String, String> ret = new HashMap<String, String>(); for (Element e : (List<Element>) output.getRootElement().elements()) { ret.put(e.getName(), e.getText()); } String newKey = ret.get("key"); if (!newKey.equals(sKey)) { sKey = newKey; sLog.debug("New registration key received..."); Properties reg = new Properties(); reg.setProperty("key", sKey); FileOutputStream out = new FileOutputStream(regFile); try { reg.store(out, "UniTime " + Constants.VERSION + " registration file, please do not delete or modify."); out.flush(); } finally { out.close(); } } sMessage = ret.get("message"); sNote = ret.get("note"); sRegistered = "1".equals(ret.get("registered")); } catch (Exception e) { sLog.error("Validation failed: " + e.getMessage(), e); } }
From source file:org.sakaiproject.component.app.help.RestConfigurationImpl.java
/** * @see org.sakaiproject.api.app.help.RestConfiguration#getResourceNameFromCorpusDoc(java.lang.String) *///from www .ja v a 2 s. co m public String getResourceNameFromCorpusDoc(String xml) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); StringReader sReader = new StringReader(xml); InputSource inputSource = new org.xml.sax.InputSource(sReader); org.w3c.dom.Document xmlDocument = builder.parse(inputSource); sReader.close(); NodeList nodeList = xmlDocument.getElementsByTagName("kbq"); int nodeListLength = nodeList.getLength(); for (int i = 0; i < nodeListLength; i++) { Node currentNode = nodeList.item(i); NodeList nlChildren = currentNode.getChildNodes(); for (int j = 0; j < nlChildren.getLength(); j++) { if (nlChildren.item(j).getNodeType() == Node.TEXT_NODE) { return nlChildren.item(j).getNodeValue(); } } } return null; } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; }
From source file:com.hypirion.io.PipeTest.java
/** * Test that basic reader/writer capabilities work as expected. *//*from ww w . j a va 2s.c om*/ @Test(timeout = 1000) public void testBasicReaderCapabilities() throws Exception { String input = RandomStringUtils.random(3708); StringReader rdr = new StringReader(input); StringWriter wrt = new StringWriter(); Pipe p = new Pipe(rdr, wrt); p.start(); p.join(); String output = wrt.toString(); rdr.close(); wrt.close(); assertEquals(input, output); }
From source file:org.jboss.dashboard.export.ImportManagerImpl.java
/** * Creates elements (KPI, DataProvider ,..) parsing the specified XML fragment. *//*ww w . ja va 2 s. c o m*/ public ImportResults parse(String xml, ImportOptions options) throws Exception { StringReader isr = new StringReader(xml); DocumentBuilder dBuilder = createDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(isr)); isr.close(); return parse(doc.getChildNodes(), options); }
From source file:op.tools.SYSTools.java
public static Properties load(String text) { Properties props = new Properties(); try {//from w w w .j a va 2s. c o m StringReader reader = new StringReader(text); props.load(reader); reader.close(); } catch (IOException ex) { OPDE.fatal(ex); } return props; }
From source file:com.panet.imeta.core.xml.XMLHandler.java
/** * Load a String into an XML document//w ww . j av a 2s . c o m * * @param string * The XML text to load into a document * @return the Document if all went well, null if an error occurred! */ public static final Document loadXMLString(String string) throws KettleXMLException { DocumentBuilderFactory dbf; DocumentBuilder db; Document doc; try { // Check and open XML document dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); StringReader stringReader = new java.io.StringReader(string); InputSource inputSource = new InputSource(stringReader); try { doc = db.parse(inputSource); } catch (IOException ef) { throw new KettleXMLException("Error parsing XML", ef); } finally { stringReader.close(); } return doc; } catch (Exception e) { throw new KettleXMLException("Error reading information from XML string : " + Const.CR + string, e); } }
From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java
/** * Description of the Method/*from w w w. j a va 2s. c o m*/ * * @param context Description of the Parameter * @param text Description of the Parameter * @throws Exception Description of the Exception */ public void sendTextAsFile(ActionContext context, String text) throws Exception { context.getResponse().setContentType("application/octet-stream"); context.getResponse().setHeader("Content-Disposition", "attachment;filename=" + displayName + ";"); context.getResponse().setContentLength((int) text.length()); ServletOutputStream outputStream = context.getResponse().getOutputStream(); StringReader strReader = new StringReader(text); int data; while ((data = strReader.read()) != -1) { outputStream.write(data); } strReader.close(); outputStream.close(); }
From source file:org.knime.ext.textprocessing.nodes.tokenization.tokenizer.word.StanfordNlpHtmlHandlingSupportedTokenizer.java
private static String handleSkippedParts(final StringReader sr, final List<String> tokenList, final String sentence, String token, final String normalizedToken) { // add untokenized parts as token (this happens if there is a whitespace HTML entity in the text // e.g. " " - the tokenizer will detect it as a whitespace and will not add to the word // list, but we want it as a token, so we add the skipped part manually) // -> get indices of word and normalized word int wordStart = sentence.indexOf(token); final int normWordStart = sentence.indexOf(normalizedToken); // if normalized word exists in sentence and its index is smaller than the index of the // tokenized word, check for the normalized word. also check for the normalized word, if only // the normalized word exists in the text. in other cases (normWordStart < 0 or normWordStart > // wordStart) the tokenized word will be used for checking. if (((wordStart >= 0) && (normWordStart >= 0) && (wordStart > normWordStart)) || ((wordStart < 0) && (normWordStart >= 0))) { wordStart = normWordStart;//from w w w. j av a 2s. c o m token = normalizedToken; } else if ((wordStart < 0) && (normWordStart < 0)) { // if neither the tokenized word nor the normalized word could be found throw an exception sr.close(); throw new RuntimeException("The token " + token + " / " + normalizedToken + " cannot be found in the sentence: \"" + sentence + "\"!"); } // get the skipped part final String skippedWord = sentence.substring(0, wordStart).trim(); // transform the skipped part into useful tokens and add them to the token list splitSkippedWordAndAdd(skippedWord, tokenList); tokenList.add(token); return sentence.substring(wordStart + token.length()); }
From source file:org.pentaho.di.core.xml.XMLHandler.java
/** * Load a String into an XML document//from w w w . j a v a 2s. co m * * @param string * The XML text to load into a document * @param Boolean * true to defer node expansion, false to not defer. * @return the Document if all went well, null if an error occurred! */ public static final Document loadXMLString(String string, Boolean namespaceAware, Boolean deferNodeExpansion) throws KettleXMLException { DocumentBuilderFactory dbf; DocumentBuilder db; Document doc; try { // Check and open XML document dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", deferNodeExpansion); dbf.setNamespaceAware(namespaceAware); // parameterize this as well db = dbf.newDocumentBuilder(); StringReader stringReader = new java.io.StringReader(string); InputSource inputSource = new InputSource(stringReader); try { doc = db.parse(inputSource); } catch (IOException ef) { throw new KettleXMLException("Error parsing XML", ef); } finally { stringReader.close(); } return doc; } catch (Exception e) { throw new KettleXMLException("Error reading information from XML string : " + Const.CR + string, e); } }
From source file:org.nuxeo.theme.webengine.fm.extensions.NXThemesFragmentDirective.java
@SuppressWarnings("unchecked") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (loopVars.length != 0) { throw new TemplateModelException("This directive doesn't allow loop variables."); }//from ww w . ja v a 2 s .c o m if (body != null) { throw new TemplateModelException("Didn't expect a body"); } WebContext ctx = WebEngine.getActiveContext(); if (ctx == null) { throw new IllegalStateException("Not In a Web Context"); } env.setVariable("nxthemesInfo", BeansWrapper.getDefaultInstance().wrap(InfoPool.getInfoMap())); Map<String, String> attributes = Utils.getTemplateDirectiveParameters(params); final URL elementUrl = new URL(String.format("nxtheme://element/%s/%s/%s/%s", attributes.get("engine"), attributes.get("mode"), templateEngine, attributes.get("uid"))); String rendered = ""; try { rendered = ThemeManager.renderElement(elementUrl); } catch (ThemeException e) { log.error("Element rendering failed: " + e.getMessage()); return; } StringReader sr = new StringReader(rendered); BufferedReader reader = new BufferedReader(sr); Template tpl = new Template(elementUrl.toString(), reader, env.getConfiguration(), env.getTemplate().getEncoding()); try { env.include(tpl); } catch (Exception e) { log.error("Rendering of Freemarker template failed: \n" + rendered, e); } finally { reader.close(); sr.close(); } }