Java Code Examples for java.util.Optional#get()

The following examples show how to use java.util.Optional#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlertAuthenticationProvider.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: DefaultPexToolProvider.java    From buck with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example 3
Source File: JpaKubernetesRuntimeStateCache.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: DistributedVirtualNetworkStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 5
Source File: SmtpMailer.java    From Singularity with Apache License 2.0 6 votes vote down vote up
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()
    )
  );
}
 
Example 6
Source File: EventScheduler.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
  }
}
 
Example 7
Source File: SdxServiceDecorator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
}
 
Example 8
Source File: LevelDbLogReader.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 9
Source File: DiffCasesTest.java    From coming with MIT License 5 votes vote down vote up
@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());

}
 
Example 10
Source File: ClouderaManagerModificationService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: KubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 12
Source File: ModuleBootstrap.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
                }
            }
        }
    }
}
 
Example 13
Source File: UniversalMarketServlet.java    From Web-API with MIT License 5 votes vote down vote up
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();
}
 
Example 14
Source File: PersonImpl.java    From demo-gwt-springboot with Apache License 2.0 5 votes vote down vote up
@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");
	}
}
 
Example 15
Source File: AccountService.java    From Using-Spring-Oauth2-to-secure-REST with MIT License 5 votes vote down vote up
@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));
    }
}
 
Example 16
Source File: Model.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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();
}
 
Example 17
Source File: BGPUpdateMessageParser.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: CloudConfigAutoConfiguration.java    From kork with Apache License 2.0 4 votes vote down vote up
@Bean
ConfigFileService configFileService(
    Optional<CloudConfigResourceService> cloudConfigResourceService) {
  return new ConfigFileService(cloudConfigResourceService.get());
}
 
Example 19
Source File: RoleBindingController.java    From pulsar-manager with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: VulnerabilityNotificationMessageBuilder.java    From blackduck-alert with Apache License 2.0 4 votes vote down vote up
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;
}