Java 类java.io.StringReader 实例源码

项目:incubator-netbeans    文件:LogFormatterTest.java   
public void testUnknownLevels() throws IOException {
    TestLevel level = new TestLevel("WARN", 233);
    LogRecord r = new LogRecord(level, "Custom level test");
    Formatter formatter = new LogFormatter();
    String s = formatter.format(r);
    cleanKnownLevels();
    final LogRecord[] rPtr = new LogRecord[] { null };
    Handler h = new Handler() {
        @Override
        public void publish(LogRecord record) {
            rPtr[0] = record;
        }
        @Override
        public void flush() {}
        @Override
        public void close() throws SecurityException {}
    };
    LogRecords.scan(new ReaderInputStream(new StringReader(s)), h);
    assertEquals("level", r.getLevel(), rPtr[0].getLevel());
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected aud claim is as expected")
public void verifyInjectedAudience() throws Exception {
    Reporter.log("Begin verifyInjectedAudience\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    System.out.println(reply);
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
项目:code-sentinel    文件:VarTermTest.java   
public void testSimple2() throws ParseException {
    VarTerm v = new VarTerm("X");
    assertFalse(v.isAtom());
    assertTrue(v.isVar());
    Term t;

    as2jTokenManager tokens = new as2jTokenManager(new SimpleCharStream(new StringReader("Event")));
    Token tk = tokens.getNextToken();
    assertEquals(tk.kind, jason.asSyntax.parser.as2jConstants.VAR);

    t = ASSyntax.parseVar("Ea");
    assertFalse(t.isAtom());
    assertTrue(t.isVar());

    t = ASSyntax.parseTerm("Event");
    assertFalse(t.isAtom());
    assertTrue(t.isVar());

}
项目:dhus-core    文件:ProcessingUtils.java   
/**
 * Check GML Footprint validity
 */
public static boolean checkGMLFootprint (String footprint)
{
   try
   {
      Configuration configuration = new GMLConfiguration ();
      Parser parser = new Parser (configuration);

      Geometry geom =
            (Geometry) parser.parse (new InputSource (
                  new StringReader (footprint)));
      if (!geom.isEmpty() && !geom.isValid())
      {
         LOGGER.error("Wrong footprint");
         return false;
      }
   }
   catch (Exception e)
   {
      LOGGER.error("Error in extracted footprint: " + e.getMessage());
      return false;
   }
   return true;
}
项目:hadoop    文件:MiniKdc.java   
/**
 * Creates a principal in the KDC with the specified user and password.
 *
 * @param principal principal name, do not include the domain.
 * @param password password.
 * @throws Exception thrown if the principal could not be created.
 */
public synchronized void createPrincipal(String principal, String password)
        throws Exception {
  String orgName= conf.getProperty(ORG_NAME);
  String orgDomain = conf.getProperty(ORG_DOMAIN);
  String baseDn = "ou=users,dc=" + orgName.toLowerCase(Locale.ENGLISH)
                  + ",dc=" + orgDomain.toLowerCase(Locale.ENGLISH);
  String content = "dn: uid=" + principal + "," + baseDn + "\n" +
          "objectClass: top\n" +
          "objectClass: person\n" +
          "objectClass: inetOrgPerson\n" +
          "objectClass: krb5principal\n" +
          "objectClass: krb5kdcentry\n" +
          "cn: " + principal + "\n" +
          "sn: " + principal + "\n" +
          "uid: " + principal + "\n" +
          "userPassword: " + password + "\n" +
          "krb5PrincipalName: " + principal + "@" + getRealm() + "\n" +
          "krb5KeyVersionNumber: 0";

  for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
    ds.getAdminSession().add(new DefaultEntry(ds.getSchemaManager(),
            ldifEntry.getEntry()));
  }
}
项目:openjdk-jdk10    文件:EntityTest.java   
@Test
public void testCharacterReferences() {
    try {
        URL fileName = EntityTest.class.getResource("testCharRef.xml");
        URL outputFileName = EntityTest.class.getResource("testCharRef.xml.output");
        XMLStreamReader xmlr = factory.createXMLStreamReader(new InputStreamReader(fileName.openStream()));
        int eventType = 0;
        while (xmlr.hasNext()) {
            eventType = xmlr.next();
            handleEvent(xmlr, eventType);
        }
        System.out.println("Output:");
        System.out.println(output);
        Assert.assertTrue(compareOutput(new InputStreamReader(outputFileName.openStream()), new StringReader(output)));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}
项目:openjdk-jdk10    文件:StAXSourceTest.java   
/**
 * @bug 8152530
 * Verifies that StAXSource handles empty namespace properly. NPE was thrown
 * before the fix.
 * @throws Exception if the test fails
 */
@Test
public final void testStAXSourceWEmptyNS() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<EntityList>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "</EntityList> ";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) {
        StringWriter stringResult = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(stringResult));
        System.out.println("result: \n" + stringResult.toString());
    }
}
项目:JavaPlot    文件:SVGTerminal.java   
/**
 * Retrieve a JPanel whith the provided SVG drawn on it.
 *
 * @return The JPanel with the SVG drawing
 * @throws java.lang.ClassNotFoundException If the SVGSalamander library
 * could not be found, or if any other error occurred.
 */
