Search in sources :

Example 56 with Optional

use of java.util.Optional in project buck by facebook.

the class ConditionalStepTest method testExecuteConditionalStepWhenTrue.

@Test
public void testExecuteConditionalStepWhenTrue() throws IOException, InterruptedException {
    // Create a Supplier<Boolean> that returns a value once an external condition has been
    // satisfied.
    final AtomicReference<Optional<Boolean>> condition = new AtomicReference<>(Optional.empty());
    Supplier<Boolean> conditional = () -> {
        if (!condition.get().isPresent()) {
            throw new IllegalStateException("condition must be satisfied before this is queried.");
        } else {
            return condition.get().get();
        }
    };
    // Create a step to run when the Supplier<Boolean> is true. Exit code is always 37.
    final AtomicInteger numCalls = new AtomicInteger(0);
    Step stepToRunWhenSupplierIsTrue = new AbstractExecutionStep("inc") {

        @Override
        public StepExecutionResult execute(ExecutionContext context) {
            numCalls.incrementAndGet();
            return StepExecutionResult.of(37);
        }
    };
    // Create and execute the ConditionalStep.
    ConditionalStep conditionalStep = new ConditionalStep(conditional, stepToRunWhenSupplierIsTrue);
    condition.set(Optional.of(true));
    ExecutionContext context = TestExecutionContext.newInstance();
    int exitCode = conditionalStep.execute(context).getExitCode();
    assertEquals("stepToRunWhenSupplierIsTrue should have been run once.", 1, numCalls.get());
    assertEquals("The exit code of stepToRunWhenSupplierIsTrue should be passed through.", 37, exitCode);
    assertEquals("inc", conditionalStep.getShortName());
    assertEquals("conditionally: inc", conditionalStep.getDescription(context));
}
Also used : Optional(java.util.Optional) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 57 with Optional

use of java.util.Optional in project buck by facebook.

the class ConditionalStepTest method testExecuteConditionalStepWhenFalse.

@Test
public void testExecuteConditionalStepWhenFalse() throws IOException, InterruptedException {
    // Create a Supplier<Boolean> that returns a value once an external condition has been
    // satisfied.
    final AtomicReference<Optional<Boolean>> condition = new AtomicReference<>(Optional.empty());
    Supplier<Boolean> conditional = () -> {
        if (!condition.get().isPresent()) {
            throw new IllegalStateException("condition must be satisfied before this is queried.");
        } else {
            return condition.get().get();
        }
    };
    // Create a step to run when the Supplier<Boolean> is true. Because the Supplier<Boolean> will
    // be false, this step should not be run.
    final AtomicInteger numCalls = new AtomicInteger(0);
    Step stepToRunWhenSupplierIsTrue = new AbstractExecutionStep("inc") {

        @Override
        public StepExecutionResult execute(ExecutionContext context) {
            numCalls.incrementAndGet();
            throw new IllegalStateException("This step should not be executed.");
        }
    };
    // Create and execute the ConditionalStep.
    ConditionalStep conditionalStep = new ConditionalStep(conditional, stepToRunWhenSupplierIsTrue);
    condition.set(Optional.of(false));
    ExecutionContext context = TestExecutionContext.newInstance();
    int exitCode = conditionalStep.execute(context).getExitCode();
    assertEquals("stepToRunWhenSupplierIsTrue should not have been run.", 0, numCalls.get());
    assertEquals("The exit code should be zero when the conditional is false.", 0, exitCode);
    assertEquals("inc", conditionalStep.getShortName());
    assertEquals("conditionally: inc", conditionalStep.getDescription(context));
}
Also used : Optional(java.util.Optional) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 58 with Optional

use of java.util.Optional in project sonarqube by SonarSource.

the class BulkDeleteAction method handle.

@Override
public void handle(Request request, Response response) throws Exception {
    userSession.checkLoggedIn();
    List<String> uuids = request.paramAsStrings(PARAM_PROJECT_IDS);
    List<String> keys = request.paramAsStrings(PARAM_PROJECTS);
    String orgKey = request.param(ProjectsWsSupport.PARAM_ORGANIZATION);
    try (DbSession dbSession = dbClient.openSession(false)) {
        Optional<OrganizationDto> org = loadOrganizationByKey(dbSession, orgKey);
        List<ComponentDto> projects = searchProjects(dbSession, uuids, keys);
        projects.stream().filter(p -> !org.isPresent() || org.get().getUuid().equals(p.getOrganizationUuid())).forEach(p -> componentCleanerService.delete(dbSession, p));
    }
    response.noContent();
}
Also used : ADMINISTER(org.sonar.db.permission.OrganizationPermission.ADMINISTER) DbSession(org.sonar.db.DbSession) Request(org.sonar.api.server.ws.Request) DbClient(org.sonar.db.DbClient) List(java.util.List) ComponentDto(org.sonar.db.component.ComponentDto) WebService(org.sonar.api.server.ws.WebService) Response(org.sonar.api.server.ws.Response) Optional(java.util.Optional) KEY_PROJECT_EXAMPLE_001(org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001) OrganizationDto(org.sonar.db.organization.OrganizationDto) UserSession(org.sonar.server.user.UserSession) Nullable(javax.annotation.Nullable) ComponentCleanerService(org.sonar.server.component.ComponentCleanerService) DbSession(org.sonar.db.DbSession) ComponentDto(org.sonar.db.component.ComponentDto) OrganizationDto(org.sonar.db.organization.OrganizationDto)

