@Test
  public void ensurePersonCanBeCreatedWithOnlyLoginName() {

    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.empty(), Optional.empty(), Optional.empty());

    Mockito.verify(personService)
        .create(
            "murygina",
            null,
            null,
            null,
            Collections.singletonList(MailNotification.NOTIFICATION_USER),
            Collections.singletonList(Role.USER));
  }
  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);
        });
  }
 @RequestMapping(value = "/events/check", method = POST)
 public ValidationResult validateEvent(
     @RequestBody EventModification eventModification, Errors errors) {
   ValidationResult base =
       validateEventHeader(Optional.<Event>empty(), eventModification, errors)
           .or(validateEventPrices(Optional.<Event>empty(), eventModification, errors))
           .or(
               eventModification
                   .getAdditionalServices()
                   .stream()
                   .map(as -> validateAdditionalService(as, eventModification, errors))
                   .reduce(ValidationResult::or)
                   .orElse(ValidationResult.success()));
   AtomicInteger counter = new AtomicInteger();
   return base.or(
           eventModification
               .getTicketCategories()
               .stream()
               .map(
                   c ->
                       validateCategory(
                           c, errors, "ticketCategories[" + counter.getAndIncrement() + "]."))
               .reduce(ValidationResult::or)
               .orElse(ValidationResult.success()))
       .or(validateAdditionalTicketFields(eventModification.getTicketFields(), errors));
 }