public JPanel getPanel() throws ClassNotFoundException {
    /*
     * Use reflection API to create the representation in SVG format
     */
    if (output == null || output.equals(""))
        throw new NullPointerException("SVG output is empty; probably SVG terminal is not used or plot() not executed yet.");
    try {
        SVGUniverse universe = new SVGUniverse();
        universe.loadSVG(new StringReader(output), "plot");
        SVGDiagram diagram = universe.getDiagram(universe.getStreamBuiltURI("plot"));

        SVGDisplayPanel svgDisplayPanel = new SVGDisplayPanel();
        svgDisplayPanel.setDiagram(diagram);
        return svgDisplayPanel;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }
}
项目:empiria.player    文件:JAXBParserImpl.java   
@Override
public T parse(String xml) {
    try {
        JAXBBindings bindings = clazz.getAnnotation(JAXBBindings.class);
        ArrayList<Class<?>> binds = new ArrayList<Class<?>>();
        binds.add(bindings.value());

        for (Class<?> c : bindings.objects()) {
            binds.add(c);
        }

        final JAXBContext context = JAXBContext.newInstance(binds.toArray(new Class<?>[0])); // NOPMD
        return (T) context.createUnmarshaller().unmarshal(new StringReader(xml));
    } catch (JAXBException e) {
        Assert.fail(e.getMessage());
        return null;
    }
}
项目:OperatieBRP    文件:BRPStelselServiceImpl.java   
@Override
public void verzendVrijBericht(final VrijBerichtGegevens berichtGegevens) {
    LOGGER.debug("Verzenden Vrij Bericht");
    final String endpointUrl = berichtGegevens.getBrpEndpointURI();
    Assert.notNull(endpointUrl, "Endpoint URL leeg");
    final String leveringBericht = berichtGegevens.getArchiveringOpdracht().getData();

    if (leveringBericht != null) {
        LOGGER.info(VERSTUUR_BERICHT_NAAR_ENDPOINT, endpointUrl);
        // Versturen van request
        final Source request = new StreamSource(new StringReader(leveringBericht));
        LOGGER.info("Vrij bericht wordt verstuurd naar endpoint '{}'", endpointUrl);
        MDC.voerUit(zetMDCMDCVeld(berichtGegevens), () -> {
            try {
                verzendingVerwerkVrijBerichtWebServiceClient.verstuurRequest(request, endpointUrl);
            } catch (final WebServiceException e) {
                throw new VerzendExceptie(String.format("Het is niet gelukt om het vrij bericht te verzenden voor partij %1$d : %2$s",
                        berichtGegevens.getArchiveringOpdracht().getOntvangendePartijId(), leveringBericht), e);
            } finally {
                verwijderMDCVelden();
            }
        });
    } else {
        throw new VerzendExceptie(BERICHT_IS_NIET_GEVONDEN_OP_DE_CONTEXT_EN_NIET_VERSTUURD_ENDPOINT + endpointUrl);
    }
}
项目:Equella    文件:IMSUtilities.java   
/**
 * Retrieves the description from an IMS manifest.
 */
