Java Code Examples for java.io.StringReader
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project and-bible, under directory /IgnoreAndBibleExperiments/experiments/.
Source file: ZVerseBackendLite.java

public Element getOsis(Key key,SwordBookMetaData sbmd) throws BookException { try { String plain=getRawText(key); StringReader in=new StringReader("<div>" + plain + "</div>"); InputSource is=new InputSource(in); SAXBuilder builder=new SAXBuilder(); Document doc=builder.build(is); Element div=doc.getRootElement(); return div; } catch ( Exception e) { throw new BookException(UserMsg.READ_FAIL,e,new Object[]{key.getName()}); } }
Example 2
From project activejdbc, under directory /javalite-common/src/main/java/org/javalite/test/.
Source file: XPathHelper.java

/** * Use constructor and instance methods to only parse once and reuse a parsed tree. Use this method in high performance applicaitons when you need to pull many values from the same document. * @param xml XML to parse. */ public XPathHelper(String xml){ StringReader reader=new StringReader(xml); try { doc=new SAXReader().read(reader); } catch ( DocumentException e) { throw new IllegalArgumentException("failed to parse XML",e); } }
Example 3
/** * This method deserializes the specified Json into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use {@link #fromJson(String,Class)} instead. If you have the Json in a {@link Reader} instead ofa String, use {@link #fromJson(Reader,Type)} instead. * @param < T > the type of the desired object * @param json the string from which the object is to be deserialized * @param typeOfT The specific genericized type of src. You can obtain this type by using the{@link com.google.gson.reflect.TypeToken} class. For example, to get the type for{@code Collection<Foo>}, you should use: <pre> Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType(); </pre> * @return an object of type T from the string * @throws JsonParseException if json is not a valid representation for an object of type typeOfT * @throws JsonSyntaxException if json is not a valid representation for an object of type */ @SuppressWarnings("unchecked") public <T>T fromJson(String json,Type typeOfT) throws JsonSyntaxException { if (json == null) { return null; } StringReader reader=new StringReader(json); T target=(T)fromJson(reader,typeOfT); return target; }
Example 4
From project Archimedes, under directory /br.org.archimedes.io.xml.tests/plugin-test/br/org/archimedes/io/xml/parsers/.
Source file: NPointParserTestHelper.java

protected Node getNodeLine(String xmlSample) throws Exception { DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=null; docBuilder=docBuilderFactory.newDocumentBuilder(); StringReader ir=new StringReader(xmlSample); InputSource is=new InputSource(ir); Document doc=docBuilder.parse(is); doc.normalize(); return doc.getFirstChild(); }
Example 5
From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.
Source file: DocumentationUtils.java

private static ASDocParser parserOn(String text) throws IOException { StringReader in=new StringReader(text); ANTLRReaderStream cs=new ANTLRReaderStream(in); ASDocLexer lexer=new ASDocLexer(cs); LinkedListTokenSource source=new LinkedListTokenSource(lexer); LinkedListTokenStream stream=new LinkedListTokenStream(source); ASDocParser parser=new ASDocParser(stream); parser.setTreeAdaptor(TREE_ADAPTOR); return parser; }
Example 6
From project bel-editor, under directory /org.openbel.editor.core/src/org/openbel/editor/core/parser/.
Source file: BELScriptElementParser.java

/** * {@inheritDoc} */ @Override public void parseSourceModule(IModuleSource source){ String sc=source.getSourceContents(); BELScriptDocument modules=new BELScriptDocument(sc.length()); StringReader sr=new StringReader(source.getSourceContents()); BELModel model=parse(sr,modules); modules.setFunctions(model.getFunctions()); modules.setVariables(model.getVariables()); processNode(model,modules); }
Example 7
From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.
Source file: BioportalRestUtils.java

/** * Gets the document. * @param xml the xml * @return the document */ public static Document getDocument(String xml){ StringReader reader=new StringReader(xml); InputSource inputStream=new InputSource(reader); Document doc; try { synchronized (DOCUMENT_BUILDER) { doc=DOCUMENT_BUILDER.parse(inputStream); } } catch ( Exception e) { throw new Cts2RuntimeException(e); } return doc; }
Example 8
From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.
Source file: BlacktieStompAdministrationService.java

Element stringToElement(String s) throws Exception { StringReader sreader=new StringReader(s); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder parser=factory.newDocumentBuilder(); Document doc=parser.parse(new InputSource(sreader)); return doc.getDocumentElement(); }
Example 9
From project bpelunit, under directory /tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/util/schema/.
Source file: WSDLParser.java

/** * Creates a StringReader for the passed Element. * @param element * @return * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException * @throws TransformerException */ private StringReader getStringReaderFromElement(org.w3c.dom.Element element) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { DOMSource source=new DOMSource(element); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); StringReader stringReader=new StringReader(stringWriter.getBuffer().toString()); return stringReader; }
Example 10
From project build-info, under directory /build-info-extractor-maven3/src/main/java/org/jfrog/build/extractor/maven/reader/.
Source file: ProjectReader.java

/** * @return Construct a Maven {@link Model} from the pom. */ private Model readModel(File pom) throws IOException { MavenXpp3Reader reader=new MavenXpp3Reader(); StringReader stringReader=null; try { stringReader=new StringReader(Files.toString(pom,Charset.forName("UTF-8"))); return reader.read(stringReader); } catch ( XmlPullParserException e) { throw new IOException(e); } finally { Closeables.closeQuietly(stringReader); } }
Example 11
From project cdk, under directory /attributes/src/test/java/org/richfaces/cdk/attributes/.
Source file: AttributesTest.java

private SchemaSet unmarshal(String xmlData) throws Exception { StringReader reader=new StringReader(xmlData); JAXBContext jc=JAXBContext.newInstance(SchemaSet.class); Unmarshaller unmarshaller=jc.createUnmarshaller(); return (SchemaSet)unmarshaller.unmarshal(reader); }
Example 12
From project ceres, under directory /ceres-launcher/src/test/java/com/bc/ceres/util/.
Source file: TemplateReaderTest.java

private static void test(Properties properties,String input,String expectedOutput) throws IOException { StringReader stringReader=new StringReader(input); TemplateReader templateReader=new TemplateReader(stringReader,properties); String actualOutput=templateReader.readAll(); assertEquals(expectedOutput,actualOutput); }
Example 13
From project clearcase-plugin, under directory /src/test/java/hudson/plugins/clearcase/base/.
Source file: BaseHistoryActionTest.java

@Test(expected=IOException.class) public void assertReaderIsClosed() throws Exception { final StringReader reader=new StringReader("\"20071015.151822\" \"user\" \"Customer\\DataSet.xsd\" \"\\main\\sit_r6a\\1\" \"create version\" \"mkelem\" "); when(cleartool.doesViewExist("viewTag")).thenReturn(Boolean.TRUE); when(cleartoolLsHistoryWithStandardInput()).thenReturn(reader); BaseHistoryAction action=new BaseHistoryAction(cleartool,false,null,0); action.hasChanges(null,"view","viewTag",new String[]{"branch"},new String[]{"vobpath"}); reader.ready(); }
Example 14
private Statement parseNtriples(String ntriples) throws IOException, RDFParseException, RDFHandlerException { RDFParser parser=Rio.createParser(RDFFormat.NTRIPLES,vf); parser.setPreserveBNodeIDs(true); StatementCollector collector=new StatementCollector(); parser.setRDFHandler(collector); parser.parse(new StringReader(ntriples),"http://example.com/"); Statement st=collector.getStatements().iterator().next(); return st; }
Example 15
From project ajah, under directory /ajah-syndicate/src/main/java/com/ajah/syndicate/rome/.
Source file: RomeUtils.java

