Java Code Examples for java.util.Optional

The following are top voted examples for showing how to use java.util.Optional. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mxisd   File: BridgeFetcher.java   View source code 7 votes vote down vote up
@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    Optional<String> mediumUrl = Optional.ofNullable(cfg.getMappings().get(request.getType()));
    if (mediumUrl.isPresent() && !StringUtils.isBlank(mediumUrl.get())) {
        log.info("Using specific medium bridge lookup URL {}", mediumUrl.get());

        return fetcher.find(mediumUrl.get(), request);
    } else if (!StringUtils.isBlank(cfg.getServer())) {
        log.info("Using generic bridge lookup URL {}", cfg.getServer());

        return fetcher.find(cfg.getServer(), request);
    } else {
        log.info("No bridge lookup URL found/configured, skipping");

        return Optional.empty();
    }
}
 
Example 2
Project: Code4Health-Platform   File: UserService.java   View source code 7 votes vote down vote up
/**
 * Update all information for a specific user, and return the modified user.
 */
public Optional<UserDTO> updateUser(UserDTO userDTO) {
    return Optional.of(userRepository
        .findOne(userDTO.getId()))
        .map(user -> {
            user.setLogin(userDTO.getLogin());
            user.setFirstName(userDTO.getFirstName());
            user.setLastName(userDTO.getLastName());
            user.setEmail(userDTO.getEmail());
            user.setImageUrl(userDTO.getImageUrl());
            user.setActivated(userDTO.isActivated());
            user.setLangKey(userDTO.getLangKey());
            Set<Authority> managedAuthorities = user.getAuthorities();
            managedAuthorities.clear();
            userDTO.getAuthorities().stream()
                .map(authorityRepository::findOne)
                .forEach(managedAuthorities::add);
            log.debug("Changed Information for User: {}", user);
            return user;
        })
        .map(UserDTO::new);
}
 
Example 3
Project: athena   File: EncodableDiscreteResources.java   View source code 6 votes vote down vote up
@Override
public Optional<DiscreteResource> lookup(DiscreteResourceId id) {
    DiscreteResource resource = Resources.discrete(id).resource();
    Class<?> cls = getClass(resource);
    return Optional.ofNullable(values.get(cls))
            .filter(x -> x.contains(resource))
            .map(x -> resource);
}
 
Example 4
Project: pac4j-async   File: AsyncBaseClient.java   View source code 6 votes vote down vote up
/**
 * Retrieve the credentials.
 *
 * @param context the web context
 * @return the credentials
 * @throws HttpAction whether an additional HTTP action is required
 */
protected CompletableFuture<C> retrieveCredentials(final AsyncWebContext context) throws HttpAction {
    return this.credentialsExtractor.extract(context)
            .thenCompose(creds -> {
                return Optional.ofNullable(creds)
                        .map(c -> this.authenticator.validate(creds, context).thenApply(v -> creds))
                        .orElse(CompletableFuture.completedFuture(creds)); // The orElse leaves any null returns
            })
            // Now translate a CredentialsException to null
            .handle(ExceptionSoftener.softenBiFunction((creds, throwable) -> {
                // throwable being non-null means creds will be null, so we can make this check here
                logger.info("In handle call");
                if (throwable == null || throwable instanceof CredentialsException) {
                    return creds;
                } else {
                    throw throwable;
                }
            }));
}
 
Example 5
Project: paraflow   File: GetStorageFormatNameAction.java   View source code 6 votes vote down vote up
@Override
public ActionResponse act(ActionResponse input, Connection connection) throws ParaFlowException
{
    Optional<Object> sfIdOp = input.getProperties("sfId");
    Optional<Object> paramOp = input.getParam();
    if (paramOp.isPresent() && sfIdOp.isPresent()) {
        long sfId = (long) sfIdOp.get();
        String sqlStatement = SQLTemplate.findStorageFormatName(sfId);
        ResultList resultList = connection.executeQuery(sqlStatement);
        if (!resultList.isEmpty()) {
            input.setProperties("sfName", resultList.get(0).get(0));
        }
        else {
            throw new StorageFormatNotFoundException(String.valueOf(sfId));
        }
    }
    else {
        throw new ActionParamNotValidException();
    }
    return input;
}
 
