org.apache.http.impl.client.BasicResponseHandler#java.io.StringReader源码实例Demo

下面列出了org.apache.http.impl.client.BasicResponseHandler#java.io.StringReader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void readBlock_SHOULD_handle_CRLF_line_endings() throws Exception {
    // Given

    String blockText = "{1:a}{2:b}{3:c}{4:\r\n-}";

    SwiftBlockReader subjectUnderTest = new SwiftBlockReader(new StringReader(blockText));

    // When
    List<GeneralBlock> blockList = TestUtils.collectUntilNull(subjectUnderTest::readBlock);

    // Then

    assertThat(blockList).hasSize(4);
    assertThat(blockList.get(0).getId()).isEqualTo("1");
    assertThat(blockList.get(0).getContent()).isEqualTo("a");
    assertThat(blockList.get(1).getId()).isEqualTo("2");
    assertThat(blockList.get(1).getContent()).isEqualTo("b");
    assertThat(blockList.get(2).getId()).isEqualTo("3");
    assertThat(blockList.get(2).getContent()).isEqualTo("c");
    assertThat(blockList.get(3).getId()).isEqualTo("4");
    assertThat(blockList.get(3).getContent()).isEqualTo("\n-");
}
 
源代码2 项目: birt   文件: SPParameterPositionUtil.java
/**
 * get the quoted string
 * 
 * @param strBuf
 * @param reader
 * @return
 * @throws IOException
 */
private void readNextQuote( StringReader reader, int quote )
		throws IOException
{
	int i = -1;
	while ( ( i = reader.read( ) ) != -1 )
	{
		if ( i != quote )
		{
			continue;
		}
		else
		{
			break;
		}
	}
}
 
源代码3 项目: Tomcat8-Source-Read   文件: Request.java
/**
 * Parse accept-language header value.
 *
 * @param value the header value
 * @param locales the map that will hold the result
 */
protected void parseLocalesHeader(String value, TreeMap<Double, ArrayList<Locale>> locales) {

    List<AcceptLanguage> acceptLanguages;
    try {
        acceptLanguages = AcceptLanguage.parse(new StringReader(value));
    } catch (IOException e) {
        // Mal-formed headers are ignore. Do the same in the unlikely event
        // of an IOException.
        return;
    }

    for (AcceptLanguage acceptLanguage : acceptLanguages) {
        // Add a new Locale to the list of Locales for this quality level
        Double key = Double.valueOf(-acceptLanguage.getQuality());  // Reverse the order
        ArrayList<Locale> values = locales.get(key);
        if (values == null) {
            values = new ArrayList<>();
            locales.put(key, values);
        }
        values.add(acceptLanguage.getLocale());
    }
}
 
@Test
public void saveAndRetrieve() throws Exception {
  Path root = temporaryFolder.getRoot();

  NodeContext topology = new NodeContext(Cluster.newDefaultCluster("bar", new Stripe(Node.newDefaultNode("node-1", "localhost"))), 1, "node-1");
  Properties properties = Props.load(new StringReader(new String(Files.readAllBytes(Paths.get(getClass().getResource("/config.properties").toURI())), StandardCharsets.UTF_8).replace("\\", "/")));

  FileConfigStorage storage = new FileConfigStorage(root, "node-1");

  assertFalse(Files.exists(root.resolve("node-1.1.properties")));
  storage.saveConfig(1L, topology);
  assertTrue(Files.exists(root.resolve("node-1.1.properties")));

  Properties written = Props.load(new StringReader(new String(Files.readAllBytes(root.resolve("node-1.1.properties")), StandardCharsets.UTF_8).replace("\\", "/")));
  assertThat(written.toString(), written, is(equalTo(properties)));

  NodeContext loaded = storage.getConfig(1L);
  assertThat(loaded, is(topology));
}
 
源代码5 项目: olat   文件: SearchInputController.java
protected Set<String> getHighlightWords(final String searchString) {
    try {
        final Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
        final TokenStream stream = analyzer.tokenStream("content", new StringReader(searchString));
        final TermAttribute termAtt = stream.addAttribute(TermAttribute.class);
        for (boolean next = stream.incrementToken(); next; next = stream.incrementToken()) {
            final String term = termAtt.term();
            if (log.isDebugEnabled()) {
                log.debug(term);
            }
        }
    } catch (final IOException e) {
        log.error("", e);
    }
    return null;
}
 