/** * Creates a feed from an {@link XmlString}. * @param xmlString The XML version of the feed. * @param feedSource The source of the feed. * @return A Feed instance created from the XML. * @throws FeedException if the xml could not be parsed or did not have valid data. */ public static Feed createFeed(final XmlString xmlString,final FeedSource feedSource) throws FeedException { final SyndFeedInput input=new SyndFeedInput(); try { final SyndFeed syndFeed=input.build(new StringReader(xmlString.toString())); return createFeed(syndFeed,xmlString.getSha1(),feedSource); } catch ( final IllegalArgumentException e) { throw new FeedException(e.getMessage()); } }
Example 16
From project akubra, under directory /akubra-map/src/test/java/org/akubraproject/map/.
Source file: IdMappingBlobStoreConnectionTest.java

private static void addTestBlob(BlobStoreConnection connection,URI blobId) throws Exception { Blob blob=connection.getBlob(blobId,null); OutputStream out=blob.openOutputStream(-1,false); IOUtils.copy(new StringReader(blobId.toString()),out); out.close(); }
Example 17
From project android-client_1, under directory /src/com/googlecode/asmack/parser/.
Source file: SmackParser.java

/** * Create a new xml pull parser for a given stanza. * @param stanza The stanza to use as input. * @return A new pull parser, seeked to the first START_TAG. * @throws XmlPullParserException In case of a XML error. * @throws IOException In case of a read error. */ private XmlPullParser getParser(Stanza stanza) throws XmlPullParserException, IOException { XmlPullParser parser=xmlPullParserFactory.newPullParser(); parser.setInput(new StringReader(stanza.getXml())); parser.nextTag(); return parser; }
Example 18
From project AndroidLab, under directory /src/src/de/tubs/ibr/android/ldap/core/activities/.
Source file: LDAPContactMapper.java

public Entry entryFromLocalContact(Uri rawcontacturi){ StringReader sr=new StringReader(""); BufferedReader br=new BufferedReader(sr); LDIFReader ldifreader=new LDIFReader(br); try { Entry contactentry=ldifreader.readEntry(); return contactentry; } catch ( LDIFException e) { return null; } catch ( IOException e) { return null; } }
Example 19
From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.
Source file: TurtleHTMLExtractor.java

/** * Processes a single <i>html script</i> node. * @param turtleParser the parser used to digest node content. * @param documentURI the URI of the original HTML document. * @param n the script node. * @param er the extraction result used to store triples. */ private void processScriptNode(RDFParser turtleParser,URI documentURI,Node n,ExtractionResult er){ final Node idAttribute=n.getAttributes().getNamedItem("id"); final String graphName=documentURI.stringValue() + (idAttribute == null ? "" : "#" + idAttribute.getTextContent()); try { turtleParser.parse(new StringReader(n.getTextContent()),graphName); } catch ( RDFParseException rdfpe) { er.notifyIssue(IssueReport.IssueLevel.Error,String.format("An error occurred while parsing turtle content within script node: %s",Arrays.toString(DomUtils.getXPathListForNode(n))),rdfpe.getLineNumber(),rdfpe.getColumnNumber()); } catch ( Exception e) { er.notifyIssue(IssueReport.IssueLevel.Error,"An error occurred while processing RDF data.",-1,-1); } }
Example 20
From project Application-Builder, under directory /src/main/java/org/silverpeas/helpbuilder/.
Source file: TemplateBasedBuilder.java

public void writeInDirectory(String _targetDirectory) throws IOException, Exception { Reader srcText=new StringReader(getTargetContents()); FileWriter out=new FileWriter(new File(_targetDirectory,targetFileName)); int charsRead; while ((charsRead=srcText.read(data,0,BUFSIZE)) > 0) { out.write(data,0,charsRead); } out.close(); srcText.close(); }
Example 21
From project arquillian-extension-byteman, under directory /src/main/java/org/jboss/arquillian/extension/byteman/impl/common/.
Source file: BytemanConfiguration.java

private static Map<String,String> loadPropertiesString(String properties){ Map<String,String> result=new HashMap<String,String>(); Properties props=new Properties(); try { props.load(new StringReader(properties)); } catch ( IOException e) { } for ( Map.Entry<Object,Object> entry : props.entrySet()) { result.put(String.valueOf(entry.getKey()),String.valueOf(entry.getValue())); } return result; }
Example 22
From project atlas, under directory /src/main/java/com/ning/atlas/.
Source file: JRubyTemplateParser.java

@SuppressWarnings("unchecked") public List<Template> parseSystem(File template){ ScriptingContainer container=new ScriptingContainer(); container.setCompileMode(RubyInstanceConfig.CompileMode.OFF); container.setCompatVersion(CompatVersion.RUBY1_9); try { container.runScriptlet(new StringReader(Resources.toString(Resources.getResource("atlas/parser.rb"),Charset.defaultCharset())),"atlas/parser.rb"); } catch ( IOException e) { throw new IllegalStateException("cannot open atlas/parser.rb from classpath",e); } return (List<Template>)container.runScriptlet("Atlas.parse_system('" + template.getAbsolutePath() + "')"); }
Example 23
From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/.
Source file: Schema.java

/** * Parse a schema from the provided string. If named, the schema is added to the names known to this parser. */ public Schema parse(String s){ try { return parse(FACTORY.createJsonParser(new StringReader(s))); } catch ( IOException e) { throw new SchemaParseException(e); } }
Example 24
From project azkaban, under directory /azkaban/src/unit/azkaban/utils/json/.
Source file: JSONUtilTest.java

@SuppressWarnings("unchecked") @Test public void objectFromStream() throws Exception { String jsonTest="{\"test\":[1,2,\"tree\"], \"test2\":{\"a\":\"b\"}, \"test4\":\"bye\"}"; StringReader reader=new StringReader(jsonTest); Object obj=null; try { obj=JSONUtils.fromJSONStream(reader); } catch ( Exception e) { e.printStackTrace(); throw e; } assertTrue("Testing for instance Map",obj instanceof Map); if (obj instanceof Map) { Map mobj=(Map)obj; assertEquals("Main map size should be 3",mobj.size(),3); assertTrue("Testing for key test",mobj.containsKey("test")); assertTrue("Testing for key test2",mobj.containsKey("test2")); assertTrue("Testing for key test4",mobj.containsKey("test4")); Object testObj=mobj.get("test"); assertTrue(testObj instanceof List); List ltestObj=(List)testObj; assertEquals("List size should be 3",ltestObj.size(),3); assertEquals("First list item should be 1",ltestObj.get(0),1); assertEquals("First list item should be 2",ltestObj.get(1),2); assertEquals("First list item should be tree",ltestObj.get(2),"tree"); Object test2Obj=mobj.get("test2"); assertTrue("test2 should be a map",test2Obj instanceof Map); Map mtest2=(Map)test2Obj; assertEquals("test2 size should be 1",mtest2.size(),1); assertEquals("test2 a = b",mtest2.get("a"),"b"); Object test4Obj=mobj.get("test4"); assertTrue("test4 is a string",test4Obj instanceof String); assertEquals("test4 content is bye",test4Obj,"bye"); } }
Example 25
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/util/.
Source file: Markdowns.java