Example 6
Project: iotplatform   File: SendMailAction.java   View source code 6 votes vote down vote up
@Override
public Optional<RuleToPluginMsg<?>> convert(RuleContext ctx, ToDeviceActorMsg toDeviceActorMsg,
    RuleProcessingMetaData metadata) {
  String sendFlag = configuration.getSendFlag();
  if (StringUtils.isEmpty(sendFlag) || (Boolean) metadata.get(sendFlag).orElse(Boolean.FALSE)) {
    VelocityContext context = VelocityUtils.createContext(metadata);

    SendMailActionMsg.SendMailActionMsgBuilder builder = SendMailActionMsg.builder();
    fromTemplate.ifPresent(t -> builder.from(VelocityUtils.merge(t, context)));
    toTemplate.ifPresent(t -> builder.to(VelocityUtils.merge(t, context)));
    ccTemplate.ifPresent(t -> builder.cc(VelocityUtils.merge(t, context)));
    bccTemplate.ifPresent(t -> builder.bcc(VelocityUtils.merge(t, context)));
    subjectTemplate.ifPresent(t -> builder.subject(VelocityUtils.merge(t, context)));
    bodyTemplate.ifPresent(t -> builder.body(VelocityUtils.merge(t, context)));
    return Optional.of(new SendMailRuleToPluginActionMsg(toDeviceActorMsg.getTenantId(),
        toDeviceActorMsg.getCustomerId(), toDeviceActorMsg.getDeviceId(), builder.build()));
  } else {
    return Optional.empty();
  }
}
 
Example 7
Project: NioSmtpClient   File: SmtpSession.java   View source code 6 votes vote down vote up
private SendSequence sendPipelinedIfPossible(SmtpRequest mailRequest, Collection<String> recipients, SmtpRequest dataRequest, Optional<SendInterceptor> sequenceInterceptor) {
  List<SmtpRequest> requests = Lists.newArrayListWithExpectedSize(2 + recipients.size());
  requests.add(mailRequest);
  requests.addAll(rpctCommands(recipients));
  requests.add(dataRequest);

  if (ehloResponse.isSupported(Extension.PIPELINING)) {
    return beginSequence(sequenceInterceptor, requests.size(), requests.toArray());
  } else {
    SendSequence s = beginSequence(sequenceInterceptor, 1, requests.get(0));

    for (int i = 1; i < requests.size(); i++) {
      s.thenSend(requests.get(i));
    }

    return s;
  }
}
 
Example 8
Project: aws-sdk-java-v2   File: SdkHttpServiceProviderChain.java   View source code 6 votes vote down vote up
@Override
public Optional<T> loadService() {
    return httpProviders.stream()
                        .map(SdkHttpServiceProvider::loadService)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .findFirst();
}
 
Example 9
Project: secrets-proxy   File: SecretSeries.java   View source code 6 votes vote down vote up
public static SecretSeries of(
        long id,
        String name,
        @Nullable String description,
        ApiDate createdAt,
        @Nullable String createdBy,
        ApiDate updatedAt,
        @Nullable String updatedBy,
        @Nullable String type,
        @Nullable Map<String, String> generationOptions,
        @Nullable Long currentVersion) {

    ImmutableMap<String, String> options = (generationOptions == null) ? ImmutableMap.of() : ImmutableMap.copyOf(generationOptions);

    return new AutoValue_SecretSeries(id,
            name,
            nullToEmpty(description),
            createdAt,
            nullToEmpty(createdBy),
            updatedAt,
            nullToEmpty(updatedBy),
            Optional.ofNullable(type), options,
            Optional.ofNullable(currentVersion));
}
 
Example 10
Project: incubator-netbeans   File: MultiModuleJavadocForBinaryQueryImpl.java   View source code 6 votes vote down vote up
@Override
public URL[] getRoots() {
    URL[] res = cache.get();
    if (res == null) {
        final boolean exists = moduleExists();
        res = Optional.ofNullable(exists ? evaluator.getProperty(jdocProperty) : null)
                .filter((path) -> getOwner(evaluator, helper, artefact, new String[]{prop}) != null)
                .map((path) -> FileUtil.urlForArchiveOrDir(helper.resolveFile(path)))
                .map((url) -> new URL[]{url})
                .orElse(EMPTY);
        if (!cache.compareAndSet(null, res)) {
            URL[] tmp = cache.get();
            res = tmp != null ?
                    tmp :
                    res;
        } else {
            currentModuleExists.set(exists);
        }
    }
    return Arrays.copyOf(res, res.length);
}
 
