Ejemplo n.º 1
0
 @Override
 public void handle(StateContext state, SubCollectionReadCollectionContext ctx) {
   String subCollection = ctx.term().getText();
   EntityDictionary dictionary = state.getRequestScope().getDictionary();
   try {
     Set<PersistentResource> collection = resource.getRelation(subCollection); // Check if exists.
     String entityName =
         dictionary.getBinding(
             dictionary.getParameterizedType(resource.getObject(), subCollection));
     Class<?> entityClass = dictionary.getBinding(entityName);
     if (entityClass == null) {
       throw new IllegalArgumentException("Unknown type " + entityName);
     }
     final BaseState nextState;
     if (collection instanceof SingleElementSet) {
       PersistentResource record = collection.iterator().next();
       nextState = new RecordTerminalState(subCollection, record);
     } else {
       nextState =
           new CollectionTerminalState(
               entityClass, Optional.of(resource), Optional.of(subCollection));
     }
     state.setState(nextState);
   } catch (InvalidAttributeException e) {
     throw new InvalidCollectionException(subCollection);
   }
 }
Ejemplo n.º 2
0
  public static Optional<TypeSignature> getCommonSuperTypeSignature(
      TypeSignature firstType, TypeSignature secondType) {
    // Special handling for UnknownType is necessary because we forbid cast between types with
    // different number of type parameters.
    // Without this, cast from null to map<bigint, bigint> will not be allowed.
    if (UnknownType.NAME.equals(firstType.getBase())) {
      return Optional.of(secondType);
    }
    if (UnknownType.NAME.equals(secondType.getBase())) {
      return Optional.of(firstType);
    }

    List<TypeSignatureParameter> firstTypeTypeParameters = firstType.getParameters();
    List<TypeSignatureParameter> secondTypeTypeParameters = secondType.getParameters();
    if (firstTypeTypeParameters.size() != secondTypeTypeParameters.size()) {
      return Optional.empty();
    }

    Optional<String> commonSuperTypeBase =
        getCommonSuperTypeBase(firstType.getBase(), secondType.getBase());
    if (!commonSuperTypeBase.isPresent()) {
      return Optional.empty();
    }

    ImmutableList.Builder<TypeSignatureParameter> typeParameters = ImmutableList.builder();
    for (int i = 0; i < firstTypeTypeParameters.size(); i++) {
      TypeSignatureParameter firstParameter = firstTypeTypeParameters.get(i);
      TypeSignatureParameter secondParameter = secondTypeTypeParameters.get(i);

      if (firstParameter.getKind() == secondParameter.getKind()
          && firstParameter.getKind() == ParameterKind.LONG_LITERAL) {
        typeParameters.add(
            TypeSignatureParameter.of(
                Math.max(firstParameter.getLongLiteral(), secondParameter.getLongLiteral())));
      } else if (isCovariantParameterPosition(commonSuperTypeBase.get(), i)) {
        Optional<TypeSignature> firstParameterSignature =
            firstParameter.getTypeSignatureOrNamedTypeSignature();
        Optional<TypeSignature> secondParameterSignature =
            secondParameter.getTypeSignatureOrNamedTypeSignature();
        if (!firstParameterSignature.isPresent() || !secondParameterSignature.isPresent()) {
          return Optional.empty();
        }

        Optional<TypeSignature> commonSuperType =
            getCommonSuperTypeSignature(
                firstParameterSignature.get(), secondParameterSignature.get());
        if (!commonSuperType.isPresent()) {
          return Optional.empty();
        }
        typeParameters.add(TypeSignatureParameter.of(commonSuperType.get()));
      } else {
        if (!firstParameter.equals(secondParameter)) {
          return Optional.empty();
        }
        typeParameters.add(firstParameter);
      }
    }

    return Optional.of(new TypeSignature(commonSuperTypeBase.get(), typeParameters.build()));
  }