/** * Converts the specified markdown text to HTML. * @param markdownText the specified markdown text * @return converted HTML, returns {@code null} if the specified markdown text is "" or {@code null} * @throws Exception exception */ public static String toHTML(final String markdownText) throws Exception { if (Strings.isEmptyOrNull(markdownText)) { return null; } final StringWriter writer=new StringWriter(); final Markdown markdown=new Markdown(); markdown.transform(new StringReader(markdownText),writer); return writer.toString(); }
Example 26
From project beanmill_1, under directory /src/main/java/de/cismet/beanmill/.
Source file: LoggingTopComponent.java

/** * DOCUMENT ME! * @return DOCUMENT ME! */ public Object readResolve(){ final LoggingTopComponent ltc=LoggingTopComponent.getDefault(); try { final SAXBuilder sb=new SAXBuilder(); final org.jdom.Document result=sb.build(new StringReader(storeString)); ltc.bmp.setAllFilters(result.getRootElement()); } catch ( final Exception ex) { LOG.error("cannot read top component",ex); } ltc.bmp.setSplitPaneDividerLocation(dividerLocation); return ltc; }
Example 27
From project big-data-plugin, under directory /src/org/pentaho/di/job/entries/sqoop/.
Source file: SqoopUtils.java

/** * Parse a string into arguments as if it were provided on the command line. * @param commandLineString 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); tokenizer.ordinaryChar('-'); tokenizer.wordChars('\u0000','\uFFFF'); tokenizer.whitespaceChars(0,' '); tokenizer.quoteChar('"'); tokenizer.quoteChar('\''); boolean skipToken=false; 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 ("sqoop".equals(s)) { skipToken=true; continue; } else if (skipToken) { ignoreSqoopCommand=false; skipToken=false; continue; } } args.add(escapeEscapeSequences(s)); } } } finally { reader.close(); } return args; }
Example 28
From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.ui/lib/opencsv-2.1/test/au/com/bytecode/opencsv/bean/.
Source file: HeaderColumnNameMappingStrategyTest.java

@Test public void testParse(){ String s="name,orderNumber,num\n" + "kyle,abc123456,123\n" + "jimmy,def098765,456"; HeaderColumnNameMappingStrategy<MockBean> strat=new HeaderColumnNameMappingStrategy<MockBean>(); strat.setType(MockBean.class); CsvToBean<MockBean> csv=new CsvToBean<MockBean>(); List<MockBean> list=csv.parse(strat,new StringReader(s)); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean=list.get(0); assertEquals("kyle",bean.getName()); assertEquals("abc123456",bean.getOrderNumber()); assertEquals(123,bean.getNum()); }
Example 29
From project BMach, under directory /src/jsyntaxpane/actions/.
Source file: XmlPrettifyAction.java

@Override public void actionPerformed(ActionEvent e){ if (transformer == null) { return; } JTextComponent target=getTextComponent(e); try { SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target); StringWriter out=new StringWriter(sdoc.getLength()); StringReader reader=new StringReader(target.getText()); InputSource src=new InputSource(reader); Document doc=getDocBuilder().parse(src); getTransformer().transform(new DOMSource(doc),new StreamResult(out)); target.setText(out.toString()); } catch ( SAXParseException ex) { showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber())); ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1); } catch ( TransformerException ex) { showErrorMessage(target,ex.getMessageAndLocation()); } catch ( SAXException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } catch ( IOException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } }
Example 30
From project book, under directory /src/main/java/com/tamingtext/classifier/bayes/.
Source file: BayesUpdateRequestProcessor.java

public String[] tokenizeField(String fieldName,SolrInputField field) throws IOException { if (field == null) return new String[0]; if (!(field.getValue() instanceof String)) return new String[0]; String input=(String)field.getValue(); ArrayList<String> tokenList=new ArrayList<String>(); TokenStream ts=analyzer.tokenStream(inputField,new StringReader(input)); while (ts.incrementToken()) { tokenList.add(ts.getAttribute(CharTermAttribute.class).toString()); } String[] tokens=tokenList.toArray(new String[tokenList.size()]); return tokens; }
Example 31
From project Cafe, under directory /webapp/src/org/openqa/selenium/internal/.
Source file: Base64Encoder.java

public byte[] decode(String input){ try { ByteArrayOutputStream out=new ByteArrayOutputStream(); StringReader in=new StringReader(input); for (int i=0; i < input.length(); i+=4) { int a[]={mapCharToInt(in),mapCharToInt(in),mapCharToInt(in),mapCharToInt(in)}; int oneBigNumber=(a[0] & 0x3f) << 18 | (a[1] & 0x3f) << 12 | (a[2] & 0x3f) << 6 | (a[3] & 0x3f); for (int j=0; j < 3; j++) if (a[j + 1] >= 0) out.write(0xff & oneBigNumber >> 8 * (2 - j)); } return out.toByteArray(); } catch ( IOException e) { throw new Error(e + ": " + e.getMessage()); } }
Example 32
From project candlepin, under directory /src/test/java/org/candlepin/sync/.
Source file: ConsumerImporterTest.java

@Test public void importHandlesUnknownPropertiesGracefully() throws Exception { Map<String,String> configProps=new HashMap<String,String>(); configProps.put(ConfigProperties.FAIL_ON_UNKNOWN_IMPORT_PROPERTIES,"false"); mapper=SyncUtils.getObjectMapper(new Config(configProps)); ConsumerDto consumer=importer.createObject(mapper,new StringReader("{\"uuid\":\"test-uuid\", \"unknown\":\"notreal\"}")); assertEquals("test-uuid",consumer.getUuid()); }
Example 33
From project capedwarf-blue, under directory /datastore/src/main/java/org/jboss/capedwarf/datastore/query/.
Source file: Projections.java

/** * Read bridges. * @param field the types field * @return bridges */ static Properties readPropertiesBridges(String field){ try { Properties bridges=new Properties(); bridges.load(new StringReader(field)); return bridges; } catch ( IOException e) { throw new IllegalArgumentException("Cannot read bridges!",e); } }
Example 34
From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/util/.
Source file: TripleStoreQueryServiceMulgaraImpl.java

private List<Element> getQuerySolutions(String response){ List<Element> result=null; Document r=null; StringReader sr=null; try { sr=new StringReader(response); r=new SAXBuilder().build(sr); result=extracted(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(); } } }
Example 35
From project cb2java, under directory /src/main/java/net/sf/cb2java/copybook/.
Source file: CopybookParser.java

/** * Parses a copybook definition and returns a Copybook instance * @param name the name of the copybook. For future use. * @param reader the copybook definition's source reader * @return a copybook instance containing the parse tree for the definition */ public static Copybook parse(String name,Reader reader){ Copybook document=null; Lexer lexer=null; try { String preProcessed=CobolPreprocessor.preProcess(reader); StringReader sr=new StringReader(preProcessed); PushbackReader pbr=new PushbackReader(sr,1000); if (debug) { lexer=new DebugLexer(pbr); } else { lexer=new Lexer(pbr); } Parser parser=new Parser(lexer); Start ast=parser.parse(); CopybookAnalyzer copyBookAnalyzer=new CopybookAnalyzer(name,parser); ast.apply(copyBookAnalyzer); document=copyBookAnalyzer.getDocument(); } catch ( Exception e) { throw new RuntimeException("fatal parse error\n" + (lexer instanceof DebugLexer ? "=== buffer dump start ===\n" + ((DebugLexer)lexer).getBuffer() + "\n=== buffer dump end ===" : ""),e); } return document; }
Example 36
/** * @param text * @param analyzer * @return * @throws IOException */ public static List<String> tokenize(String text,Analyzer analyzer) throws IOException { TokenStream stream=analyzer.tokenStream("contents",new StringReader(text)); List<String> tokens=new ArrayList<String>(); CharTermAttribute termAttribute=(CharTermAttribute)stream.getAttribute(CharTermAttribute.class); while (stream.incrementToken()) { String token=termAttribute.toString(); tokens.add(token); } return tokens; }
Example 37
From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/http/.
Source file: KeywordUtils.java

