@Test public void shouldMapWithCustomizedClassMapBuilder() { // given MapperFactory mapperFactory = new DefaultMapperFactory.Builder() .classMapBuilderFactory(new ScoringClassMapBuilder.Factory()) .build(); mapperFactory.classMap(Source.class, Destination.class).byDefault().register(); MapperFacade mapperFacade = mapperFactory.getMapperFacade(); Source src = new Source(); src.firstName = "Jan"; src.postalAddress = new PostalAddress(); src.postalAddress.country = new Country(); src.postalAddress.country.alphaCode = "PL"; // when Destination result = mapperFacade.map(src, Destination.class); // then assertThat(result.name.first).isEqualTo("Jan"); assertThat(result.countryCode).isEqualTo("PL"); }
/** * Returns a string representation of this object useful for debugging purposes. * * <p>The output includes details of all the {@link #getRegisteredOutputSegments() registered * output segments}. * * @return a string representation of this object useful for debugging purposes. */ public String getDebugInfo() { StringBuffer sb = new StringBuffer(); for (Iterator i = getRegisteredOutputSegments().iterator(); i.hasNext(); ) { OutputSegment outputSegment = (OutputSegment) i.next(); if (outputSegment instanceof BlankOutputSegment) sb.append("Replace with Spaces: "); else if (outputSegment instanceof RemoveOutputSegment) sb.append("Remove: "); else sb.append("Replace: "); if (sourceText instanceof Source) { Source source = (Source) sourceText; sb.append('('); source.getRowColumnVector(outputSegment.getBegin()).appendTo(sb); sb.append('-'); source.getRowColumnVector(outputSegment.getEnd()).appendTo(sb); sb.append(')'); } else { sb.append("(p") .append(outputSegment.getBegin()) .append("-p") .append(outputSegment.getEnd()) .append(')'); } sb.append(' '); String outputFromSegment = outputSegment.toString(); if (outputFromSegment.length() <= 20) { sb.append(outputFromSegment); } else { sb.append(outputFromSegment.substring(0, 20)).append("..."); } sb.append(Config.NewLine); } return sb.toString(); }
@Test public void mustBeAbleToRecover() throws Exception { final ManualProbe<Integer> publisherProbe = TestPublisher.manualProbe(true, system); final JavaTestKit probe = new JavaTestKit(system); final Source<Integer, NotUsed> source = Source.fromPublisher(publisherProbe) .map( elem -> { if (elem == 1) throw new RuntimeException("ex"); else return elem; }) .recover(new PFBuilder<Throwable, Integer>().matchAny(ex -> 0).build()); final CompletionStage<Done> future = source.runWith( Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription<Integer> s = publisherProbe.expectSubscription(); s.sendNext(0); probe.expectMsgEquals(0); s.sendNext(1); probe.expectMsgEquals(0); future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS); }
/** Specify which classes are visible to the compiler through -classpath. */ public void setVisibleClasses(Map<String, Source> vs) { visibleSrcs = new HashSet<>(); for (String s : vs.keySet()) { Source src = vs.get(s); visibleSrcs.add(src.file().toURI()); } }
/** * Method removes a Spring bean definition from the XML application context file. Bean definition * is identified by its id or bean name. * * @param project * @param id */ public void removeBeanDefinition(File configFile, Project project, String id) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_id", id); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
@Test public void mustBeAbleToUseZipWith() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Iterable<String> input1 = Arrays.asList("A", "B", "C"); final Iterable<String> input2 = Arrays.asList("D", "E", "F"); Source.from(input1) .zipWith( Source.from(input2), new Function2<String, String, String>() { public String apply(String s1, String s2) { return s1 + "-" + s2; } }) .runForeach( new Procedure<String>() { public void apply(String elem) { probe.getRef().tell(elem, ActorRef.noSender()); } }, materializer); probe.expectMsgEquals("A-D"); probe.expectMsgEquals("B-E"); probe.expectMsgEquals("C-F"); }
@Test public void mustProduceTicks() throws Exception { final JavaTestKit probe = new JavaTestKit(system); Source<String, Cancellable> tickSource = Source.tick( FiniteDuration.create(1, TimeUnit.SECONDS), FiniteDuration.create(500, TimeUnit.MILLISECONDS), "tick"); @SuppressWarnings("unused") Cancellable cancellable = tickSource .to( Sink.foreach( new Procedure<String>() { public void apply(String elem) { probe.getRef().tell(elem, ActorRef.noSender()); } })) .run(materializer); probe.expectNoMsg(FiniteDuration.create(600, TimeUnit.MILLISECONDS)); probe.expectMsgEquals("tick"); probe.expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS)); probe.expectMsgEquals("tick"); probe.expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS)); }
/** * Method adds a new Spring bean definition to the XML application context file. * * @param project * @param jaxbElement */ public void addBeanDefinition(File configFile, Project project, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream()); xsltSource.setSystemId("add-bean"); xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), configFile); return; } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
@Test public void mustBeAbleToUseFlatMapMerge() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Iterable<Integer> input1 = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); final Iterable<Integer> input2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19); final Iterable<Integer> input3 = Arrays.asList(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); final Iterable<Integer> input4 = Arrays.asList(30, 31, 32, 33, 34, 35, 36, 37, 38, 39); final List<Source<Integer, NotUsed>> mainInputs = new ArrayList<Source<Integer, NotUsed>>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); mainInputs.add(Source.from(input3)); mainInputs.add(Source.from(input4)); CompletionStage<List<Integer>> future = Source.from(mainInputs) .flatMapMerge(3, ConstantFun.<Source<Integer, NotUsed>>javaIdentityFunction()) .grouped(60) .runWith(Sink.<List<Integer>>head(), materializer); List<Integer> result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); final Set<Integer> set = new HashSet<Integer>(); for (Integer i : result) { set.add(i); } final Set<Integer> expected = new HashSet<Integer>(); for (int i = 0; i < 40; ++i) { expected.add(i); } assertEquals(expected, set); }
@Test public void mustWorkFromFuture() throws Exception { final Iterable<String> input = Arrays.asList("A", "B", "C"); CompletionStage<String> future1 = Source.from(input).runWith(Sink.<String>head(), materializer); CompletionStage<String> future2 = Source.fromCompletionStage(future1).runWith(Sink.<String>head(), materializer); String result = future2.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("A", result); }
private static String getMetaValue(Source source, String key) { for (int pos = 0; pos < source.length(); ) { StartTag startTag = source.getNextStartTag(pos, "name", key, false); if (startTag == null) return null; if (startTag.getName() == HTMLElementName.META) return startTag.getAttributeValue("content"); // Attribute values are automatically decoded pos = startTag.getEnd(); } return null; }
/** Store the source into the set of sources belonging to the given transform. */ private void addFileToTransform( Map<Transformer, Map<String, Set<URI>>> gs, Transformer t, Source s) { Map<String, Set<URI>> fs = gs.get(t); if (fs == null) { fs = new HashMap<>(); gs.put(t, fs); } Set<URI> ss = fs.get(s.pkg().name()); if (ss == null) { ss = new HashSet<>(); fs.put(s.pkg().name(), ss); } ss.add(s.file().toURI()); }
/** * Method updates existing Spring bean definitions in a XML application context file. Bean * definition is identified by its type defining class. * * @param project * @param type * @param jaxbElement */ public void updateBeanDefinitions( File configFile, Project project, Class<?> type, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/update-bean-type.xsl").getInputStream()); xsltSource.setSystemId("update-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); LSParser parser = XMLUtils.createLSParser(); GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null); parser.setFilter(getBeanFilter); for (File file : configFiles) { parser.parseURI(file.toURI().toString()); if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1") .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), file); return; } } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
@Test public void passwordDidntMatchError() { SignUpResultPage resultPage = signUpPage.signUp(correctName, password, incorrectConfirmPassword, "", correctEmail); Assert.assertEquals( Source.getValue("SignUpErrorPasswordDidntMatchError"), resultPage.getErrorText()); }
@Test public void mustBeAbleToUseVoidTypeInForeach() { final JavaTestKit probe = new JavaTestKit(system); final java.lang.Iterable<String> input = Arrays.asList("a", "b", "c"); Source<String, NotUsed> ints = Source.from(input); final CompletionStage<Done> completion = ints.runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); completion.thenAccept(elem -> probe.getRef().tell(String.valueOf(elem), ActorRef.noSender())); probe.expectMsgEquals("a"); probe.expectMsgEquals("b"); probe.expectMsgEquals("c"); probe.expectMsgEquals("Done"); }
public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) { this.context = context; log = Log.instance(context); source = Source.instance(context); diags = JCDiagnostic.Factory.instance(context); options = Options.instance(context); printProcessorInfo = options.isSet(XPRINTPROCESSORINFO); printRounds = options.isSet(XPRINTROUNDS); verbose = options.isSet(VERBOSE); lint = Lint.instance(context).isEnabled(PROCESSING); procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT); fatalErrors = options.isSet("fatalEnterError"); showResolveErrors = options.isSet("showResolveErrors"); werror = options.isSet(WERROR); platformAnnotations = initPlatformAnnotations(); foundTypeProcessors = false; // Initialize services before any processors are initialized // in case processors use them. filer = new JavacFiler(context); messager = new JavacMessager(context, this); elementUtils = JavacElements.instance(context); typeUtils = JavacTypes.instance(context); processorOptions = initProcessorOptions(context); unmatchedProcessorOptions = initUnmatchedProcessorOptions(); messages = JavacMessages.instance(context); initProcessorIterator(context, processors); }
@Test public void resolve() throws RuleBaseException, TransformException { final Node m1 = content.query().single("/id('m1')").node(); final Node m2 = content.query().single("/id('m2')").node(); final SortBlock mockBlock = mockery.mock(SortBlock.class); SortBlock block = new SortBlock( db.getFolder("/") .documents() .load( Name.create("rule"), Source.xml("<rule><sort by='ascending'>@foo</sort></rule>")) .root() .query() .single("*") .node()) { @Override void resolveOrder(Builder aModBuilder, Node node) throws TransformException { mockBlock.resolveOrder(aModBuilder, node); } @Override public Seg createSeg(Mod unused) { fail(); return null; } }; modBuilder = mockery.mock(Mod.Builder.class); mockery.checking( new Expectations() { { one(modBuilder).dependOn(m1.document()); one(modBuilder).dependOn(m2.document()); Sequence seq1 = mockery.sequence("pre-commit resolveOrder 1"); Sequence seq2 = mockery.sequence("pre-commit resolveOrder 2"); one(mockBlock).resolveOrder(modBuilder, m1); inSequence(seq1); one(mockBlock).resolveOrder(modBuilder, m2); inSequence(seq2); modBuilderPriors.add(seq1); modBuilderPriors.add(seq2); } }); block.requiredVariables = Arrays.asList(new QName[] {new QName(null, "a", null), new QName(null, "b", null)}); dependOnNearest( NodeTarget.class, false, new NodeTarget() { public ItemList targets() throws TransformException { return content.query().all("/id('m1 m2')"); } }); order("m1"); order("m2"); dependOnVariables(new QName(null, "a", null), new QName(null, "b", null)); thenCommit(); block.resolve(modBuilder); }
@Test public void nameIsTakenError() { String userName = getExistentName(); Assume.assumeThat(userName, CoreMatchers.notNullValue()); SignUpResultPage resultPage = signUpPage.signUp(userName, password, password, "", correctEmail); Assert.assertEquals(Source.getValue("SignUpErrorNameIsTakenError"), resultPage.getErrorText()); }
public void writeTo(final Writer writer) throws IOException { this.writer = writer; if (segment instanceof Source) ((Source) segment).fullSequentialParse(); nextTag = segment.source.findNextTag(segment.begin); index = segment.begin; writeContent(segment.end, segment.getChildElements(), 0); writer.flush(); }
@Test public void mustRepeat() throws Exception { final CompletionStage<List<Integer>> f = Source.repeat(42).grouped(10000).runWith(Sink.<List<Integer>>head(), materializer); final List<Integer> result = f.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(result.size(), 10000); for (Integer i : result) assertEquals(i, (Integer) 42); }
@Test public void mustBeAbleToUseToFuture() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Iterable<String> input = Arrays.asList("A", "B", "C"); CompletionStage<String> future = Source.from(input).runWith(Sink.<String>head(), materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("A", result); }
public void mustSuitablyOverrideAttributeHandlingMethods() { @SuppressWarnings("unused") final Source<Integer, NotUsed> f = Source.single(42) .withAttributes(Attributes.name("")) .addAttributes(Attributes.asyncBoundary()) .named(""); }
@Test public void mustWorkFromRange() throws Exception { CompletionStage<List<Integer>> f = Source.range(0, 10).grouped(20).runWith(Sink.<List<Integer>>head(), materializer); final List<Integer> result = f.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(11, result.size()); Integer counter = 0; for (Integer i : result) assertEquals(i, counter++); }
@Test public void mustBeAbleToUseMerge2() { final JavaTestKit probe = new JavaTestKit(system); final Iterable<String> input1 = Arrays.asList("A", "B", "C"); final Iterable<String> input2 = Arrays.asList("D", "E", "F"); Source.from(input1) .merge(Source.from(input2)) .runForeach( new Procedure<String>() { public void apply(String elem) { probe.getRef().tell(elem, ActorRef.noSender()); } }, materializer); probe.expectMsgAllOf("A", "B", "C", "D", "E", "F"); }
@Ignore("StatefulStage to be converted to GraphStage when Java Api is available (#18817)") @Test public void mustBeAbleToUseTransform() { final JavaTestKit probe = new JavaTestKit(system); final Iterable<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7); // duplicate each element, stop after 4 elements, and emit sum to the end Source.from(input) .transform( new Creator<Stage<Integer, Integer>>() { @Override public PushPullStage<Integer, Integer> create() throws Exception { return new StatefulStage<Integer, Integer>() { int sum = 0; int count = 0; @Override public StageState<Integer, Integer> initial() { return new StageState<Integer, Integer>() { @Override public SyncDirective onPush(Integer element, Context<Integer> ctx) { sum += element; count += 1; if (count == 4) { return emitAndFinish( Arrays.asList(element, element, sum).iterator(), ctx); } else { return emit(Arrays.asList(element, element).iterator(), ctx); } } }; } @Override public TerminationDirective onUpstreamFinish(Context<Integer> ctx) { return terminationEmit(Collections.singletonList(sum).iterator(), ctx); } }; } }) .runForeach( new Procedure<Integer>() { public void apply(Integer elem) { probe.getRef().tell(elem, ActorRef.noSender()); } }, materializer); probe.expectMsgEquals(0); probe.expectMsgEquals(0); probe.expectMsgEquals(1); probe.expectMsgEquals(1); probe.expectMsgEquals(2); probe.expectMsgEquals(2); probe.expectMsgEquals(3); probe.expectMsgEquals(3); probe.expectMsgEquals(6); }
@Test public void mustBeAbleToUseActorRefSource() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Source<Integer, ActorRef> actorRefSource = Source.actorRef(10, OverflowStrategy.fail()); final ActorRef ref = actorRefSource .to( Sink.foreach( new Procedure<Integer>() { public void apply(Integer elem) { probe.getRef().tell(elem, ActorRef.noSender()); } })) .run(materializer); ref.tell(1, ActorRef.noSender()); probe.expectMsgEquals(1); ref.tell(2, ActorRef.noSender()); probe.expectMsgEquals(2); }
public void demonstrateAGraphStageWithATimer() throws Exception { // tests: CompletionStage<Integer> result = Source.from(Arrays.asList(1, 2, 3)) .via(new TimedGate<>(Duration.create(2, "seconds"))) .takeWithin(Duration.create(250, "millis")) .runFold(0, (n, sum) -> n + sum, mat); assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); }
@Test public void demonstrateASimplerOneToManyStage() throws Exception { // tests: Graph<FlowShape<Integer, Integer>, NotUsed> duplicator = Flow.fromGraph(new Duplicator2<Integer>()); CompletionStage<Integer> result = Source.from(Arrays.asList(1, 2, 3)).via(duplicator).runFold(0, (n, sum) -> n + sum, mat); assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); }
public void demonstrateACustomMaterializedValue() throws Exception { // tests: RunnableGraph<CompletionStage<Integer>> flow = Source.from(Arrays.asList(1, 2, 3)) .viaMat(new FirstValue(), Keep.right()) .to(Sink.ignore()); CompletionStage<Integer> result = flow.run(mat); assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); }
@Test public void demonstrateCustomSourceUsage() throws Exception { // #simple-source-usage // A GraphStage is a proper Graph, just like what GraphDSL.create would return Graph<SourceShape<Integer>, NotUsed> sourceGraph = new NumbersSource(); // Create a Source from the Graph to access the DSL Source<Integer, NotUsed> mySource = Source.fromGraph(sourceGraph); // Returns 55 CompletionStage<Integer> result1 = mySource.take(10).runFold(0, (sum, next) -> sum + next, mat); // The source is reusable. This returns 5050 CompletionStage<Integer> result2 = mySource.take(100).runFold(0, (sum, next) -> sum + next, mat); // #simple-source-usage assertEquals(result1.toCompletableFuture().get(3, TimeUnit.SECONDS), (Integer) 55); assertEquals(result2.toCompletableFuture().get(3, TimeUnit.SECONDS), (Integer) 5050); }