Ejemplo n.º 3
0
  /**
   * Returns the target types that need to have conversion. The types contain first as many
   * constructor parameter types as we have and then the types of properties of object as given by
   * names of result-set.
   */
  @NotNull
  private static Optional<List<Type>> findTargetTypes(
      @NotNull Constructor<?> ctor, @NotNull List<String> resultSetColumns) {
    List<Type> constructorParameterTypes = asList(ctor.getGenericParameterTypes());

    int constructorParameterCount = constructorParameterTypes.size();

    if (constructorParameterCount > resultSetColumns.size()) {
      // We don't have enough columns in ResultSet to instantiate this constructor, discard it.
      return Optional.empty();

    } else if (constructorParameterCount == resultSetColumns.size()) {
      // We have exactly enough column in ResultSet. Use the constructor as it is.
      return Optional.of(constructorParameterTypes);

    } else {
      // Get the types of remaining properties
      ArrayList<Type> result = new ArrayList<>(resultSetColumns.size());
      result.addAll(constructorParameterTypes);

      List<String> propertyNames =
          resultSetColumns.subList(constructorParameterCount, resultSetColumns.size());
      for (String name : propertyNames) {
        Type type = PropertyAccessor.findPropertyType(ctor.getDeclaringClass(), name).orElse(null);
        if (type != null) result.add(type);
        else return Optional.empty();
      }

      return Optional.of(result);
    }
  }
Ejemplo n.º 4
0
  public static <A, B, C> PromiseWithoutUpdates<C> lift(
      final Lambda2<A, B, C> f, PromiseWithoutUpdates<A> pa, PromiseWithoutUpdates<B> pb) {
    return Transaction.run(
        () -> {
          class Tuple {
            Tuple(Optional<A> oa, Optional<B> ob) {
              this.oa = oa;
              this.ob = ob;
            }

            Optional<A> oa;
            Optional<B> ob;
          };
          Lambda2<Tuple, Tuple, Tuple> combine =
              (l, r) -> new Tuple(l.oa.isPresent() ? l.oa : r.oa, l.ob.isPresent() ? l.ob : r.ob);
          Lambda1<Tuple, Optional<C>> result =
              t ->
                  t.oa.isPresent() && t.ob.isPresent()
                      ? Optional.of(f.apply(t.oa.get(), t.ob.get()))
                      : Optional.empty();
          Stream<Tuple> sA = pa.sDeliver.map(a -> new Tuple(Optional.of(a), Optional.empty()));
          Cell<Tuple> vA = pa.oValue.map(oa -> new Tuple(oa, Optional.empty()));
          Stream<Tuple> sB = pb.sDeliver.map(b -> new Tuple(Optional.empty(), Optional.of(b)));
          Cell<Tuple> vB = pb.oValue.map(ob -> new Tuple(Optional.empty(), ob));
          Stream<Tuple> sAArrives = sA.snapshot(vB, combine);
          Stream<Tuple> sBArrives = sB.snapshot(vA, combine);
          Stream<Tuple> sSimultaneous = sA.merge(sB, combine);
          Stream<C> sDeliver =
              Stream.filterOptional(sAArrives.orElse(sBArrives).orElse(sSimultaneous).map(result))
                  .once();
          Cell<Optional<C>> oValue = Cell.lift(combine, vA, vB).map(result);
          return new PromiseWithoutUpdates<C>(sDeliver, oValue);
        });
  }
  private Optional<Resource> loadProperties() {

    String applicationPropertyFileName = new ConfigAccessor().get().getPropertiesName();

    Optional<Resource> resource = Optional.empty();

    if (new File("./" + applicationPropertyFileName).exists()) {
      resource = Optional.of(new FileSystemResource(new File("./" + applicationPropertyFileName)));
      logger.info("./" + applicationPropertyFileName + " added");
    }

    URL urlResource = getClass().getClassLoader().getResource(applicationPropertyFileName);
    if (urlResource != null) {
      resource = Optional.of(new UrlResource(urlResource));
      logger.info(applicationPropertyFileName + " added");
    }

    if (System.getProperty("application.env") != null) {
      URL envResource =
          getClass()
              .getClassLoader()
              .getResource(createEnvBasedPropertyFileName(applicationPropertyFileName));
      if (envResource != null) {
        resource = Optional.of(new UrlResource(envResource));
        logger.info(createEnvBasedPropertyFileName(applicationPropertyFileName) + " added");
      }
    }
    if (System.getProperty("application.property.file") != null) {
      resource =
          Optional.of(
              new FileSystemResource(new File(System.getProperty("application.property.file"))));
      logger.info(System.getProperty("application.property.file") + " added");
    }
    return resource;
  }