public static List<String> getTokens(String queryString){ try { GermanAnalyzer a=new GermanAnalyzer(Version.LUCENE_33); TokenStream ts=a.tokenStream("",new StringReader(queryString)); List<String> tokens=new ArrayList<String>(); CharTermAttribute termAtt=ts.getAttribute(CharTermAttribute.class); ts.reset(); while (ts.incrementToken()) { String token=termAtt.toString(); tokens.add(token); } ts.end(); ts.close(); return tokens; } catch ( IOException e) { logger.error("",e); } return null; }
Example 38
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.
Source file: HttpBuilder.java

private <T>HttpResult<T> doRequest(HttpUriRequest request,Type target){ DefaultHttpClient client=new DefaultHttpClient(); HttpResult<T> result=new HttpResult<T>(); Reader reader=null; InputStream content=null; String fullJson=null; try { client.addRequestInterceptor(preemptiveAuth(),0); HttpResponse response=client.execute(request); content=response.getEntity().getContent(); reader=new InputStreamReader(content); if (Constants.isDevMode()) { List<String> strings=CharStreams.readLines(reader); fullJson=Joiner.on("\n").join(strings); reader=new StringReader(fullJson); } T output=gson.fromJson(reader,target); result.setContent(output); result.setStatus(response.getStatusLine().getStatusCode() < 300 ? Status.SUCCESS : Status.FAILURE); } catch ( Exception e) { Log.e(Constants.TAG,"Http request failed",e); result.setStatus(Status.ERROR); return result; } finally { closeQuietly(content); closeQuietly(reader); client.getConnectionManager().shutdown(); } return result; }
Example 39
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/sqljep/.
Source file: BaseJEP.java

/** * Parses the expression. The root of the expression tree is returned by {@link #getTopNode()} method * @throws com.meidusa.amoeba.sqljep.ParseException If there are errors in the expression then it fires the exception */ final public void parseExpression(Map<String,Integer> columnMapping,Map<String,Variable> variableMapping,final Map<String,PostfixCommand> funMap) throws ParseException { Reader reader=new StringReader(expression); Parser parser=new Parser(reader){ @Override public boolean containsKey( String key){ return funMap.containsKey(key); } @Override public PostfixCommandI getFunction( String name){ return funMap.get(name); } } ; parser.setColumnMapping(columnMapping); parser.setVariableMapping(variableMapping); try { topNode=parser.parseStream(reader); errorList.clear(); errorList.addAll(parser.getErrorList()); } catch ( ParseException e) { topNode=null; errorList.add(e.getMessage()); } catch ( Throwable e) { throw new com.meidusa.amoeba.sqljep.ParseException(toString(),e); } if (hasError()) { throw new com.meidusa.amoeba.sqljep.ParseException(getErrorInfo()); } if (debug) { ParserVisitor v=new ParserDumpVisitor(); try { topNode.jjtAccept(v,null); } catch ( ParseException e) { errorList.add(e.getMessage()); e.printStackTrace(); } } }
Example 40
From project beanstalker, under directory /beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/config/.
Source file: DescribeConfigurationTemplatesMojo.java

void describeConfigurationTemplate(String configTemplateName){ DescribeConfigurationSettingsRequest req=new DescribeConfigurationSettingsRequest().withApplicationName(applicationName).withTemplateName(configTemplateName); DescribeConfigurationSettingsResult configSettings=getService().describeConfigurationSettings(req); List<String> buf=new ArrayList<String>(); buf.add("<optionSettings>"); for ( ConfigurationSettingsDescription configSetting : configSettings.getConfigurationSettings()) { for ( ConfigurationOptionSetting setting : configSetting.getOptionSettings()) { buf.add(" <optionSetting>"); buf.add(String.format(" <%s>%s</%1$s>","namespace",setting.getNamespace())); buf.add(String.format(" <%s>%s</%1$s>","optionName",setting.getOptionName())); buf.add(String.format(" <%s>%s</%1$s>","value",setting.getValue())); buf.add(" </optionSetting>"); } } buf.add("</optionSettings>"); if (null != outputFile) { getLog().info("Dumping results to file: " + outputFile.getName()); String bufChars=StringUtils.join(buf.iterator(),ENDL); FileWriter writer=null; try { writer=new FileWriter(outputFile); IOUtils.copy(new StringReader(bufChars),writer); } catch ( IOException e) { throw new RuntimeException("Failure when writing to file: " + outputFile.getName(),e); } finally { IOUtils.closeQuietly(writer); } } else { getLog().info("Dumping results to stdout"); for ( String e : buf) getLog().info(e); } }
Example 41
From project behemoth, under directory /mahout/src/main/java/com/digitalpebble/behemoth/mahout/.
Source file: LuceneTokenizerMapper.java

@Override protected void map(Text key,BehemothDocument value,Context context) throws IOException, InterruptedException { String sContent=value.getText(); if (sContent == null) { context.getCounter("LuceneTokenizer","BehemothDocWithoutText").increment(1); return; } TokenStream stream=analyzer.reusableTokenStream(key.toString(),new StringReader(sContent.toString())); CharTermAttribute termAtt=stream.addAttribute(CharTermAttribute.class); StringTuple document=new StringTuple(); stream.reset(); while (stream.incrementToken()) { if (termAtt.length() > 0) { document.add(new String(termAtt.buffer(),0,termAtt.length())); } } context.write(key,document); }
Example 42
From project bioclipse.speclipse, under directory /plugins/net.bioclipse.bibtex/src/net/bioclipse/bibtex/domain/.
Source file: JabrefBibliodata.java

public Document getJabrefDatabaseAsXml() throws BioclipseException { HashSet<String> hs=new HashSet<String>(); Iterator it=db.getEntries().iterator(); int i=0; while (it.hasNext()) { BibtexEntry entry=(BibtexEntry)it.next(); hs.add(entry.getId()); } StringWriter sw=new StringWriter(); try { FileActions.exportDatabase(db,hs,"/resource/layout/","bibtexml",sw); Builder parser=new Builder(); Document doc=parser.build(new StringReader(sw.toString())); return doc; } catch ( Exception e) { e.printStackTrace(); throw new BioclipseException(e.getMessage()); } }
Example 43
From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/jcr/.
Source file: RepositoryUtil.java

public static void registerNodeType(Workspace workspace,String typeName,boolean referenceable,boolean orderable,boolean mixin){ try { NodeTypeManager manager=workspace.getNodeTypeManager(); if (manager.hasNodeType(typeName) == false) { logger.info("Registering node type: {} in workspace {}",typeName,workspace.getName()); String type="[" + typeName + "] > nt:unstructured "; if (referenceable) { type+=", mix:referenceable "; } if (orderable) { type+="orderable "; } if (mixin) { type+=" mixin"; } CndImporter.registerNodeTypes(new StringReader(type),workspace.getSession()); } else { logger.info("Type: {} already registered in workspace {}",typeName,workspace.getName()); } } catch ( Exception e) { throw new RuntimeException("Could not register type: " + typeName,e); } }
Example 44
From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/reader/.
Source file: C24ItemReader.java

