Search in sources :

Example 61 with Objects

use of java.util.Objects in project gerrit by GerritCodeReview.

the class ReviewersUtil method loadAccounts.

private List<SuggestedReviewerInfo> loadAccounts(List<Account.Id> accountIds) throws OrmException {
    try (Timer0.Context ctx = metrics.loadAccountsLatency.start()) {
        List<SuggestedReviewerInfo> reviewer = accountIds.stream().map(accountLoader::get).filter(Objects::nonNull).map(a -> {
            SuggestedReviewerInfo info = new SuggestedReviewerInfo();
            info.account = a;
            info.count = 1;
            return info;
        }).collect(toList());
        accountLoader.fill();
        return reviewer;
    }
}
Also used : GroupBackend(com.google.gerrit.server.account.GroupBackend) Iterables(com.google.common.collect.Iterables) AccountLoader(com.google.gerrit.server.account.AccountLoader) OrmException(com.google.gwtorm.server.OrmException) Inject(com.google.inject.Inject) QueryResult(com.google.gerrit.server.query.QueryResult) AccountQueryProcessor(com.google.gerrit.server.query.account.AccountQueryProcessor) NoSuchGroupException(com.google.gerrit.common.errors.NoSuchGroupException) GroupMembers(com.google.gerrit.server.account.GroupMembers) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Description(com.google.gerrit.metrics.Description) Account(com.google.gerrit.reviewdb.client.Account) EnumSet(java.util.EnumSet) SuggestedReviewerInfo(com.google.gerrit.extensions.common.SuggestedReviewerInfo) Project(com.google.gerrit.reviewdb.client.Project) PostReviewers(com.google.gerrit.server.change.PostReviewers) ProjectControl(com.google.gerrit.server.project.ProjectControl) GroupBaseInfo(com.google.gerrit.extensions.common.GroupBaseInfo) Timer0(com.google.gerrit.metrics.Timer0) Units(com.google.gerrit.metrics.Description.Units) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) AccountQueryBuilder(com.google.gerrit.server.query.account.AccountQueryBuilder) Set(java.util.Set) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Objects(java.util.Objects) QueryParseException(com.google.gerrit.server.query.QueryParseException) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) List(java.util.List) Url(com.google.gerrit.extensions.restapi.Url) MetricMaker(com.google.gerrit.metrics.MetricMaker) SuggestReviewers(com.google.gerrit.server.change.SuggestReviewers) AccountState(com.google.gerrit.server.account.AccountState) Collections(java.util.Collections) GroupReference(com.google.gerrit.common.data.GroupReference) Singleton(com.google.inject.Singleton) SuggestedReviewerInfo(com.google.gerrit.extensions.common.SuggestedReviewerInfo) Objects(java.util.Objects) Timer0(com.google.gerrit.metrics.Timer0)

Example 62 with Objects

use of java.util.Objects in project midpoint by Evolveum.

the class AccCertCaseOperationsHelper method getDeltasToCreateCases.