Example 11
Project: wall-t   File: ApiControllerTest.java   View source code 6 votes vote down vote up
@Test
public void loadBuildTypeList_callback_dispatches_parent_project_on_event_bus( ) throws Exception {
    // Setup
    final ProjectData project = new ProjectData( "p1", "pname", Optional.<String>empty( ) );
    final ProjectData project2 = new ProjectData( "p2", "pname", Optional.<String>empty( ) );
    _projectManager.registerProjects( ImmutableList.of( project, project2 ) );

    final BuildTypeList buildTypelist = new BuildTypeList( );
    buildTypelist.addBuildType( new BuildType( "bt1", "btName", "pname", "p2" ) );

    when( _mockRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class ) )
            .thenReturn( Futures.immediateFuture( buildTypelist ) );
    // Exercise
    _apiController.loadBuildTypeList( );
    // Verify
    assertThat( _dispatchedObjects, not( hasItem( project ) ) );
    assertThat( _dispatchedObjects, hasItem( project2 ) );
}
 
Example 12
Project: newrelic-alerts-configurator   File: PolicyConfigurator.java   View source code 6 votes vote down vote up
void sync(@NonNull PolicyConfiguration config) {
    LOG.info("Synchronizing policy {}...", config.getPolicyName());

    AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder()
        .name(config.getPolicyName())
        .incidentPreference(config.getIncidentPreference().name())
        .build();

    Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName());

    if (policy.isPresent()) {
        AlertsPolicy oldPolicy = policy.get();
        if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) {
            api.getAlertsPoliciesApi().delete(oldPolicy.getId());
            api.getAlertsPoliciesApi().create(alertsPolicyFromConfig);
            LOG.info(format("Policy %s updated", config.getPolicyName()));
        }
    } else {
        api.getAlertsPoliciesApi().create(alertsPolicyFromConfig);
        LOG.info("Policy {} created", config.getPolicyName());
    }
    LOG.info("Policy {} synchronized", config.getPolicyName());
}
 
Example 13
Project: ExPetrum   File: IWeightProvider.java   View source code 5 votes vote down vote up
static Optional<Pair<Byte, Byte>> tryGetRegisteredVolume(ItemStack is)
{
	if (is.isEmpty())
	{
		return Optional.empty();
	}
	
	String name = is.getItem().getRegistryName().toString();
	int meta = is.getMetadata();
	Pair<String, Short> p = Pair.of(name, (short) meta);
	if (configVolumes.containsKey(p))
	{
		return Optional.of(configVolumes.get(p));
	}
	
	Pair<String, Short> p2 = Pair.of(name, (short) OreDictionary.WILDCARD_VALUE);
	if (configVolumes.containsKey(p2))
	{
		return Optional.of(configVolumes.get(p2));
	}
	
	return Optional.empty();
}
 
Example 14
Project: buenojo   File: UserServiceTest.java   View source code 5 votes vote down vote up
@Test
public void assertThatUserMustExistToResetPassword() {
    Optional<User> maybeUser = userService.requestPasswordReset("[email protected]");
    assertThat(maybeUser.isPresent()).isFalse();

    maybeUser = userService.requestPasswordReset("[email protected]");
    assertThat(maybeUser.isPresent()).isTrue();

    assertThat(maybeUser.get().getEmail()).isEqualTo("[email protected]");
    assertThat(maybeUser.get().getResetDate()).isNotNull();
    assertThat(maybeUser.get().getResetKey()).isNotNull();
}
 
Example 15
Project: ProjectAres   File: MarkupParser.java   View source code 5 votes vote down vote up
BaseComponent anchor(Element el) {
    final Optional<String> href = XML.attrValue(el, "href");
    final Optional<BaseComponent> content = nonEmptyContent(el);
    final String type = XML.attrValue(el, "type").orElse("url");
    final Renderable<URI> uri;

    try {
        switch(type) {
            case "user":
                uri = new UserURI(href.orElse(""));
                break;

            case "home":
                uri = Renderable.of(Links.homeUri(href.orElse("/")));
                break;

            case "url":
                uri = Renderable.of(new URI(href.orElseThrow(() -> new MissingException("attribute", "href"))));
                break;

            default:
                throw new ValueException("Unknown anchor type '" + type + "'");
        }
    } catch(URISyntaxException e) {
        throw new ValueException(e.getMessage());
    }

    return new LinkComponent(uri, content);
}
 