/** * Gets the appropriate iO Source to use to read the message. If ioSourceFactory is not set, it defaults to the model's default source. * @param An optional BufferedReader to pass to the source's setReader method * @return A configured iO source */ private Source getIoSource(BufferedReader reader){ Source source=null; if (ioSourceFactory == null) { source=elementType.getModel().source(); if (reader != null) { source.setReader(reader); } } else { source=ioSourceFactory.getSource(reader != null ? reader : new StringReader("")); } if (source instanceof TextualSource) { ((TextualSource)source).setEndOfDataRequired(false); } return source; }
Example 45
From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/explorer/.
Source file: PackageExplorerPart.java

@Override public void init(IViewSite site,IMemento memento) throws PartInitException { super.init(site,memento); if (memento == null) { String persistedMemento=fDialogSettings.get(TAG_MEMENTO); if (persistedMemento != null) { try { memento=XMLMemento.createReadRoot(new StringReader(persistedMemento)); } catch ( WorkbenchException e) { } } } fMemento=memento; if (memento != null) { restoreLayoutState(memento); restoreLinkingEnabled(memento); restoreRootMode(memento); } if (getRootMode() == WORKING_SETS_AS_ROOTS) { createWorkingSetModel(); } }
Example 46
From project ChessCraft, under directory /src/main/java/fr/free/jchecs/core/.
Source file: PGNUtilsTest.java

/** * Teste la convertion flux PGN / dscription de partie. */ @Test public void testToGame(){ final String pgn1="[Event \"jChecs vX.X.X chess game\"]\n" + "[Site \"" + _site + "\"]\n"+ "[Date \"2006.12.31\"]\n"+ "[Round \"-\"]\n"+ "[White \"jChecs.AlphaBeta\"]\n"+ "[Black \"Test\"]\n"+ "[Result \"*\"]\n"+ "\n"+ "1. Pa4 h6? 2. N@c3 *\n"; try { final Game partie=toGame(new BufferedReader(new StringReader(pgn1))); Player joueur=partie.getPlayer(true); assertEquals("AlphaBeta",joueur.getName()); assertEquals(EngineFactory.newInstance("jChecs.AlphaBeta").getClass(),joueur.getEngine().getClass()); joueur=partie.getPlayer(false); assertEquals("Test",joueur.getName()); assertNull(joueur.getEngine()); assertTrue(partie.getState() == Game.State.IN_PROGRESS); assertEquals("rnbqkbnr/ppppppp1/7p/8/P7/2N5/1PPPPPPP/R1BQKBNR b KQkq - 1 2",toFEN(partie.getBoard())); } catch ( final PGNException e) { fail(e.toString()); } final String pgn2="[Event \"jChecs vX.X.X chess game\"]\n" + "[Site \"" + _site + "\"]\n"+ "[Date \"2006.12.31\"]\n"+ "[Round \"-\"]\n"+ "[White \"\"]\n"+ "[Black \"\"]\n"+ "[Result \"*\"]\n"+ "[SetUp \"1\"]\n"+ "[FEN \"rnbqkb1r/pp3ppp/4pn2/2pp4/3P4/2PBP3/PP3PPP/RNBQK1NR w KQkq c6 0 5\"]\n"+ "\n"+ "5. e4 *\n"; try { final Game partie=toGame(new BufferedReader(new StringReader(pgn2))); Player joueur=partie.getPlayer(true); assertEquals("",joueur.getName()); assertNull(joueur.getEngine()); joueur=partie.getPlayer(false); assertEquals("",joueur.getName()); assertNull(joueur.getEngine()); assertTrue(partie.getState() == Game.State.IN_PROGRESS); assertEquals("rnbqkb1r/pp3ppp/4pn2/2pp4/3P4/2PBP3/PP3PPP/RNBQK1NR w KQkq c6 0 5",partie.getStartingPosition()); assertEquals("rnbqkb1r/pp3ppp/4pn2/2pp4/3PP3/2PB4/PP3PPP/RNBQK1NR b KQkq - 0 5",toFEN(partie.getBoard())); } catch ( final PGNException e) { fail(e.toString()); } }
Example 47
From project chililog-server, under directory /src/test/java/org/chililog/server/common/.
Source file: TextTokenizerTest.java

/** * Used for benchmarking ... basic tokenizing without regular expression * @param text * @return * @throws IOException */ public List<String> basicTokenize(String text) throws IOException { List<String> tokens=new ArrayList<String>(); if (StringUtils.isEmpty(text)) { return tokens; } Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_30); HashMap<String,String> lookup=new HashMap<String,String>(); TokenStream stream=analyzer.tokenStream("field",new StringReader(text)); TermAttribute termAttribute=stream.getAttribute(TermAttribute.class); while (stream.incrementToken()) { String term=termAttribute.term(); if (!lookup.containsKey(term)) { tokens.add(term); lookup.put(term,null); } } return tokens; }
Example 48
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/jplugin/.
Source file: GenericChukwaMetricsList.java

public void fromXml(String xml) throws Exception { InputSource is=new InputSource(new StringReader(xml)); Document doc=docBuilder.parse(is); Element root=doc.getDocumentElement(); setRecordType(root.getTagName()); long timestamp=Long.parseLong(root.getAttribute("ts")); setTimestamp(timestamp); NodeList children=root.getChildNodes(); for (int i=0; i < children.getLength(); i++) { if (!children.item(i).getNodeName().equals("Metrics")) { continue; } NamedNodeMap attrs=children.item(i).getAttributes(); if (attrs == null) { continue; } GenericChukwaMetrics metrics=new GenericChukwaMetrics(); for (int a=0; a < attrs.getLength(); a++) { Attr attr=(Attr)attrs.item(a); String name=attr.getName(); String value=attr.getValue(); if (name.equals("key")) { metrics.setKey(value); } else { metrics.put(name,value); } } addMetrics(metrics); } }
Example 49
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generator/model/.
Source file: Model.java

@Override public int readFromStream(BufferedReader in){ String line=null; try { while ((line=in.readLine()) != null) { Relation r=new Relation(new BufferedReader(new StringReader(line))); this.addRelation(r); } return 1; } catch ( IOException e) { e.printStackTrace(); return -1; } }
Example 50
From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.
Source file: EclipseConWizard.java

/** * Tries and find an encoding value on the very first line of the file contents. * @param fileContent The content from which to read an encoding value. * @return The charset name if it exists and is supported, <code>null</code> otherwise */ private static String getCharset(String fileContent){ String trimmedContent=fileContent.trim(); String charsetName=null; if (trimmedContent.length() > 0) { BufferedReader reader=new BufferedReader(new StringReader(trimmedContent)); String firstLine=trimmedContent; try { firstLine=reader.readLine(); } catch ( IOException e) { } Pattern encodingPattern=Pattern.compile("encoding\\s*=\\s*(\"|\')?([-a-zA-Z0-9]+)\1?"); Matcher matcher=encodingPattern.matcher(firstLine); if (matcher.find()) { charsetName=matcher.group(2); } } if (charsetName != null && Charset.isSupported(charsetName)) { return charsetName; } return null; }
Example 51
From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.
Source file: AlfrescoKickstartServiceImpl.java

protected void prettyLogXml(String xml){ try { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); Source xmlInput=new StreamSource(new StringReader(xml)); StreamResult xmlOutput=new StreamResult(new StringWriter()); transformer.transform(xmlInput,xmlOutput); LOGGER.info(xmlOutput.getWriter().toString()); } catch ( Exception e) { e.printStackTrace(); } }
Example 52
From project addis, under directory /application/src/main/java/org/drugis/addis/imports/.
Source file: ClinicaltrialsImporter.java

