下面列出了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;
}
@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();
}
@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));
}
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();
}
}
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());
}
}
}
@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;
}
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()
)
);
}
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()));
}
/**
* 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));
}
}
@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");
}
}
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();
}
/**
* 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;
}
@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());
}
@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);
}
@Bean
ConfigFileService configFileService(
Optional<CloudConfigResourceService> cloudConfigResourceService) {
return new ConfigFileService(cloudConfigResourceService.get());
}
/**
* 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;
}