@Test
public void readField_WHEN_detecting_content_without_field_tag_THEN_throw_exception() throws Exception {

    // Given
    String swiftMessage = "fizz\n:2:buzz";
    SwiftFieldReader classUnderTest = new SwiftFieldReader(new StringReader(swiftMessage));

    // When
    Throwable exception = catchThrowable(() -> TestUtils.collectUntilNull(classUnderTest::readField));

    // Then
    assertThat(exception).as("Exception").isInstanceOf(FieldParseException.class);

    FieldParseException parseException = (FieldParseException) exception;
    assertThat(parseException.getLineNumber()).isEqualTo(1);

}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected jti claim using @Claim(standard) is as expected")
public void verifyInjectedJTIStandard() throws Exception {
    Reporter.log("Begin verifyInjectedJTIStandard\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedJTIStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.jti.name(), "a-123")
        .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();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码8 项目: lucene-solr   文件: TestSuggestStopFilter.java
public void testEndNotStopWord() throws Exception {
  CharArraySet stopWords = StopFilter.makeStopSet("to");
  Tokenizer stream = new MockTokenizer();
  stream.setReader(new StringReader("go to"));
  TokenStream filter = new SuggestStopFilter(stream, stopWords);
  assertTokenStreamContents(filter,
                            new String[] {"go", "to"},
                            new int[] {0, 3},
                            new int[] {2, 5},
                            null,
                            new int[] {1, 1},
                            null,
                            5,
                            new boolean[] {false, true},
                            true);
}
 
源代码9 项目: android-oauth-client   文件: GitHubRequest.java
@Override
public T execute() throws IOException {
    HttpResponse response = super.executeUnparsed();
    ObjectParser parser = response.getRequest().getParser();
    // This will degrade parsing performance but is an inevitable workaround
    // for the inability to parse JSON arrays.
    String content = response.parseAsString();
    if (response.isSuccessStatusCode()
            && !TextUtils.isEmpty(content)
            && content.charAt(0) == '[') {
        content = TextUtils.concat("{\"", GitHubResponse.KEY_DATA, "\":", content, "}")
                .toString();
    }
    Reader reader = new StringReader(content);
    T parsedResponse = parser.parseAndClose(reader, getResponseClass());

    // parse pagination from Link header
    if (parsedResponse instanceof GitHubResponse) {
        Pagination pagination =
                new Pagination(response.getHeaders().getFirstHeaderStringValue("Link"));
        ((GitHubResponse) parsedResponse).setPagination(pagination);
    }

    return parsedResponse;
}
 
public void testOffsetChange() throws Exception {
    String resource = "worddelimiter.json";
    Settings settings = Settings.builder()
            .loadFromStream(resource, getClass().getResourceAsStream(resource), true)
            .build();
    ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"),
            settings,
            new BundlePlugin(Settings.EMPTY));
    Tokenizer tokenizer = analysis.tokenizer.get("keyword").create();
    tokenizer.setReader(new StringReader("übelkeit"));
    TokenStream ts = analysis.tokenFilter.get("wd").create(tokenizer);

    assertTokenStreamContents(ts,
            new String[]{"übelkeit" },
            new int[]{0},
            new int[]{8});
}
 
源代码11 项目: lucene-solr   文件: TestXPathRecordReader.java
@Test
public void testMixedContent() {
  String xml = "<xhtml:p xmlns:xhtml=\"http://xhtml.com/\" >This text is \n" +
          "  <xhtml:b>bold</xhtml:b> and this text is \n" +
          "  <xhtml:u>underlined</xhtml:u>!\n" +
          "</xhtml:p>";
  XPathRecordReader rr = new XPathRecordReader("/p");
  rr.addField("p", "/p", true);
  rr.addField("b", "/p/b", true);
  rr.addField("u", "/p/u", true);
  List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml));
  Map<String, Object> row = l.get(0);

  assertEquals("bold", ((List) row.get("b")).get(0));
  assertEquals("underlined", ((List) row.get("u")).get(0));
  String p = (String) ((List) row.get("p")).get(0);
  assertTrue(p.contains("This text is"));
  assertTrue(p.contains("and this text is"));
  assertTrue(p.contains("!"));
  // Should not contain content from child elements
  assertFalse(p.contains("bold"));
}
 
源代码12 项目: metacat   文件: DirectSqlGetPartition.java
private Collection<String> getSinglePartitionExprs(@Nullable final String filterExpression) {
    Collection<String> result = Lists.newArrayList();
    if (!Strings.isNullOrEmpty(filterExpression)) {
        try {
            result = (Collection<String>) new PartitionParser(
                new StringReader(filterExpression)).filter().jjtAccept(new PartitionKeyParserEval(),
                null
            );
        } catch (Throwable ignored) {
            //
        }
    }
    if (result != null) {
        result = result.stream().filter(s -> !(s.startsWith("batchid=") || s.startsWith("dateCreated="))).collect(
            Collectors.toList());
    }
    return result;
}
 