Exemple #4
0
  public FManager() {

    loaded =
        Collections.synchronizedSet(
            new HashSet<File>() {
              @Override
              public boolean add(File e) {
                synchronized (loadedObserver) {
                  loadedObserver.setChanged();
                  loadedObserver.notifyObservers(e);
                }
                return super.add(e);
              }
            });
    pending = Collections.synchronizedSet(new HashSet<>());
    filterChange = new InvokeObservable(this);
    loadedObserver = new InvokeObservable(this);
    activityObserver = new InvokeObservable(this);
    autoLoad = true;
    verbose = true;
    activity = IDLE;
    stdErr = Optional.empty();
    stdOut = Optional.empty();
    FPC fpcObject = null;
    try {
      fpcObject = new FPC(DataDetails.class);
      fpcObject.onFilterChange(this::setActiveFilter);
    } catch (Exception ex) {
      Logger.getLogger(FManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    fpc = fpcObject;
    checkProperties();
  }
  /**
   * Sets up BGP speakers.
   *
   * @return configured BGP speakers as a map from speaker name to speaker
   */
  private Set<BgpConfig.BgpSpeakerConfig> setUpBgpSpeakers() {

    BgpConfig.BgpSpeakerConfig speaker1 =
        new BgpConfig.BgpSpeakerConfig(
            Optional.empty(),
            NO_VLAN,
            s1Eth100,
            Collections.singleton(IpAddress.valueOf("192.168.10.1")));

    BgpConfig.BgpSpeakerConfig speaker2 =
        new BgpConfig.BgpSpeakerConfig(
            Optional.empty(),
            NO_VLAN,
            s1Eth100,
            Sets.newHashSet(IpAddress.valueOf("192.168.20.1"), IpAddress.valueOf("192.168.30.1")));

    BgpConfig.BgpSpeakerConfig speaker3 =
        new BgpConfig.BgpSpeakerConfig(
            Optional.empty(),
            VLAN30,
            s3Eth100,
            Sets.newHashSet(IpAddress.valueOf("192.168.40.1"), IpAddress.valueOf("192.168.50.1")));

    Set<BgpConfig.BgpSpeakerConfig> bgpSpeakers = Sets.newHashSet();
    bgpSpeakers.add(speaker1);
    bgpSpeakers.add(speaker2);
    bgpSpeakers.add(speaker3);

    return bgpSpeakers;
  }
Exemple #6
0
  private Optional<ResolvedField> resolveField(Expression node, QualifiedName name, boolean local) {
    List<Field> matches = relation.resolveFields(name);
    if (matches.size() > 1) {
      throwAmbiguousAttributeException(node, name);
    }

    if (matches.isEmpty()) {
      if (isColumnReference(name, relation)) {
        return Optional.empty();
      }
      Scope boundary = this;
      while (!boundary.queryBoundary) {
        if (boundary.parent.isPresent()) {
          boundary = boundary.parent.get();
        } else {
          return Optional.empty();
        }
      }
      if (boundary.parent.isPresent()) {
        // jump over the query boundary
        return boundary.parent.get().resolveField(node, name, false);
      }
      return Optional.empty();
    } else {
      return Optional.of(asResolvedField(getOnlyElement(matches), local));
    }
  }
  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();
  }
  @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());
  }
 /** Create a new test instance for the given visitor */
 public CommanderVisitorTest() {
   super(
       new CommanderVisitor(),
       Optional.of("Good to see you commander"),
       Optional.empty(),
       Optional.empty());
 }
  public ASTTemplateargument deepClone(ASTTemplateargument result) {

    /* generated by template ast.ErrorIfNull*/
    Log.errorIfNull(result, "0xA7006_977 Parameter 'result' must not be null.");

    /* generated by template ast.additionalmethods.DeepCloneWithParameters*/

    super.deepClone(result);

    result.constantexpression =
        this.constantexpression.isPresent()
            ? Optional.ofNullable(
                (cpp14._ast.ASTConstantexpression) this.constantexpression.get().deepClone())
            : Optional.empty();
    result.typeidP =
        this.typeidP.isPresent()
            ? Optional.ofNullable((cpp14._ast.ASTTypeidP) this.typeidP.get().deepClone())
            : Optional.empty();
    result.idexpression =
        this.idexpression.isPresent()
            ? Optional.ofNullable((cpp14._ast.ASTIdexpression) this.idexpression.get().deepClone())
            : Optional.empty();
    result.symbol =
        this.symbol.isPresent()
            ? Optional.ofNullable((Symbol) this.symbol.get())
            : Optional.empty();
    result.enclosingScope =
        this.enclosingScope.isPresent()
            ? Optional.ofNullable((Scope) this.enclosingScope.get())
            : Optional.empty();
    return result;
  }
  public static Optional<List<FixMessage>> toFixMessage(String line) {
    try {
      FixType fixType = resolveFixType(line);

      List<String> messages = extractMessageFromLine(line, fixType);
      if (messages.isEmpty()) {
        return Optional.empty();
      }

      String delimiter = getDelimiter(messages.get(0));
      List<FixMessage> fixMessages = new ArrayList<FixMessage>();

      for (String message : messages) {
        if (!message.isEmpty()) {
          FixMessage fixMessage = new FixMessage(fixType);
          fillFixMessage(message, delimiter, fixMessage);
          fixMessages.add(fixMessage);
        }
      }

      return Optional.of(fixMessages);
    } catch (IllegalArgumentException e) {
      return Optional.empty();
    }
  }
  /** Unit tests */
  public static void main(String[] args) {
    final Tree targetTree =
        tree(
            1,
            tree(
                2,
                tree(3, tree(4), tree(3, tree(4), tree(5))),
                tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))),
            tree(12));

    System.out.println("    Test Pattern");
    checkPattern(targetTree, tree(), Optional.of(targetTree));

    checkPattern(targetTree, tree(9), Optional.of(tree(9)));
    checkPattern(targetTree, tree(12), Optional.of(tree(12)));
    checkPattern(targetTree, tree(13), Optional.empty());
    checkPattern(targetTree, tree(1), Optional.of(targetTree));

    checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left()));
    checkPattern(
        targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right()));
    checkPattern(
        targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left()));
    checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty());

    checkPattern(
        targetTree,
        tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())),
        Optional.of(targetTree.left().right()));
  }
  public ASTUnannReferenceType deepClone(ASTUnannReferenceType result) {

    /* generated by template ast.ErrorIfNull*/
    Log.errorIfNull(result, "0xA7006_806 Parameter 'result' must not be null.");

    /* generated by template ast.additionalmethods.DeepCloneWithParameters*/

    super.deepClone(result);

    result.unannClassOrInterfaceType =
        this.unannClassOrInterfaceType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannClassOrInterfaceType)
                    this.unannClassOrInterfaceType.get().deepClone())
            : Optional.empty();
    result.unannTypeVariable =
        this.unannTypeVariable.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannTypeVariable) this.unannTypeVariable.get().deepClone())
            : Optional.empty();
    result.unannArrayType =
        this.unannArrayType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannArrayType) this.unannArrayType.get().deepClone())
            : Optional.empty();
    result.symbol =
        this.symbol.isPresent()
            ? Optional.ofNullable((Symbol) this.symbol.get())
            : Optional.empty();
    result.enclosingScope =
        this.enclosingScope.isPresent()
            ? Optional.ofNullable((Scope) this.enclosingScope.get())
            : Optional.empty();
    return result;
  }
  /**
   * 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);
    }
  }
Exemple #15
0
 public Optional<Response> get(Optional<Request> request) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   Response response = new Response();
   if (request.isPresent()) {
     Request r = request.get();
     response.key = r.key;
     response.table = r.table;
     try {
       final Table htable = connection.getTable(TableName.valueOf(r.table));
       Result result = htable.get(new Get(r.key));
       if (result == null || result.isEmpty()) {
         return Optional.empty();
       }
       r.columns.forEach(
           c ->
               response.columns.add(
                   new Request.Column(
                       c.family,
                       c.qualifier,
                       result.getValue(c.family.getBytes(), c.qualifier.getBytes()))));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return Optional.of(response);
 }
Exemple #16
0
 public Optional<byte[]> get(
     Optional<String> table,
     Optional<String> family,
     Optional<String> qualifier,
     Optional<String> key) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   if (table.isPresent()
       && family.isPresent()
       && qualifier.isPresent()
       && key.isPresent()
       && !key.get().isEmpty()) {
     try {
       final Table htable = connection.getTable(TableName.valueOf(table.get()));
       Result result = htable.get(new Get(key.get().getBytes("UTF8")));
       return Optional.ofNullable(
           result.getValue(family.get().getBytes("UTF8"), qualifier.get().getBytes("UTF8")));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return Optional.empty();
 }
Exemple #17
0
  private PlanBuilder appendSemiJoin(PlanBuilder subPlan, InPredicate inPredicate) {
    TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis);
    translations.copyMappingsFrom(subPlan.getTranslations());

    subPlan = appendProjections(subPlan, ImmutableList.of(inPredicate.getValue()));
    Symbol sourceJoinSymbol = subPlan.translate(inPredicate.getValue());

    checkState(inPredicate.getValueList() instanceof SubqueryExpression);
    SubqueryExpression subqueryExpression = (SubqueryExpression) inPredicate.getValueList();
    RelationPlanner relationPlanner =
        new RelationPlanner(analysis, symbolAllocator, idAllocator, metadata, session);
    RelationPlan valueListRelation = relationPlanner.process(subqueryExpression.getQuery(), null);
    Symbol filteringSourceJoinSymbol =
        Iterables.getOnlyElement(valueListRelation.getRoot().getOutputSymbols());

    Symbol semiJoinOutputSymbol = symbolAllocator.newSymbol("semijoinresult", BOOLEAN);

    translations.put(inPredicate, semiJoinOutputSymbol);

    return new PlanBuilder(
        translations,
        new SemiJoinNode(
            idAllocator.getNextId(),
            subPlan.getRoot(),
            valueListRelation.getRoot(),
            sourceJoinSymbol,
            filteringSourceJoinSymbol,
            semiJoinOutputSymbol,
            Optional.empty(),
            Optional.empty()),
        subPlan.getSampleWeight());
  }
Exemple #18
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();
  }
  /*
   * TotalDebt = MarginDebt + DfDebt+dfOustandingDebt +accumulatedDepositFee + overdueDepositFee
   */
  public Optional<JsonObject> parse(String json) {
    try {
      final JsonObject body = new JsonObject(json);
      final String type = body.getString(ATDAccountMastKey.MSG_TYPE);
      if (!isATDAccountMastMessage(type)) return Optional.empty();
      System.out.println(body);
      final JsonObject jsonData = body.getJsonObject("data");
      if (jsonData == null) return Optional.empty();
      JsonObject result = new JsonObject();
      result
          .put(ATDAccountMastKey.ACCOUNT, jsonData.getString(ATDAccountMastKey.ACCOUNT))
          .put(
              ATDAccountMastKey.RECEIVING,
              string2Double(jsonData.getString(ATDAccountMastKey.RECEIVING)))
          .put(
              ATDAccountMastKey.BALANCE,
              string2Double(jsonData.getString(ATDAccountMastKey.BALANCE)))
          .put(
              ATDAccountMastKey.TOTALDEBT,
              string2Double(jsonData.getString(ATDAccountMastKey.TOTALDEBT)));
      return Optional.of(result);

    } catch (DecodeException e) {
      LOGGER.error("Cannot decode message to json: ", e);
    }
    return Optional.empty();
  }
 @Test
 public void testOnlyOne() {
   List<Integer> ints = IntStreamEx.rangeClosed(1, 100).boxed().toList();
   checkShortCircuitCollector("One", Optional.empty(), 2, ints::stream, MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterSeveral",
       Optional.empty(),
       2,
       () -> ints.stream().filter(x -> x % 20 == 0),
       MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterSeveral2",
       Optional.empty(),
       40,
       ints::stream,
       MoreCollectors.filtering(x -> x % 20 == 0, MoreCollectors.onlyOne()));
   checkShortCircuitCollector(
       "FilterOne",
       Optional.of(60),
       1,
       () -> ints.stream().filter(x -> x % 60 == 0),
       MoreCollectors.onlyOne());
   checkShortCircuitCollector(
       "FilterNone",
       Optional.empty(),
       0,
       () -> ints.stream().filter(x -> x % 110 == 0),
       MoreCollectors.onlyOne());
 }