public static String getDescriptionFromManifest(Reader xml) throws XmlPullParserException, IOException
{
    StringWriter sr = new StringWriter();
    CharStreams.copy(xml, sr);

    String bufXml = sr.getBuffer().toString();

    String v = getValueForPath("manifest/metadata/lom/general/description/string|langstring", new StringReader(
        bufXml));
    if( v == null )
    {
        v = getValueForPath(
            "manifest/organizations/organization/item/metadata/lom/general/description/string|langstring",
            new StringReader(bufXml));
    }
    return v;
}
项目:Artatawe    文件:TestJson.java   
private void assertParseFailure(String jsonString)
{
    try
    {
        JsonParser.readFrom(new StringReader(jsonString));
    }
    catch (JsonParserException e)
    {
        System.out.println("Error detected successfully:");
        System.out.println(e.getMessage());
        return;
    }

    System.err.println("Json compiled successfully when it shouldn't have");
    Assert.fail();
}
项目:jdk8u-jdk    文件:Utils.java   
public static byte[] parse(String s) {
    try {
        int n = s.length();
        ByteArrayOutputStream out = new ByteArrayOutputStream(n >> 1);
        StringReader r = new StringReader(s);
        while (true) {
            int b1 = nextNibble(r);
            if (b1 < 0) {
                break;
            }
            int b2 = nextNibble(r);
            if (b2 < 0) {
                throw new RuntimeException("Invalid string " + s);
            }
            int b = (b1 << 4) | b2;
            out.write(b);
        }
        return out.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:openjdk-jdk10    文件:Bug6889654Test.java   
void parse() throws SAXException {
    String xml = "<data>\n<broken/>\u0000</data>";

    try {
        InputSource is = new InputSource(new StringReader(xml));
        is.setSystemId("file:///path/to/some.xml");
        // notice that exception thrown here doesn't include the line number
        // information when reported by JVM -- CR6889654
        SAXParserFactory.newInstance().newSAXParser().parse(is, new DefaultHandler());
    } catch (SAXException e) {
        // notice that this message isn't getting displayed -- CR6889649
        throw new SAXException(MSG, e);
    } catch (ParserConfigurationException pce) {

    } catch (IOException ioe) {

    }

}
项目:abhot    文件:Main.java   
public void runImport(InputStream in) throws IOException, DatastoreException
{
    KairosDatastore ds = m_injector.getInstance(KairosDatastore.class);
    KairosDataPointFactory dpFactory = m_injector.getInstance(KairosDataPointFactory.class);

    BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8));

    Gson gson = new Gson();
    String line;
    while ((line = reader.readLine()) != null)
    {
        DataPointsParser dataPointsParser = new DataPointsParser(ds, new StringReader(line),
                gson, dpFactory);

        ValidationErrors validationErrors = dataPointsParser.parse();

        for (String error : validationErrors.getErrors())
        {
            logger.error(error);
            System.err.println(error);
        }
    }
}
项目:openjdk-jdk10    文件:TestTransmit.java   
private static int nextNibble(StringReader r) throws IOException {
    while (true) {
        int ch = r.read();
        if (ch == -1) {
            return -1;
        } else if ((ch >= '0') && (ch <= '9')) {
            return ch - '0';
        } else if ((ch >= 'a') && (ch <= 'f')) {
            return ch - 'a' + 10;
        } else if ((ch >= 'A') && (ch <= 'F')) {
            return ch - 'A' + 10;
        } else if (ch == 'X') {
            return -2;
        }
    }
}
项目:cdversion-maven-extension    文件:Plugins.java   
public Plugin getEnforcerPlugin(MavenProject project)
        throws MavenExecutionException {
    StringBuilder configString = new StringBuilder()
            .append("<configuration><rules>")
            .append("<requireReleaseDeps><message>No Snapshots Allowed!</message><excludes><exclude>"+project.getGroupId()+":*</exclude></excludes></requireReleaseDeps>")
            .append("</rules></configuration>");
    Xpp3Dom config = null;
    try {
        config = Xpp3DomBuilder.build(new StringReader(configString.toString()));
    } catch (XmlPullParserException | IOException ex) {
        throw new MavenExecutionException("Issue creating cofig for enforcer plugin", ex);
    }

    PluginExecution execution = new PluginExecution();
    execution.setId("no-snapshot-deps");
    execution.addGoal("enforce");
    execution.setConfiguration(config);

    Plugin result = new Plugin();
    result.setArtifactId("maven-enforcer-plugin");
    result.setVersion("1.4.1");
    result.addExecution(execution);

    return result;
}
项目:TrabalhoFinalEDA2    文件:mxXmlUtils.java   
/**
 * Returns a new document for the given XML string.
 * 
 * @param xml
 *            String that represents the XML data.
 * @return Returns a new XML document.
 */