Ejemplo n.º 6
0
 @Test
 public void testGetType_Unknown() throws Exception {
   command =
       AutoCommand.create(
           Optional.of("server"), Optional.of("network"), Optional.empty(), "response");
   assertEquals(AutoCommandType.UNKNOWN, command.getType());
 }
Ejemplo n.º 7
0
 @Test
 public void replaceOptional() {
   assertEquals(Optional.of(1), map.replaceOptional("Key1", 11));
   assertEquals(Optional.of(11), map.replaceOptional("Key1", 12));
   assertEquals(Optional.empty(), map.replaceOptional("NonExistingKey", 999));
   assertEquals(Optional.empty(), map.replaceOptional("NonExistingKey", 1000));
 }
Ejemplo n.º 8
0
  public TurboIssue(String repoId, Issue issue) {
    this.id = issue.getNumber();
    this.title = issue.getTitle() == null ? "" : issue.getTitle();
    this.creator = issue.getUser().getLogin();
    this.createdAt = Utility.dateToLocalDateTime(issue.getCreatedAt());
    this.isPullRequest = isPullRequest(issue);

    this.description = issue.getBody() == null ? "" : issue.getBody();
    this.updatedAt =
        issue.getUpdatedAt() != null
            ? Utility.dateToLocalDateTime(issue.getUpdatedAt())
            : this.createdAt;
    this.commentCount = issue.getComments();
    this.isOpen = issue.getState().equals(STATE_OPEN);
    this.assignee =
        issue.getAssignee() == null
            ? Optional.empty()
            : Optional.of(issue.getAssignee().getLogin());
    this.labels = issue.getLabels().stream().map(Label::getName).collect(Collectors.toList());
    this.milestone =
        issue.getMilestone() == null
            ? Optional.empty()
            : Optional.of(issue.getMilestone().getNumber());

    this.metadata = IssueMetadata.empty();
    this.repoId = repoId;
    this.markedReadAt = Optional.empty();
  }
 @Test
 public void testQueryClauseWithLimit() {
   final Expression expr1 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setService("my-test-service")
           .setCluster("my-test-cluster")
           .build();
   final Expression expr2 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setService("my-test-service")
           .setCluster("my-test-cluster")
           .build();
   exprRepo.addOrUpdateExpression(expr1, Organization.DEFAULT);
   exprRepo.addOrUpdateExpression(expr2, Organization.DEFAULT);
   final ExpressionQuery query1 = new DefaultExpressionQuery(exprRepo, Organization.DEFAULT);
   query1.service(Optional.of("my-test-service"));
   query1.cluster(Optional.of("my-test-cluster"));
   query1.limit(1);
   final QueryResult<Expression> result1 = exprRepo.query(query1);
   Assert.assertEquals(1, result1.values().size());
   final ExpressionQuery query2 = new DefaultExpressionQuery(exprRepo, Organization.DEFAULT);
   query2.service(Optional.of("my-test-service"));
   query2.cluster(Optional.of("my-test-cluster"));
   query2.limit(2);
   final QueryResult<Expression> result2 = exprRepo.query(query2);
   Assert.assertEquals(2, result2.values().size());
 }
Ejemplo n.º 10
0
    @Override
    public <K extends Comparable<? super K>, V extends Record, T extends KeyValuePage<K, V>>
        RecordPageContainer<T> combineRecordPagesForModification(
            final List<T> pages,
            final @Nonnegative int revToRestore,
            final PageReadTrx pageReadTrx,
            final PageReference reference) {
      assert pages.size() == 1;
      final T firstPage = pages.get(0);
      final long recordPageKey = firstPage.getPageKey();
      final List<T> returnVal = new ArrayList<>(2);
      returnVal.add(
          firstPage.<T>newInstance(
              recordPageKey, firstPage.getPageKind(), Optional.of(reference), pageReadTrx));
      returnVal.add(
          firstPage.<T>newInstance(
              recordPageKey, firstPage.getPageKind(), Optional.of(reference), pageReadTrx));

      for (final Map.Entry<K, V> entry : pages.get(0).entrySet()) {
        returnVal.get(0).setEntry(entry.getKey(), entry.getValue());
        returnVal.get(1).setEntry(entry.getKey(), entry.getValue());
      }

      return new RecordPageContainer<>(returnVal.get(0), returnVal.get(1));
    }
 /**
  * Sets up the test fixture.
  *
  * @throws java.lang.Exception If an error occurs.
  */
 @Before
 public void setUp() throws Exception {
   niceMocksControl_ = Optional.of(EasyMock.createNiceControl());
   final T node = createDisconnectedNode();
   node_ = Optional.of(node);
   nodeLayerRunner_ = Optional.of(createNodeLayerRunner(node));
 }