Exemple #21
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()));
  }
 public void test_migratedFrom() throws Exception {
   assertTrue(
       OptionalThing.migratedFrom(
               Optional.of("sea"),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   assertFalse(
       OptionalThing.migratedFrom(
               Optional.empty(),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   try {
     OptionalThing.migratedFrom(
             Optional.empty(),
             () -> {
               throw new IllegalStateException("land");
             })
         .get();
     fail();
   } catch (IllegalStateException e) {
     String message = e.getMessage();
     log(message);
     assertContains(message, "land");
   }
 }
Exemple #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__________")));
  }
 @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));
 }
Exemple #25
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));
 }
 @Test
 public void testThatCountsExactlyOneSubmittedRequest() throws Exception {
   executorService.submit(new MockTextQuery(), Optional.empty());
   executorService.submit(new MockTextQuery(), Optional.empty());
   executorService.submit(new MockTextQuery(), Optional.empty());
   sleep(MockTextProvider.FETCH_DELAY / 2);
   assertEquals(1, executorService.countSubmitted());
 }
 @Override
 public List<File> list(String folderPath) {
   return list(
       folderPath,
       Optional.<List<String>>empty(),
       Optional.<FileType>empty(),
       Optional.<String>empty());
 }
  @Test
  public void _07_옵션값_생성() {
    assertThat(inverse(0d), is(Optional.empty()));
    assertThat(inverse(10d), is(Optional.of(0.1d)));

    // ofNullalbe -> null 값 처리
    assertThat(Optional.ofNullable(null), is(Optional.empty()));
    assertThat(Optional.ofNullable("test"), is(Optional.of("test")));
  }