/** * Remove indentation and text wrapping from a text field. All leading and trailing whitespace is removed from each line of input. Single newlines are removed, double newlines are retained. */ private static String deindent(String textblock){ BufferedReader bufferedReader=new BufferedReader(new StringReader(textblock.trim())); StringBuilder builder=new StringBuilder(); try { boolean first=true; for (String line=bufferedReader.readLine(); line != null; line=bufferedReader.readLine()) { line=line.trim(); if (!line.isEmpty()) { builder.append((first ? "" : " ") + line); first=false; } else { builder.append("\n\n"); first=true; } } bufferedReader.close(); } catch ( IOException e) { throw new RuntimeException(e); } return builder.toString(); }
Example 53
From project aether-core, under directory /aether-test-util/src/main/java/org/eclipse/aether/internal/test/util/.
Source file: DependencyGraphParser.java

/** * Parse the given graph definition. */ public DependencyNode parseLiteral(String dependencyGraph) throws IOException { BufferedReader reader=new BufferedReader(new StringReader(dependencyGraph)); DependencyNode node=parse(reader); reader.close(); return node; }
Example 54
From project airlift, under directory /bootstrap/src/main/java/io/airlift/bootstrap/.
Source file: LoggingWriter.java

@Override public void flush(){ BufferedReader in=new BufferedReader(new StringReader(getBuffer().toString())); for (; ; ) { try { String line=in.readLine(); if (line == null) { break; } switch (type) { default : case DEBUG: { if (logger.isDebugEnabled()) { logger.debug(line); } break; } case INFO: { if (logger.isInfoEnabled()) { logger.info(line); } break; } } } catch (IOException e) { throw new Error(e); } } getBuffer().setLength(0); }
Example 55
From project ALP, under directory /workspace/alp-reporter-fe/src/main/java/com/lohika/alp/reporter/fe/controller/.
Source file: SuiteCotroller.java

@RequestMapping(method=RequestMethod.POST,value="/suite") String addSuite(Model model,@RequestBody String body){ Source source=new StreamSource(new StringReader(body)); Suite suite=(Suite)jaxb2Mashaller.unmarshal(source); suite.setId(1L); model.addAttribute(suite); return view; }
Example 56
From project anadix, under directory /anadix-tests/src/test/java/org/anadix/impl/.
Source file: AnalyzerImplTest.java

@Test(expectedExceptions={RuntimeException.class}) public void testCreateKnowledgeBuilder3(){ String drl="package org.sample\nrule nonsense\nwhen\nn : Nonsense( )\nthen\nend\n"; DroolsResource resource=new DroolsResource(ResourceFactory.newReaderResource(new StringReader(drl)),ResourceType.DRL); when(p.getDroolsResources()).thenReturn(Arrays.asList(resource)); new AnalyzerImpl(p,c); }
Example 57
From project Android, under directory /integration-tests/src/main/java/com/github/mobile/tests/commit/.
Source file: DiffStylerTest.java

private void compareStyled(String patch) throws IOException { assertNotNull(patch); String fileName="file.txt"; DiffStyler styler=new DiffStyler(getContext().getResources()); CommitFile file=new CommitFile(); file.setFilename(fileName); file.setPatch(patch); styler.setFiles(Collections.singletonList(file)); List<CharSequence> styled=styler.get(fileName); assertNotNull(styled); BufferedReader reader=new BufferedReader(new StringReader(patch)); String line=reader.readLine(); int processed=0; while (line != null) { assertEquals(line,styled.get(processed).toString()); line=reader.readLine(); processed++; } assertEquals(processed,styled.size()); }
Example 58
From project android-rackspacecloud, under directory /src/com/rackspace/cloud/servers/api/client/.
Source file: FlavorManager.java

public ArrayList<Flavor> createList(boolean detail,Context context){ CustomHttpClient httpclient=new CustomHttpClient(context); HttpGet get=new HttpGet(Account.getAccount().getServerUrl() + "/flavors/detail.xml?now=cache_time2"); ArrayList<Flavor> flavors=new ArrayList<Flavor>(); get.addHeader("X-Auth-Token",Account.getAccount().getAuthToken()); try { HttpResponse resp=httpclient.execute(get); BasicResponseHandler responseHandler=new BasicResponseHandler(); String body=responseHandler.handleResponse(resp); if (resp.getStatusLine().getStatusCode() == 200 || resp.getStatusLine().getStatusCode() == 203) { FlavorsXMLParser flavorsXMLParser=new FlavorsXMLParser(); SAXParser saxParser=SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader=saxParser.getXMLReader(); xmlReader.setContentHandler(flavorsXMLParser); xmlReader.parse(new InputSource(new StringReader(body))); flavors=flavorsXMLParser.getFlavors(); } } catch ( ClientProtocolException cpe) { } catch ( IOException e) { } catch ( ParserConfigurationException e) { } catch ( SAXException e) { } catch ( FactoryConfigurationError e) { } return flavors; }
Example 59
From project android_external_guava, under directory /src/com/google/common/io/.
Source file: CharStreams.java

/** * Returns a factory that will supply instances of {@link StringReader} thatread a string value. * @param value the string to read * @return the factory */ public static InputSupplier<StringReader> newReaderSupplier(final String value){ Preconditions.checkNotNull(value); return new InputSupplier<StringReader>(){ public StringReader getInput(){ return new StringReader(value); } } ; }
Example 60
From project android_packages_apps_Exchange, under directory /tests/src/com/android/exchange/utility/.
Source file: CalendarUtilitiesTests.java

private BlockHash parseIcsContent(byte[] bytes) throws IOException { BufferedReader reader=new BufferedReader(new StringReader(Utility.fromUtf8(bytes))); String line=reader.readLine(); if (!line.equals("BEGIN:VCALENDAR")) { throw new IllegalArgumentException(); } return new BlockHash("VCALENDAR",reader); }
Example 61
From project ANNIS, under directory /annis-service/src/test/java/annis/ql/parser/.
Source file: TestSearchExpressionCounter.java

private Start parse(String input){ try { Parser parser=new Parser(new Lexer(new PushbackReader(new StringReader(input)))); Start start=parser.parse(); return start; } catch ( Exception e) { throw new RuntimeException(e); } }
Example 62
From project ant4eclipse, under directory /org.ant4eclipse.ant.platform/src/org/ant4eclipse/ant/platform/core/delegate/.
Source file: ConditionalMacroDef.java

/** * <p> Sets the filter expression. </p> * @param filter the filter expression. */ @SuppressWarnings("unchecked") public void setFilter(String filter){ try { new LdapFilter(new HashMap<String,String>(),new StringReader(filter)).validate(); } catch ( ParseException e) { try { if (A4ELogging.isDebuggingEnabled()) { A4ELogging.debug("Exception while parsing filter string '%s'.",filter); } UnknownElement element=(UnknownElement)this._conditionalMacroDef.getProject().getThreadTask(Thread.currentThread()); if (A4ELogging.isDebuggingEnabled()) { A4ELogging.debug("Current UnknownElement is '%s'.",element); } for ( UnknownElement unknownElement : (List<UnknownElement>)element.getChildren()) { if (equals(unknownElement.getWrapper().getProxy())) { throw new BuildException("Invalid filter '" + filter + "'.",unknownElement.getLocation()); } } throw new BuildException("Invalid filter '" + filter + "'."); } catch ( BuildException exception) { throw exception; } catch ( Exception exception) { if (A4ELogging.isDebuggingEnabled()) { A4ELogging.debug("Exception while computing the line number for an exception: '%s'",exception.getMessage()); } throw new BuildException("Invalid filter '" + filter + "'."); } } this._filter=filter; }
Example 63
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/data/script/.
Source file: ScriptExecutor.java