protected PrivateKey toPrivateKey(String privateKey) {
    StringReader reader = new StringReader(privateKey);

    // プライベートキーを読み込み
    PEMReader pemReader = new PEMReader(reader);
    try {
        Object pemObject = pemReader.readObject();
        KeyPair keyPair = KeyPair.class.cast(pemObject);
        return keyPair.getPrivate();
    } catch (Exception e) {
        // プライベートキーの読み込みに失敗した場合
        throw new AutoApplicationException("ESERVICE-000705", e);
    } finally {
        try {
            pemReader.close();
        } catch (IOException ignore) {
        }
    }
}
 
源代码14 项目: hipparchus   文件: LongFrequencyTest.java
/**
 * Tests toString()
 */
@Test
public void testToString() throws Exception {
    LongFrequency f = new LongFrequency();

    f.addValue(ONE_LONG);
    f.addValue(TWO_LONG);
    f.addValue((long) ONE);
    f.addValue((long) TWO);

    String s = f.toString();
    //System.out.println(s);
    assertNotNull(s);
    BufferedReader reader = new BufferedReader(new StringReader(s));
    String line = reader.readLine(); // header line
    assertNotNull(line);

    line = reader.readLine(); // one's or two's line
    assertNotNull(line);

    line = reader.readLine(); // one's or two's line
    assertNotNull(line);

    line = reader.readLine(); // no more elements
    assertNull(line);
}
 
/**
 * Returns a DOM object representing parsed xml.
 *
 * @param xml The xml to parse
 * @return Parsed XML document
 */
private static Document parse(String xml)
    throws IOException, ParserConfigurationException, SAXException {
  ErrorHandler errors = new ErrorHandler();
  try {
    synchronized (factory) {
      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setErrorHandler(errors);
      return builder.parse(new InputSource(new StringReader(xml)));
    }
  } catch (SAXException se) {
    // Prefer parse errors over general errors.
    errors.throwIfErrors();
    throw se;
  }
}
 
源代码16 项目: microprofile-jwt-auth   文件: RequiredClaimsTest.java
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
        description = "Verify that the aud claim is as expected")
public void verifyOptionalAudience() throws Exception {
    Reporter.log("Begin verifyOptionalAudience\n");
    String uri = baseURL.toExternalForm() + "endp/verifyOptionalAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.aud.name(), null)
            .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();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码17 项目: ironjacamar   文件: JCA10TestCase.java
/**
 * Write
 * @throws Exception In case of an error
 */
@Test
public void testWrite() throws Exception
{
   RaParser parser = new RaParser();

   InputStream is = JCA10TestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/spec/ra-1.0.xml");
   assertNotNull(is);

   XMLInputFactory inputFactory = XMLInputFactory.newInstance();
   inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);

   XMLStreamReader xsr = inputFactory.createXMLStreamReader(is);
   
   Connector c = parser.parse(xsr);
   assertNotNull(c);

   is.close();

   StringReader sr = new StringReader(c.toString());
   XMLStreamReader nxsr = XMLInputFactory.newInstance().createXMLStreamReader(sr);
   Connector cn = parser.parse(nxsr);
   checkConnector(cn);
   assertEquals(c, cn);
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected iat claim is as expected")
public void verifyInjectedIssuedAt() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAt\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuedAt";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iat.name(), iatClaim)
        .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();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码19 项目: logback-gelf   文件: GelfEncoderTest.java
@Test
public void simple() throws IOException {
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final String logMsg = encodeToStr(simpleLoggingEvent(logger, null));

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);

    final LineReader msg =
        new LineReader(new StringReader(jsonNode.get("full_message").textValue()));
    assertEquals("message 1", msg.readLine());
}
 
源代码20 项目: netbeans   文件: ConflictDescriptionParser.java
private void parse (String description) throws IOException {
    StringReader sr = new StringReader(description);
    if (sr.read() == DELIMITER_OPEN_BRACKET) {
        while (true) {
            int c;
            while ((c = sr.read()) != -1 && c != DELIMITER_OPEN_BRACKET && c != DELIMITER_CLOSING_BRACKET); // wait for a bracket opening new conflict
            if (c == DELIMITER_CLOSING_BRACKET) { // end of description
                break;
            } else if (c != DELIMITER_OPEN_BRACKET) { // error
                throw new IOException("Error parsing description: " + description); //NOI18N
            }
            ParserConflictDescriptor conflict = readConflict(sr);
            if (conflict != null) {
                conflicts.add(conflict);
            }
        }
    }
}
 