Example 16
Project: stock-patterns-recognition   File: PatternsDetectorTest.java   View source code 5 votes vote down vote up
@Test
public void groupsOfThreeAbandonBabyBearish() {
    final List<Pattern> patterns =
            PROCESSOR.scan(Stream.of(buildCandlestick(5.0, 7.0, 9.0, 1.0, BodyType.MARIBOZU_LONG, TrendDirection.UPPER),
                                     buildCandlestick(15.0, 15.0, 15.0, 14.0, BodyType.DOJI, TrendDirection.UPPER),
                                     buildCandlestick(10.0, 6.0, 11.0, 1.0, BodyType.MARIBOZU_LONG, TrendDirection.UPPER)))
                    .collect(toList());
    assertEquals(2, patterns.size());

    final Optional<Pattern> detectedPattern = patterns.stream()
            .filter(p -> p.getPatternType() != PatternType.DOJI_STAR_BEARISH)
            .findFirst();
    assertTrue(detectedPattern.isPresent());
    assertEquals(PatternType.ABANDON_BABY_BEARISH, detectedPattern.get().getPatternType());
}
 
Example 17
Project: cmc-claim-store   File: PartyUtils.java   View source code 5 votes vote down vote up
public static Optional<String> getContactPerson(Party party) {
    if (party instanceof Company) {
        return ((Company) party).getContactPerson();
    } else if (party instanceof Organisation) {
        return ((Organisation) party).getContactPerson();
    }
    return Optional.empty();
}
 
Example 18
Project: ci-hands-on   File: UserRemoteServiceTest.java   View source code 5 votes vote down vote up
@Test
public void should_get_user_by_call_douban_user_api() {
    // given
    final String userId = "ahbei";
    when(remoteConfig.getDoubanUserGetUrl()).thenReturn("user/");
    when(restTemplate.getForEntity("user/ahbei", User.class)).thenReturn(ResponseEntity.ok(new User()));

    // when
    Optional<User> userOptional = userRemoteService.get(userId);

    // then
    assertThat(userOptional.isPresent()).isEqualTo(true);
}
 
Example 19
Project: gwm_Crates   File: Drop.java   View source code 5 votes vote down vote up
public Drop(ConfigurationNode node) {
    super(node);
    try {
        ConfigurationNode price_node = node.getNode("PRICE");
        ConfigurationNode drop_item_node = node.getNode("DROP_ITEM");
        ConfigurationNode fake_level_node = node.getNode("FAKE_LEVEL");
        ConfigurationNode level_node = node.getNode("LEVEL");
        ConfigurationNode permission_levels_node = node.getNode("PERMISSION_LEVELS");
        ConfigurationNode permission_fake_levels_node = node.getNode("PERMISSION_FAKE_LEVELS");
        if (!price_node.isVirtual()) {
            price = Optional.of(new BigDecimal(price_node.getString("0")));
        }
        if (!drop_item_node.isVirtual()) {
            drop_item = Optional.of(Utils.parseItem(drop_item_node));
        }
        if (!fake_level_node.isVirtual()) {
            fake_level = Optional.of(fake_level_node.getInt(1));
        }
        if (!permission_levels_node.isVirtual()) {
            permission_levels = permission_levels_node.getValue(new TypeToken<Map<String, Integer>>(){});
        }
        if (!permission_fake_levels_node.isVirtual()) {
            permission_fake_levels = permission_fake_levels_node.getValue(new TypeToken<Map<String, Integer>>(){});
        }
        level = level_node.getInt(1);
        if (level < 1) {
            level = 1;
        }
    } catch (Exception e) {
        throw new RuntimeException("Exception creating Drop!", e);
    }
}
 