Example 59 with Optional

use of java.util.Optional in project sonarqube by SonarSource.

the class UserUpdater method addDefaultGroup.

private void addDefaultGroup(DbSession dbSession, UserDto userDto) {
    String defaultGroupName = settings.getString(CoreProperties.CORE_DEFAULT_GROUP);
    if (defaultGroupName == null) {
        return;
    }
    String defOrgUuid = defaultOrganizationProvider.get().getUuid();
    List<GroupDto> userGroups = dbClient.groupDao().selectByUserLogin(dbSession, userDto.getLogin());
    if (!userGroups.stream().anyMatch(g -> defOrgUuid.equals(g.getOrganizationUuid()) && g.getName().equals(defaultGroupName))) {
        Optional<GroupDto> groupDto = dbClient.groupDao().selectByName(dbSession, defOrgUuid, defaultGroupName);
        if (!groupDto.isPresent()) {
            throw new ServerException(HttpURLConnection.HTTP_INTERNAL_ERROR, format("The default group '%s' for new users does not exist. Please update the general security settings to fix this issue.", defaultGroupName));
        }
        dbClient.userGroupDao().insert(dbSession, new UserGroupDto().setUserId(userDto.getId()).setGroupId(groupDto.get().getId()));
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) UserGroupDto(org.sonar.db.user.UserGroupDto) UserDto(org.sonar.db.user.UserDto) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) Random(java.util.Random) ServerException(org.sonar.server.exceptions.ServerException) DbSession(org.sonar.db.DbSession) SecureRandom(java.security.SecureRandom) Strings(com.google.common.base.Strings) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OrganizationCreation(org.sonar.server.organization.OrganizationCreation) WsUtils.checkFound(org.sonar.server.ws.WsUtils.checkFound) WsUtils.checkRequest(org.sonar.server.ws.WsUtils.checkRequest) Validation(org.sonar.server.util.Validation) NewUserHandler(org.sonar.api.platform.NewUserHandler) Nullable(javax.annotation.Nullable) GroupDto(org.sonar.db.user.GroupDto) DefaultOrganizationProvider(org.sonar.server.organization.DefaultOrganizationProvider) System2(org.sonar.api.utils.System2) CoreProperties(org.sonar.api.CoreProperties) Collectors(org.sonar.core.util.stream.Collectors) String.format(java.lang.String.format) Objects(java.util.Objects) UserIndexer(org.sonar.server.user.index.UserIndexer) DbClient(org.sonar.db.DbClient) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) UserDto.encryptPassword(org.sonar.db.user.UserDto.encryptPassword) Settings(org.sonar.api.config.Settings) ServerSide(org.sonar.api.server.ServerSide) Optional(java.util.Optional) DigestUtils(org.apache.commons.codec.digest.DigestUtils) Collections(java.util.Collections) Joiner(com.google.common.base.Joiner) ServerException(org.sonar.server.exceptions.ServerException) UserGroupDto(org.sonar.db.user.UserGroupDto) GroupDto(org.sonar.db.user.GroupDto) UserGroupDto(org.sonar.db.user.UserGroupDto)

Example 60 with Optional

use of java.util.Optional in project fastjson by alibaba.

the class OptionalCodec method write.

public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    if (object == null) {
        serializer.writeNull();
        return;
    }
    if (object instanceof Optional) {
        Optional<?> optional = (Optional<?>) object;
        Object value = optional.isPresent() ? optional.get() : null;
        serializer.write(value);
        return;
    }
    if (object instanceof OptionalDouble) {
        OptionalDouble optional = (OptionalDouble) object;
        if (optional.isPresent()) {
            double value = optional.getAsDouble();
            serializer.write(value);
        } else {
            serializer.writeNull();
        }
        return;
    }
    if (object instanceof OptionalInt) {
        OptionalInt optional = (OptionalInt) object;
        if (optional.isPresent()) {
            int value = optional.getAsInt();
            serializer.out.writeInt(value);
        } else {
            serializer.writeNull();
        }
        return;
    }
    if (object instanceof OptionalLong) {
        OptionalLong optional = (OptionalLong) object;
        if (optional.isPresent()) {
            long value = optional.getAsLong();
            serializer.out.writeLong(value);
        } else {
            serializer.writeNull();
        }
        return;
    }
    throw new JSONException("not support optional : " + object.getClass());
}
Also used : Optional(java.util.Optional) OptionalLong(java.util.OptionalLong) JSONException(com.alibaba.fastjson.JSONException) OptionalInt(java.util.OptionalInt) OptionalDouble(java.util.OptionalDouble)

Aggregations

Optional (java.util.Optional)414 List (java.util.List)208 Map (java.util.Map)138 ArrayList (java.util.ArrayList)107 Set (java.util.Set)95 Collectors (java.util.stream.Collectors)92 IOException (java.io.IOException)85 ImmutableList (com.google.common.collect.ImmutableList)82 ImmutableMap (com.google.common.collect.ImmutableMap)75 Test (org.junit.Test)69 ImmutableSet (com.google.common.collect.ImmutableSet)65 HashMap (java.util.HashMap)65 Path (java.nio.file.Path)55 Logger (org.slf4j.Logger)54 LoggerFactory (org.slf4j.LoggerFactory)53 Collections (java.util.Collections)51 Collection (java.util.Collection)48 Arrays (java.util.Arrays)42 BuildTarget (com.facebook.buck.model.BuildTarget)40 HashSet (java.util.HashSet)37