源代码21 项目: recheck   文件: JSFilterImplTest.java
@Test
void calling_erroneous_method_twice_with_different_args_should_actually_call_method() {
	final JSFilterImpl cut = new JSFilterImpl( ctorArg ) {
		@Override
		Reader readScriptFile( final Path path ) {
			return new StringReader( //
					"function matches(element) { " //
							+ "if (element != null) {" //
							+ "  return true;" //
							+ "}" //
							+ "throw 42;" //
							+ "}" );
		}
	};
	cut.matches( null );
	assertThat( cut.matches( mock( Element.class ) ) ).isTrue();
}
 
源代码22 项目: rice   文件: RuleRoutingAttribute.java
public List<RuleRoutingAttribute> parseDocContent(DocumentContent docContent) {
    try {
        Document doc2 = (Document) XmlHelper.buildJDocument(new StringReader(docContent.getDocContent()));
        
        List<RuleRoutingAttribute> doctypeAttributes = new ArrayList<RuleRoutingAttribute>();
        Collection<Element> ruleRoutings = XmlHelper.findElements(doc2.getRootElement(), "docTypeName");
        List<String> usedDTs = new ArrayList<String>();
        for (Iterator<Element> iter = ruleRoutings.iterator(); iter.hasNext();) {
            Element ruleRoutingElement = (Element) iter.next();

            //Element docTypeElement = ruleRoutingElement.getChild("doctype");
            Element docTypeElement = ruleRoutingElement;
            String elTxt = docTypeElement.getText();
            if (docTypeElement != null && !usedDTs.contains(elTxt)) {
            	usedDTs.add(elTxt);
                doctypeAttributes.add(new RuleRoutingAttribute(elTxt));
            }
        }

        return doctypeAttributes;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码23 项目: big-c   文件: TestHsWebServicesJobs.java
@Test
public void testJobsXML() throws Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").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 jobs = dom.getElementsByTagName("jobs");
  assertEquals("incorrect number of elements", 1, jobs.getLength());
  NodeList job = dom.getElementsByTagName("job");
  assertEquals("incorrect number of elements", 1, job.getLength());
  verifyHsJobPartialXML(job, appContext);
}
 
public void testSix() throws Exception {
    String source = "Programmieren in C++ für Einsteiger";
    String[] expected = {
            "programmieren",
            "programmi",
            "c++",
            "einsteiger",
            "einsteig"
    };
    String resource = "unstemmed.json";
    Settings settings = Settings.builder()
            .loadFromStream(resource, getClass().getResourceAsStream(resource), true)
            .build();
    ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"),
            settings,
            new BundlePlugin(Settings.EMPTY), new CommonAnalysisPlugin());
    Analyzer analyzer = analysis.indexAnalyzers.get("default");
    assertTokenStreamContents(analyzer.tokenStream(null, new StringReader(source)), expected);
}
 
源代码25 项目: j2objc   文件: DataReadWriteTest.java
@Test
public void testBoolArray() {
    boolean[][] datas = {
        {},
        { true },
        { true, false },
        { true, false, true },
    };

    String[] targets = {
        "<testList></testList>",
        "<testList><test>true</test></testList>",
        "<testList><test>true</test><test>false</test></testList>",
        "<testList><test>true</test><test>false</test>" +
        "<test>true</test></testList>",
    };

    for (int j = 0; j < datas.length; ++j) {
        boolean[] data = datas[j];
        String target = targets[j];

        StringWriter sw = new StringWriter();
        XMLRecordWriter xrw = new XMLRecordWriter(sw);
        xrw.boolArray("test", data);
        xrw.flush();
        String str = sw.toString();
        assertEquals("" + j, target, normalize(str));

        StringReader sr = new StringReader(str);
        XMLRecordReader xrr = new XMLRecordReader(sr);
        boolean[] out = xrr.boolArray("test");

        assertNotNull("" + j, out);
        assertEquals("" + j, data.length, out.length);
        for (int i = 0; i < data.length; ++i) {
            assertEquals("" + j + "/" + i, data[i], out[i]);
        }
    }
}
 
