@Test public void testBigContent() throws Exception { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 1000; i++) buffer.append("abcdefghijklmnopqrstuvwxyz"); WikiPageUtil.addPage(root, PathParser.parse("BigPage"), buffer.toString()); String content = root.getChildPage("BigPage").getData().getContent(); assertTrue(buffer.toString().equals(content)); }
@Test public void testServerShutdown3() throws Exception { final StringBuilder error = new StringBuilder(); Thread callThread = new Thread() { public void run() { try { EchoMessage message = EchoMessage.newBuilder().setMessage(MESSAGE).build(); stub.delay(null, message); } catch (Exception e) { error.append(e.getMessage()); } synchronized (error) { error.notifyAll(); } } }; callThread.start(); final CountDownLatch latch = new CountDownLatch(1); Thread shutdownThread = new Thread() { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } try { server.shutdown(); server = null; latch.countDown(); } catch (Throwable e) { e.printStackTrace(); } } }; shutdownThread.start(); assertTrue(latch.await(5 * 1000, TimeUnit.MILLISECONDS)); assertTrue(latch.getCount() == 0); synchronized (error) { error.wait(5 * 1000); } if (!error.toString().isEmpty()) { fail(error.toString()); } }
@Test @Category(com.absolute.util.helper.FastTest.class) public void test_cant_add_missing_media_to_policy() throws Exception { String[] policyIds = Helpers.getPolicyIdsForPolicyNames(logonCookie, Policies.STANDARD_POLICY_NAMES[0]); StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("\"contentIds\":["); sb.append("0],"); sb.append("\"policyAssignments\":[{"); sb.append("\"policyId\":\"" + policyIds[0] + "\","); sb.append("\"assignmentType\": 1,"); sb.append("\"availabilitySelector\": 2,"); sb.append("\"startTime\":\"2012-10-18T19:01:00Z\","); sb.append("\"endTime\":\"2012-10-19T20:12:00Z\""); sb.append("}]"); sb.append("}"); System.out.println("Request body=" + sb.toString()); Helpers.postJsonRequestGetResultCheckStatus( logonCookie, Helpers.WEBAPI_BASE_URL + POLICY_CONTENT_API, sb.toString(), HttpStatus.SC_BAD_REQUEST); }
public String bestmod(String s, int k) { String ret = s; StringBuilder sub = new StringBuilder(s); for (int i = 1, size = s.length(); i < size; ++i) { sub = new StringBuilder( sub.toString().substring(size - 1) + sub.toString().substring(0, size - 1)); StringBuilder sub2 = new StringBuilder(sub); int count = k; for (int j = 1; j <= sub2.length() && count > 0; ++j) { if (sub2.charAt(j - 1) != 'a') { sub2.setCharAt(j - 1, 'a'); --count; } } if (sub2.toString().compareTo(ret) < 0) { ret = sub2.toString(); } } return ret; }
/** * Asserts that the table contains the specified number of rows with field=>value pairs matching * the given map. * * @param tableName the table to interrogate. * @param values a map of field=>value of the expected values * @param expectedRows the number of rows we expect to match exactly * @throws SQLException */ public void assertTableContains( final String tableName, final Map<String, Object> values, final int expectedRows) throws SQLException { Connection conn = tester.getConnection(); // We will rebuild the values as a list so we can have guaranteed ordering List<Object> valueList = new ArrayList<Object>(); StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM \""); sql.append(tableName); sql.append("\" WHERE TRUE"); for (Entry<String, Object> field : values.entrySet()) { valueList.add(field.getValue()); sql.append(" AND \""); sql.append(field.getKey()); sql.append("\" = ?"); } sql.append(";"); PreparedStatement stmt = conn.prepareStatement(sql.toString()); for (int i = 0; i < valueList.size(); ++i) { stmt.setObject(i + 1, valueList.get(i)); } ResultSet rs = stmt.executeQuery(); rs.next(); assertEquals( "Expected query " + sql.toString() + " to return " + expectedRows, expectedRows, rs.getInt(1)); }
@Test public void testUpdateLookupParameter() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); Entry<String, String> entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.SPONSOR); Assert.assertNotNull(entry); String fieldConversions = entry.getValue(); StringBuilder builder = new StringBuilder(); builder.append("sponsorCode:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); String parameter = KRADConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL + KRADConstants.METHOD_TO_CALL_BOPARM_RIGHT_DEL + KRADConstants.METHOD_TO_CALL_PARM1_LEFT_DEL + KRADConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL; String updatedParam = protocolFundingSourceService.updateLookupParameter( parameter, Sponsor.class.getName(), fieldConversions); Assert.assertThat( updatedParam, JUnitMatchers.containsString( "(!!" + Sponsor.class.getName() + "!!)(((" + builder.toString() + ")))")); }
@Test public void testFormatAddressJumpLocal2() { labels.newInstruction( new AssemblyInstruction("", 99, "", "blah", Collections.<String>emptyList(), "", labels)); labels.newInstruction( new AssemblyInstruction( "anno", 65534, "mod", "jne", asList("0x0000000000000100"), "", labels)); labels.newInstruction( new AssemblyInstruction( "anno", 65535, "mod", "jne", asList("0x0000000000001000"), "", labels)); sb.setLength(0); labels.formatAddress(256, sb); assertEquals("0x0000000000000100", sb.toString()); sb.setLength(0); labels.formatAddress(4096, sb); assertEquals("0x0000000000001000", sb.toString()); labels.buildLabels(); sb.setLength(0); labels.formatAddress(256, sb); assertEquals(" L0000", sb.toString()); sb.setLength(0); labels.formatAddress(4096, sb); assertEquals(" L0001", sb.toString()); sb.setLength(0); labels.formatAddress(65535, sb); assertEquals("0x000000000000ffff", sb.toString()); }
@Test public void tstFrom2() { Wire wire = CSVWire.from( "Symbol,Company,Price,Change,ChangePercent,Day's Volume\n" + "III,3i Group,479.4,12,2.44,2387043\n" + "3IN,3i Infrastructure,164.7,0.1,0.06,429433\n" + "AA,AA,325.9,5.7,1.72,1469834\n"); StringBuilder row = new StringBuilder(); assertTrue(wire.hasMore()); wire.readEventName(row) .marshallable( w -> { assertEquals("III", row.toString()); wire.read(() -> "company") .text(this, (o, s) -> assertEquals("3i Group", s)) .read(() -> "price") .float64(this, (o, d) -> assertEquals(479.4, d, 0.0)) .read(() -> "change") .float64(this, (o, d) -> assertEquals(12, d, 0.0)) .read(() -> "changePercent") .float64(this, (o, d) -> assertEquals(2.44, d, 0.0)) .read(() -> "daysVolume") .int64(this, (o, d) -> assertEquals(2387043, d)); }); assertTrue(wire.hasMore()); wire.readEventName(row) .marshallable( w -> { assertEquals("3IN", row.toString()); wire.read(() -> "company") .text(this, (o, s) -> assertEquals("3i Infrastructure", s)) .read(() -> "price") .float64(this, (o, d) -> assertEquals(164.7, d, 0.0)) .read(() -> "change") .float64(this, (o, d) -> assertEquals(0.1, d, 0.0)) .read(() -> "changePercent") .float64(this, (o, d) -> assertEquals(0.06, d, 0.0)) .read(() -> "daysVolume") .int64(this, (o, d) -> assertEquals(429433, d)); }); assertTrue(wire.hasMore()); wire.readEventName(row) .marshallable( w -> { assertEquals("AA", row.toString()); wire.read(() -> "company") .text(this, (o, s) -> assertEquals("AA", s)) .read(() -> "price") .float64(this, (o, d) -> assertEquals(325.9, d, 0.0)) .read(() -> "change") .float64(this, (o, d) -> assertEquals(5.7, d, 0.0)) .read(() -> "changePercent") .float64(this, (o, d) -> assertEquals(1.72, d, 0.0)) .read(() -> "daysVolume") .int64(this, (o, d) -> assertEquals(1469834, d)); }); assertFalse(wire.hasMore()); }
@Test() public void testAppendToClause() { StringBuilder sb = new StringBuilder(); classUnderTest.appendToClause(sb); assertEquals(" WHERE myCol is null", sb.toString()); classUnderTest.appendToClause(sb); assertEquals(" WHERE myCol is null AND myCol is null", sb.toString()); }
@Test public void testGetLookupParameters() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); StringBuilder builder = new StringBuilder(); Entry<String, String> entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.SPONSOR); Assert.assertNotNull(entry); builder.append("sponsorCode:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.UNIT); Assert.assertNotNull(entry); builder.append("unitNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("unitName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.PROPOSAL_DEVELOPMENT); Assert.assertNotNull(entry); builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.INSTITUTIONAL_PROPOSAL); Assert.assertNotNull(entry); builder.append("proposalId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA); builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.AWARD); Assert.assertNotNull(entry); builder.append("awardId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA); builder.append("awardNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); try { entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.OTHER); fail("IllegalArgumentException was not thrown for invalid test case using OTHER"); } catch (IllegalArgumentException e) { // yup } }
@Test public void testEncodeWithPercent() { StringBuilder buf = new StringBuilder(); RFC2231.percentEscape(buf, "foo"); assertEquals("foo", buf.toString()); buf.setLength(0); RFC2231.percentEscape(buf, "foo bar"); assertEquals("foo%20bar", buf.toString()); buf.setLength(0); RFC2231.percentEscape(buf, "R\u00e9sultat d'Activit\u00e9 (;provisoire/draft)."); assertEquals("R%C3%A9sultat%20d%27Activit%C3%A9%20%28%3Bprovisoire/draft%29.", buf.toString()); }
@Test public void alltest() { String kor = ""; // "봯"; // "봀봁봂봃봄봅봆봇봈봉봊봋봌봍봎봏"; // "봐봑봒봓봔봕봖봗봘봙봚봛봜봝봞봟"; // "봠봡봢봣봤봥봦봧봨봩봪봫봬봭봮봯"; // "봰봱봲봳봴봵봶봷봸봹봺봻봼봽봾봿"; // "뵀뵁뵂뵃뵄뵅뵆뵇뵈뵉뵊뵋뵌뵍뵎뵏"; // "뵐뵑뵒뵓뵔뵕뵖뵗뵘뵙뵚뵛뵜뵝뵞뵟"; // "뵠뵡뵢뵣뵤뵥뵦뵧뵨뵩뵪뵫뵬뵭뵮뵯"; // "뵰뵱뵲뵳뵴뵵뵶뵷뵸뵹뵺뵻뵼뵽뵾뵿"; // "부북붂붃분붅붆붇불붉붊붋붌붍붎붏"; // "붐붑붒붓붔붕붖붗붘붙붚붛붜붝붞붟"; // "붠붡붢붣붤붥붦붧붨붩붪붫붬붭붮붯"; // "붰붱붲붳붴붵붶붷붸붹붺붻붼붽붾붿"; // "뷀뷁뷂뷃뷄뷅뷆뷇뷈뷉뷊뷋뷌뷍뷎뷏"; // "뷐뷑뷒뷓뷔뷕뷖뷗뷘뷙뷚뷛뷜뷝뷞뷟"; // "뷠뷡뷢뷣뷤뷥뷦뷧뷨뷩뷪뷫뷬뷭뷮뷯"; // "뷰뷱뷲뷳뷴뷵뷶뷷뷸뷹뷺뷻뷼뷽뷾뷿"; // "븀븁븂븃븄븅븆븇븈븉븊븋브븍븎븏"; // "븐븑븒븓블븕븖븗븘븙븚븛븜븝븞븟"; // "븠븡븢븣븤븥븦븧븨븩븪븫븬븭븮븯"; // "디스플레이 관리자의 향상된 기능을 통해 화면을 조정하고 어플리케이션 사이를 전환하는 데 소요되는 시간을 줄일 수 있습니다. 이 소프트웨어 어플리케이션은 스마트 비디오 // 향상, "; // String kor = "가나다라마바사아자차카타파하"; // String kor = "가하"; Vector<String> korVector = new Vector<String>(); StringBuilder sb = new StringBuilder(); for (int i = '가', j = 1; i < '힣'; i++, j++) { sb.append((char) i); if ((j % 1000) == 0) { korVector.add(sb.toString()); sb = new StringBuilder(); } } korVector.add(sb.toString()); for (int i = 0; i < korVector.size(); i++) { kor = korVector.get(i); String eng = Han2Eng.convert(kor); String rev = Eng2Han.convert(eng); if (kor.equals(rev) == false) { System.out.println("kor :" + kor); System.out.println("eng :" + eng); System.out.println("rev :" + rev); break; } assertTrue(kor.equals(rev)); } System.out.println("alltest Complete"); }
/* This is a copy of buildDeterministicValue() from core:com.yahoo.ycsb.workloads.CoreWorkload.java. That method is neither public nor static so we need a copy. */ private String buildDeterministicValue(String key, String fieldkey) { int size = FIELD_LENGTH; StringBuilder sb = new StringBuilder(size); sb.append(key); sb.append(':'); sb.append(fieldkey); while (sb.length() < size) { sb.append(':'); sb.append(sb.toString().hashCode()); } sb.setLength(size); return sb.toString(); }
@Test public void testTrimTrailingZeros() throws Exception { StringBuilder sb1 = new StringBuilder("1.1200"); DateTimeUtil.trimTrailingZeros(sb1); assertEquals("1.12", sb1.toString()); StringBuilder sb2 = new StringBuilder("1.12000120"); DateTimeUtil.trimTrailingZeros(sb2); assertEquals("1.1200012", sb2.toString()); StringBuilder sb3 = new StringBuilder(".12000120"); DateTimeUtil.trimTrailingZeros(sb3); assertEquals(".1200012", sb3.toString()); }
private String ReadFileToString(String filePath) throws FileNotFoundException { StringBuilder fileDataBuilder = new StringBuilder(); Scanner scanner = new Scanner(new FileInputStream(filePath)); String NL = System.getProperty("line.separator"); while (scanner.hasNextLine()) { fileDataBuilder.append(scanner.nextLine() + NL); } String fileData = fileDataBuilder.toString(); return fileDataBuilder.toString(); }
@Test public void testFormatAddressNotJump2() { labels.newInstruction( new AssemblyInstruction("anno", 65535, "mod", "jjj", asList("1", "2"), "", labels)); sb.setLength(0); labels.formatAddress(65535, sb); assertEquals("0x000000000000ffff", sb.toString()); labels.buildLabels(); sb.setLength(0); labels.formatAddress(65535, sb); assertEquals("0x000000000000ffff", sb.toString()); }
@Test public void testToXmlNoNullsTwoArgs() { List<CommandArgument<?>> args = new ArrayList<CommandArgument<?>>(); args.add(CommandArgument.newCommandArgument("arg1", Type.INTEGER, 10)); args.add(CommandArgument.newCommandArgument("arg2", Type.PERCENT, "50%")); subject = new ClientCommandMessage(parameters, 0, "command", 0, args); StringBuilder builder = new StringBuilder(); try { subject.toXml(builder, 0); } catch (XmlFormatException e) { fail(e.getMessage()); } String expected = "content-type:command-client\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<message >\n" + "\t<parameters >\n" + "\t\t<parameter name=\"version\" value=\"0.0\" />\n" + "\t\t<parameter name=\"session-key\" value=\"\" />\n" + "\t</parameters>\n" + "\t<content >\n" + "\t\t<command node-id=\"0\" name=\"command\" command-id=\"0\" >\n" + "\t\t\t<argument name=\"arg1\" type=\"integer\" value=\"10\" />\n" + "\t\t\t<argument name=\"arg2\" type=\"percent\" value=\"50.0%\" />\n" + "\t\t</command>\n" + "\t</content>\n" + "</message>\n"; String actual = builder.toString(); assertEquals(expected, actual); }
@Test public void testToXmlNoNullsNoArgs() { List<CommandArgument<?>> args = new ArrayList<CommandArgument<?>>(); subject = new ClientCommandMessage(parameters, 0, "command", 0, args); StringBuilder builder = new StringBuilder(); try { subject.toXml(builder, 0); } catch (XmlFormatException e) { fail(e.getMessage()); } String expected = "content-type:command-client\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<message >\n" + "\t<parameters >\n" + "\t\t<parameter name=\"version\" value=\"0.0\" />\n" + "\t\t<parameter name=\"session-key\" value=\"\" />\n" + "\t</parameters>\n" + "\t<content >\n" + "\t\t<command node-id=\"0\" name=\"command\" command-id=\"0\" />\n" + "\t</content>\n" + "</message>\n"; String actual = builder.toString(); assertEquals(expected, actual); }
private KieBase createKnowledgeBase() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "memory/BPMN2-RuleTaskWithInsertProcessInstance.bpmn2"), ResourceType.BPMN2); kbuilder.add( ResourceFactory.newClassPathResource("memory/ProcessInstanceRule.drl"), ResourceType.DRL); if (!kbuilder.getErrors().isEmpty()) { Iterator<KnowledgeBuilderError> errIter = kbuilder.getErrors().iterator(); while (errIter.hasNext()) { KnowledgeBuilderError err = errIter.next(); StringBuilder lines = new StringBuilder(""); if (err.getLines().length > 0) { lines.append(err.getLines()[0]); for (int i = 1; i < err.getLines().length; ++i) { lines.append(", " + err.getLines()[i]); } } logger.warn(err.getMessage() + " (" + lines.toString() + ")"); } throw new IllegalArgumentException("Errors while parsing knowledge base"); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); return kbase; }
@Test public void testShuffled() { for (Integer[] perm : perms) { Group group = new Group("group"); for (Integer i : perm) { Item item = new Item(group, i); group.add(item); } Queueable[] elems = group.getQueue(); for (Queueable elem : elems) { Item item = (Item) elem; // System.out.print( " " + item.getSalience() + "/" + item.getActivationNumber() + // "/" + item.getIndex() ); if (item.getIndex() % 2 == 0) { group.remove(item); group.add(item); } } boolean ok = true; StringBuilder sb = new StringBuilder("queue:"); for (int i = max - 1; i >= 0; i--) { int sal = group.getNext().getSalience(); sb.append(" ").append(sal); if (sal != i) ok = false; } assertTrue("incorrect order in " + sb.toString(), ok); // System.out.println( sb.toString() ); } }
/** * A convenience method for performing KeyValue existence/nonexistence tests. * * @param expectedKeys The expected KeyValue keys. * @param actualKeys The actual KeyValue keys. * @throws Exception */ private void assertRuleTemplateHasExpectedKeyValues( Set<String> expectedKeys, Set<String> actualKeys) throws Exception { // Check to see if all required keys are in the set. for (Iterator<String> iterator = expectedKeys.iterator(); iterator.hasNext(); ) { final String expKey = iterator.next(); assertTrue( "The key label pair with a key of '" + expKey + "' should have been true.", actualKeys.contains(expKey)); actualKeys.remove(expKey); } // If any keys are still in the list, then fail the test because we expected their equivalent // rule template options to // have a non-true value. if (!actualKeys.isEmpty()) { // Construct the error message. final String pluralStr = (actualKeys.size() != 1) ? "s" : ""; final StringBuilder errMsg = new StringBuilder(); errMsg .append("The key label pair") .append(pluralStr) .append(" with the key") .append(pluralStr) .append(" of "); for (Iterator<String> iterator = actualKeys.iterator(); iterator.hasNext(); ) { errMsg.append("'").append(iterator.next()).append(iterator.hasNext() ? "', " : "' "); } errMsg.append("should have been false."); // Fail the test. fail(errMsg.toString()); } }
@Test public void reduceForJavaApiMustWork() throws Exception { LinkedList<Future<String>> listFutures = new LinkedList<Future<String>>(); StringBuilder expected = new StringBuilder(); for (int i = 0; i < 10; i++) { expected.append("test"); listFutures.add( Futures.future( new Callable<String>() { public String call() { return "test"; } }, system.dispatcher())); } Future<String> result = Futures.reduce( listFutures, new Function2<String, String, String>() { public String apply(String r, String t) { return r + t; } }, system.dispatcher()); assertEquals(Await.result(result, timeout), expected.toString()); }
private static String setupDatasetWithServiceNameAttribute() { StringBuilder sb = new StringBuilder() .append("<dataset name='ds1' ID='DS1' urlPath='dir/file1.nc' serviceName='odap' />"); return CatalogXmlUtils.wrapThreddsXmlInCatalogWithCompoundService( sb.toString(), null, null, null); }
private String tokenizerToString(Tokenizer tokenizer) throws Exception { OffsetAttribute extOffset = tokenizer.addAttribute(OffsetAttribute.class); PositionIncrementAttribute posIncrAtt = tokenizer.addAttribute(PositionIncrementAttribute.class); PositionLengthAttribute posLengthAtt = tokenizer.addAttribute(PositionLengthAttribute.class); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); TypeAttribute type = tokenizer.addAttribute(TypeAttribute.class); SemanticClassAttribute semanticClass = tokenizer.addAttribute(SemanticClassAttribute.class); PartOfSpeechAttribute pos = tokenizer.addAttribute(PartOfSpeechAttribute.class); StringBuilder result = new StringBuilder(); tokenizer.reset(); while (tokenizer.incrementToken() == true) { result.append(new String(term.buffer(), 0, term.length())).append(":"); result.append(type.type()).append(":"); result.append(pos.partOfSpeech()).append(":"); result.append(semanticClass.semanticClass()).append(":"); result.append(String.valueOf(posIncrAtt.getPositionIncrement())).append(":"); result.append(String.valueOf(posLengthAtt.getPositionLength())).append(":"); result.append(String.valueOf(extOffset.startOffset())).append(":"); result.append(String.valueOf(extOffset.endOffset())); result.append(","); } tokenizer.end(); return result.toString(); }
void prepareQueries(File google, File yandex) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("url: http://google.com\n"); sb.append("method: GET\n"); sb.append("cookie: name=value\n"); sb.append("param: name=value\n"); IOUtil.saveString(sb.toString(), google); sb.setLength(0); sb.append("url: http://yandex.ru\n"); sb.append("method: GET\n"); sb.append("cookie: name=value\n"); sb.append("param: name=value\n"); IOUtil.saveString(sb.toString(), yandex); }
/** Test the custom pattern */ @Test public void testCustomPattern() { final List<PatternFormatter> formatters = parser.parse(customPattern); assertNotNull(formatters); final Map<String, String> mdc = new HashMap<>(); mdc.put("loginId", "Fred"); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final Log4jLogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setMarker(MarkerManager.getMarker("TEST")) // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setContextMap(mdc) // .setThreadName("Thread1") // .setSource(elements[0]) .setTimeMillis(System.currentTimeMillis()) .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = "INFO [PatternParserTest :100 ] - Hello, world" + Strings.LINE_SEPARATOR; assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); }
private String generateOperation() { StringBuilder operation = new StringBuilder(); Random generator = new Random(new Date().getTime()); int operationName = (generator.nextInt(20)) % 2; int firstParam = generator.nextInt(10); int secondParam = generator.nextInt(10); int result = 0; switch (operationName) { case 0: operation.append("add("); result = firstParam + secondParam; break; case 1: operation.append("sub("); result = firstParam - secondParam; break; default:; } operation.append(firstParam + "," + secondParam + ")=" + result); return operation.toString(); }
@Test public void testBadPattern() { final Calendar cal = Calendar.getInstance(); cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 789); final long timestamp = cal.getTimeInMillis(); final List<PatternFormatter> formatters = parser.parse(badPattern); assertNotNull(formatters); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("a.b.c") // .setLoggerFqcn(Logger.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setSource(elements[0]) // .setTimeMillis(timestamp) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); // eats all characters until the closing '}' character final String expected = "[2001-02-03 04:05:06,789] - Hello, world"; assertTrue( "Expected to start with: " + expected + ". Actual: " + str, str.startsWith(expected)); }
private void testNestedPatternHighlight(final Level level, final String expectedStart) { final List<PatternFormatter> formatters = parser.parse(nestedPatternHighlight); assertNotNull(formatters); final Throwable t = new Throwable(); t.getStackTrace(); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("org.apache.logging.log4j.PatternParserTest") // .setMarker(MarkerManager.getMarker("TEST")) // .setLoggerFqcn(Logger.class.getName()) // .setLevel(level) // .setMessage(new SimpleMessage("Hello, world")) // .setThreadName("Thread1") // .setSource(/*stackTraceElement[0]*/ null) // .setTimeMillis(System.currentTimeMillis()) // .build(); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expectedEnd = String.format("] %-5s: Hello, world%s\u001B[m", level, Strings.LINE_SEPARATOR); assertTrue( "Expected to start with: " + expectedStart + ". Actual: " + str, str.startsWith(expectedStart)); assertTrue( "Expected to end with: \"" + expectedEnd + "\". Actual: \"" + str, str.endsWith(expectedEnd)); }
@Test public void testFrom() throws Exception { Wire wire = CSVWire.from( "heading1, heading2,heading3\n" + "data1, data2, \"data three\"\n" + "row2, row2b, row2c\n"); assertTrue(wire.hasMore()); StringBuilder row = new StringBuilder(); wire.readEventName(row) .marshallable( w -> { assertEquals("data1", row.toString()); wire.read(() -> "heading2") .text(this, (o, s) -> assertEquals("data2", s)) .read(() -> "heading3") .text(this, (o, s) -> assertEquals("data three", s)); }); assertTrue(wire.hasMore()); wire.readEventName(row) .marshallable( w -> { assertEquals("row2", row.toString()); wire.read(() -> "heading2") .text(this, (o, s) -> assertEquals("row2b", s)) .read(() -> "heading3") .text(this, (o, s) -> assertEquals("row2c", s)); }); assertFalse(wire.hasMore()); }