Example 20
Project: openjdk-jdk10   File: ModuleNamesTest.java   View source code 5 votes vote down vote up
@Test(dataProvider = "legalModuleNames")
public void testLegalExports(String mn, String expected) throws Exception {
    ModuleDescriptor md = newBuilder("m")
            .requires("java.base")
            .exports("p", Set.of(mn))
            .build();
    ByteBuffer bb = toBuffer(md);
    ModuleDescriptor descriptor = ModuleDescriptor.read(bb);
    Optional<Exports> export = descriptor.exports().stream().findAny();
    assertTrue(export.isPresent());
    assertTrue(export.get().targets().contains(expected));
}
 
Example 21
Project: paraflow   File: RenameColumnAction.java   View source code 5 votes vote down vote up
@Override
public ActionResponse act(ActionResponse input, Connection connection) throws ParaFlowException
{
    Optional<Object> dbIdOp = input.getProperties("dbId");
    Optional<Object> tblIdOp = input.getProperties("tblId");
    Optional<Object> oldNameOp = input.getProperties("oldName");
    Optional<Object> newNameOp = input.getProperties("newName");
    if (dbIdOp.isPresent()
            && tblIdOp.isPresent()
            && oldNameOp.isPresent()
            && newNameOp.isPresent()) {
        long dbId = (long) dbIdOp.get();
        long tblId = (long) tblIdOp.get();
        String oldName = oldNameOp.get().toString();
        String newName = newNameOp.get().toString();
        String sqlStatement = SQLTemplate.renameColumn(
                dbId,
                tblId,
                oldName,
                newName);
        int status = connection.executeUpdate(sqlStatement);
        if (status == 0) {
            throw new ColumnRenameException();
        }
    }
    else {
        throw new ActionParamNotValidException();
    }
    return input;
}
 
Example 22
Project: runtime-builder-java   File: AppYamlFinderTest.java   View source code 5 votes vote down vote up
@Test
public void testAppYamlAtSrcMainNoEnvVar() throws IOException {
  String yamlPath = "src/main/appengine/app.yaml";
  Path workspace = new TestWorkspaceBuilder()
      .file(yamlPath).build()
      .build();

  Optional<Path> result = new AppYamlFinder(Optional.empty()).findAppYamlFile(workspace);
  assertEquals(workspace.resolve(yamlPath), result.get());
}
 
Example 23
Project: Multi-Sentence-Compression   File: DefaultPathCompressor.java   View source code 5 votes vote down vote up
@Override
public Optional<String> compress(GraphDatabaseService graph, int maxDepth) {
    try (Transaction tx = graph.beginTx()) {
        long elapsed = System.nanoTime();
        logger.debug("Computing all the paths between START and END nodes and their costs...");
        int total = 0;
        Set<CostPath> paths = new TreeSet<>();
        PathFinder<Path> finder = GraphAlgoFactory.allPaths(EXPANDER, maxDepth);
        for (Path path : finder.findAllPaths(GraphModel.start(graph), GraphModel.end(graph))) {
            if (path.length() >= PathCompressor.MIN_DEPTH && PathCompressor.hasVerb(path)) {
                double cost = 0.0;
                for (Relationship follows : path.relationships()) {
                    cost += (double) follows.getProperty("weight", 1.0);
                }
                paths.add(new CostPath(path, cost));
            }
            total += 1;
        }
        logger.info("{} valid path/s found (out of {} possible) in {} ms.",
                paths.size(), total, String.format("%,.3f", elapsed / 1_000_000_000.0));
        if (paths.isEmpty()) {
            return Optional.empty();
        }
        logger.debug("Generating the compressive summary");
        return PathCompressor.decode(paths.iterator().next().getPath());
    }
}
 
Example 24
Project: outland   File: FeatureResource.java   View source code 5 votes vote down vote up
@POST
@Path("/{group}")
@PermitAll
@Timed(name = "registerFeature")
public Response registerFeature(
    @Auth AuthPrincipal principal,
    Feature feature,
    @Context HttpHeaders httpHeaders
) throws AuthenticationException {

  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = groupService.loadByKey(feature.getGroup());
  if (!maybe.isPresent()) {
    return notFound(start);
  }

  accessControlSupport.throwUnlessGrantedFor(principal, maybe.get());

  final URI loc = locationUrl(feature);

  final Optional<String> maybeSeen = idempotencyChecker.extractKey(httpHeaders);
  if (maybeSeen.isPresent() && idempotencyChecker.seen(maybeSeen.get())) {
    return respondAlreadyCreated(feature, start, loc, maybeSeen);
  }

  return headers.enrich(
      Response.created(loc).entity(featureService.registerFeature(feature)), start).build();
}
 
