java.util.Optional#get ( )源码实例Demo

下面列出了java.util.Optional#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        throw new IllegalArgumentException("Only UsernamePasswordAuthenticationToken is supported, " + authentication.getClass() + " was attempted");
    }

    for (AuthenticationPerformer authenticationPerformer : authenticationPerformers) {
        try {
            Optional<Authentication> completedAuthentication = authenticationPerformer.performAuthentication(authentication)
                                                                   .filter(Authentication::isAuthenticated);
            if (completedAuthentication.isPresent()) {
                return completedAuthentication.get();
            }
        } catch (Exception ex) {
            String authTypeError = String.format("Error with with authentication type %s - cause: ", authenticationPerformer.getAuthenticationType());
            logger.error(authTypeError, ex);
        }
    }

    return authentication;
}
 
源代码2 项目: che   文件: JpaKubernetesRuntimeStateCache.java
@Transactional(rollbackOn = {RuntimeException.class, InfrastructureException.class})
protected void doUpdateStatus(
    RuntimeIdentity id, Predicate<WorkspaceStatus> predicate, WorkspaceStatus newStatus)
    throws InfrastructureException {
  EntityManager entityManager = managerProvider.get();

  Optional<KubernetesRuntimeState> existingStateOpt = get(id);

  if (!existingStateOpt.isPresent()) {
    throw new InfrastructureException(
        "Runtime state for workspace with id '" + id.getWorkspaceId() + "' was not found");
  }

  KubernetesRuntimeState existingState = existingStateOpt.get();
  if (!predicate.test(existingState.getStatus())) {
    throw new IllegalStateException("Runtime status doesn't match to the specified predicate");
  }

  existingState.setStatus(newStatus);
  entityManager.flush();
}
 
源代码3 项目: onos   文件: DistributedVirtualNetworkStore.java
@Override
public void bindPort(NetworkId networkId, DeviceId deviceId,
                     PortNumber portNumber, ConnectPoint realizedBy) {

    Set<VirtualPort> virtualPortSet = networkIdVirtualPortSetMap
            .get(networkId);

    Optional<VirtualPort> virtualPortOptional = virtualPortSet.stream().filter(
            p -> p.element().id().equals(deviceId) &&
                    p.number().equals(portNumber)).findFirst();
    checkState(virtualPortOptional.isPresent(), "The virtual port has not been added.");

    VirtualDevice device = deviceIdVirtualDeviceMap.get(new VirtualDeviceId(networkId, deviceId));
    checkNotNull(device, "The device has not been created for deviceId: "
            + deviceId);

    VirtualPort vPort = virtualPortOptional.get();
    virtualPortSet.remove(vPort);
    vPort = new DefaultVirtualPort(networkId, device, portNumber, realizedBy);
    virtualPortSet.add(vPort);
    networkIdVirtualPortSetMap.put(networkId, virtualPortSet);
    notifyDelegate(new VirtualNetworkEvent(VirtualNetworkEvent.Type.VIRTUAL_PORT_UPDATED,
                                           networkId, device, vPort));
}
 
源代码4 项目: retro-game   文件: EventScheduler.java
private Event getNext() throws InterruptedException {
  lock.lock();
  try {
    Optional<Event> event;
    while (!(event = eventRepository.findFirstByOrderByAtAscIdAsc()).isPresent() ||
        event.get().getAt().after(new Date())) {
      if (event.isPresent()) {
        condition.awaitUntil(event.get().getAt());
      } else {
        condition.await();
      }
    }
    return event.get();
  } finally {
    lock.unlock();
  }
}
 
