java.io.StringReader Java Examples

The following examples show how to use java.io.StringReader. 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 check out the related API usage on the sidebar.
Example #1
Source File: SwiftFieldReaderTest.java    From banking-swift-messages-java with 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 #2
Source File: FileConfigStorageTest.java    From terracotta-platform with 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 #3
Source File: ConflictDescriptionParser.java    From netbeans with 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 #4
Source File: TestHsWebServicesJobs.java    From big-c with 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 #5
Source File: SwiftBlockReaderTest.java    From banking-swift-messages-java with 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 #6
Source File: RuleRoutingAttribute.java    From rice with 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 #7
Source File: JavaReaderToXUnitTest.java    From tutorials with MIT License 6 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 #8
Source File: SPParameterPositionUtil.java    From birt with 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 #9
Source File: Jaxb2UnmarshallerTests.java    From spring-analysis-note with MIT License 6 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("<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>")).willReturn(dataHandler);
	given(mimeContainer.getAttachment("<99bd1592-0521-41a2-9688-a8bfb40192fb@http://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:6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" +
			"</bytes>" + "<dataHandler>" +
			"<xop:Include href='cid:99bd1592-0521-41a2-9688-a8bfb40192fb@http://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 #10
Source File: SearchInputController.java    From olat with 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 #11
Source File: JSFilterImplTest.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: Request.java    From Tomcat8-Source-Read with 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 #13
Source File: UnstemmedGermanNormalizationTests.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #14
Source File: GelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #15
Source File: JsonValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: ClaimValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: JCA10TestCase.java    From ironjacamar with 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
Source File: TestSuggestStopFilter.java    From lucene-solr with 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 #19
Source File: RequiredClaimsTest.java    From microprofile-jwt-auth with 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 #20
Source File: GitHubRequest.java    From android-oauth-client with 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 #21
Source File: UiBuilderTestHelper.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #22
Source File: WordDelimiterFilter2Tests.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #23
Source File: TestXPathRecordReader.java    From lucene-solr with 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 #24
Source File: LongFrequencyTest.java    From hipparchus with 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 #25
Source File: DirectSqlGetPartition.java    From metacat with 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 #26
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
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 #27
Source File: ActionLexer.java    From dacapobench with Apache License 2.0 5 votes vote down vote up
public ActionLexer( String s,
					RuleBlock currentRule,
					CodeGenerator generator,
					ActionTransInfo transInfo) {
	this(new StringReader(s));
	this.currentRule = currentRule;
	this.generator = generator;
	this.transInfo = transInfo;
}
 
Example #28
Source File: CsvParserTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testDSLMapToTuple6() throws IOException {
    Tuple6<String, String, String, String, String, String> tuple6 = CsvParser.mapTo(String.class, String.class, String.class,
            String.class, String.class, String.class)
            .defaultHeaders().iterator(new StringReader("value1,value2,value3,value4,value5,value6")).next();
    assertEquals("value1", tuple6.first());
    assertEquals("value2", tuple6.second());
    assertEquals("value3", tuple6.third());
    assertEquals("value4", tuple6.fourth());
    assertEquals("value5", tuple6.fifth());
    assertEquals("value6", tuple6.sixth());
}
 
Example #29
Source File: GsonParcer.java    From EventApp with Apache License 2.0 5 votes vote down vote up
private static <T> T decode(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));
    try {
        reader.beginObject();
        Class<?> type = Class.forName(reader.nextName());
        return gson.fromJson(reader, type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        reader.close();
    }
}
 
Example #30
Source File: ParallelTestRunner.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void compile() throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    final List<String> args = getCompilerArgs();
    int errors;
    try {
        errors = evaluateScript(out, err, args.toArray(new String[args.size()]));
    } catch (final AssertionError e) {
        final PrintWriter writer = new PrintWriter(err);
        e.printStackTrace(writer);
        writer.flush();
        errors = 1;
    }
    if (errors != 0 || checkCompilerMsg) {
        result.err = err.toString();
        if (expectCompileFailure || checkCompilerMsg) {
            final PrintStream outputDest = new PrintStream(new FileOutputStream(getErrorFileName()));
            TestHelper.dumpFile(outputDest, new StringReader(new String(err.toByteArray())));
            outputDest.println("--");
        }
        if (errors != 0 && !expectCompileFailure) {
            fail(String.format("%d errors compiling %s", errors, testFile));
        }
        if (checkCompilerMsg) {
            compare(getErrorFileName(), expectedFileName, true);
        }
    }
    if (expectCompileFailure && errors == 0) {
        fail(String.format("No errors encountered compiling negative test %s", testFile));
    }
}