Ejemplo n.º 12
0
  static void optionalTest() {
    // 不要这样,这与!=null没什么区别
    Optional<String> stringOptional = Optional.of("alibaba");
    if (stringOptional.isPresent()) {
      System.out.println(stringOptional.get().length());
    }
    Optional<String> optionalValue = Optional.of("alibaba");
    // 下面是推荐的常用操作
    optionalValue.ifPresent(s -> System.out.println(s + " contains red"));
    // 增加到集合汇总
    List<String> results = Lists.newArrayList();
    optionalValue.ifPresent(results::add);
    // 增加到集合中,并返回操作结果
    Optional<Boolean> added = optionalValue.map(results::add);

    // 无值的optional
    Optional<String> optionalString = Optional.empty();
    // 不存在值,返回“No word”
    String result = optionalValue.orElse("No word");
    // 没值,计算一个默认值
    result = optionalString.orElseGet(() -> System.getProperty("user.dir"));
    // 无值,抛一个异常
    try {
      result = optionalString.orElseThrow(NoSuchElementException::new);
    } catch (Throwable t) {
      t.getCause();
    }
  }
Ejemplo n.º 13
0
  /**
   * Finds an annotation in an Annotated, taking stereo types into account
   *
   * @param beanManager the current bean manager
   * @param annotated the Annotated in which to search
   * @param annotationType the type of the annotation to search for
   * @return An Optional that contains an instance of annotation type for which was searched if the
   *     annotated contained this.
   */
  public static <A extends Annotation> Optional<A> getAnnotation(
      BeanManager beanManager, Annotated annotated, Class<A> annotationType) {

    annotated.getAnnotation(annotationType);

    if (annotated.getAnnotations().isEmpty()) {
      return empty();
    }

    if (annotated.isAnnotationPresent(annotationType)) {
      return Optional.of(annotated.getAnnotation(annotationType));
    }

    Queue<Annotation> annotations = new LinkedList<>(annotated.getAnnotations());

    while (!annotations.isEmpty()) {
      Annotation annotation = annotations.remove();

      if (annotation.annotationType().equals(annotationType)) {
        return Optional.of(annotationType.cast(annotation));
      }

      if (beanManager.isStereotype(annotation.annotationType())) {
        annotations.addAll(beanManager.getStereotypeDefinition(annotation.annotationType()));
      }
    }

    return empty();
  }
  @Test
  public void ensureSyncedPersonHasCorrectAttributes() {

    Person person =
        TestDataCreator.createPerson("muster", "Marlene", "Muster", "*****@*****.**");

    Person syncedPerson =
        ldapSyncService.syncPerson(
            person,
            Optional.of("Aljona"),
            Optional.of("Murygina"),
            Optional.of("*****@*****.**"));

    Mockito.verify(personService).save(Mockito.eq(person));

    Assert.assertNotNull("Missing login name", syncedPerson.getLoginName());
    Assert.assertNotNull("Missing first name", syncedPerson.getFirstName());
    Assert.assertNotNull("Missing last name", syncedPerson.getLastName());
    Assert.assertNotNull("Missing mail address", syncedPerson.getEmail());

    Assert.assertEquals("Wrong login name", "muster", syncedPerson.getLoginName());
    Assert.assertEquals("Wrong first name", "Aljona", syncedPerson.getFirstName());
    Assert.assertEquals("Wrong last name", "Murygina", syncedPerson.getLastName());
    Assert.assertEquals("Wrong mail address", "*****@*****.**", syncedPerson.getEmail());
  }
  @Test
  public void ensurePersonIsCreatedWithCorrectAttributes() {

    Person person = TestDataCreator.createPerson();

    Mockito.when(
            personService.create(
                Mockito.anyString(),
                Mockito.anyString(),
                Mockito.anyString(),
                Mockito.anyString(),
                Mockito.anyListOf(MailNotification.class),
                Mockito.anyListOf(Role.class)))
        .thenReturn(person);

    ldapSyncService.createPerson(
        "murygina",
        Optional.of("Aljona"),
        Optional.of("Murygina"),
        Optional.of("*****@*****.**"));

    Mockito.verify(personService)
        .create(
            "murygina",
            "Murygina",
            "Aljona",
            "*****@*****.**",
            Collections.singletonList(MailNotification.NOTIFICATION_USER),
            Collections.singletonList(Role.USER));
  }