List<String> splitScriptIntoStatements(String script){ final Scanner scriptReader=new Scanner(new StringReader(script)); scriptReader.useDelimiter(SQL_DELIMITER); final List<String> statements=new LinkedList<String>(); while (scriptReader.hasNext()) { final String line=scriptReader.next().trim(); if (line.length() > 0 && !isComment(line)) { statements.add(line); } } return statements; }
Example 64
From project arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/main/java/org/jboss/arquillian/container/glassfish/remote_3_1/.
Source file: GlassFishRestDeployableContainer.java

private ProtocolMetaData parseForProtocolMetaData(String xmlResponse) throws XPathExpressionException { final ProtocolMetaData protocolMetaData=new ProtocolMetaData(); final HTTPContext httpContext=new HTTPContext(this.configuration.getRemoteServerAddress(),this.configuration.getRemoteServerHttpPort()); final XPath xpath=XPathFactory.newInstance().newXPath(); NodeList servlets=(NodeList)xpath.evaluate("/map/entry[@key = 'properties']/map/entry[@value = 'Servlet']",new InputSource(new StringReader(xmlResponse)),XPathConstants.NODESET); for (int i=0; i < servlets.getLength(); i++) { httpContext.add(new Servlet(servlets.item(i).getAttributes().getNamedItem("key").getNodeValue(),this.deploymentName)); } protocolMetaData.addContext(httpContext); return protocolMetaData; }
Example 65
From project AsmackService, under directory /src/com/googlecode/asmack/.
Source file: XMLUtils.java

/** * Turn an XML String into a DOM. * @param xml The xml String. * @return A XML Document. * @throws SAXException In case of invalid XML. */ public static Document getDocument(String xml) throws SAXException { try { DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(new InputSource(new StringReader(xml))); } catch ( ParserConfigurationException e) { throw new IllegalStateException("Parser not configured",e); } catch ( IOException e) { throw new IllegalStateException("IOException on read-from-memory",e); } }
Example 66
From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.
Source file: SamlTokenValidator.java

private static Document getDocument(String doc) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentbuilder=factory.newDocumentBuilder(); return documentbuilder.parse(new InputSource(new StringReader(doc))); }
Example 67
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.
Source file: Strings.java

/** * Converts the specified string into a string list line by line. * @param string the specified string * @return a list of string lines, returns {@code null} if the specified string is {@code null} * @throws IOException io exception */ public static List<String> toLines(final String string) throws IOException { if (null == string) { return null; } final BufferedReader bufferedReader=new BufferedReader(new StringReader(string)); final List<String> ret=new ArrayList<String>(); try { String line=bufferedReader.readLine(); while (null != line) { ret.add(line); line=bufferedReader.readLine(); } } finally { bufferedReader.close(); } return ret; }
Example 68
From project bam, under directory /release/jbossas/tests/activity-management/bean-service/src/main/java/org/overlord/bam/tests/actmgmt/jbossas/beanservice/.
Source file: Transformers.java

private Element toElement(String xml){ DOMResult dom=new DOMResult(); try { TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)),dom); } catch ( Exception ex) { ex.printStackTrace(); } return ((Document)dom.getNode()).getDocumentElement(); }
Example 69
From project bioclipse.opentox, under directory /plugins/net.bioclipse.opentox/src/net/bioclipse/opentox/api/.
Source file: Dataset.java

@SuppressWarnings("serial") public static List<String> getListOfAvailableDatasets(String service) throws IOException { HttpClient client=new HttpClient(); GetMethod method=new GetMethod(service + "dataset"); HttpMethodHelper.addMethodHeaders(method,new HashMap<String,String>(){ { put("Accept","text/uri-list"); } } ); client.executeMethod(method); List<String> datasets=new ArrayList<String>(); BufferedReader reader=new BufferedReader(new StringReader(method.getResponseBodyAsString())); String line; while ((line=reader.readLine()) != null) { line=line.trim(); if (line.length() > 0) datasets.add(line); } reader.close(); method.releaseConnection(); return datasets; }
Example 70
From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.
Source file: WalletActivity.java

private void importPrivateKeys(final File file,final String password){ try { final BufferedReader cipherIn=new BufferedReader(new FileReader(file)); final StringBuilder cipherText=new StringBuilder(); while (true) { final String line=cipherIn.readLine(); if (line == null) break; cipherText.append(line); } cipherIn.close(); final String plainText=EncryptionUtils.decrypt(cipherText.toString(),password.toCharArray()); final BufferedReader plainIn=new BufferedReader(new StringReader(plainText)); final List<ECKey> importedKeys=WalletUtils.readKeys(plainIn); plainIn.close(); final Wallet wallet=getWalletApplication().getWallet(); int importCount=0; k: for ( final ECKey importedKey : importedKeys) { for ( final ECKey key : wallet.getKeys()) if (importedKey.equals(key)) continue k; wallet.addKey(importedKey); importCount++; } final AlertDialog.Builder dialog=new AlertDialog.Builder(this); dialog.setInverseBackgroundForced(true); dialog.setMessage(getString(R.string.wallet_import_keys_dialog_success,importCount)); dialog.setPositiveButton(R.string.wallet_import_keys_dialog_button_reset_blockchain,new DialogInterface.OnClickListener(){ public void onClick( final DialogInterface dialog, final int id){ getWalletApplication().resetBlockchain(); finish(); } } ); dialog.setNegativeButton(R.string.button_dismiss,null); dialog.show(); } catch ( final IOException x) { new AlertDialog.Builder(this).setInverseBackgroundForced(true).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.wallet_import_export_keys_dialog_failure_title).setMessage(getString(R.string.wallet_import_keys_dialog_failure,x.getMessage())).setNeutralButton(R.string.button_dismiss,null).show(); x.printStackTrace(); } }
Example 71
From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/xml/.
Source file: XmlElements.java

private static Document parseXmlToDocument(String xml) throws RuntimeException { DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); try { DocumentBuilder builder=builderFactory.newDocumentBuilder(); InputSource is=new InputSource(new StringReader(xml)); return builder.parse(is); } catch ( SAXException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } catch ( IOException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } catch ( ParserConfigurationException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } }
Example 72
From project boilerpipe, under directory /boilerpipe-core/src/main/de/l3s/boilerpipe/extractors/.
Source file: ExtractorBase.java

/** * Extracts text from the HTML code given as a String. * @param html The HTML code as a String. * @return The extracted text. * @throws BoilerpipeProcessingException */ public String getText(final String html) throws BoilerpipeProcessingException { try { return getText(new BoilerpipeSAXInput(new InputSource(new StringReader(html))).getTextDocument()); } catch ( SAXException e) { throw new BoilerpipeProcessingException(e); } }
Example 73
From project boilerpipe_1, under directory /boilerpipe-core/src/main/de/l3s/boilerpipe/extractors/.
Source file: ExtractorBase.java

/** * Extracts text from the HTML code given as a String. * @param html The HTML code as a String. * @return The extracted text. * @throws BoilerpipeProcessingException */ public String getText(final String html) throws BoilerpipeProcessingException { try { return getText(new BoilerpipeSAXInput(new InputSource(new StringReader(html))).getTextDocument()); } catch ( SAXException e) { throw new BoilerpipeProcessingException(e); } }
Example 74
From project byteman, under directory /agent/src/main/java/org/jboss/byteman/rule/.
Source file: Action.java

