List of usage examples for java.io StringReader close
public void close()
From source file:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java
/** * @param query//from w w w .ja v a2s. c o m * an ITQL command * @return the message returned by Mulgara * @throws RemoteException * for communication failure */ public String storeCommand(String query) { String result = null; String response = this.sendTQL(query); if (response != null) { StringReader sr = new StringReader(response); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); XMLEventReader r = null; try { boolean inMessage = false; StringBuffer message = new StringBuffer(); r = factory.createXMLEventReader(sr); while (r.hasNext()) { XMLEvent e = r.nextEvent(); if (e.isStartElement()) { StartElement s = e.asStartElement(); if ("message".equals(s.getName().getLocalPart())) { inMessage = true; } } else if (e.isEndElement()) { EndElement end = e.asEndElement(); if ("message".equals(end.getName().getLocalPart())) { inMessage = false; } } else if (inMessage && e.isCharacters()) { message.append(e.asCharacters().getData()); } } result = message.toString(); } catch (XMLStreamException e) { e.printStackTrace(); } finally { if (r != null) { try { r.close(); } catch (Exception ignored) { log.error(ignored); } } } sr.close(); } return result; }
From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java
private ResourceAdapterParams loadConfigPropertiesByAbstractName(PortletRequest request, String rarPath, String abstractName) {//from w w w.ja va 2s . c o m ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, new AbstractName(URI.create(abstractName))); String dd = module.getDeploymentDescriptor(); DocumentBuilderFactory factory = XmlUtil.newDocumentBuilderFactory(); factory.setValidating(false); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); final StringReader reader = new StringReader(dd); Document doc = builder.parse(new InputSource(reader)); reader.close(); Element elem = doc.getDocumentElement(); // connector String displayName = getFirstText(elem.getElementsByTagName("display-name")); String description = getFirstText(elem.getElementsByTagName("description")); elem = (Element) elem.getElementsByTagName("resourceadapter").item(0); elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0); NodeList defs = elem.getElementsByTagName("connection-definition"); List<ConfigParam> all = new ArrayList<ConfigParam>(); for (int i = 0; i < defs.getLength(); i++) { final Element def = (Element) defs.item(i); String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim(); if (iface.equals("javax.sql.DataSource")) { NodeList configs = def.getElementsByTagName("config-property"); for (int j = 0; j < configs.getLength(); j++) { Element config = (Element) configs.item(j); String name = getFirstText(config.getElementsByTagName("config-property-name")).trim(); String type = getFirstText(config.getElementsByTagName("config-property-type")).trim(); String test = getFirstText(config.getElementsByTagName("config-property-value")); String value = test == null ? null : test.trim(); test = getFirstText(config.getElementsByTagName("description")); String desc = test == null ? null : test.trim(); all.add(new ConfigParam(name, type, desc, value)); } } } return new ResourceAdapterParams(displayName, description, rarPath, all.toArray(new ConfigParam[all.size()])); } catch (Exception e) { log.error("Unable to read resource adapter DD", e); return null; } }
From source file:org.jamwiki.db.CacheQueryHandler.java
/** * *//* w ww . j av a 2 s. c om*/ @Override public void insertTopicVersions(List<TopicVersion> topicVersions) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; boolean useBatch = (topicVersions.size() > 1); try { conn = DatabaseConnection.getConnection(); if (!this.autoIncrementPrimaryKeys()) { stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION); } else if (useBatch) { // generated keys don't work in batch mode stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT); } else { stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT, Statement.RETURN_GENERATED_KEYS); } int topicVersionId = -1; if (!this.autoIncrementPrimaryKeys() || useBatch) { // manually retrieve next topic version id when using batch // mode or when the database doesn't support generated keys. topicVersionId = DatabaseConnection.executeSequenceQuery(STATEMENT_SELECT_TOPIC_VERSION_SEQUENCE); } for (TopicVersion topicVersion : topicVersions) { if (!this.autoIncrementPrimaryKeys() || useBatch) { // FIXME - if two threads update the database simultaneously then // it is possible that this code could set the topic version ID // to a value that is different from what the database ends up // using. topicVersion.setTopicVersionId(topicVersionId++); } StringReader sr = null; try { int index = 1; stmt.setInt(index++, topicVersion.getTopicVersionId()); if (topicVersion.getEditDate() == null) { topicVersion.setEditDate(new Timestamp(System.currentTimeMillis())); } stmt.setInt(index++, topicVersion.getTopicId()); stmt.setString(index++, topicVersion.getEditComment()); //pass the content into a stream to be passed to Cach sr = new StringReader(topicVersion.getVersionContent()); stmt.setCharacterStream(index++, sr, topicVersion.getVersionContent().length()); if (topicVersion.getAuthorId() == null) { stmt.setNull(index++, Types.INTEGER); } else { stmt.setInt(index++, topicVersion.getAuthorId()); } stmt.setInt(index++, topicVersion.getEditType()); stmt.setString(index++, topicVersion.getAuthorDisplay()); stmt.setTimestamp(index++, topicVersion.getEditDate()); if (topicVersion.getPreviousTopicVersionId() == null) { stmt.setNull(index++, Types.INTEGER); } else { stmt.setInt(index++, topicVersion.getPreviousTopicVersionId()); } stmt.setInt(index++, topicVersion.getCharactersChanged()); stmt.setString(index++, topicVersion.getVersionParamString()); } finally { if (sr != null) { sr.close(); } } if (useBatch) { stmt.addBatch(); } else { stmt.executeUpdate(); } if (this.autoIncrementPrimaryKeys() && !useBatch) { rs = stmt.getGeneratedKeys(); if (!rs.next()) { throw new SQLException("Unable to determine auto-generated ID for database record"); } topicVersion.setTopicVersionId(rs.getInt(1)); } } if (useBatch) { stmt.executeBatch(); } } catch (SQLException e) { throw new UncategorizedSQLException("insertTopicVersions", null, e); } finally { DatabaseConnection.closeConnection(conn, stmt, rs); } }
From source file:org.pentaho.big.data.kettle.plugins.sqoop.SqoopUtils.java
/** * Parse a string into arguments as if it were provided on the command line. * * @param commandLineString//w w w. jav a2s . c o m * A command line string, e.g. "sqoop import --table test --connect jdbc:mysql://bogus/bogus" * @param variableSpace * Context for resolving variable names. If {@code null}, no variable resolution we happen. * @param ignoreSqoopCommand * If set, the first "sqoop <tool>" arguments will be ignored, e.g. "sqoop import" or "sqoop export". * @return List of parsed arguments * @throws IOException * when the command line could not be parsed */ public static List<String> parseCommandLine(String commandLineString, VariableSpace variableSpace, boolean ignoreSqoopCommand) throws IOException { List<String> args = new ArrayList<String>(); StringReader reader = new StringReader(commandLineString); try { StreamTokenizer tokenizer = new StreamTokenizer(reader); // Treat a dash as an ordinary character so it gets included in the token tokenizer.ordinaryChar('-'); tokenizer.ordinaryChar('.'); tokenizer.ordinaryChars('0', '9'); // Treat all characters as word characters so nothing is parsed out tokenizer.wordChars('\u0000', '\uFFFF'); // Re-add whitespace characters tokenizer.whitespaceChars(0, ' '); // Use " and ' as quote characters tokenizer.quoteChar('"'); tokenizer.quoteChar('\''); // Flag to indicate if the next token needs to be skipped (used to control skipping of the first two arguments, // e.g. "sqoop <tool>") boolean skipToken = false; // Add all non-null string values tokenized from the string to the argument list while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if (tokenizer.sval != null) { String s = tokenizer.sval; if (variableSpace != null) { s = variableSpace.environmentSubstitute(s); } if (ignoreSqoopCommand && args.isEmpty()) { // If we encounter "sqoop <name>" we should skip the first two arguments so we can support copy/paste of // arguments directly // from a working command line if ("sqoop".equals(s)) { skipToken = true; continue; // skip this one and the next } else if (skipToken) { ignoreSqoopCommand = false; // Don't attempt to ignore any more commands // Skip this token too, reset the flag so we no longer skip any tokens, and continue parsing skipToken = false; continue; } } if (s.startsWith(ARG_D)) { handleCustomOption(args, s, tokenizer, variableSpace); continue; } args.add(escapeEscapeSequences(s)); } } } finally { reader.close(); } return args; }
From source file:jp.terasoluna.fw.web.taglib.StringFormatterTagBase.java
/** * ^O]Jn?\bh?B/* w w w . ja v a 2s .c om*/ * * @return ???w * @throws JspException ^O]G?[ */ @Override public int doStartTag() throws JspException { Object value = this.value; if (value == null) { // bean???Av?beanbNAbv // ???A^?[ if (ignore) { if (TagUtil.lookup(pageContext, name, scope) == null) { return SKIP_BODY; // ?o } } // v?v?peBlbNAbv value = TagUtil.lookup(pageContext, name, property, scope); if (value == null) { return SKIP_BODY; // ?o } } // tH?[}bg String output = doFormat(value.toString()); if (id != null) { // idw?AXNveBO?p // y?[WXR?[vZbg?B pageContext.setAttribute(id, output); } else { // idw?Av?peBlC^vg // ?BK?tB^?B if (filter) { output = TagUtil.filter(output); } // pXy?[X u StringReader sr = null; BufferedReader br = null; String line = null; try { sr = new StringReader(output); br = new BufferedReader(sr); StringBuilder sbuf = new StringBuilder(); StringBuilder strBuf = new StringBuilder(); int index = 0; while ((line = br.readLine()) != null) { // pXy?[X u if (replaceSpToNbsp && !"".equals(line)) { strBuf.setLength(0); char ch = line.charAt(0); int i = 0; for (i = 0; i < line.length(); i++) { ch = line.charAt(i); // pXy?[X???A" "?B if (ch == ' ') { strBuf.append(" "); } else { strBuf.append(ch); } } line = strBuf.toString(); } sbuf.append(line); ++index; } output = sbuf.toString(); } catch (IOException e) { if (log.isWarnEnabled()) { log.warn("StringReader IO error : " + e); } } finally { if (sr != null) { sr.close(); } try { if (br != null) { br.close(); } } catch (IOException e1) { if (log.isWarnEnabled()) { log.warn("StringReader close error : " + e1); } } } TagUtil.write(pageContext, output); } return SKIP_BODY; }
From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
private List<Element> getQuerySolutions(String response) { List<Element> result = null; Document r = null;/*w w w . j av a 2 s. co m*/ StringReader sr = null; try { sr = new StringReader(response); r = new SAXBuilder().build(sr); result = r.getRootElement().getChild("query", JDOMNamespaceUtil.MULGARA_TQL_NS).getChildren("solution", JDOMNamespaceUtil.MULGARA_TQL_NS); return result; } catch (IOException e) { log.error(response); throw new RuntimeException("IOException reading Mulgara answer string.", e); } catch (JDOMException e) { log.error(response); throw new RuntimeException("Unexpected error parsing Mulgara answer.", e); } finally { if (sr != null) { sr.close(); } } }
From source file:JiraWebClient.java
protected void handleErrorMessage(HttpMethodBase method) throws JiraException { try {// www . ja v a 2 s . c o m String response = method.getResponseBodyAsString(); // TODO consider logging the error if (method.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { throw new JiraRemoteException("JIRA system error", null); //$NON-NLS-1$ } if (response == null) { throw new JiraRemoteMessageException("Error making JIRA request: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } StringReader reader = new StringReader(response); try { StringBuilder msg = new StringBuilder(); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer .nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); String classValue = tag.getAttribute("class"); //$NON-NLS-1$ if (classValue != null) { if (tag.getTagType() == Tag.DIV) { if (classValue.startsWith("infoBox") || classValue.startsWith("errorArea") //$NON-NLS-1$ //$NON-NLS-2$ || classValue.contains("error")) { //$NON-NLS-1$ throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV)); } } else if (tag.getTagType() == Tag.SPAN) { if (classValue.startsWith("errMsg")) { //$NON-NLS-1$ msg.append(getContent(tokenizer, Tag.SPAN)); } } } } } if (msg.length() == 0) { throw new JiraRemoteMessageException(response); } else { throw new JiraRemoteMessageException(msg.toString()); } } catch (ParseException e) { throw new JiraRemoteMessageException("Error parsing JIRA response: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } finally { reader.close(); } } catch (IOException e) { throw new JiraException(e); } }
From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java
protected void handleErrorMessage(HttpMethodBase method) throws JiraException { try {/* www .j a va 2 s .c o m*/ String response = method.getResponseBodyAsString(); // TODO consider logging the error if (method.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { throw new JiraRemoteException("JIRA system error", null); //$NON-NLS-1$ } if (response == null) { throw new JiraRemoteMessageException("Error making JIRA request: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } StringReader reader = new StringReader(response); try { StringBuilder msg = new StringBuilder(); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer .nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); String classValue = tag.getAttribute("class"); //$NON-NLS-1$ if (classValue != null) { if (tag.getTagType() == Tag.DIV) { if (classValue.startsWith("infoBox")) { //$NON-NLS-1$ throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV)); } else if (classValue.startsWith("errorArea")) { //$NON-NLS-1$ throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV)); } } else if (tag.getTagType() == Tag.SPAN) { if (classValue.startsWith("errMsg")) { //$NON-NLS-1$ msg.append(getContent(tokenizer, Tag.SPAN)); } } } } } if (msg.length() == 0) { throw new JiraRemoteMessageException(response); } else { throw new JiraRemoteMessageException(msg.toString()); } } catch (ParseException e) { throw new JiraRemoteMessageException("Error parsing JIRA response: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } finally { reader.close(); } } catch (IOException e) { throw new JiraException(e); } }
From source file:com.celements.sajson.Parser.java
public void parse(String jsonExpression) throws JsonParseException, IOException { StringReader jsonReader = new StringReader(jsonExpression); try {/*from w w w . j ava 2 s. com*/ parser = factory.createJsonParser(jsonReader); workerStack.clear(); JsonToken nextToken = parser.nextToken(); lexParser.initEvent(); while (parser.hasCurrentToken()) { switch (nextToken) { case VALUE_TRUE: case VALUE_FALSE: boolean boolValue = parser.getBooleanValue(); lastValue = Boolean.toString(boolValue); lexParser.booleanEvent(boolValue); impliciteCloseProperty(); break; case VALUE_STRING: lastValue = parser.getText(); lexParser.stringEvent(lastValue); impliciteCloseProperty(); break; case START_ARRAY: checkIllegalStackState(ECommand.DICTIONARY_COMMAND, nextToken); workerStack.push(ECommand.ARRAY_COMMAND); lexParser.openArrayEvent(); break; case END_ARRAY: checkStackState(ECommand.ARRAY_COMMAND); lexParser.closeArrayEvent(); workerStack.pop(); impliciteCloseProperty(); break; case START_OBJECT: checkIllegalStackState(ECommand.DICTIONARY_COMMAND, nextToken); workerStack.push(ECommand.DICTIONARY_COMMAND); lexParser.openDictionaryEvent(); break; case END_OBJECT: checkStackState(ECommand.DICTIONARY_COMMAND); lexParser.closeDictionaryEvent(); workerStack.pop(); impliciteCloseProperty(); break; case FIELD_NAME: checkStackState(ECommand.DICTIONARY_COMMAND); workerStack.push(ECommand.PROPERTY_COMMAND); lastKey = parser.getText(); lexParser.openPropertyEvent(lastKey); break; default: LOGGER.warn("unkown token [" + nextToken + "] lastKey [" + lastKey + "] lastValue [" + lastValue + "]."); break; } nextToken = parser.nextToken(); } lexParser.finishEvent(); } finally { jsonReader.close(); } }
From source file:com.amalto.workbench.utils.Util.java
/** * Returns and XSDSchema Object from an xsd * //from w w w. j ava 2 s . com * @param schema * @return * @throws Exception */ public static XSDSchema getXSDSchema(String schema) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setValidating(false); StringReader reader = new StringReader(schema); InputSource source = new InputSource(new StringReader(schema)); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); XSDSchema xsdSchema = null; xsdSchema = XSDSchemaImpl.createSchema(document.getDocumentElement()); reader.close(); return xsdSchema; }