Java 类java.util.Optional 实例源码

项目:mxisd    文件:BridgeFetcher.java   
@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();
    }
}
项目:Code4Health-Platform    文件:UserService.java   
/**
 * 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);
}
项目:ExPetrum    文件:IWeightProvider.java   
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();
}
项目:athena    文件:EncodableDiscreteResources.java   
@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);
}
项目:pac4j-async    文件:AsyncBaseClient.java   
/**
 * 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;
                }
            }));
}
项目:paraflow    文件:GetStorageFormatNameAction.java   
@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;
}
项目:iotplatform    文件:SendMailAction.java   
@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();
  }
}
项目:NioSmtpClient    文件:SmtpSession.java   
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;
  }
}
项目:aws-sdk-java-v2    文件:SdkHttpServiceProviderChain.java   
@Override
public Optional<T> loadService() {
    return httpProviders.stream()
                        .map(SdkHttpServiceProvider::loadService)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .findFirst();
}
项目:secrets-proxy    文件:SecretSeries.java   
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));
}
项目:incubator-netbeans    文件:MultiModuleJavadocForBinaryQueryImpl.java   
@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);
}
项目:wall-t    文件:ApiControllerTest.java   
@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 ) );
}
项目:newrelic-alerts-configurator    文件:PolicyConfigurator.java   
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());
}
项目:ProjectAres    文件:MarkupParser.java   
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);
}
项目:stock-patterns-recognition    文件:PatternsDetectorTest.java   
@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());
}
项目:cmc-claim-store    文件:PartyUtils.java   
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();
}
项目:ci-hands-on    文件:UserRemoteServiceTest.java   
@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);
}
项目:gwm_Crates    文件:Drop.java   
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);
    }
}
项目:openjdk-jdk10    文件:ModuleNamesTest.java   
@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));
}
项目:paraflow    文件:RenameColumnAction.java   
@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;
}
项目:runtime-builder-java    文件:AppYamlFinderTest.java   
@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());
}
项目:Multi-Sentence-Compression    文件:DefaultPathCompressor.java   
@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());
    }
}
项目:outland    文件:FeatureResource.java   
@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();
}
项目:opentracing-prometheus-example    文件:OrderMgrController.java   
@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();
}
项目:queries    文件:OptionalNamedParameterFeatureBase.java   
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;
}
项目:Dr-Assistant    文件:NewTemplateController.java   
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);
    }
}
项目:r8    文件:PrintUsageTest.java   
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());
}
项目:esup-ecandidat    文件:OffreFormationController.java   
/** 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;
}
项目:jdk8u-jdk    文件:ObjectInputFilter.java   
/**
 * {@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;
}
项目:jdbishard    文件:ShardRegistry.java   
@Override
public Optional<ShardIdT> getShardFor(KeyT shardKey) {
    if (shardMap.containsKey(shardKey)) {
        return Optional.of(shardMap.get(shardKey));
    }
    return Optional.empty();
}
项目:DreamBlocks    文件:NewGameMenu.java   
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();
    }
}
项目:buckaroo    文件:PartialDependency.java   
public static PartialDependency of(final Identifier organization, final Identifier project) {
    return new PartialDependency(
        Optional.empty(),
        Optional.of(organization),
        project,
        Optional.empty());
}
项目:gemoc-studio-modeldebugging    文件:GenericTraceExtractor.java   
@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;
}
项目:REST-Web-Services    文件:ImageValidator.java   
@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;
}
项目:java-monitoring-client-library    文件:MetricReporterTest.java   
@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()));
}
项目:mux2fs    文件:MuxFsTest.java   
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();
}
项目:matrix-appservice-email    文件:EmailFormatterOutboud.java   
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);
}
项目:SensorThingsManager    文件:ControllerCollection.java   
@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 = "";
        }
    }
}
项目:trading4j    文件:MessageBasedClientConnectionTest.java   
/**
 * 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);
}