源代码26 项目: cxf   文件: IntegrationBaseTest.java
protected Representation getRepresentation(String content) throws XMLStreamException {
    Document doc = null;
    doc = StaxUtils.read(new StringReader(content));
    Representation representation = new Representation();
    representation.setAny(doc.getDocumentElement());
    return representation;
}
 
private void insertData(String tableName, int startIndex, int endIndex) throws SQLException{
  Connection connection = TestUtil.getConnection();
  PreparedStatement ps = connection.prepareStatement("INSERT INTO " + tableName + "(bigIntegerField, blobField, charField," +
      "charForBitData, clobField, dateField, decimalField, doubleField, floatField, longVarcharForBitDataField, numericField," +
      "realField, smallIntField, timeField, timestampField, varcharField, varcharForBitData, xmlField) values( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, xmlparse(document cast (? as clob) PRESERVE WHITESPACE))");
 
  for (int i = startIndex; i < endIndex; i++) {
    int lessThan10 = i % 10;

    ps.setLong(1, i); //BIG INT
    ps.setBlob(2,new ByteArrayInputStream(new byte[]{(byte)i,(byte)i,(byte)i,(byte)i}));
    ps.setString(3, ""+lessThan10);
    ps.setBytes(4, ("" + lessThan10).getBytes());
    ps.setClob(5, new StringReader("SOME CLOB " + i));
    ps.setDate(6, new Date(System.currentTimeMillis()));
    ps.setBigDecimal(7, new BigDecimal(lessThan10 + .8));
    ps.setDouble(8, i + .88);
    ps.setFloat(9, i + .9f);
    ps.setBytes(10, ("A" + lessThan10).getBytes());
    ps.setBigDecimal(11, new BigDecimal(i));
    ps.setFloat(12, lessThan10 * 1111);
    ps.setShort(13, (short)i);
    ps.setTime(14, new Time(System.currentTimeMillis()));
    ps.setTimestamp(15, new Timestamp(System.currentTimeMillis()));
    ps.setString(16, "HI" + lessThan10);
    ps.setBytes(17, ("" + lessThan10).getBytes());
    ps.setClob(18, new StringReader("<xml><sometag>SOME XML CLOB " + i + "</sometag></xml>"));
    ps.execute();
  }
}
 
源代码28 项目: tutorials   文件: JavaReaderToXUnitTest.java
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
    String initialString = "With Commons IO";
    final Reader initialReader = new StringReader(initialString);
    final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);

    String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
    assertThat(finalString, equalTo(initialString));

    initialReader.close();
    targetStream.close();
}
 
@Test
public void marshalAttachments() throws Exception {
	unmarshaller = new Jaxb2Marshaller();
	unmarshaller.setClassesToBeBound(BinaryObject.class);
	unmarshaller.setMtomEnabled(true);
	unmarshaller.afterPropertiesSet();
	MimeContainer mimeContainer = mock(MimeContainer.class);

	Resource logo = new ClassPathResource("spring-ws.png", getClass());
	DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));

	given(mimeContainer.isXopPackage()).willReturn(true);
	given(mimeContainer.getAttachment("<[email protected]://springframework.org/spring-ws>")).willReturn(dataHandler);
	given(mimeContainer.getAttachment("<[email protected]://springframework.org/spring-ws>")).willReturn(dataHandler);
	given(mimeContainer.getAttachment("[email protected]")).willReturn(dataHandler);
	String content = "<binaryObject xmlns='http://springframework.org/spring-ws'>" + "<bytes>" +
			"<xop:Include href='cid:[email protected]://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" +
			"</bytes>" + "<dataHandler>" +
			"<xop:Include href='cid:[email protected]://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" +
			"</dataHandler>" +
			"<swaDataHandler>[email protected]</swaDataHandler>" +
			"</binaryObject>";

	StringReader reader = new StringReader(content);
	Object result = unmarshaller.unmarshal(new StreamSource(reader), mimeContainer);
	assertTrue("Result is not a BinaryObject", result instanceof BinaryObject);
	BinaryObject object = (BinaryObject) result;
	assertNotNull("bytes property not set", object.getBytes());
	assertTrue("bytes property not set", object.getBytes().length > 0);
	assertNotNull("datahandler property not set", object.getSwaDataHandler());
}
 
源代码30 项目: freehealth-connector   文件: ConnectorXmlUtils.java
private static Document parseXmlFile(String in) {
   try {
      InputSource is = new InputSource(new StringReader(in));
      return getDocumentBuilder().parse(is);
   } catch (Exception var2) {
      throw new InstantiationException(var2);
   }
}