<F extends FocusType> List<ItemDelta<?, ?>> getDeltasToCreateCases(final AccessCertificationCampaignType campaign, AccessCertificationStageType stage, final CertificationHandler handler, final Task task, final OperationResult result) throws SchemaException, ObjectNotFoundException {
    final List<ItemDelta<?, ?>> rv = new ArrayList<>();
    final String campaignShortName = toShortString(campaign);
    final AccessCertificationScopeType scope = campaign.getScopeDefinition();
    LOGGER.trace("Creating cases for scope {} in campaign {}", scope, campaignShortName);
    if (scope != null && !(scope instanceof AccessCertificationObjectBasedScopeType)) {
        throw new IllegalStateException("Unsupported access certification scope type: " + scope.getClass() + " for campaign " + campaignShortName);
    }
    final AccessCertificationObjectBasedScopeType objectBasedScope = (AccessCertificationObjectBasedScopeType) scope;
    final List<AccessCertificationCaseType> existingCases = queryHelper.searchCases(campaign.getOid(), null, null, result);
    if (!existingCases.isEmpty()) {
        throw new IllegalStateException("Unexpected " + existingCases.size() + " certification case(s) in campaign object " + campaignShortName + ". At this time there should be none.");
    }
    // create a query to find target objects from which certification cases will be created
    final ObjectQuery query = new ObjectQuery();
    final QName scopeDeclaredObjectType;
    if (objectBasedScope != null) {
        scopeDeclaredObjectType = objectBasedScope.getObjectType();
    } else {
        scopeDeclaredObjectType = null;
    }
    final QName objectType;
    if (scopeDeclaredObjectType != null) {
        objectType = scopeDeclaredObjectType;
    } else {
        objectType = handler.getDefaultObjectType();
    }
    if (objectType == null) {
        throw new IllegalStateException("Unspecified object type (and no default one provided) for campaign " + campaignShortName);
    }
    @SuppressWarnings({ "unchecked", "raw" }) final Class<F> objectClass = (Class<F>) prismContext.getSchemaRegistry().getCompileTimeClassForObjectType(objectType);
    if (objectClass == null) {
        throw new IllegalStateException("Object class not found for object type " + objectType + " in campaign " + campaignShortName);
    }
    final SearchFilterType searchFilter = objectBasedScope != null ? objectBasedScope.getSearchFilter() : null;
    if (searchFilter != null) {
        ObjectFilter filter = QueryConvertor.parseFilter(searchFilter, objectClass, prismContext);
        query.setFilter(filter);
    }
    final List<AccessCertificationCaseType> caseList = new ArrayList<>();
    // create certification cases by executing the query and caseExpression on its results
    // here the subclasses of this class come into play
    ResultHandler<F> resultHandler = (object, parentResult) -> {
        try {
            caseList.addAll(handler.createCasesForObject(object, campaign, task, parentResult));
        } catch (ExpressionEvaluationException | ObjectNotFoundException | SchemaException e) {
            // TODO process the exception more intelligently
            throw new SystemException("Cannot create certification case for object " + toShortString(object.asObjectable()) + ": " + e.getMessage(), e);
        }
        return true;
    };
    repositoryService.searchObjectsIterative(objectClass, query, resultHandler, null, false, result);
    AccessCertificationReviewerSpecificationType reviewerSpec = reviewersHelper.findReviewersSpecification(campaign, 1, task, result);
    ContainerDelta<AccessCertificationCaseType> caseDelta = ContainerDelta.createDelta(F_CASE, AccessCertificationCampaignType.class, prismContext);
    for (AccessCertificationCaseType _case : caseList) {
        _case.setStageNumber(1);
        _case.setCurrentStageCreateTimestamp(stage.getStartTimestamp());
        _case.setCurrentStageDeadline(stage.getDeadline());
        List<ObjectReferenceType> reviewers = reviewersHelper.getReviewersForCase(_case, campaign, reviewerSpec, task, result);
        _case.getWorkItem().addAll(createWorkItems(reviewers, 1));
        String currentStageOutcome = OutcomeUtils.toUri(computationHelper.computeOutcomeForStage(_case, campaign, 1));
        _case.setCurrentStageOutcome(currentStageOutcome);
        _case.setOutcome(OutcomeUtils.toUri(computationHelper.computeOverallOutcome(_case, campaign, currentStageOutcome)));
        @SuppressWarnings({ "raw", "unchecked" }) PrismContainerValue<AccessCertificationCaseType> caseCVal = _case.asPrismContainerValue();
        caseDelta.addValueToAdd(caseCVal);
        LOGGER.trace("Adding certification case:\n{}", caseCVal.debugDumpLazily());
    }
    rv.add(caseDelta);
    LOGGER.trace("Created {} deltas to create {} cases for campaign {}", rv.size(), caseList.size(), campaignShortName);
    return rv;
}
Also used : java.util(java.util) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SecurityEnforcer(com.evolveum.midpoint.security.api.SecurityEnforcer) Autowired(org.springframework.beans.factory.annotation.Autowired) Trace(com.evolveum.midpoint.util.logging.Trace) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectTypeUtil(com.evolveum.midpoint.schema.util.ObjectTypeUtil) PrismContext(com.evolveum.midpoint.prism.PrismContext) Qualifier(org.springframework.beans.factory.annotation.Qualifier) F_CASE(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_CASE) RepositoryService(com.evolveum.midpoint.repo.api.RepositoryService) ContainerDelta(com.evolveum.midpoint.prism.delta.ContainerDelta) CloneUtil(com.evolveum.midpoint.prism.util.CloneUtil) XmlTypeConverter(com.evolveum.midpoint.prism.xml.XmlTypeConverter) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) DeltaBuilder(com.evolveum.midpoint.prism.delta.builder.DeltaBuilder) IdItemPathSegment(com.evolveum.midpoint.prism.path.IdItemPathSegment) Task(com.evolveum.midpoint.task.api.Task) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) CertCampaignTypeUtil(com.evolveum.midpoint.schema.util.CertCampaignTypeUtil) ObjectUtils(org.apache.commons.lang.ObjectUtils) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) QueryConvertor(com.evolveum.midpoint.prism.marshaller.QueryConvertor) Objects(java.util.Objects) Component(org.springframework.stereotype.Component) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) NameItemPathSegment(com.evolveum.midpoint.prism.path.NameItemPathSegment) SearchFilterType(com.evolveum.prism.xml.ns._public.query_3.SearchFilterType) CertificationHandler(com.evolveum.midpoint.certification.impl.handlers.CertificationHandler) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) QName(javax.xml.namespace.QName) NotNull(org.jetbrains.annotations.NotNull) Clock(com.evolveum.midpoint.common.Clock) AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) OutcomeUtils(com.evolveum.midpoint.certification.api.OutcomeUtils) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) ObjectTypeUtil.toShortString(com.evolveum.midpoint.schema.util.ObjectTypeUtil.toShortString) AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectTypeUtil.toShortString(com.evolveum.midpoint.schema.util.ObjectTypeUtil.toShortString) SearchFilterType(com.evolveum.prism.xml.ns._public.query_3.SearchFilterType) QName(javax.xml.namespace.QName) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery)