Exemple #29
0
 public Optional<MetricSet> getValues(String metricName, Interval interval) {
   Instant now = Clock.systemUTC().instant();
   Optional<RetentionLevel> accessLevel =
       environment.retentions().findAccessLevelForMetric(metricName);
   Optional<MetricSet> setWithHighestQoS = Optional.empty();
   double highestAvailableQoS = 0;
   if (!accessLevel.isPresent()) {
     return Optional.empty();
   }
   EvictionStrategy evictionStrategy = findEvictionStrategyForAccessLevel(accessLevel.get()).get();
   evictionStrategy.accessing(metricName);
   while (accessLevel.isPresent() && caches.containsKey(accessLevel.get().name())) {
     log.trace("Found accessLevel " + accessLevel.get().name());
     Optional<CachingLevel> cachingLevel =
         environment.cachingConfiguration().findLevelForLevelName(accessLevel.get().name());
     if (cachingLevel.isPresent()) {
       long cachingLevelStart =
           now.minusSeconds(cachingLevel.get().cacheLineWidth() * accessLevel.get().frequency())
               .getEpochSecond();
       if (cachingLevelStart < interval.start()) {
         Optional<MetricSet> metricSet = doGetValues(metricName, interval, cachingLevel.get());
         if (!metricSet.isPresent()) {
           try {
             createNewCacheLines(metricName).get();
           } catch (InterruptedException | ExecutionException e) {
             log.warn("Exception while waiting for threads loading metrics", e);
           }
           metricSet = doGetValues(metricName, interval, cachingLevel.get());
         }
         if (metricSet.isPresent()) {
           log.trace("metricSet contains {} timestamps", metricSet.get().size());
           log.trace("accesslevel: {} | metricSet: {}", accessLevel.get().name(), metricSet.get());
           OptionalDouble serviceAvailable = calculateQoS(interval, metricSet.get());
           if (serviceAvailable.isPresent()
               && serviceAvailable.getAsDouble()
                   >= environment.cachingConfiguration().qualityOfService()) {
             log.trace("returning metricSet");
             return metricSet;
           } else if (serviceAvailable.isPresent()
               && serviceAvailable.getAsDouble() > highestAvailableQoS) {
             log.trace("new highestAvailable set");
             highestAvailableQoS = serviceAvailable.getAsDouble();
             setWithHighestQoS = metricSet;
           }
         } else {
           log.debug(
               "no metricSet for cacheLevel {} metric {} found!",
               accessLevel.get().name(),
               metricName);
         }
       }
     }
     accessLevel = environment.retentions().getNextLevel(accessLevel.get());
   }
   log.trace("service requested not available, returning highest available");
   return setWithHighestQoS;
 }
 private static QualifiedTablePrefix extractQualifiedTablePrefix(
     String catalogName, Map<String, NullableValue> filters) {
   Optional<String> schemaName = getFilterColumn(filters, "table_schema");
   Optional<String> tableName = getFilterColumn(filters, "table_name");
   if (!schemaName.isPresent()) {
     return new QualifiedTablePrefix(catalogName, Optional.empty(), Optional.empty());
   }
   return new QualifiedTablePrefix(catalogName, schemaName, tableName);
 }