Ejemplo n.º 16
0
  @Test
  public void testPackageNameMustBePrefixOfQualifiedSymbolName() {
    final CommonResolvingFilter<EntitySymbol> classResolver =
        new CommonResolvingFilter<>(EntitySymbol.KIND);

    final MutableScope globalScope =
        new GlobalScope(new ModelPath(), new LinkedHashSet<>(), new ResolverConfiguration());
    globalScope.addResolver(classResolver);

    ArtifactScope artifactScope1 =
        new ArtifactScope(Optional.of(globalScope), "p", new ArrayList<>());
    artifactScope1.addResolver(classResolver);
    EntitySymbol classA = new EntitySymbol("A");
    artifactScope1.add(classA);

    ArtifactScope artifactScope2 =
        new ArtifactScope(Optional.of(globalScope), "p2", new ArrayList<>());
    artifactScope2.addResolver(classResolver);
    EntitySymbol classA2 = new EntitySymbol("A");
    artifactScope2.add(classA2);

    assertSame(classA, globalScope.resolve("p.A", EntitySymbol.KIND).get());
    assertSame(classA2, globalScope.resolve("p2.A", EntitySymbol.KIND).get());
    assertNotSame(classA, classA2);
  }
 @Test
 public void testQueryClauseWithOffsetAndLimit() {
   final Expression expr1 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setService("my-test-service")
           .setCluster("my-test-cluster")
           .build();
   final Expression expr2 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setService("my-test-service")
           .setCluster("my-test-cluster")
           .build();
   final Expression expr3 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setService("my-test-service")
           .setCluster("my-test-cluster")
           .build();
   exprRepo.addOrUpdateExpression(expr1, Organization.DEFAULT);
   exprRepo.addOrUpdateExpression(expr2, Organization.DEFAULT);
   exprRepo.addOrUpdateExpression(expr3, Organization.DEFAULT);
   final ExpressionQuery query = new DefaultExpressionQuery(exprRepo, Organization.DEFAULT);
   query.service(Optional.of("my-test-service"));
   query.cluster(Optional.of("my-test-cluster"));
   query.offset(Optional.of(2));
   query.limit(2);
   final QueryResult<Expression> result = exprRepo.query(query);
   Assert.assertEquals(1, result.values().size());
   Assert.assertEquals(expr3.getId(), result.values().get(0).getId());
 }
