List of usage examples for java.io StringReader close
public void close()
From source file:org.openxdm.xcap.client.test.subscription.SubscribeDocumentTest.java
protected XcapDiff processNotify(RequestEvent requestEvent) throws ParseException, SipException, InvalidArgumentException, JAXBException { Request notify = requestEvent.getRequest(); javax.sip.message.Response response = messageFactory.createResponse(200, notify); // SHOULD add a Contact ContactHeader contact = (ContactHeader) contactHeader.clone(); ((SipURI) contact.getAddress().getURI()).setParameter("id", "sub"); response.addHeader(contact);//w w w . j a v a 2s. com requestEvent.getServerTransaction().sendResponse(response); SubscriptionStateHeader subscriptionState = (SubscriptionStateHeader) requestEvent.getRequest() .getHeader(SubscriptionStateHeader.NAME); assertTrue("subscription not active", subscriptionState.getState().equalsIgnoreCase(SubscriptionStateHeader.ACTIVE)); // unmarshall content StringReader stringReader = new StringReader(new String(requestEvent.getRequest().getRawContent())); XcapDiff xcapDiff = (XcapDiff) jaxbContext.createUnmarshaller().unmarshal(stringReader); assertTrue("unexpected xcap root in xcap diff", xcapDiff.getXcapRoot().equals("http://" + ServerConfiguration.SERVER_HOST + ":" + ServerConfiguration.SERVER_PORT + ServerConfiguration.SERVER_XCAP_ROOT + "/")); stringReader.close(); return xcapDiff; }
From source file:com.stratelia.webactiv.servlets.RestOnlineFileServer.java
private void displayWarningHtmlCode(HttpServletResponse res) throws IOException { StringReader sr = null; OutputStream out2 = res.getOutputStream(); int read;//from ww w .j a v a 2s . c om ResourceLocator resourceLocator = new ResourceLocator( "com.stratelia.webactiv.util.peasUtil.multiLang.fileServerBundle", ""); sr = new StringReader(resourceLocator.getString("warning")); try { read = sr.read(); while (read != -1) { SilverTrace.info("peasUtil", "RestOnlineFileServer.displayHtmlCode()", "root.MSG_GEN_ENTER_METHOD", " StringReader read " + read); out2.write(read); // writes bytes into the response read = sr.read(); } } catch (Exception e) { SilverTrace.warn("peasUtil", "RestOnlineFileServer.displayWarningHtmlCode", "root.EX_CANT_READ_FILE", "warning properties"); } finally { try { if (sr != null) { sr.close(); } out2.close(); } catch (Exception e) { SilverTrace.warn("peasUtil", "RestOnlineFileServer.displayHtmlCode", "root.EX_CANT_READ_FILE", "close failed"); } } }
From source file:org.jboss.processFlow.knowledgeService.BaseKnowledgeSessionBean.java
protected synchronized void createKnowledgeBaseViaKnowledgeAgent(boolean forceRefresh) throws ConnectException { log.info("createKnowledgeBaseViaKnowledgeAgent() forceRefresh = " + forceRefresh); if (kbase != null && !forceRefresh) return;/*from w ww .jav a2 s . c om*/ if (kagent != null) { kagent.dispose(); kagent = null; } // investigate: List<String> guvnorPackages = guvnorUtils.getBuiltPackageNames(); // http://ratwateribm:8080/jboss-brms/org.drools.guvnor.Guvnor/package/org.jboss.processFlow/test-pfp-snapshot if (!guvnorUtils.guvnorExists()) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(guvnorUtils.getGuvnorProtocol()); sBuilder.append("://"); sBuilder.append(guvnorUtils.getGuvnorHost()); sBuilder.append("/"); sBuilder.append(guvnorUtils.getGuvnorSubdomain()); sBuilder.append("/rest/packages/"); throw new ConnectException( "createKnowledgeBase() cannot connect to guvnor at URL : " + sBuilder.toString()); } // for polling of guvnor to occur, the polling and notifier services must be started ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService() .newResourceChangeScannerConfiguration(); // Do not start change set notifications Integer droolsResourceScannerIntervalValue = -1; try { droolsResourceScannerIntervalValue = Integer.valueOf(droolsResourceScannerInterval); } catch (NumberFormatException nfe) { log.error("DroolsResourceScannerInterval is not an integer: " + droolsResourceScannerInterval, nfe); } if (droolsResourceScannerIntervalValue > 0) { sconf.setProperty("drools.resource.scanner.interval", droolsResourceScannerInterval); ResourceFactory.getResourceChangeScannerService().configure(sconf); ResourceFactory.getResourceChangeScannerService().start(); ResourceFactory.getResourceChangeNotifierService().start(); } KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); // implementation = org.drools.agent.impl.KnowledgeAgentConfigurationImpl /* - incremental change set processing enabled - will create a single KnowledgeBase and always refresh that same instance */ aconf.setProperty("drools.agent.newInstance", "false"); if (droolsResourceScannerIntervalValue < 0) { aconf.setProperty("drools.agent.scanResources", Boolean.FALSE.toString()); aconf.setProperty("drools.agent.scanDirectories", Boolean.FALSE.toString()); aconf.setProperty("drools.agent.monitorChangeSetEvents", Boolean.FALSE.toString()); } /* -- Knowledge Agent provides automatic loading, caching and re-loading of resources -- the knowledge agent can update or rebuild this knowledge base as the resources it uses are changed */ kagent = KnowledgeAgentFactory.newKnowledgeAgent("Guvnor default", aconf); StringReader sReader = guvnorUtils.createChangeSet(); try { guvnorChangeSet = IOUtils.toString(sReader); sReader.close(); } catch (Exception x) { x.printStackTrace(); } kagent.applyChangeSet(ResourceFactory.newByteArrayResource(guvnorChangeSet.getBytes())); /* - set KnowledgeBase as instance variable to this mbean for use throughout all functionality of this service - a knowledge base is a collection of compiled definitions, such as rules and processes, which are compiled using the KnowledgeBuilder - the knowledge base itself does not contain instance data, known as facts - instead, sessions are created from the knowledge base into which data can be inserted and where process instances may be started - creating the knowledge base can be heavy, whereas session creation is very light : http://blog.athico.com/2011/09/small-efforts-big-improvements.html - a knowledge base is also serializable, allowing for it to be stored */ kbase = kagent.getKnowledgeBase(); lastKAgentRefresh = System.currentTimeMillis(); log.info("createKnowledgeBaseViaKnowledgeAgent() just refreshed kBase via knowledgeAgent"); }
From source file:de.fhg.iais.cortex.services.AbstractAipIngestService.java
private String sanitizeOldAscFormat(String inputString) throws JDOMException, IOException { if (!StringUtils.containsIgnoreCase(inputString, GlobalConstants.CORTEX_NAMESPACE_URI)) { inputString = inputString.replaceFirst("<cortex>", "<cortex xmlns=\"" + GlobalConstants.CORTEX_NAMESPACE_URI + "\">"); }//w ww . j a v a2 s . co m StringReader reader = null; try { reader = new StringReader(inputString); Document jdomAip = new SAXBuilder().build(reader); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat().setEncoding(Charsets.UTF_8.name())); if (jdomAip.getRootElement().getChild("edm", GlobalConstants.CORTEX_NAMESPACE) == null) { Element child = jdomAip.getRootElement() .getChild("provider-metadata-sets", GlobalConstants.CORTEX_NAMESPACE) .getChild("original-source", GlobalConstants.CORTEX_NAMESPACE); if (child.getChildren().size() > 0) { String originalSourceCData = outp.outputString((Element) child.getChildren().get(0)); child.removeContent(); child.addContent(new CDATA(originalSourceCData)); } } return outp.outputString(jdomAip); } finally { if (reader != null) { reader.close(); } } }
From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java
/** * Saves an entry to the object table.//from w ww . j av a2s . co m * * @param tid {@code int}, the object type id * @param v {@link String}, the non-null object value * @return {@code int}, the object primary key * @throws SQLException - Thrown if a sql error occurred saving an entry to * the object table */ protected int saveObject(int tid, String v) throws SQLException { final String objectsIdColumn = (dbConnection.isPostgresql() ? OBJECTS_ID_COLUMN_POSTGRESQL : OBJECTS_ID_COLUMN); PreparedStatement ps = getPreparedStatement(OBJECTS_SQL, new String[] { objectsIdColumn }); ResultSet rs = null; if (v == null) { throw new InvalidArgument("object value cannot be null"); } try { String encryptedString = encryptionService.encrypt(v); // Insert into objects_text if we are over MAX_VARCHAR_LENGTH Integer objectsTextId = null; if (encryptedString.length() > MAX_VARCHAR_LENGTH) { final String objectsTextColumn = (dbConnection.isPostgresql() ? OBJECTS_TEXT_COLUMN_POSTGRESQL : OBJECTS_TEXT_COLUMN); PreparedStatement otps = getPreparedStatement(OBJECTS_TEXT_SQL, new String[] { objectsTextColumn }); ResultSet otrs = null; StringReader sr = null; try { sr = new StringReader(encryptedString); otps.setClob(1, sr, encryptedString.length()); otps.execute(); otrs = otps.getGeneratedKeys(); if (otrs.next()) { objectsTextId = otrs.getInt(1); } } finally { close(otrs); if (sr != null) { sr.close(); } } } // FIXME Hardcoding objects_type to 1? ps.setInt(1, 1); if (objectsTextId == null) { // insert value into objects table ps.setString(2, encryptedString); ps.setNull(3, Types.INTEGER); } else { ps.setNull(2, Types.VARCHAR); ps.setInt(3, objectsTextId); } ps.execute(); rs = ps.getGeneratedKeys(); int oid; if (rs.next()) { oid = rs.getInt(1); } else { throw new IllegalStateException("object insert failed."); } return oid; } catch (EncryptionServiceException e) { throw new SQLException("Unable to encrypt string for object table.", e); } finally { close(rs); } }
From source file:org.opencms.main.CmsShell.java
/** * Executes all commands read from the given input stream.<p> * //from w ww . ja va 2 s . c o m * @param fileInputStream a file input stream from which the commands are read */ private void executeCommands(FileInputStream fileInputStream) { try { LineNumberReader lnr = new LineNumberReader(new InputStreamReader(fileInputStream)); while (!m_exitCalled) { printPrompt(); String line = lnr.readLine(); if (line == null) { // if null the file has been read to the end try { Thread.sleep(500); } catch (Throwable t) { // noop } break; } if (line.trim().startsWith("#")) { System.out.println(line); continue; } StringReader reader = new StringReader(line); StreamTokenizer st = new StreamTokenizer(reader); st.eolIsSignificant(true); // put all tokens into a List List<String> parameters = new ArrayList<String>(); while (st.nextToken() != StreamTokenizer.TT_EOF) { if (st.ttype == StreamTokenizer.TT_NUMBER) { parameters.add(Integer.toString(new Double(st.nval).intValue())); } else { parameters.add(st.sval); } } reader.close(); // extract command and arguments if (parameters.size() == 0) { if (m_echo) { System.out.println(); } continue; } String command = parameters.get(0); parameters = parameters.subList(1, parameters.size()); // execute the command executeCommand(command, parameters); } } catch (Throwable t) { t.printStackTrace(System.err); } }
From source file:org.waarp.openr66.database.data.DbRule.java
/** * Get Tasks from String. If it is not ok, then it sets the default values and return new array * of Tasks or null if in error.//from w ww .j a v a 2s .co m * * @param tasks * @return Array of tasks or empty array if in error. */ private String[][] getTasksRule(String tasks) { if (tasks == null) { // No tasks so setting to the default! return new String[0][0]; } StringReader reader = new StringReader(tasks); Document document = null; try { document = new SAXReader().read(reader); } catch (DocumentException e) { logger.info("Unable to read the tasks for Rule: " + tasks, e); // No tasks so setting to the default! reader.close(); return new String[0][0]; } XmlValue[] values = XmlUtil.read(document, RuleFileBasedConfiguration.tasksDecl); String[][] result = RuleFileBasedConfiguration.getTasksRule(values[0]); reader.close(); return result; }
From source file:org.waarp.openr66.database.data.DbRule.java
/** * Get Ids from String. If it is not ok, then it sets the default values and return False, else * returns True.//from w ww . j av a 2 s. c o m * * @param idsref * @return True if ok, else False (default values). */ private boolean getIdsRule(String idsref) { if (idsref == null) { // No ids so setting to the default! ids = null; idsArray = null; return false; } ids = idsref; StringReader reader = new StringReader(idsref); Document document = null; try { document = new SAXReader().read(reader); } catch (DocumentException e) { logger.warn("Unable to read the ids for Rule: " + idsref, e); // No ids so setting to the default! ids = null; idsArray = null; reader.close(); return false; } XmlValue[] values = XmlUtil.read(document, RuleFileBasedConfiguration.hostsDecls); idsArray = RuleFileBasedConfiguration.getHostIds(values[0]); reader.close(); return true; }
From source file:org.sakaiproject.component.app.help.HelpManagerImpl.java
/** * register external help content/*from w w w .j a va 2 s . c om*/ * build document from external reg file * @param externalHelpReg */ public void registerExternalHelpContent(String helpFile) { Set<Category> categories = new TreeSet<Category>(); URL urlResource = null; InputStream ism = null; BufferedInputStream bis = null; try { try { urlResource = new URL(EXTERNAL_URL + "/" + helpFile); ism = urlResource.openStream(); } catch (IOException e) { // Try default help file helpFile = DEFAULT_HELP_FILE; urlResource = new URL(EXTERNAL_URL + "/" + helpFile); ism = urlResource.openStream(); } bis = new BufferedInputStream(ism); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); InputSource is = new org.xml.sax.InputSource(bis); org.w3c.dom.Document xmlDocument = builder.parse(is); Node helpRegNode = (Node) xmlDocument.getDocumentElement(); recursiveExternalReg(helpRegNode, null, categories); // handle corpus docs if (!getRestConfiguration().getOrganization().equals("sakai")) { // get corpus document String corpusXml = getRestConfiguration().getCorpusDocument(); DocumentBuilderFactory dbfCorpus = DocumentBuilderFactory.newInstance(); dbfCorpus.setNamespaceAware(true); DocumentBuilder builderCorpus = dbfCorpus.newDocumentBuilder(); StringReader sReader = new StringReader(corpusXml); InputSource isCorpus = new org.xml.sax.InputSource(sReader); org.w3c.dom.Document xmlDocumentCorpus = builderCorpus.parse(isCorpus); registerCorpusDocs(xmlDocumentCorpus); sReader.close(); } } catch (MalformedURLException e) { LOG.warn("Unable to load external URL: " + EXTERNAL_URL + "/" + helpFile, e); } catch (IOException e) { LOG.warn("I/O error opening external URL: " + EXTERNAL_URL + "/" + helpFile, e); } catch (ParserConfigurationException e) { LOG.error(e.getMessage(), e); } catch (SAXException e) { LOG.error(e.getMessage(), e); } finally { try { if (bis != null) { bis.close(); } } catch (IOException e) { LOG.error("error closing stream", e); } } // Add to toc map TableOfContentsBean externalToc = new TableOfContentsBean(); externalToc.setCategories(categories); setTableOfContents(externalToc); }
From source file:org.rapidandroid.activity.FormReviewer.java
private void doCsvDirectBednetsInjection() { String rawMessageText = ""; try {/*from ww w. j av a 2 s . c om*/ InputStream is = this.getAssets().open("testdata/rawdata.csv"); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a Java string. String text = new String(buffer); rawMessageText = text; } catch (IOException e) { // Should never happen! throw new RuntimeException(e); } StringReader sr = new StringReader(rawMessageText); BufferedReader bufRdr = new BufferedReader(sr); String line = null; // int row = 0; // int col = 0; Vector<String[]> lines = new Vector<String[]>(); // read each line of text file try { while ((line = bufRdr.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, ","); int tokCount = st.countTokens(); String[] tokenizedLine = new String[tokCount]; int toki = 0; while (st.hasMoreTokens()) { tokenizedLine[toki] = st.nextToken(); toki++; } lines.add(tokenizedLine); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { sr.close(); bufRdr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int len = lines.size(); for (int i = 0; i < len; i++) { String[] csvline = lines.get(i); String datestr = csvline[0]; Date dateval = new Date(); try { dateval = Message.SQLDateFormatter.parse(datestr); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sender = csvline[1]; String text = csvline[2]; Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, sender); ContentValues messageValues = new ContentValues(); messageValues.put(RapidSmsDBConstants.Message.MESSAGE, text); messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID()); messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(dateval)); messageValues.put(RapidSmsDBConstants.Message.RECEIVE_TIME, Message.SQLDateFormatter.format(dateval)); messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false); Uri msgUri = null; msgUri = this.getContentResolver().insert(RapidSmsDBConstants.Message.CONTENT_URI, messageValues); Vector<IParseResult> results = ParsingService.ParseMessage(mForm, text); ParsedDataTranslator.InsertFormData(this, mForm, Integer.valueOf(msgUri.getPathSegments().get(1)).intValue(), results); } }