源代码5 项目: cloudbreak   文件: SdxServiceDecorator.java
public void prepareMultipleSdxAttributes(Set<StackViewV4Response> stackViewResponses) {
    List<SdxClusterResponse> responses = sdxClientService.list();
    for (StackViewV4Response stackViewResponse : stackViewResponses) {
        Optional<SdxClusterResponse> first = responses.stream()
                .filter(x -> x.getEnvironmentCrn().equals(stackViewResponse.getEnvironmentCrn()))
                .findFirst();
        if (first.isPresent()) {
            SdxClusterResponse sdxCluster = first.get();
            SharedServiceV4Response sharedServiceResponse = stackViewResponse.getCluster().getSharedServiceResponse();
            sharedServiceResponse.setSdxCrn(sdxCluster.getCrn());
            sharedServiceResponse.setSdxName(sdxCluster.getName());
        } else {
            LOGGER.info("No SDX cluster found for stack {}.", stackViewResponse.getCrn());
        }
    }
}
 
源代码6 项目: nomulus   文件: LevelDbLogReader.java
@Override
public boolean hasNext() {
  while (recordList.isEmpty()) {
    try {
      Optional<byte[]> block = readFromChannel();
      if (!block.isPresent()) {
        return false;
      }
      if (block.get().length != BLOCK_SIZE) {
        throw new IllegalStateException("Data size is not multiple of " + BLOCK_SIZE);
      }
      processBlock(block.get());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  return true;
}
 
源代码7 项目: Singularity   文件: SmtpMailer.java
private void setupExpireFormat(
  Map<String, Object> additionalProperties,
  Optional<Long> durationMillis
) {
  if (!durationMillis.isPresent()) {
    return;
  }

  additionalProperties.put("expiring", Boolean.TRUE);

  final long now = System.currentTimeMillis();
  final long future = now + durationMillis.get();
  additionalProperties.put(
    "expireFormat",
    DateFormatUtils.format(
      new Date(future),
      smtpConfiguration.getMailerDatePattern(),
      smtpConfiguration.getMailerTimeZone()
    )
  );
}
 
源代码8 项目: buck   文件: DefaultPexToolProvider.java
private Tool getRawPexTool(
    BuildRuleResolver resolver,
    RuleKeyConfiguration ruleKeyConfiguration,
    TargetConfiguration targetConfiguration) {
  Optional<Tool> executable = pythonBuckConfig.getRawPexTool(resolver, targetConfiguration);
  if (executable.isPresent()) {
    return executable.get();
  }

  PythonInterpreter pythonInterpreter =
      toolchainProvider.getByName(
          PythonInterpreter.DEFAULT_NAME, targetConfiguration, PythonInterpreter.class);

  return VersionedTool.of(
      "pex",
      pythonBuckConfig.getSourcePath(pythonInterpreter.getPythonInterpreterPath()),
      ruleKeyConfiguration.getCoreKey(),
      ImmutableList.of(DEFAULT_PATH_TO_PEX.toString()));
}
 
源代码9 项目: rdf4j   文件: Model.java
/**
 * Sets the prefix for a namespace. This will replace any existing namespace associated to the prefix.
 *
 * @param prefix The new prefix.
 * @param name   The namespace name that the prefix maps to.
 * @return The {@link Namespace} object for the given namespace.
 */
public default Namespace setNamespace(String prefix, String name) {
	Optional<? extends Namespace> result = getNamespace(prefix);
	if (!result.isPresent() || !result.get().getName().equals(name)) {
		result = Optional.of(new SimpleNamespace(prefix, name));
		setNamespace(result.get());
	}
	return result.get();
}
 
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    Optional<Account> account = accountRepo.findByUsername( s );
    if ( account.isPresent() ) {
        return account.get();
    } else {
        throw new UsernameNotFoundException(String.format("Username[%s] not found", s));
    }
}
 
源代码11 项目: demo-gwt-springboot   文件: PersonImpl.java
@Override
public void changeLastAddress(Address address, Boolean isLastOne) {
	if (!isLastOne) {
		Optional<AddressImpl> findFirst = addresses.stream().findFirst();
		Address addressFound = findFirst.get();
		addressFound.setStreet("New Street on the Blocks");
	}
}
 
源代码12 项目: Web-API   文件: UniversalMarketServlet.java
private UniversalMarket getUMPlugin() {
    Optional<PluginContainer> optContainer = Sponge.getPluginManager().getPlugin("universalmarket");
    if (!optContainer.isPresent()) {
        throw new InternalServerErrorException("UniversalMarket plugin not found");
    }

    Optional<?> optPlugin = optContainer.get().getInstance();
    if (!optPlugin.isPresent()) {
        throw new InternalServerErrorException("UniversalMarket plugin instance not found");
    }

    return (UniversalMarket)optPlugin.get();
}
 
源代码13 项目: Bytecoder   文件: ModuleBootstrap.java
/**
 * Process the --add-reads options to add any additional read edges that
 * are specified on the command-line.
 */
private static void addExtraReads(ModuleLayer bootLayer) {

    // decode the command line options
    Map<String, List<String>> map = decode("jdk.module.addreads.");
    if (map.isEmpty())
        return;

    for (Map.Entry<String, List<String>> e : map.entrySet()) {

        // the key is $MODULE
        String mn = e.getKey();
        Optional<Module> om = bootLayer.findModule(mn);
        if (!om.isPresent()) {
            warnUnknownModule(ADD_READS, mn);
            continue;
        }
        Module m = om.get();

        // the value is the set of other modules (by name)
        for (String name : e.getValue()) {
            if (ALL_UNNAMED.equals(name)) {
                Modules.addReadsAllUnnamed(m);
            } else {
                om = bootLayer.findModule(name);
                if (om.isPresent()) {
                    Modules.addReads(m, om.get());
                } else {
                    warnUnknownModule(ADD_READS, name);
                }
            }
        }
    }
}
 
/**
 * If the new state is Finished and the pod had a container that ran then make sure that the StartInitiated
 * and Started states were populated in the task state machine due to apiserver sending the latest event.
 */
private void fillInMissingTaskStatusesIfNeeded(TaskState state, V1Pod pod, Task task,
                                               Optional<TitusExecutorDetails> executorDetailsOpt) {
    if (state != Finished) {
        return;
    }

    Optional<V1ContainerStateTerminated> terminatedContainerStatusOpt = KubeUtil.findTerminatedContainerStatus(pod);
    if (!terminatedContainerStatusOpt.isPresent()) {
        return;
    }

    String taskId = task.getId();
    V1ContainerStateTerminated containerStateTerminated = terminatedContainerStatusOpt.get();
    DateTime startedAt = containerStateTerminated.getStartedAt();
    if (startedAt != null) {
        Optional<Long> timestampOpt = Optional.of(startedAt.getMillis());
        Optional<TaskStatus> startInitiatedOpt = JobFunctions.findTaskStatus(task, StartInitiated);
        if (!startInitiatedOpt.isPresent()) {
            logger.debug("Publishing missing task status: StartInitiated for task: {}", taskId);
            publishContainerEvent(taskId, StartInitiated, TaskStatus.REASON_NORMAL, "",
                    executorDetailsOpt, timestampOpt);
        }
        Optional<TaskStatus> startedOpt = JobFunctions.findTaskStatus(task, Started);
        if (!startedOpt.isPresent()) {
            logger.debug("Publishing missing task status: Started for task: {}", taskId);
            publishContainerEvent(taskId, Started, TaskStatus.REASON_NORMAL, "",
                    executorDetailsOpt, timestampOpt);
        }
    }
}
 
private ApiCommand getApiCommand(List<ApiCommand> commands, String commandString, String clusterName, CheckedFunction<String, ApiCommand, ApiException> fn)
        throws ApiException {
    Optional<ApiCommand> optionalCommand = commands.stream().filter(cmd -> commandString.equals(cmd.getName())).findFirst();
    ApiCommand command;
    if (optionalCommand.isPresent()) {
        command = optionalCommand.get();
        LOGGER.debug("{} is already running with id: [{}]", commandString, command.getId());
    } else {
        command = fn.apply(clusterName);
    }
    return command;
}
 
源代码16 项目: coming   文件: DiffCasesTest.java
@SuppressWarnings("unchecked")
@Test
public void testNameFileGit() throws Exception {
	ComingMain cm = new ComingMain();
	Object result = cm.run(new String[] { "-location", "repogit4testv0", });
	assertNotNull(result);
	assertTrue(result instanceof CommitFinalResult);
	CommitFinalResult cfres = (CommitFinalResult) result;
	Map<Commit, RevisionResult> commits = cfres.getAllResults();

	Commit c1 = commits.keySet().stream()
			.filter(e -> e.getName().equals("4120ab0c714911a9c9f26b591cb3222eaf57d127")).findFirst().get();
	DiffResult<Commit, Diff> diff1 = (DiffResult<Commit, Diff>) commits.get(c1)
			.getResultFromClass(FineGrainDifftAnalyzer.class);

	assertEquals(1, diff1.getAll().size());

	Diff diffOut = diff1.getAll().get(0);
	Optional<Operation> firstInsert = diffOut.getRootOperations().stream().filter(e -> e instanceof InsertOperation)
			.findFirst();
	assertTrue(firstInsert.isPresent());
	InsertOperation insop = (InsertOperation) firstInsert.get();
	assertNotNull(insop);

	assertEquals("CharSequenceUtils.java", insop.getSrcNode().getPosition().getFile().getName());
	assertEquals("CharSequenceUtils.java", insop.getParent().getPosition().getFile().getName());

}
 
源代码17 项目: pulsar-manager   文件: RoleBindingController.java
@ApiOperation(value = "Create a role binding")
@ApiResponses({
        @ApiResponse(code = 200, message = "ok"),
        @ApiResponse(code = 404, message = "Not found"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/role-binding/{roleName}/{userName}", method =  RequestMethod.POST)
public ResponseEntity<Map<String, Object>> updateRoleBinding(
        @PathVariable String roleName,
        @PathVariable String userName,
        @RequestBody RoleBindingEntity roleBindingEntity) {
    Map<String, Object> result = Maps.newHashMap();
    HttpServletRequest request = ((ServletRequestAttributes)
            RequestContextHolder.getRequestAttributes()).getRequest();
    String token = request.getHeader("token");
    Map<String, String> stringMap = roleBindingService.validateCurrentUser(token, roleBindingEntity);
    if (stringMap.get("error") != null) {
        result.put("error", stringMap.get("error"));
        return ResponseEntity.ok(result);
    }
    // check old role binding
    Optional<RoleBindingEntity> oldRoleBindingEntityOptional = roleBindingRepository.findByUserIdAndRoleId(
            roleBindingEntity.getUserId(), roleBindingEntity.getRoleId());
    if (!oldRoleBindingEntityOptional.isPresent()) {
        result.put("error", "Update failed, role binding no exist");
        return ResponseEntity.ok(result);
    }

    Optional<UserInfoEntity> checkUserInfoEntityOptional = usersRepository.findByUserName(userName);
    if (!checkUserInfoEntityOptional.isPresent()) {
        result.put("error", "User no exist.");
        return ResponseEntity.ok(result);
    }
    UserInfoEntity checkUserInfoEntity = checkUserInfoEntityOptional.get();
    // check new role biding
    Optional<RoleBindingEntity> newRoleBindingEntityOptional = roleBindingRepository.findByUserIdAndRoleId(
            checkUserInfoEntity.getUserId(), roleBindingEntity.getRoleId());
    if (newRoleBindingEntityOptional.isPresent()) {
        result.put("error", "This role binding is exist");
        return ResponseEntity.ok(result);
    }
    roleBindingEntity.setRoleBindingId(oldRoleBindingEntityOptional.get().getRoleBindingId());

    roleBindingEntity.setUserId(checkUserInfoEntity.getUserId());
    roleBindingRepository.update(roleBindingEntity);
    result.put("message", "Role binding update success");
    return ResponseEntity.ok(result);
}
 
源代码18 项目: kork   文件: CloudConfigAutoConfiguration.java
@Bean
ConfigFileService configFileService(
    Optional<CloudConfigResourceService> cloudConfigResourceService) {
  return new ConfigFileService(cloudConfigResourceService.get());
}
 
源代码19 项目: bgpcep   文件: BGPUpdateMessageParser.java
/**
 * Parse Update message from buffer. Calls {@link #checkMandatoryAttributesPresence(Update, RevisedErrorHandling)}
 * to check for presence of mandatory attributes.
 *
 * @param buffer Encoded BGP message in ByteBuf
 * @param messageLength Length of the BGP message
 * @param constraint Peer specific constraints
 * @return Parsed Update message body
 */
@Override
public Update parseMessageBody(final ByteBuf buffer, final int messageLength,
        final PeerSpecificParserConstraint constraint) throws BGPDocumentedException {
    checkArgument(buffer != null && buffer.isReadable(),"Buffer cannot be null or empty.");

    final UpdateBuilder builder = new UpdateBuilder();
    final boolean isMultiPathSupported = MultiPathSupportUtil.isTableTypeSupported(constraint,
            new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class));
    final RevisedErrorHandling errorHandling = RevisedErrorHandling.from(constraint);

    final int withdrawnRoutesLength = buffer.readUnsignedShort();
    if (withdrawnRoutesLength > 0) {
        final List<WithdrawnRoutes> withdrawnRoutes = new ArrayList<>();
        final ByteBuf withdrawnRoutesBuffer = buffer.readBytes(withdrawnRoutesLength);
        while (withdrawnRoutesBuffer.isReadable()) {
            final WithdrawnRoutesBuilder withdrawnRoutesBuilder = new WithdrawnRoutesBuilder();
            if (isMultiPathSupported) {
                withdrawnRoutesBuilder.setPathId(PathIdUtil.readPathId(withdrawnRoutesBuffer));
            }
            withdrawnRoutesBuilder.setPrefix(readPrefix(withdrawnRoutesBuffer, errorHandling, "Withdrawn Routes"));
            withdrawnRoutes.add(withdrawnRoutesBuilder.build());
        }
        withdrawnRoutesBuffer.release();
        builder.setWithdrawnRoutes(withdrawnRoutes);
    }
    final int totalPathAttrLength = buffer.readUnsignedShort();
    if (withdrawnRoutesLength == 0 && totalPathAttrLength == 0) {
        return builder.build();
    }

    Optional<BGPTreatAsWithdrawException> withdrawCauseOpt;
    if (totalPathAttrLength > 0) {
        final ParsedAttributes attributes = parseAttributes(buffer, totalPathAttrLength, constraint);
        builder.setAttributes(attributes.getAttributes());
        withdrawCauseOpt = attributes.getWithdrawCause();
    } else {
        withdrawCauseOpt = Optional.empty();
    }

    final List<Nlri> nlri = new ArrayList<>();
    while (buffer.isReadable()) {
        final NlriBuilder nlriBuilder = new NlriBuilder();
        if (isMultiPathSupported) {
            nlriBuilder.setPathId(PathIdUtil.readPathId(buffer));
        }
        nlriBuilder.setPrefix(readPrefix(buffer, errorHandling, "NLRI"));
        nlri.add(nlriBuilder.build());
    }
    if (!nlri.isEmpty()) {
        builder.setNlri(nlri);
    }

    try {
        checkMandatoryAttributesPresence(builder.build(), errorHandling);
    } catch (BGPTreatAsWithdrawException e) {
        LOG.debug("Well-known mandatory attributes missing", e);
        if (withdrawCauseOpt.isPresent()) {
            final BGPTreatAsWithdrawException exception = withdrawCauseOpt.get();
            exception.addSuppressed(e);
            withdrawCauseOpt = Optional.of(exception);
        } else {
            withdrawCauseOpt = Optional.of(e);
        }
    }

    Update msg = builder.build();
    if (withdrawCauseOpt.isPresent()) {
        // Attempt to apply treat-as-withdraw
        msg = withdrawUpdate(msg, errorHandling, withdrawCauseOpt.get());
    }

    LOG.debug("BGP Update message was parsed {}.", msg);
    return msg;
}
 
private List<ProviderMessageContent> createMessageContents(CommonMessageData commonMessageData, ItemOperation itemOperation, BlackDuckServicesFactory blackDuckServicesFactory, BlackDuckResponseCache blackDuckResponseCache,
    VulnerabilityNotificationContent content, List<VulnerabilitySourceQualifiedId> vulnerabilities, Collection<String> vulnerabilityFilters, boolean addRemediationData) {
    List<ProviderMessageContent> messageContents = new LinkedList<>();
    BlackDuckService blackDuckService = blackDuckServicesFactory.createBlackDuckService();
    ComponentService componentService = blackDuckServicesFactory.createComponentService();

    List<AffectedProjectVersion> affectedProjectVersions = content.getAffectedProjectVersions();
    for (AffectedProjectVersion affectedProjectVersion : affectedProjectVersions) {
        String affectedProjectName = affectedProjectVersion.getProjectName();
        String projectUrl = retrieveNullableProjectUrlAndLog(affectedProjectName, blackDuckServicesFactory.createProjectService(), logger::warn);

        ProviderMessageContent.Builder messageContentBuilder = new ProviderMessageContent.Builder()
                                                                   .applyCommonData(commonMessageData)
                                                                   .applyTopic(MessageBuilderConstants.LABEL_PROJECT_NAME, affectedProjectName, projectUrl)
                                                                   .applySubTopic(MessageBuilderConstants.LABEL_PROJECT_VERSION_NAME, affectedProjectVersion.getProjectVersionName(), affectedProjectVersion.getProjectVersion());
        ComponentItemCallbackInfo componentItemCallbackInfo = null;
        List<LinkableItem> componentAttributes = new LinkedList<>();
        Optional<ProjectVersionComponentView> bomComponentViewOptional = blackDuckResponseCache.getBomComponentView(affectedProjectVersion.getBomComponent());
        if (bomComponentViewOptional.isPresent()) {
            ProjectVersionComponentView bomComponent = bomComponentViewOptional.get();
            componentItemCallbackInfo = blackDuckIssueTrackerCallbackUtility.createCallbackInfo(getNotificationType(), bomComponent).orElse(null);
            componentAttributes.addAll(ComponentBuilderUtil.getLicenseLinkableItems(bomComponent));
            componentAttributes.addAll(ComponentBuilderUtil.getUsageLinkableItems(bomComponent));
        }

        try {
            String componentName = content.getComponentName();
            String componentVersionName = content.getVersionName();
            String componentVersionUrl = content.getComponentVersion();
            String projectVersionUrl = affectedProjectVersion.getProjectVersion();
            ComponentData componentData = new ComponentData(componentName, componentVersionName, projectVersionUrl, ProjectVersionView.VULNERABLE_COMPONENTS_LINK);
            if (addRemediationData && StringUtils.isNotBlank(componentVersionUrl)) {
                ComponentVersionView componentVersionView = blackDuckService.getResponse(componentVersionUrl, ComponentVersionView.class);

                List<LinkableItem> remediationItems = VulnerabilityUtil.getRemediationItems(componentService, componentVersionView);
                componentAttributes.addAll(remediationItems);
            }
            messageContentBuilder.applyAllComponentItems(
                createVulnerabilityItems(commonMessageData.getNotificationId(), itemOperation, componentData, componentItemCallbackInfo, componentAttributes, vulnerabilities, blackDuckResponseCache, vulnerabilityFilters));
            messageContents.add(messageContentBuilder.build());
        } catch (Exception e) {
            logger.error("Mishandled the expected type of a notification field", e);
        }
    }
    return messageContents;
}