Example 63 with Objects

use of java.util.Objects in project indy by Commonjava.

the class ScheduleManager method setSnapshotTimeouts.

public synchronized void setSnapshotTimeouts(final StoreKey key, final String path) throws IndySchedulerException {
    if (!schedulerConfig.isEnabled()) {
        logger.debug("Scheduler disabled.");
        return;
    }
    HostedRepository deploy = null;
    try {
        final ArtifactStore store = dataManager.getArtifactStore(key);
        if (store == null) {
            return;
        }
        if (store instanceof HostedRepository) {
            deploy = (HostedRepository) store;
        } else if (store instanceof Group) {
            final Group group = (Group) store;
            deploy = findDeployPoint(group);
        }
    } catch (final IndyDataException e) {
        logger.error(String.format("Failed to retrieve deploy point for: %s. Reason: %s", key, e.getMessage()), e);
    }
    if (deploy == null) {
        return;
    }
    final ContentAdvisor advisor = StreamSupport.stream(Spliterators.spliteratorUnknownSize(contentAdvisor.iterator(), Spliterator.ORDERED), false).filter(Objects::nonNull).findFirst().orElse(null);
    final ContentQuality quality = advisor == null ? null : advisor.getContentQuality(path);
    if (quality == null) {
        return;
    }
    if (ContentQuality.SNAPSHOT == quality && deploy.getSnapshotTimeoutSeconds() > 0) {
        final int timeout = deploy.getSnapshotTimeoutSeconds();
        //            //            logger.info( "[SNAPSHOT TIMEOUT SET] {}/{}; {}", deploy.getKey(), path, new Date( timeout ) );
        //            cancel( new StoreKeyMatcher( key, CONTENT_JOB_TYPE ), path );
        scheduleContentExpiration(key, path, timeout);
    }
}
Also used : IndyDataException(org.commonjava.indy.data.IndyDataException) Group(org.commonjava.indy.model.core.Group) ContentAdvisor(org.commonjava.indy.spi.pkg.ContentAdvisor) ContentQuality(org.commonjava.indy.spi.pkg.ContentQuality) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) Objects(java.util.Objects) HostedRepository(org.commonjava.indy.model.core.HostedRepository)