Ejemplo n.º 18
0
  // -------------------------------------------------------------------------
  public void test_of() {
    DiscountFxForwardRates test =
        DiscountFxForwardRates.of(CURRENCY_PAIR, FX_RATE, DFCURVE_GBP, DFCURVE_USD);
    assertEquals(test.getCurrencyPair(), CURRENCY_PAIR);
    assertEquals(test.getValuationDate(), DATE_VAL);
    assertEquals(test.getBaseCurrencyDiscountFactors(), DFCURVE_GBP);
    assertEquals(test.getCounterCurrencyDiscountFactors(), DFCURVE_USD);
    assertEquals(test.getFxRateProvider(), FX_RATE);
    assertEquals(test.findData(CURVE1.getName()), Optional.of(CURVE1));
    assertEquals(test.findData(CURVE2.getName()), Optional.of(CURVE2));
    assertEquals(test.findData(CurveName.of("Rubbish")), Optional.empty());

    int baseSize = DFCURVE_USD.getParameterCount();
    assertEquals(test.getParameterCount(), DFCURVE_GBP.getParameterCount() + baseSize);
    assertEquals(test.getParameter(0), DFCURVE_GBP.getParameter(0));
    assertEquals(test.getParameter(baseSize), DFCURVE_USD.getParameter(0));
    assertEquals(test.getParameterMetadata(0), DFCURVE_GBP.getParameterMetadata(0));
    assertEquals(test.getParameterMetadata(baseSize), DFCURVE_USD.getParameterMetadata(0));
    assertEquals(
        test.withParameter(0, 1d).getBaseCurrencyDiscountFactors(),
        DFCURVE_GBP.withParameter(0, 1d));
    assertEquals(test.withParameter(0, 1d).getCounterCurrencyDiscountFactors(), DFCURVE_USD);
    assertEquals(test.withParameter(baseSize, 1d).getBaseCurrencyDiscountFactors(), DFCURVE_GBP);
    assertEquals(
        test.withParameter(baseSize, 1d).getCounterCurrencyDiscountFactors(),
        DFCURVE_USD.withParameter(0, 1d));
    assertEquals(
        test.withPerturbation((i, v, m) -> v + 1d).getBaseCurrencyDiscountFactors(),
        DFCURVE_GBP.withPerturbation((i, v, m) -> v + 1d));
    assertEquals(
        test.withPerturbation((i, v, m) -> v + 1d).getCounterCurrencyDiscountFactors(),
        DFCURVE_USD.withPerturbation((i, v, m) -> v + 1d));
  }
 @Test
 public void testQueryWithContainsAndServiceClause() {
   final Expression expr1 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setMetric("my-contained-metric")
           .setService("my-service")
           .build();
   final Expression expr2 =
       TestBeanFactory.createExpressionBuilder()
           .setId(UUID.randomUUID())
           .setScript("my-contained-script")
           .setService("my-service")
           .build();
   final Expression expr3 =
       TestBeanFactory.createExpressionBuilder().setId(UUID.randomUUID()).build();
   exprRepo.addOrUpdateExpression(expr1, Organization.DEFAULT);
   exprRepo.addOrUpdateExpression(expr2, Organization.DEFAULT);
   exprRepo.addOrUpdateExpression(expr3, Organization.DEFAULT);
   final ExpressionQuery query = new DefaultExpressionQuery(exprRepo, Organization.DEFAULT);
   query.contains(Optional.of("contained"));
   query.service(Optional.of("my-service"));
   final QueryResult<Expression> result = exprRepo.query(query);
   Assert.assertEquals(2, result.values().size());
   Assert.assertEquals(expr1.getId(), result.values().get(0).getId());
   Assert.assertEquals(expr2.getId(), result.values().get(1).getId());
 }
Ejemplo n.º 20
0
 public PeerConnection(
     Peer peer, SocketChannel channel, TorrentStorage storage, TorrentMetadata torrentMetadata) {
   this(peer, channel);
   this.torrentMetadata = Optional.of(torrentMetadata);
   this.bitField = Optional.of(new BitField(torrentMetadata.getPieceHashes().size()));
   this.storage = Optional.of(storage);
 }
Ejemplo n.º 21
0
  @Test
  public void testResolveUnqualifiedSymbolInSamePackage() {
    final CommonResolvingFilter<EntitySymbol> classResolver =
        new CommonResolvingFilter<>(EntitySymbol.KIND);

    final MutableScope globalScope =
        new GlobalScope(new ModelPath(), new LinkedHashSet<>(), new ResolverConfiguration());
    globalScope.addResolver(classResolver);

    ArtifactScope artifactScope1 =
        new ArtifactScope(Optional.of(globalScope), "p", new ArrayList<>());
    artifactScope1.addResolver(classResolver);
    EntitySymbol classA = new EntitySymbol("A");
    artifactScope1.add(classA);
    Scope classAScope = classA.getSpannedScope();

    ArtifactScope artifactScope2 =
        new ArtifactScope(Optional.of(globalScope), "p", new ArrayList<>());
    artifactScope2.addResolver(classResolver);
    EntitySymbol classB = new EntitySymbol("B");
    artifactScope2.add(classB);

    // resolve B with unqualified name, because it is in the same package as A.
    assertSame(classB, classAScope.resolve("B", EntitySymbol.KIND).get());

    assertSame(classA, classAScope.resolve("A", EntitySymbol.KIND).get());
  }