Example 25
Project: opentracing-prometheus-example   File: OrderMgrController.java   View source code 5 votes vote down vote up
@RequestMapping("/sell")
public String sell() throws InterruptedException {
    Thread.sleep(1 + (long)(Math.random()*500));
    Optional.ofNullable(tracer.activeSpan()).ifPresent(as -> as.setBaggageItem("transaction", "sell"));
    ResponseEntity<String> response = restTemplate.getForEntity(accountMgrUrl + "/account", String.class);
    return "SELL + " + response.getBody();
}
 
Example 26
Project: queries   File: OptionalNamedParameterFeatureBase.java   View source code 5 votes vote down vote up
public CompiledQueryOneParameterPart(String beforeSql, String afterSql, List<Expression> expressions,
		ParameterBinder parameterBinder) {
	this.beforeSql = beforeSql;
	this.afterSql = afterSql;
	this.valueExpression = expressions.get(0);
	this.conditionalExpression = expressions.size() == 1 ? Optional.empty() : Optional.of(expressions.get(1));
	this.parameterBinder = parameterBinder;
}
 
Example 27
Project: Dr-Assistant   File: NewTemplateController.java   View source code 5 votes vote down vote up
private void deleteDrugFromList(TemplateDrug drug) {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Confirm");
    alert.setHeaderText("Are you sure");
    alert.setContentText("Click ok if you want to delete this drug");
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK) {
        drugTable.getItems().remove(drug);
        templateDrugList.remove(drug);
    }
}
 
Example 28
Project: r8   File: PrintUsageTest.java   View source code 5 votes vote down vote up
private static void inspectShaking8(PrintUsageInspector inspector) {
  Optional<ClassSubject> thing = inspector.clazz("shaking8.Thing");
  assertTrue(thing.isPresent());
  assertTrue(thing.get().field("int", "aField"));
  assertFalse(inspector.clazz("shaking8.OtherThing").isPresent());
  assertTrue(inspector.clazz("shaking8.YetAnotherThing").isPresent());
}
 
Example 29
Project: esup-ecandidat   File: OffreFormationController.java   View source code 5 votes vote down vote up
/** Recupere un objet de type OdfDiplome suivant son code
 * @param ctrCand
 * @param siScolTypDiplome
 * @return l'odfFormation
 */
private OdfFormation getFormationFromOffre(OdfDiplome odfDiplome, Formation formation){
	if (odfDiplome.getListeFormation()==null || odfDiplome.getListeFormation().size()==0){
		return null;
	}
	
	Optional<OdfFormation> formOpt = odfDiplome.getListeFormation().stream().filter(form->form.getIdFormation().equals(formation.getIdForm())).findFirst();
	if (formOpt.isPresent()){
		return formOpt.get();
	}
	return null;
}
 
Example 30
Project: jdk8u-jdk   File: ObjectInputFilter.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Status checkInput(FilterInfo filterInfo) {
    if (filterInfo.references() < 0
            || filterInfo.depth() < 0
            || filterInfo.streamBytes() < 0
            || filterInfo.references() > maxReferences
            || filterInfo.depth() > maxDepth
            || filterInfo.streamBytes() > maxStreamBytes) {
        return Status.REJECTED;
    }

    Class<?> clazz = filterInfo.serialClass();
    if (clazz != null) {
        if (clazz.isArray()) {
            if (filterInfo.arrayLength() >= 0 && filterInfo.arrayLength() > maxArrayLength) {
                // array length is too big
                return Status.REJECTED;
            }
            do {
                // Arrays are decided based on the component type
                clazz = clazz.getComponentType();
            } while (clazz.isArray());
        }

        if (clazz.isPrimitive())  {
            // Primitive types are undecided; let someone else decide
            return Status.UNDECIDED;
        } else {
            // Find any filter that allowed or rejected the class
            final Class<?> cl = clazz;
            Optional<Status> status = filters.stream()
                    .map(f -> f.apply(cl))
                    .filter(p -> p != Status.UNDECIDED)
                    .findFirst();
            return status.orElse(Status.UNDECIDED);
        }
    }
    return Status.UNDECIDED;
}
 