Example 64 with Objects

use of java.util.Objects in project intellij-plugins by StepicOrg.

the class StudySerializationUtils method convertToFourthVersion.

public static Element convertToFourthVersion(Element state) throws StudyUnrecognizedFormatException {
    Element stepManager = getStepManager(state);
    Element courseNode = getCourseNode(stepManager);
    List<Element> sectionNodes = getSectionNodes(stepManager);
    if (sectionNodes != null) {
        sectionNodes.stream().map(sectionNode -> getListFieldWithNameOrNull(sectionNode, LESSON_NODES, LESSON_NODE_CLASS)).filter(Objects::nonNull).forEach(lessonNodes -> lessonNodes.forEach(lessonNode -> {
            Element data = getFieldWithNameOrNull(lessonNode, DATA);
            Element dataClassTag;
            if (data == null) {
                return;
            }
            dataClassTag = data.getChild(LESSON_CLASS);
            Element dataCloned;
            if (dataClassTag == null) {
                dataClassTag = createFieldWithClass(lessonNode, LESSON, LESSON_CLASS);
                dataCloned = dataClassTag.getParentElement();
            } else {
                dataCloned = data.clone();
                dataCloned.getAttribute(NAME).setValue(LESSON);
            }
            dataClassTag.removeContent();
            dataClassTag.addContent(dataCloned);
            Element unit = getFieldWithNameOrNull(lessonNode, UNIT);
            if (unit != null) {
                Element unitCloned = unit.clone();
                dataClassTag.addContent(unitCloned);
                removeChild(lessonNode, unit);
            }
            dataClassTag.setName(COMPOUND_UNIT_LESSON_CLASS);
            List<Element> stepNodes = getListFieldWithNameOrNull(lessonNode, STEP_NODES, STEP_NODE_CLASS);
            if (stepNodes == null) {
                return;
            }
            stepNodes.forEach(stepNode -> removeOption(stepNode, LIMITS));
            silentRenameField(lessonNode, STEP_NODES, CHILDREN);
        }));
        sectionNodes.forEach(sectionNode -> silentRenameField(sectionNode, LESSON_NODES, CHILDREN));
        silentRenameField(courseNode, SECTIONS_NODES, CHILDREN);
    }
    List<Element> elements = stepManager.getChildren();
    Element root = renameField(stepManager, COURSE_NODE, ROOT);
    root.setAttribute("class", COURSE_NODE_CLASS);
    convertToXStreamStyle(elements);
    return state;
}
Also used : Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Matcher(java.util.regex.Matcher) Map(java.util.Map) Attribute(org.jdom.Attribute) HashMap(java.util.HashMap) Pattern(java.util.regex.Pattern) Logger(com.intellij.openapi.diagnostic.Logger) NotNull(org.jetbrains.annotations.NotNull) Element(org.jdom.Element) ArrayList(java.util.ArrayList) Element(org.jdom.Element) List(java.util.List) ArrayList(java.util.ArrayList)

Example 65 with Objects

use of java.util.Objects in project jgnash by ccavanaugh.

the class Engine method emptyTrash.

/**
     * Empty the trash if any objects are older than the defined time.
     */