Ejemplo n.º 22
0
  private Optional<Player> validPlayer(Cause cause) {
    Optional<EntityDamageSource> optionalSrc = cause.first(EntityDamageSource.class);

    if (optionalSrc.isPresent()) {
      Entity src = optionalSrc.get().getSource();

      if (src instanceof Player) {
        return Optional.of((Player) src);
      } else if (src instanceof Projectile) {
        Projectile projectile = (Projectile) src;

        Optional<UUID> optionalUUID = projectile.getCreator();

        if (!optionalUUID.isPresent()) {
          return Optional.empty();
        }

        Optional<Player> optionalPlayer = Sponge.getServer().getPlayer(optionalUUID.get());

        if (!optionalPlayer.isPresent()) {
          return Optional.empty();
        }

        return Optional.of(optionalPlayer.get());
      }
    }

    return Optional.empty();
  }
Ejemplo n.º 23
0
  @Test
  public void test_getUniqueBucketSignature() {

    final String path1 = "/test+extra/";
    final String path2 = "/test+extra/4354____42";
    final String path3 = "test+extra/4354____42/some/more/COMPONENTS_VERY_VERY_LONG";

    assertEquals(
        "test_extra__c1651d4c69ed", BucketUtils.getUniqueSignature(path1, Optional.empty()));
    assertEquals(
        "test_extra_test_12345__c1651d4c69ed",
        BucketUtils.getUniqueSignature(path1, Optional.of("test+;12345")));
    assertEquals(
        "test_extra_4354_42__bb8a6a382d7b",
        BucketUtils.getUniqueSignature(path2, Optional.empty()));
    assertEquals(
        "test_extra_4354_42_t__bb8a6a382d7b",
        BucketUtils.getUniqueSignature(path2, Optional.of("t")));
    assertEquals(
        "test_extra_more_components_very__7768508661fc",
        BucketUtils.getUniqueSignature(path3, Optional.empty()));
    assertEquals(
        "test_extra_more_components_very_xx__7768508661fc",
        BucketUtils.getUniqueSignature(path3, Optional.of("XX__________")));
  }
Ejemplo n.º 24
0
  @Test
  public void subTitleTest() throws Exception {
    try (InputStream is =
        GvkParserTest.class.getResourceAsStream("gvk_artificial_subtitle_test.xml")) {
      GvkParser parser = new GvkParser();
      List<BibEntry> entries = parser.parseEntries(is);
      Assert.assertNotNull(entries);
      Assert.assertEquals(5, entries.size());

      BibEntry entry = entries.get(0);
      Assert.assertEquals(Optional.empty(), entry.getField("subtitle"));

      entry = entries.get(1);
      Assert.assertEquals(Optional.of("C"), entry.getField("subtitle"));

      entry = entries.get(2);
      Assert.assertEquals(Optional.of("Word"), entry.getField("subtitle"));

      entry = entries.get(3);
      Assert.assertEquals(Optional.of("Word1 word2"), entry.getField("subtitle"));

      entry = entries.get(4);
      Assert.assertEquals(Optional.of("Word1 word2"), entry.getField("subtitle"));
    }
  }