Example 31
Project: jdbishard   File: ShardRegistry.java   View source code 5 votes vote down vote up
@Override
public Optional<ShardIdT> getShardFor(KeyT shardKey) {
    if (shardMap.containsKey(shardKey)) {
        return Optional.of(shardMap.get(shardKey));
    }
    return Optional.empty();
}
 
Example 32
Project: DreamBlocks   File: NewGameMenu.java   View source code 5 votes vote down vote up
public Optional<WORLD_WIDTH> handleClick(int x, int y){
    if(menu_mini.isInside(x, y)){
        return Optional.of(WORLD_WIDTH.MINI);
    } else if (menu_medium.isInside(x, y)){
        return Optional.of(WORLD_WIDTH.MEDIUM);
    } else if (menu_big.isInside(x, y)){
        return Optional.of(WORLD_WIDTH.BIG);
    } else {
        return Optional.empty();
    }
}
 
Example 33
Project: buckaroo   File: PartialDependency.java   View source code 5 votes vote down vote up
public static PartialDependency of(final Identifier organization, final Identifier project) {
    return new PartialDependency(
        Optional.empty(),
        Optional.of(organization),
        project,
        Optional.empty());
}
 
Example 34
Project: gemoc-studio-modeldebugging   File: GenericTraceExtractor.java   View source code 5 votes vote down vote up
@Override
public String getValueDescription(Value<?> value) {
	if (value == null) {
		return "";
	}
	String description = getDimensionLabel((Dimension<?>) value.eContainer()) + " : ";
	final String attributeName;
	if (value instanceof GenericValue) {
		if (value instanceof GenericAttributeValue) {
			attributeName = "attributeValue";
		} else if (value instanceof SingleReferenceValue) {
			attributeName = "referenceValue";
		} else {
			attributeName = "referenceValues";
		}
	} else {
		attributeName = getValueName(value);
	}
	if (attributeName.length() > 0) {
		final Optional<EStructuralFeature> attribute = value.eClass().getEAllStructuralFeatures().stream()
				.filter(r -> r.getName().equals(attributeName)).findFirst();
		if (attribute.isPresent()) {
			final Object o = value.eGet(attribute.get());
			return description + getObjectDescription(o);
		}
	}
	return description + value;
}
 
Example 35
Project: REST-Web-Services   File: ImageValidator.java   View source code 5 votes vote down vote up
@Override
public boolean isValid(File file, ConstraintValidatorContext context) {
    if(Optional.ofNullable(file).isPresent()) {
        String contentType;
        try {
            contentType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            throw new ResourcePreconditionException("An I/O error occurs");
        }
        return contentType.equals("image/png")
                || contentType.equals("image/jpeg");
    }

    return true;
}
 
Example 36
Project: java-monitoring-client-library   File: MetricReporterTest.java   View source code 5 votes vote down vote up
@Test
public void testRunOneIteration_enqueuesBatch() throws Exception {
  Metric<?> metric =
      new Counter("/name", "description", "vdn", ImmutableSet.<LabelDescriptor>of());
  when(registry.getRegisteredMetrics()).thenReturn(ImmutableList.of(metric, metric));
  MetricReporter reporter = new MetricReporter(writer, 10L, threadFactory, registry, writeQueue);

  reporter.runOneIteration();

  verify(writeQueue).offer(Optional.of(ImmutableList.<MetricPoint<?>>of()));
}
 