public static Document parseXml(String xml)
{
    try
    {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        return docBuilder.parse(new InputSource(new StringReader(xml)));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}
项目:GitHub    文件:JSONReaderTest_object_object.java   
public void test_read() throws Exception {

        JSONReader reader = new JSONReader(new StringReader(text));
        reader.startObject();

        int count = 0;
        while (reader.hasNext()) {
            String key = (String) reader.readObject();
            Object value = reader.readObject();
            Assert.assertNotNull(key);
            Assert.assertNotNull(value);
            count++;
        }
        Assert.assertEquals(10, count);

        reader.endObject();
        reader.close();
    }
项目:openjdk-jdk10    文件:CommandExecutor.java   
/**
 * createTokenizer - build up StreamTokenizer for the command script
 * @param script command script to parsed
 * @return StreamTokenizer for command script
 */
private static StreamTokenizer createTokenizer(final String script) {
    final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(script));
    tokenizer.resetSyntax();
    // Default all characters to word.
    tokenizer.wordChars(0, 255);
    // Spaces and special characters are white spaces.
    tokenizer.whitespaceChars(0, ' ');
    // Ignore # comments.
    tokenizer.commentChar('#');
    // Handle double and single quote strings.
    tokenizer.quoteChar('"');
    tokenizer.quoteChar('\'');
    // Need to recognize the end of a command.
    tokenizer.eolIsSignificant(true);
    // Command separator.
    tokenizer.ordinaryChar(';');
    // Pipe separator.
    tokenizer.ordinaryChar('|');

    return tokenizer;
}
项目:configx    文件:PropertiesFileConfigItemPostProcessor.java   
/**
 * 加载属性文件内容
 *
 * @param filename
 * @param value
 * @return
 */