private void emptyTrash() {
    if (backGroundCounter.incrementAndGet() == 1) {
        messageBus.fireEvent(new Message(MessageChannel.SYSTEM, ChannelEvent.BACKGROUND_PROCESS_STARTED, Engine.this));
    }
    dataLock.writeLock().lock();
    try {
        logger.info("Checking for trash");
        final List<TrashObject> trash = getTrashDAO().getTrashObjects();
        /* always sort by the timestamp of the trash object to prevent
             * foreign key removal exceptions when multiple related accounts
             * or objects are removed */
        Collections.sort(trash);
        if (trash.isEmpty()) {
            logger.info("No trash was found");
        }
        trash.stream().filter(o -> ChronoUnit.MILLIS.between(o.getDate(), LocalDateTime.now()) >= MAXIMUM_TRASH_AGE).forEach(o -> getTrashDAO().remove(o));
    } finally {
        dataLock.writeLock().unlock();
        if (backGroundCounter.decrementAndGet() == 0) {
            messageBus.fireEvent(new Message(MessageChannel.SYSTEM, ChannelEvent.BACKGROUND_PROCESS_STOPPED, Engine.this));
        }
    }
}
Also used : EngineDAO(jgnash.engine.dao.EngineDAO) CurrencyUpdateFactory(jgnash.net.currency.CurrencyUpdateFactory) ScheduledFuture(java.util.concurrent.ScheduledFuture) UpdateFactory(jgnash.net.security.UpdateFactory) TimeoutException(java.util.concurrent.TimeoutException) LockManager(jgnash.engine.concurrent.LockManager) MessageBus(jgnash.engine.message.MessageBus) BigDecimal(java.math.BigDecimal) Nullable(jgnash.util.Nullable) Future(java.util.concurrent.Future) Budget(jgnash.engine.budget.Budget) MessageProperty(jgnash.engine.message.MessageProperty) RecurringIterator(jgnash.engine.recurring.RecurringIterator) MessageChannel(jgnash.engine.message.MessageChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultDaemonThreadFactory(jgnash.util.DefaultDaemonThreadFactory) Path(java.nio.file.Path) AttachmentManager(jgnash.engine.attachment.AttachmentManager) NotNull(jgnash.util.NotNull) CancellationException(java.util.concurrent.CancellationException) Collection(java.util.Collection) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) PendingReminder(jgnash.engine.recurring.PendingReminder) Objects(java.util.Objects) BudgetGoal(jgnash.engine.budget.BudgetGoal) List(java.util.List) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Handler(java.util.logging.Handler) Message(jgnash.engine.message.Message) ConfigDAO(jgnash.engine.dao.ConfigDAO) TrashDAO(jgnash.engine.dao.TrashDAO) LocalDateTime(java.time.LocalDateTime) ResourceUtils(jgnash.util.ResourceUtils) MonthlyReminder(jgnash.engine.recurring.MonthlyReminder) Callable(java.util.concurrent.Callable) CommodityDAO(jgnash.engine.dao.CommodityDAO) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ChannelEvent(jgnash.engine.message.ChannelEvent) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ResourceBundle(java.util.ResourceBundle) ExecutorService(java.util.concurrent.ExecutorService) DateUtils(jgnash.time.DateUtils) IOException(java.io.IOException) AccountDAO(jgnash.engine.dao.AccountDAO) TransactionDAO(jgnash.engine.dao.TransactionDAO) Reminder(jgnash.engine.recurring.Reminder) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) DayOfWeek(java.time.DayOfWeek) BudgetDAO(jgnash.engine.dao.BudgetDAO) Collections(java.util.Collections) CollectionUtils(jgnash.util.CollectionUtils) RecurringDAO(jgnash.engine.dao.RecurringDAO) Message(jgnash.engine.message.Message)

Aggregations

Objects (java.util.Objects)83 List (java.util.List)45 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)32 ArrayList (java.util.ArrayList)30 Set (java.util.Set)30 IOException (java.io.IOException)22 HashMap (java.util.HashMap)21 Optional (java.util.Optional)19 Collections (java.util.Collections)18 LoggerFactory (org.slf4j.LoggerFactory)17 Stream (java.util.stream.Stream)16 Logger (org.slf4j.Logger)16 HashSet (java.util.HashSet)14 Collection (java.util.Collection)13 InputStream (java.io.InputStream)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Result (ddf.catalog.data.Result)9 TimeUnit (java.util.concurrent.TimeUnit)9 Metacard (ddf.catalog.data.Metacard)8