Example 37
Project: mux2fs   File: MuxFsTest.java   View source code 5 votes vote down vote up
private File openAndClose(String name, int nonce, long size)
		throws Exception {
	String mkvName = name + ".mkv";
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path mkv = mockPath(mkvName);
	Path srt = mockPath(name + ".srt");
	mockShuffledDirectoryStream(mirrorRoot, mkv, srt);
	mockAttributes(mkv, nonce, size);
	Muxer muxer = mock(Muxer.class);
	when(muxerFactory.from(mkv, srt, tempDir)).thenReturn(muxer);
	Path muxedFile = mockPath(tempDir, "file1.mkv");
	when(muxer.getOutput()).thenReturn(Optional.of(muxedFile));
	when(fileSystem.provider().newFileChannel(eq(muxedFile), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class));
	fs.open(mkvName, filler);
	fs.release(mkvName, handleCaptor.getValue());
	verify(muxerFactory).from(mkv, srt, tempDir);
	verifyNoMoreInteractions(muxerFactory);
	verify(muxer).start();
	verify(muxer).waitForOutput();
	verify(muxer, atLeast(1)).getOutput();
	verifyNoMoreInteractions(muxer);
	verify(filler).setFileHandle(gt(1));
	verify(fileSystem.provider()).newFileChannel(eq(muxedFile), eq(set(StandardOpenOption.READ)));
	return muxedFile.toFile();
}
 
Example 38
Project: matrix-appservice-email   File: EmailFormatterOutboud.java   View source code 5 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, List<_BridgeMessageContent> contents, boolean allowReply) throws MessagingException, IOException {
    MimeMultipart body = new MimeMultipart();
    body.setSubType("alternative");

    for (_BridgeMessageContent content : contents) {
        MimeMultipart contentBody = new MimeMultipart();
        contentBody.setSubType("related");

        Optional<_EmailTemplateContent> contentTemplateOpt = template.getContent(content.getMime());
        if (!contentTemplateOpt.isPresent()) {
            continue;
        }

        _EmailTemplateContent contentTemplate = contentTemplateOpt.get();
        contentBody.addBodyPart(makeBodyPart(data, contentTemplate, content));

        if (contentTemplate.getContent().contains(EmailTemplateToken.SenderAvatar.getToken()) &&
                data.getSenderAvatar() != null && data.getSenderAvatar().isValid()) {
            log.info("Adding avatar for sender");

            MimeBodyPart avatarBp = new MimeBodyPart();
            _MatrixContent avatar = data.getSenderAvatar();
            String filename = avatar.getFilename().orElse("unknown." + avatar.getType().replace("image/", ""));

            avatarBp.setContent(avatar.getData(), avatar.getType());
            avatarBp.setContentID("<" + senderAvatarId + ">");
            avatarBp.setDisposition("inline; filename=" + filename + "; size=" + avatar.getData().length + ";");

            contentBody.addBodyPart(avatarBp);
        }

        MimeBodyPart part = new MimeBodyPart();
        part.setContent(contentBody);

        body.addBodyPart(part);
    }

    return makeEmail(data, template, body, allowReply);
}
 
Example 39
Project: SensorThingsManager   File: ControllerCollection.java   View source code 5 votes vote down vote up
@FXML
private void actionButtonFilter(ActionEvent event) {
    LOGGER.info("Filter button clicked.");
    if (buttonFilter.isSelected()) {
        TextInputDialog textInputDialog = new TextInputDialog(filter);
        textInputDialog.setHeaderText("Set filter");
        textInputDialog.setResizable(true);
        Optional<String> filterOptional = textInputDialog.showAndWait();
        if (filterOptional.isPresent()) {
            this.filter = filterOptional.get();
        } else {
            this.filter = "";
        }
    }
}
 
Example 40
Project: trading4j   File: MessageBasedClientConnectionTest.java   View source code 5 votes vote down vote up
/**
 * The class should be able to write {@link TrendForMarketDataMessage} correctly.
 * 
 * @throws CommunicationException
 *             Not expected to leave the test method.
 */
@Test
public void shouldWriteTrendForMarketDataMessages() throws CommunicationException {
    final TrendForMarketDataMessage trend1 = new TrendForMarketDataMessage(Optional.of(MarketDirection.DOWN));
    final TrendForMarketDataMessage trend2 = new TrendForMarketDataMessage(Optional.of(MarketDirection.UP));

    cut.sendMessage(trend1);
    cut.sendMessage(trend2);

    final InOrder inOrder = inOrder(client);
    inOrder.verify(client).trySendByte(MessageType.TREND_FOR_MARKET_DATA.getMessageNumber());
    inOrder.verify(client).trySendByte((byte) 1);
    inOrder.verify(client).trySendByte(MessageType.TREND_FOR_MARKET_DATA.getMessageNumber());
    inOrder.verify(client).trySendByte((byte) 0);
}