예제 #1
1
 @Override
 public String getHeaderField(final String field) {
   final List<String> values = headers.get(field);
   final StringBuilder sb = new StringBuilder();
   for (final String v : values) sb.append(v).append(';');
   return sb.substring(0, sb.length() - 1);
 }
예제 #2
0
  /* This file and method are generated by TestGenerator, any edits will be overwritten by the next generation. */
  @Test
  public void testToLeftWithVaryingPredicate() throws Exception {
    mkdir(tmpdir);

    StringBuilder grammarBuilder = new StringBuilder(228);
    grammarBuilder.append("grammar T;\n");
    grammarBuilder.append("@members {i = 0}\n");
    grammarBuilder.append("s : ({self.i += 1\n");
    grammarBuilder.append("print(\"i=\" + str(self.i))} a)+ ;\n");
    grammarBuilder.append("a : {self.i % 2 == 0}? ID {print(\"alt 1\")}\n");
    grammarBuilder.append("  | {self.i % 2 != 0}? ID {print(\"alt 2\")}\n");
    grammarBuilder.append("  ;\n");
    grammarBuilder.append("ID : 'a'..'z'+ ;\n");
    grammarBuilder.append("INT : '0'..'9'+;\n");
    grammarBuilder.append("WS : (' '|'\\n') -> skip ;");
    String grammar = grammarBuilder.toString();

    String input = "x x y";
    String found =
        execParser(
            "T.g4", grammar, "TParser", "TLexer", "TListener", "TVisitor", "s", input, false);

    assertEquals("i=1\n" + "alt 2\n" + "i=2\n" + "alt 1\n" + "i=3\n" + "alt 2\n", found);
    assertNull(this.stderrDuringParse);
  }
예제 #3
0
  /* This file and method are generated by TestGenerator, any edits will be overwritten by the next generation. */
  @Test
  public void testPredicateDependentOnArg2() throws Exception {
    mkdir(tmpdir);

    StringBuilder grammarBuilder = new StringBuilder(149);
    grammarBuilder.append("grammar T;\n");
    grammarBuilder.append("@members {i = 0}\n");
    grammarBuilder.append("s : a[2] a[1];\n");
    grammarBuilder.append("a[int i]\n");
    grammarBuilder.append("  : {$i==1}? ID \n");
    grammarBuilder.append("  | {$i==2}? ID \n");
    grammarBuilder.append("  ;\n");
    grammarBuilder.append("ID : 'a'..'z'+ ;\n");
    grammarBuilder.append("INT : '0'..'9'+;\n");
    grammarBuilder.append("WS : (' '|'\\n') -> skip ;");
    String grammar = grammarBuilder.toString();

    String input = "a b";
    String found =
        execParser(
            "T.g4", grammar, "TParser", "TLexer", "TListener", "TVisitor", "s", input, false);

    assertEquals("", found);
    assertNull(this.stderrDuringParse);
  }
 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);
 }
예제 #5
0
 @Test
 public void maxLength() {
   StringBuilder body = new StringBuilder();
   for (int i = 0; i < 1100; i++) {
     body.append("1234567890");
   }
   assertThat(
       status(
           callWithStringBody(
               new MockJavaAction() {
                 // #max-length
                 // Accept only 10KB of data.
                 @BodyParser.Of(value = BodyParser.Text.class, maxLength = 10 * 1024)
                 public Result index() {
                   if (request().body().isMaxSizeExceeded()) {
                     return badRequest("Too much data!");
                   } else {
                     return ok("Got body: " + request().body().asText());
                   }
                 }
                 // #max-length
               },
               fakeRequest(),
               body.toString())),
       equalTo(400));
 }
예제 #6
0
  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;
  }
 /**
  * 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 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() );
    }
  }
 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));
 }
예제 #10
0
  @Test
  public void testEmptyModel() {
    final HasImports model =
        new HasImports() {

          private Imports imports = new Imports();

          @Override
          public Imports getImports() {
            return imports;
          }

          @Override
          public void setImports(final Imports imports) {
            // Nothing to do here
          }
        };

    final StringBuilder sb = new StringBuilder();
    ImportsWriter.write(sb, model);

    final String drl = sb.toString();
    assertNotNull(drl);

    assertTrue(drl.isEmpty());
  }
  @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() + ")))"));
  }
예제 #12
0
 /** 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));
 }
예제 #13
0
  @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());
  }
예제 #14
0
  @Test // (timeout=2000)
  public void testGetNextWord() {
    List<String> expected = Arrays.asList("word1", "word2", "word3", "word4");
    List<String> actual = new ArrayList<String>();

    String text =
        "\t"
            + expected.get(0)
            + "  "
            + expected.get(1)
            + " \n\n"
            + expected.get(2)
            + "\n \t"
            + expected.get(3)
            + "\n";

    int index = 0;
    StringBuilder str = new StringBuilder();

    while ((index = MiscUtils.getNextWord(text, index, str, "\\s")) < text.length()) {
      // index = ItecoUtil.getNextWord(text, index, str, "\\s");
      String word = str.toString();
      index += word.length();
      actual.add(word);
      str = new StringBuilder();
    }

    assertEquals(expected, actual);
  }
예제 #15
0
  /** Backward compatibility test. */
  @Test
  public void testLatin1() {
    CodeFunctions functions = CodeFunctions.createEncoderForLBL("latin1");
    assertEquals("code page", 1252, functions.getCodepage());
    assertEquals("encoding type", 9, functions.getEncodingType());

    StringBuilder sb = new StringBuilder();
    for (char c = 1; c < 256; c++) {
      sb.append(c);
    }

    CharacterEncoder encoder = functions.getEncoder();
    EncodedText text = encoder.encodeText(sb.toString());

    // This encoder appends a null byte.
    assertEquals("length of encoded text", 256, text.getLength());

    for (int i = 1; i < 256; i++) {
      // The following characters do not display on my GPS.  This covers
      // the region where windows-1252 differs from iso 8859 so we don't
      // really know which it is meant to be.
      if (i >= 0x80 && i <= 0xbf) continue;
      assertEquals("character", i, text.getCtext()[i - 1] & 0xff);
    }
  }
 public static String reverseString(String input) {
   StringBuilder backwards = new StringBuilder();
   for (int i = 0; i < input.length(); i++) {
     backwards.append(input.charAt(input.length() - 1 - i));
   }
   return backwards.toString();
 }