public static Action create(Rule rule,String text) throws ParseException, TypeException { if ("".equals(text)) { return new Action(rule); } String fullText="BIND NOTHING IF TRUE DO \n" + text; try { ECATokenLexer lexer=new ECATokenLexer(new StringReader(text)); ECAGrammarParser parser=new ECAGrammarParser(lexer); Symbol parse=parser.parse(); ParseNode parseTree=(ParseNode)parse.value; ParseNode actionTree=(ParseNode)parseTree.getChild(3); Action action=new Action(rule,actionTree); return action; } catch ( Exception e) { throw new ParseException("org.jboss.byteman.rule.Action : error parsing action\n" + text); } }
Example 75
From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/corpora/.
Source file: PubMedDocumentReader.java

/** * {@inheritDoc} */ public Document readDocument(String originalText,String corpusName){ inAbstract=false; inTitle=false; inPMID=false; inTitle=false; labels.clear(); b.setLength(0); try { saxParser.parse(new InputSource(new StringReader(originalText)),this); } catch ( SAXException se) { throw new RuntimeException(se); } catch ( IOException ioe) { throw new IOError(ioe); } return new SimpleDocument(corpusName,docText,originalText,key,id,title,labels); }
Example 76
From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.
Source file: ScreenScrapingService.java

/** * Get portlet-specific XML for clean, valid HTML. * @param cleanHtml * @return * @throws TransformerException * @throws IOException */ protected String getXml(String cleanHtml) throws TransformerException, IOException { final StreamSource xsltSource=new StreamSource(xslt.getInputStream()); final Transformer identityTransformer=transformerFactory.newTransformer(xsltSource); identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); final StringWriter outputWriter=new StringWriter(); final StreamResult outputTarget=new StreamResult(outputWriter); final StreamSource xmlSource=new StreamSource(new StringReader(cleanHtml)); identityTransformer.transform(xmlSource,outputTarget); final String content=outputWriter.toString(); return content; }
Example 77
From project capedwarf-green, under directory /common/src/test/java/org/jboss/test/capedwarf/common/serialization/test/.
Source file: RemotingTestCase.java

@Test public void testFakeRemoting() throws Exception { File file=new File("/Users/alesj/java_lib/android-sdk-mac_86/platforms/android-1.5/android.jar"); if (file.exists() == false) return; ClassLoader cl=new URLClassLoader(new URL[]{file.toURI().toURL()}); Class<?> jsonClass=cl.loadClass(JSONObject.class.getName()); Object jsonInstance=jsonClass.newInstance(); Method put=jsonClass.getMethod("put",String.class,Object.class); put.invoke(jsonInstance,"key","Dummy. ;-)"); String toString=jsonInstance.toString(); JSONObject jo=new JSONObject(new JSONTokener(new StringReader(toString))); System.out.println("jo.getString(\"key\") = " + jo.getString("key")); }
Example 78
From project cascading, under directory /src/core/cascading/operation/expression/.
Source file: ExpressionOperation.java

private String[] getParameterNames(){ if (parameterNames != null) return parameterNames; try { parameterNames=ExpressionEvaluator.guessParameterNames(new Scanner("expressionEval",new StringReader(expression))); } catch ( Parser.ParseException exception) { throw new OperationException("could not parse expression: " + expression,exception); } catch ( Scanner.ScanException exception) { throw new OperationException("could not scan expression: " + expression,exception); } catch ( IOException exception) { throw new OperationException("could not read expression: " + expression,exception); } return parameterNames; }
Example 79
From project caseconductor-platform, under directory /utest-domain-services/src/main/java/com/utest/domain/service/impl/.
Source file: TestCaseServiceImpl.java

@Override public void importSingleStepTestCasesFromCsv(final String cvs_,final Integer productId_) throws Exception { Product product=getRequiredEntityById(Product.class,productId_); final String[] columns={"testCaseName","externalAuthorEmail","createDate","description","bugList","instruction","expectedResult","tagList","testSuiteList","type"}; final CSVReader reader=new CSVReader(new StringReader(cvs_)); final ColumnPositionMappingStrategy<TestCaseExportSingleStepExtendedView> strat=new ColumnPositionMappingStrategy<TestCaseExportSingleStepExtendedView>(); strat.setColumnMapping(columns); strat.setType(TestCaseExportSingleStepExtendedView.class); final CsvToBean<TestCaseExportSingleStepExtendedView> csvToBean=new CsvToBean<TestCaseExportSingleStepExtendedView>(); final List<TestCaseExportSingleStepExtendedView> nodes=csvToBean.parse(strat,reader); TestCase testCase=null; TestCaseVersion testCaseVersion=null; Map<String,Set<Integer>> tagMap=new HashMap<String,Set<Integer>>(); Map<String,Set<Integer>> suiteMap=new HashMap<String,Set<Integer>>(); for (int i=1; i < nodes.size(); i++) { final TestCaseExportSingleStepExtendedView export=nodes.get(i); if (!TestCaseExportSingleStepExtendedView.HEADER_TYPE.equalsIgnoreCase(export.getType())) { throw new InvalidImportFileFormatException(InvalidImportFileFormatException.ERROR_INVALID_TEST_CASE_HEADER_TYPE + ", row: " + i); } testCase=addTestCase(productId_,10,3,export.getTestCaseName() + " : " + new Date().getTime(),export.getDescription(),export.getExternalAuthorEmail()); testCaseVersion=testCase.getLatestVersion(); addTestCaseStep(testCaseVersion.getId(),testCase.getName() + " : step 1",1,export.getInstruction(),export.getExpectedResult(),TestCase.DEFAULT_STEP_ESTIMATED_TIME_IN_MIN); if (export.getTagList() != null && export.getTagList().length() > 0) { loadTestCaseAssociations(tagMap,export.getTagList(),",",testCaseVersion.getId()); } if (export.getTestSuiteList() != null && export.getTestSuiteList().length() > 0) { loadTestCaseAssociations(suiteMap,export.getTestSuiteList(),",",testCaseVersion.getId()); } } createAssociatedTags(tagMap,product); createAssociatedTestSuites(suiteMap,product); }
Example 80
From project ccw, under directory /ccw.core/src/java/ccw/editors/outline/.
Source file: ClojureOutlinePage.java

private void refreshInput(){ Job job=new Job("Outline browser tree refresh"){ @Override protected IStatus run( IProgressMonitor monitor){ String string=document.get(); LineNumberingPushbackReader pushbackReader=new LineNumberingPushbackReader(new StringReader(string)); Object EOF=new Object(); ArrayList<List> input=new ArrayList<List>(); Object result=null; while (true) { try { result=LispReader.read(pushbackReader,false,EOF,false); if (result == EOF) break; if (result instanceof List) input.add((List)result); } catch ( ReaderException e) { CCWPlugin.logWarning(String.format("Failed to read file %s (%s)",editor.getEditorInput().getName(),e.getMessage())); break; } catch ( Exception e) { throw new RuntimeException(e); } } ClojureOutlinePage.this.forms=input; setInputInUiThread(input); return Status.OK_STATUS; } @Override public boolean belongsTo( Object family){ return REFRESH_OUTLINE_JOB_FAMILY.equals(family); } } ; job.setSystem(true); Job.getJobManager().cancel(REFRESH_OUTLINE_JOB_FAMILY); job.schedule(500); }