Java Code Examples for java.io.StringReader

The following examples show how to use java.io.StringReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: banking-swift-messages-java   Source File: SwiftBlockReaderTest.java    License: MIT License 6 votes vote down vote up
@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-");
}
 
Example 2
Source Project: birt   Source File: SPParameterPositionUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
		}
	}
}
 
Example 3
Source Project: Tomcat8-Source-Read   Source File: Request.java    License: MIT License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 4
Source Project: terracotta-platform   Source File: FileConfigStorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 5
Source Project: olat   Source File: SearchInputController.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source Project: banking-swift-messages-java   Source File: SwiftFieldReaderTest.java    License: MIT License 6 votes vote down vote up
@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);

}
 
Example 7
@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"));
}
 
Example 8
Source Project: lucene-solr   Source File: TestSuggestStopFilter.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 9
Source Project: android-oauth-client   Source File: GitHubRequest.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 10
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});
}
 
Example 11
Source Project: lucene-solr   Source File: TestXPathRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 12
Source Project: metacat   Source File: DirectSqlGetPartition.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 13
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) {
        }
    }
}
 
Example 14
Source Project: hipparchus   Source File: LongFrequencyTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 15
/**
 * 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;
  }
}
 
Example 16
Source Project: microprofile-jwt-auth   Source File: RequiredClaimsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 17
Source Project: ironjacamar   Source File: JCA10TestCase.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 18
@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"));
}
 
Example 19
@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());
}
 
Example 20
Source Project: netbeans   Source File: ConflictDescriptionParser.java    License: Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 21
@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();
}
 
Example 22
Source Project: rice   Source File: RuleRoutingAttribute.java    License: Educational Community License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 23
Source Project: big-c   Source File: TestHsWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 24
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);
}
 
Example 25
Source Project: j2objc   Source File: DataReadWriteTest.java    License: Apache License 2.0 5 votes vote down vote up
@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]);
        }
    }
}
 
Example 26
Source Project: cxf   Source File: IntegrationBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Source Project: gemfirexd-oss   Source File: GemFireXDDataExtractorDUnit.java    License: Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example 28
Source Project: tutorials   Source File: JavaReaderToXUnitTest.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 29
Source Project: spring-analysis-note   Source File: Jaxb2UnmarshallerTests.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 30
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);
   }
}