예제 #17
0
 @Test
 public void testInstance() throws Exception {
   String path = "src/test/resources/prettyprint/instance/let/";
   StringBuilder sb = TestUtil.translate(path + "InstanceLet.tla");
   String expected = TestUtil.fileToString(path + "InstanceLet.mch");
   assertEquals(TestUtil.getTreeAsString(expected), TestUtil.getTreeAsString(sb.toString()));
 }
 @Test
 public void testToXml() {
   subject = new ServerPingMessage(parameters);
   StringBuilder builder = new StringBuilder();
   try {
     subject.toXml(builder, 0);
   } catch (XmlFormatException e) {
     fail(e.getMessage());
   }
   String expected =
       "content-type:ping\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-valid\" value=\"true\" />\n"
           + "\t\t<parameter name=\"session-key\" value=\"session\" />\n"
           + "\t</parameters>\n"
           + "\t<content >\n"
           + "\t\t<ping />\n"
           + "\t</content>\n"
           + "</message>\n";
   String actual = builder.toString();
   assertEquals(expected, actual);
 }
예제 #19
0
  @Test
  public void testSingleImportModel() {
    final String expectedDrl = "import java.lang.String;\n\n";

    final HasImports model =
        new HasImports() {

          private Imports imports = new Imports();

          {
            imports.addImport(new Import("java.lang.String"));
          }

          @Override
          public Imports getImports() {
            return imports;
          }

          @Override
          public void setImports(final Imports imports) {
            // Nothing to do here
          }
        };

    final StringBuilder sb = new StringBuilder();
    ImportsWriter.write(sb, model);

    final String drl = sb.toString();
    assertNotNull(drl);

    assertEquals(expectedDrl, drl);
  }
 @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);
 }
예제 #21
0
  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 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);
 }
예제 #23
0
  public static String simulateFormPostForTR(
      BraintreeGateway gateway, Request trParams, Request request, String postUrl) {
    String response = "";
    try {
      String trData = gateway.transparentRedirect().trData(trParams, "http://example.com");
      StringBuilder postData =
          new StringBuilder("tr_data=")
              .append(URLEncoder.encode(trData, "UTF-8"))
              .append("&")
              .append(request.toQueryString());

      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setInstanceFollowRedirects(false);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.addRequestProperty("Accept", "application/xml");
      connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.getOutputStream().write(postData.toString().getBytes("UTF-8"));
      connection.getOutputStream().close();
      if (connection.getResponseCode() == 422) {
        connection.getErrorStream();
      } else {
        connection.getInputStream();
      }

      response = new URL(connection.getHeaderField("Location")).getQuery();
    } catch (IOException e) {
      throw new UnexpectedException(e.getMessage());
    }

    return response;
  }
예제 #24
0
  @Test
  public void testTweetNotWorks() throws Exception {
    reset(blockingIOProcessor);

    clientPair.hardwareClient.send("tweet");
    verify(clientPair.hardwareClient.responseMock, timeout(500))
        .channelRead(any(), eq(new ResponseMessage(1, NOTIFICATION_INVALID_BODY_EXCEPTION)));

    clientPair.hardwareClient.send("tweet ");
    verify(clientPair.hardwareClient.responseMock, timeout(500))
        .channelRead(any(), eq(new ResponseMessage(2, NOTIFICATION_INVALID_BODY_EXCEPTION)));

    StringBuilder a = new StringBuilder();
    for (int i = 0; i < 141; i++) {
      a.append("a");
    }

    clientPair.hardwareClient.send("tweet " + a);
    verify(clientPair.hardwareClient.responseMock, timeout(500))
        .channelRead(any(), eq(new ResponseMessage(3, NOTIFICATION_INVALID_BODY_EXCEPTION)));

    clientPair.appClient.send("deactivate 1");
    verify(clientPair.appClient.responseMock, timeout(500))
        .channelRead(any(), eq(new ResponseMessage(1, OK)));

    clientPair.hardwareClient.send("tweet yo");
    verify(clientPair.hardwareClient.responseMock, timeout(500))
        .channelRead(any(), eq(new ResponseMessage(4, NOTIFICATION_NOT_AUTHORIZED_EXCEPTION)));
  }
예제 #25
0
  @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());
  }
예제 #26
0
  @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));
  }
예제 #27
0
 @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());
 }
 private String protoToString(List<Protos.Key> keys) {
   StringBuilder sb = new StringBuilder();
   for (Protos.Key key : keys) {
     sb.append(key.toString());
     sb.append("\n");
   }
   return sb.toString().trim();
 }
예제 #29
0
 @Override
 public String toString() {
   final StringBuilder sb = new StringBuilder("TestMessage{");
   sb.append("publisher=").append(publisher);
   sb.append(", data='").append(data).append('\'');
   sb.append('}');
   return sb.toString();
 }
예제 #30
-1
 @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());
 }