Ejemplo n.º 25
0
  @Test
  public void testMapping() {
    List<String> input = Arrays.asList("Capital", "lower", "Foo", "bar");
    Collector<String, ?, Map<Boolean, Optional<Integer>>> collector =
        MoreCollectors.partitioningBy(
            str -> Character.isUpperCase(str.charAt(0)),
            MoreCollectors.mapping(String::length, MoreCollectors.first()));
    checkShortCircuitCollector(
        "mapping", new BooleanMap<>(Optional.of(7), Optional.of(5)), 2, input::stream, collector);
    Collector<String, ?, Map<Boolean, Optional<Integer>>> collectorLast =
        MoreCollectors.partitioningBy(
            str -> Character.isUpperCase(str.charAt(0)),
            MoreCollectors.mapping(String::length, MoreCollectors.last()));
    checkCollector(
        "last", new BooleanMap<>(Optional.of(3), Optional.of(3)), input::stream, collectorLast);

    input = Arrays.asList("Abc", "Bac", "Aac", "Abv", "Bbc", "Bgd", "Atc", "Bpv");
    Map<Character, List<String>> expected =
        EntryStream.of('A', Arrays.asList("Abc", "Aac"), 'B', Arrays.asList("Bac", "Bbc")).toMap();
    AtomicInteger cnt = new AtomicInteger();
    Collector<String, ?, Map<Character, List<String>>> groupMap =
        Collectors.groupingBy(
            s -> s.charAt(0),
            MoreCollectors.mapping(
                x -> {
                  cnt.incrementAndGet();
                  return x;
                },
                MoreCollectors.head(2)));
    checkCollector("groupMap", expected, input::stream, groupMap);
    cnt.set(0);
    assertEquals(expected, input.stream().collect(groupMap));
    assertEquals(4, cnt.get());
  }
Ejemplo n.º 26
0
  @Test
  public void testFirstLast() {
    Supplier<Stream<Integer>> s = () -> IntStreamEx.range(1000).boxed();
    checkShortCircuitCollector("first", Optional.of(0), 1, s, MoreCollectors.first());
    checkShortCircuitCollector(
        "firstLong",
        Optional.of(0),
        1,
        () -> Stream.of(1).flatMap(x -> IntStream.range(0, 1000000000).boxed()),
        MoreCollectors.first(),
        true);
    checkShortCircuitCollector(
        "first",
        Optional.of(1),
        1,
        () -> Stream.iterate(1, x -> x + 1),
        MoreCollectors.first(),
        true);
    assertEquals(
        1, (int) StreamEx.iterate(1, x -> x + 1).parallel().collect(MoreCollectors.first()).get());

    checkCollector("last", Optional.of(999), s, MoreCollectors.last());
    checkCollectorEmpty("first", Optional.empty(), MoreCollectors.first());
    checkCollectorEmpty("last", Optional.empty(), MoreCollectors.last());
  }
Ejemplo n.º 27
0
 @Test
 public void testConvertToKnownLocale() throws Exception {
   assertEquals(Optional.of("en"), Languages.convertToKnownLocale("en"));
   assertEquals(Optional.of("en"), Languages.convertToKnownLocale("en_US"));
   assertEquals(Optional.of("de"), Languages.convertToKnownLocale("de_DE"));
   assertEquals(Optional.empty(), Languages.convertToKnownLocale("WHATEVER"));
 }
Ejemplo n.º 28
0
  public AlignmentRecord(Term sourceTerm, Term targetTerm) {
    super();

    this.sourceTerm = Optional.of(sourceTerm);
    this.sourceLemma = Optional.of(sourceTerm.getLemma());
    this.targetTerm = Optional.of(targetTerm);
    this.targetLemma = Optional.of(targetTerm.getLemma());
  }
Ejemplo n.º 29
0
 public void test_getLeg_PayReceive() {
   assertEquals(Swap.of(MOCK_GBP1, MOCK_USD1).getLeg(PAY), Optional.of(MOCK_GBP1));
   assertEquals(Swap.of(MOCK_GBP1, MOCK_USD1).getLeg(RECEIVE), Optional.of(MOCK_USD1));
   assertEquals(Swap.of(MOCK_GBP1).getLeg(PAY), Optional.of(MOCK_GBP1));
   assertEquals(Swap.of(MOCK_USD1).getLeg(PAY), Optional.empty());
   assertEquals(Swap.of(MOCK_GBP1).getLeg(RECEIVE), Optional.empty());
   assertEquals(Swap.of(MOCK_USD1).getLeg(RECEIVE), Optional.of(MOCK_USD1));
 }
 @Override
 protected Optional<FluidStackSnapshot> getVal(ItemStack dataHolder) {
   if (dataHolder.getItem() == Items.water_bucket) {
     return Optional.of(WATER);
   } else if (dataHolder.getItem() == Items.lava_bucket) {
     return Optional.of(LAVA);
   }
   return Optional.empty();
 }