protected Properties loadProperties(String filename, String value) {
    Properties props = new Properties();
    if (org.apache.commons.lang.StringUtils.isEmpty(value)) {
        return props;
    }
    try {
        if (filename.endsWith(XML_SUFFIX)) {
            this.propertiesPersister.loadFromXml(props, new ByteArrayInputStream(value.getBytes()));
        } else {
            this.propertiesPersister.load(props, new StringReader(value));
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not parse properties file [" + filename + "]" + e.getMessage());
    }

    return props;
}
项目:openjdk-jdk10    文件:XSDHandler.java   
private void validateAnnotations(ArrayList annotationInfo) {
    if (fAnnotationValidator == null) {
        createAnnotationValidator();
    }
    final int size = annotationInfo.size();
    final XMLInputSource src = new XMLInputSource(null, null, null, false);
    fGrammarBucketAdapter.refreshGrammars(fGrammarBucket);
    for (int i = 0; i < size; i += 2) {
        src.setSystemId((String) annotationInfo.get(i));
        XSAnnotationInfo annotation = (XSAnnotationInfo) annotationInfo.get(i+1);
        while (annotation != null) {
            src.setCharacterStream(new StringReader(annotation.fAnnotation));
            try {
                fAnnotationValidator.parse(src);
            }
            catch (IOException exc) {}
            annotation = annotation.next;
        }
    }
}
项目:Dahlem_SER316    文件:HTMLEditor.java   
public void insertHTML(String html, int location) {
    //assumes editor is already set to "text/html" type
    try {
        HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
        Document doc = editor.getDocument();
        StringReader reader = new StringReader(html);
        kit.read(reader, doc, location);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:CatalogResolverImpl.java   
@Override
public InputSource resolveEntity(String publicId, String systemId) {
    //8150187: NPE expected if the system identifier is null for CatalogResolver
    CatalogMessages.reportNPEOnNull("systemId", systemId);

    //Normalize publicId and systemId
    systemId = Normalizer.normalizeURI(Util.getNotNullOrEmpty(systemId));
    publicId = Normalizer.normalizePublicId(Normalizer.decodeURN(Util.getNotNullOrEmpty(publicId)));

    //check whether systemId is a urn
    if (systemId != null && systemId.startsWith(Util.URN)) {
        systemId = Normalizer.decodeURN(systemId);
        if (publicId != null && !publicId.equals(systemId)) {
            systemId = null;
        } else {
            publicId = systemId;
            systemId = null;
        }
    }

    CatalogImpl c = (CatalogImpl)catalog;
    String resolvedSystemId = Util.resolve(c, publicId, systemId);

    if (resolvedSystemId != null) {
        return new InputSource(resolvedSystemId);
    }

    GroupEntry.ResolveType resolveType = ((CatalogImpl) catalog).getResolve();
    switch (resolveType) {
        case IGNORE:
            return new InputSource(new StringReader(""));
        case STRICT:
            CatalogMessages.reportError(CatalogMessages.ERR_NO_MATCH,
                    new Object[]{publicId, systemId});
    }

    //no action, allow the parser to continue
    return null;
}
项目:dss-demonstrations    文件:FOPService.java   
public void generateDetailedReport(String detailedReport, OutputStream os) throws Exception {
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, os);
    Result res = new SAXResult(fop.getDefaultHandler());
    Transformer transformer = templateDetailedReport.newTransformer();
    transformer.setErrorListener(new DSSXmlErrorListener());
    transformer.transform(new StreamSource(new StringReader(detailedReport)), res);
}
项目:elasticsearch_my    文件:KuromojiAnalysisTests.java   
public void testIterationMarkCharFilter() throws IOException {
    TestAnalysis analysis = createTestAnalysis();
    // test only kanji
    CharFilterFactory charFilterFactory = analysis.charFilter.get("kuromoji_im_only_kanji");
    assertNotNull(charFilterFactory);
    assertThat(charFilterFactory, instanceOf(KuromojiIterationMarkCharFilterFactory.class));

    String source = "ところゞゝゝ、ジヾが、時々、馬鹿々々しい";
    String expected = "ところゞゝゝ、ジヾが、時時、馬鹿馬鹿しい";

    assertCharFilterEquals(charFilterFactory.create(new StringReader(source)), expected);

    // test only kana

    charFilterFactory = analysis.charFilter.get("kuromoji_im_only_kana");
    assertNotNull(charFilterFactory);
    assertThat(charFilterFactory, instanceOf(KuromojiIterationMarkCharFilterFactory.class));

    expected = "ところどころ、ジジが、時々、馬鹿々々しい";

    assertCharFilterEquals(charFilterFactory.create(new StringReader(source)), expected);

    // test default

    charFilterFactory = analysis.charFilter.get("kuromoji_im_default");
    assertNotNull(charFilterFactory);
    assertThat(charFilterFactory, instanceOf(KuromojiIterationMarkCharFilterFactory.class));

    expected = "ところどころ、ジジが、時時、馬鹿馬鹿しい";

    assertCharFilterEquals(charFilterFactory.create(new StringReader(source)), expected);
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestAuthorizationDigest.java   
@Test
public void testBug54060b() throws Exception {
    String header = "Digest username=\"mthornton\", " +
            "realm=\"optrak.com\", " +
            "nonce=\"1351427480964:a01c16fed5168d72a2b5267395a2022e\", " +
            "uri=\"/files\", " +
            "algorithm=MD5, " +
            "response=\"f310c44b87efc0bc0a7aab7096fd36b6\", " +
            "opaque=\"DB85C1A73933A7EB586D10E4BF2924EF\", " +
            "cnonce=\"MHg3ZjA3ZGMwMTUwMTA6NzI2OToxMzUxNDI3NDgw\", " +
            "nc=00000001, " +
            "qop=auth";

    StringReader input = new StringReader(header);

    Map<String,String> result = HttpParser.parseAuthorizationDigest(input);

    Assert.assertEquals("mthornton", result.get("username"));
    Assert.assertEquals("optrak.com", result.get("realm"));
    Assert.assertEquals("1351427480964:a01c16fed5168d72a2b5267395a2022e",
            result.get("nonce"));
    Assert.assertEquals("/files", result.get("uri"));
    Assert.assertEquals("MD5", result.get("algorithm"));
    Assert.assertEquals("f310c44b87efc0bc0a7aab7096fd36b6",
            result.get("response"));
    Assert.assertEquals("DB85C1A73933A7EB586D10E4BF2924EF",
            result.get("opaque"));
    Assert.assertEquals("MHg3ZjA3ZGMwMTUwMTA6NzI2OToxMzUxNDI3NDgw",
            result.get("cnonce"));
    Assert.assertEquals("00000001", result.get("nc"));
    Assert.assertEquals("auth", result.get("qop"));
}
项目:alfresco-remote-api    文件:SerializerTestHelper.java   
public SearchQuery extractFromJson(String json) throws IOException
{
    Content content = mock(Content.class);
    when(content.getReader()).thenReturn(new StringReader(json));
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getContent()).thenReturn(content);
    return extractJsonContent(request, jsonHelper, SearchQuery.class);
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestAuthorizationDigest.java   
@Test
public void testBug54060c() throws Exception {
    String header = "Digest username=\"mthornton\", qop=auth";

    StringReader input = new StringReader(header);

    Map<String,String> result = HttpParser.parseAuthorizationDigest(input);

    Assert.assertEquals("mthornton", result.get("username"));
    Assert.assertEquals("auth", result.get("qop"));
}
项目:hadoop    文件:TestHsWebServicesAttempts.java   
@Test
public void testTaskAttemptIdXMLCounters() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      for (TaskAttempt att : task.getAttempts().values()) {
        TaskAttemptId attemptid = att.getID();
        String attid = MRApps.toString(attemptid);

        ClientResponse response = r.path("ws").path("v1").path("history")
            .path("mapreduce").path("jobs").path(jobId).path("tasks")
            .path(tid).path("attempts").path(attid).path("counters")
            .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);

        assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
        String xml = response.getEntity(String.class);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        Document dom = db.parse(is);
        NodeList nodes = dom.getElementsByTagName("jobTaskAttemptCounters");

        verifyHsTaskCountersXML(nodes, att);
      }
    }
  }
}
项目:openjdk-jdk10    文件:DefaultFactoryWrapperTest.java   
@DataProvider(name = "jaxpFactories")
public Object[][] jaxpFactories() throws Exception {
    return new Object[][] {
            { DocumentBuilderFactory.newInstance(), (Produce)factory -> ((DocumentBuilderFactory)factory).newDocumentBuilder() },
            { SAXParserFactory.newInstance(), (Produce)factory -> ((SAXParserFactory)factory).newSAXParser() },
            { SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI), (Produce)factory -> ((SchemaFactory)factory).newSchema() },
            { TransformerFactory.newInstance(), (Produce)factory -> ((TransformerFactory)factory).newTransformer() },
            { XMLEventFactory.newInstance(), (Produce)factory -> ((XMLEventFactory)factory).createStartDocument() },
            { XMLInputFactory.newInstance(), (Produce)factory -> ((XMLInputFactory)factory).createXMLEventReader(new StringReader("")) },
            { XMLOutputFactory.newInstance(), (Produce)factory -> ((XMLOutputFactory)factory).createXMLEventWriter(new StringWriter()) },
            { XPathFactory.newInstance(), (Produce)factory -> ((XPathFactory)factory).newXPath() },
            { DatatypeFactory.newInstance(), (Produce)factory -> ((DatatypeFactory)factory).newXMLGregorianCalendar() }
    };
}
项目:gcp    文件:ParseXML.java   
@Override
public ExampleXML call(String input) throws Exception {
  JAXBContext jaxb = JAXBContext.newInstance(ExampleXML.class);
  Unmarshaller um = jaxb.createUnmarshaller();
  Object xml = um.unmarshal(new StringReader(input));
  return (ExampleXML) xml;
}
项目:stdds-monitor    文件:StatusMessageParserV4.java   
@Override
protected void parseAPDSStatusMessage(Tracon tracon, String messageText) {
    long timestamp = System.currentTimeMillis();

    AirportDataServiceStatus apdsMessage = null;
    try {
        JAXBContext context = JAXBContext.newInstance(AirportDataServiceStatus.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StringReader reader = new StringReader(messageText);
        apdsMessage = (AirportDataServiceStatus) unmarshaller.unmarshal(reader);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Service service = tracon.getService(Constants.APDS);
    if ((service == null) && (DYNAMIC_MODE)) {
        service = new Service();
        service.setName(Constants.APDS);
        tracon.addService(service);
    }
    if (service != null) {
        service.setTimeStamp(timestamp);
        RVRExternalLinks rvrLinks = apdsMessage.getRvrLinks();
        if (rvrLinks != null) {
            for (ExternalLink exLink : rvrLinks.getRvrLink()) {
                handleLink(timestamp, service, tracon.getName(), exLink);
            }
        }
        // Don't set the service status if not configured for override
        boolean changed = false;
        if (!OVERRIDE_STATUS) {
            changed = service.setStatus(getMessageStatus(apdsMessage.getServiceStatus()));
        } else {
            changed = service.refreshStatus();
        }
        if (changed) {
            notificationRepo.save(new Notification(timestamp, service.getStatus(),
                    service.getName(), tracon.getName(), NotificationType.SERVICE));
        }
    }
}
项目:tomcat7    文件:ELParser.java   
public static Node parse(String ref) throws ELException
{
    try {
        return (new ELParser(new StringReader(ref))).CompositeExpression();
    } catch (ParseException pe) {
        throw new ELException(pe.getMessage());
    }
}
项目:OpenJSharp    文件:SourceWriter.java   
private static String[] splitLines(String text) {
    if (text == null)
        return new String[0];

    List<String> lines = new ArrayList<String>();
    lines.add(""); // dummy line 0
    try {
        BufferedReader r = new BufferedReader(new StringReader(text));
        String line;
        while ((line = r.readLine()) != null)
            lines.add(line);
    } catch (IOException ignore) {
    }
    return lines.toArray(new String[lines.size()]);
}
项目:joai-project    文件:XMLConversionService.java   
/**
 *  Converts XML from one format to another, without the use of a cache to
 *  store or save results. Returns null if there are no known conversions
 *  available for the requested conversion, or if a processing error occurs.
 *  Characters returned in the StringBuffer are encoded in UTF-8.
 *
 * @param  fromFormat   The XML format to convert from. Example: 'dlese_ims.'
 * @param  toFormat     The format to convert to. Example: 'adn.'
 * @param  originalXML  The original XML as a String, in the 'from' format.
 *      Should not be null.
 * @return              Content converted to the 'to' format, or null if unable
 *      to process.
 */
public String convertXml(String fromFormat,
                               String toFormat,
                               String originalXML) {
    // Check to see if the input and output formats are the same.
    if (fromFormat.equals(toFormat)) {
        if (originalXML != null) {
            try {
                if (filter)
                    return stripXmlDeclaration(new BufferedReader(
                        new StringReader(originalXML))).toString();
                else
                    return originalXML;
            } catch (Exception e) {
                prtlnErr("Unable to process originalXML file: " + e);
                return null;
            }
        }
    }

    // Grab the converter, checking to see if we can convert.
    XmlConverter xmlConverter = (XmlConverter) getConverter(fromFormat, toFormat);
    if (xmlConverter == null)
        return null;

    return xmlConverter.convertXml(originalXML);
}
项目:ZhiHuIndex-master    文件:GsonTool.java   
public static User getUser(String jsonStr){
    User node = new User();
    try{
    Gson gson = new Gson();
        JsonReader jreader = new JsonReader(new StringReader(jsonStr));
        jreader.setLenient(true);
        node = gson.fromJson(jreader,User.class);
}catch(Exception e){
        e.printStackTrace();
    }
    return node;
}
项目:OpenJSharp    文件:XSAnnotationImpl.java   
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
项目:elasticsearch_my    文件:StreamsTests.java   
public void testCopyFromReader() throws IOException {
    String content = "content";
    StringReader in = new StringReader(content);
    StringWriter out = new StringWriter();
    int count = copy(in, out);
    assertThat(content.length(), equalTo(count));
    assertThat(out.toString(), equalTo(content));
}
项目:jdk8u-jdk    文件:SaajEmptyNamespaceTest.java   
@Test
public void testResetDefaultNamespaceSAAJ() throws Exception {
    // Create SOAP message from XML string and process it with SAAJ reader
    XMLStreamReader envelope = XMLInputFactory.newFactory().createXMLStreamReader(
            new StringReader(INPUT_SOAP_MESSAGE));
    StreamMessage streamMessage = new StreamMessage(SOAPVersion.SOAP_11,
            envelope, null);
    SAAJFactory saajFact = new SAAJFactory();
    SOAPMessage soapMessage = saajFact.readAsSOAPMessage(SOAPVersion.SOAP_11, streamMessage);

    // Check if constructed object model meets local names and namespace expectations
    SOAPElement request = (SOAPElement) soapMessage.getSOAPBody().getFirstChild();
    // Check top body element name
    Assert.assertEquals(request.getLocalName(), "SampleServiceRequest");
    // Check top body element namespace
    Assert.assertEquals(request.getNamespaceURI(), TEST_NS);
    SOAPElement params = (SOAPElement) request.getFirstChild();
    // Check first child name
    Assert.assertEquals(params.getLocalName(), "RequestParams");
    // Check if first child namespace is null
    Assert.assertNull(params.getNamespaceURI());

    // Check inner elements of the first child
    SOAPElement param1 = (SOAPElement) params.getFirstChild();
    Assert.assertEquals(param1.getLocalName(), "Param1");
    Assert.assertNull(param1.getNamespaceURI());
    SOAPElement param2 = (SOAPElement) params.getChildNodes().item(1);
    Assert.assertEquals(param2.getLocalName(), "Param2");
    Assert.assertNull(param2.getNamespaceURI());
    // Check full content of SOAP body
    Assert.assertEquals(nodeToText(request), EXPECTED_RESULT);
}