Search in sources :

Example 31 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class RemoteNodesManager method redirectTaskToNode.

public void redirectTaskToNode(@NotNull Task task, @NotNull NodeType node, @NotNull OperationResult result) {
    LOGGER.trace("Trying to schedule task {} on {}", task, node.getNodeIdentifier());
    Holder<JMXConnector> connectorHolder = new Holder<>();
    try {
        QuartzSchedulerMBean mbeanProxy = getSchedulerBean(node, connectorHolder, result);
        if (mbeanProxy != null) {
            try {
                createStarterJobIfNeeded();
                mbeanProxy.triggerJob(STARTER_JOB_KEY.getName(), STARTER_JOB_KEY.getGroup(), Collections.singletonMap(JobStarter.TASK_OID, task.getOid()));
                LOGGER.debug("Successfully requested start of " + task + " at " + getClusterManager().dumpNodeInfo(node));
                result.recordSuccessIfUnknown();
            } catch (Exception e) {
                // necessary because of mbeanProxy
                String message = "Cannot schedule " + task + " at " + getClusterManager().dumpNodeInfo(node);
                LoggingUtils.logUnexpectedException(LOGGER, message, e);
                result.recordFatalError(message + ":" + e.getMessage(), e);
            }
        } else {
            LOGGER.warn("Couldn't obtain Quartz MBean so couldn't reschedule task {} on {}", task, node.getNodeIdentifier());
        }
    } finally {
        closeJmxConnection(connectorHolder, getClusterManager().dumpNodeInfo(node));
    }
}
Also used : JMXConnector(javax.management.remote.JMXConnector) Holder(com.evolveum.midpoint.util.Holder) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) SystemException(com.evolveum.midpoint.util.exception.SystemException) QuartzSchedulerMBean(org.quartz.core.jmx.QuartzSchedulerMBean)

Example 32 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method count.

@Override
public int count(ObjectClassComplexTypeDefinition objectClassDefinition, final ObjectQuery query, PagedSearchCapabilityType pagedSearchCapabilityType, StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SchemaException, UnsupportedOperationException {
    // Result type for this operation
    final OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".count");
    result.addParam("objectClass", objectClassDefinition);
    result.addContext("connector", connectorType);
    if (objectClassDefinition == null) {
        result.recordFatalError("Object class not defined");
        throw new IllegalArgumentException("objectClass not defined");
    }
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(objectClassDefinition, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        IllegalArgumentException ex = new IllegalArgumentException("Unable to determine object class from QName " + objectClassDefinition + " while attempting to search objects by " + ObjectTypeUtil.toShortString(connectorType));
        result.recordFatalError("Unable to determine object class", ex);
        throw ex;
    }
    final boolean useConnectorPaging = pagedSearchCapabilityType != null;
    if (!useConnectorPaging) {
        throw new UnsupportedOperationException("ConnectorInstanceIcfImpl.count operation is supported only in combination with connector-implemented paging");
    }
    OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
    optionsBuilder.setAttributesToGet(Name.NAME);
    optionsBuilder.setPagedResultsOffset(1);
    optionsBuilder.setPageSize(1);
    if (pagedSearchCapabilityType.getDefaultSortField() != null) {
        String orderByIcfName = connIdNameMapper.convertAttributeNameToIcf(pagedSearchCapabilityType.getDefaultSortField(), objectClassDefinition, "(default sorting field)");
        boolean isAscending = pagedSearchCapabilityType.getDefaultSortDirection() != OrderDirectionType.DESCENDING;
        optionsBuilder.setSortKeys(new SortKey(orderByIcfName, isAscending));
    }
    OperationOptions options = optionsBuilder.build();
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".search");
    icfResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    icfResult.addContext("connector", connIdConnectorFacade.getClass());
    int retval;
    try {
        Filter filter = convertFilterToIcf(query, objectClassDefinition);
        final Holder<Integer> fetched = new Holder<>(0);
        ResultsHandler icfHandler = new ResultsHandler() {

            @Override
            public boolean handle(ConnectorObject connectorObject) {
                // actually, this should execute at most once
                fetched.setValue(fetched.getValue() + 1);
                return false;
            }
        };
        InternalMonitor.recordConnectorOperation("search");
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        SearchResult searchResult = connIdConnectorFacade.search(icfObjectClass, filter, icfHandler, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        if (searchResult == null || searchResult.getRemainingPagedResults() == -1) {
            throw new UnsupportedOperationException("Connector does not seem to support paged searches or does not provide object count information");
        } else {
            retval = fetched.getValue() + searchResult.getRemainingPagedResults();
        }
        icfResult.recordSuccess();
    } catch (IntermediateException inex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, inex);
        SchemaException ex = (SchemaException) inex.getCause();
        icfResult.recordFatalError(ex);
        result.recordFatalError(ex);
        throw ex;
    } catch (UnsupportedOperationException uoe) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, uoe);
        icfResult.recordFatalError(uoe);
        result.recordFatalError(uoe);
        throw uoe;
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, ex);
        Throwable midpointEx = processIcfException(ex, this, icfResult);
        result.computeStatus();
        // exception
        if (midpointEx instanceof CommunicationException) {
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    if (result.isUnknown()) {
        result.recordSuccess();
    }
    return retval;
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) SortKey(org.identityconnectors.framework.common.objects.SortKey) GuardedString(org.identityconnectors.common.security.GuardedString) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) SystemException(com.evolveum.midpoint.util.exception.SystemException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) Holder(com.evolveum.midpoint.util.Holder) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) SyncResultsHandler(org.identityconnectors.framework.common.objects.SyncResultsHandler) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) Filter(org.identityconnectors.framework.common.objects.filter.Filter)

Example 33 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class ReconciliationTaskHandler method performShadowReconciliation.

// returns false in case of execution interruption
private boolean performShadowReconciliation(final PrismObject<ResourceType> resource, final ObjectClassComplexTypeDefinition objectclassDef, long startTimestamp, long endTimestamp, ReconciliationTaskResult reconResult, final Task task, OperationResult result) throws SchemaException {
    boolean interrupted;
    // find accounts
    LOGGER.trace("Shadow reconciliation starting for {}, {} -> {}", new Object[] { resource, startTimestamp, endTimestamp });
    OperationResult opResult = result.createSubresult(OperationConstants.RECONCILIATION + ".shadowReconciliation");
    ObjectQuery query = QueryBuilder.queryFor(ShadowType.class, prismContext).block().item(ShadowType.F_FULL_SYNCHRONIZATION_TIMESTAMP).le(XmlTypeConverter.createXMLGregorianCalendar(startTimestamp)).or().item(ShadowType.F_FULL_SYNCHRONIZATION_TIMESTAMP).isNull().endBlock().and().item(ShadowType.F_RESOURCE_REF).ref(ObjectTypeUtil.createObjectRef(resource).asReferenceValue()).and().item(ShadowType.F_OBJECT_CLASS).eq(objectclassDef.getTypeName()).build();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Shadow recon query:\n{}", query.debugDump());
    }
    long started = System.currentTimeMillis();
    final Holder<Long> countHolder = new Holder<Long>(0L);
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {

        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            if ((objectclassDef instanceof RefinedObjectClassDefinition) && !((RefinedObjectClassDefinition) objectclassDef).matches(shadow.asObjectable())) {
                return true;
            }
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Shadow reconciliation of {}, fullSynchronizationTimestamp={}", shadow, shadow.asObjectable().getFullSynchronizationTimestamp());
            }
            long started = System.currentTimeMillis();
            PrismObject<ShadowType> resourceShadow = null;
            try {
                task.recordIterativeOperationStart(shadow.asObjectable());
                resourceShadow = reconcileShadow(shadow, resource, task);
                task.recordIterativeOperationEnd(shadow.asObjectable(), started, null);
            } catch (Throwable t) {
                task.recordIterativeOperationEnd(shadow.asObjectable(), started, t);
                throw t;
            }
            if (ShadowUtil.isProtected(resourceShadow)) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Skipping recording counter for {} because it is protected", shadow);
                }
                return task.canRun();
            }
            countHolder.setValue(countHolder.getValue() + 1);
            // reconcileShadow writes to its own dummy OperationResult, so we do the same here
            incrementAndRecordProgress(task, new OperationResult("dummy"));
            return task.canRun();
        }
    };
    repositoryService.searchObjectsIterative(ShadowType.class, query, handler, null, true, opResult);
    interrupted = !task.canRun();
    // for each try the operation again
    opResult.computeStatus();
    LOGGER.trace("Shadow reconciliation finished, processed {} shadows for {}, result: {}", new Object[] { countHolder.getValue(), resource, opResult.getStatus() });
    reconResult.setShadowReconCount(countHolder.getValue());
    result.createSubresult(OperationConstants.RECONCILIATION + ".shadowReconciliation.statistics").recordStatus(OperationResultStatus.SUCCESS, "Processed " + countHolder.getValue() + " shadow(s) in " + (System.currentTimeMillis() - started) + " ms." + (interrupted ? " Was interrupted during processing." : ""));
    return !interrupted;
}
Also used : ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) Holder(com.evolveum.midpoint.util.Holder) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) PrismObject(com.evolveum.midpoint.prism.PrismObject) RefinedObjectClassDefinition(com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition)

Example 34 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class TestConnectorMultiInstance method test120ReadJackDummyYellowTwoOperationsOneBlocking.

/**
	 * Block one read operation and let go the other. Make sure that new connector instance is created
	 * for the second operation and that it goes smoothly.
	 */
@Test
public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exception {
    final String TEST_NAME = "test120ReadJackDummyYellowTwoOperationsOneBlocking";
    TestUtil.displayTestTile(this, TEST_NAME);
    dummyResourceYellow.setBlockOperations(true);
    final Holder<PrismObject<ShadowType>> shadowHolder1 = new Holder<>();
    final Holder<PrismObject<ShadowType>> shadowHolder2 = new Holder<>();
    // WHEN
    Thread t1 = executeInNewThread("get1", new FailableRunnable() {

        @Override
        public void run() throws Exception {
            PrismObject<ShadowType> shadow = getShadowModel(accountJackYellowOid);
            LOGGER.trace("Got shadow {}", shadow);
            shadowHolder1.setValue(shadow);
        }
    });
    // Give the new thread a chance to get blocked
    Thread.sleep(200);
    assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 0);
    assertNull("Unexpected shadow 1", shadowHolder1.getValue());
    dummyResourceYellow.setBlockOperations(false);
    // This should not be blocked and it should proceed immediately
    Thread t2 = executeInNewThread("get2", new FailableRunnable() {

        @Override
        public void run() throws Exception {
            PrismObject<ShadowType> shadow = getShadowModel(accountJackYellowOid);
            LOGGER.trace("Got shadow {}", shadow);
            shadowHolder2.setValue(shadow);
        }
    });
    t2.join(1000);
    assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 1);
    assertNull("Unexpected shadow 1", shadowHolder1.getValue());
    dummyResourceYellow.unblock();
    t1.join();
    // THEN
    PrismObject<ShadowType> shadowYellow1 = shadowHolder1.getValue();
    assertNotNull("No shadow 1", shadowHolder1.getValue());
    display("Shadow yellow 1", shadowYellow1);
    PrismObject<ShadowType> shadowYellow2 = shadowHolder2.getValue();
    assertNotNull("No shadow 2", shadowHolder2.getValue());
    display("Shadow yellow 2", shadowYellow2);
    assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2);
    assertConnectorToString(shadowYellow1, dummyResourceCtlYellow, initialConnectorToString);
    assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal);
    assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, initialConnectorToString);
    assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal);
    assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true);
}
Also used : PrismObject(com.evolveum.midpoint.prism.PrismObject) FailableRunnable(com.evolveum.midpoint.util.FailableRunnable) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) Holder(com.evolveum.midpoint.util.Holder) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) Test(org.testng.annotations.Test)

Example 35 with Holder

use of com.evolveum.midpoint.util.Holder in project midpoint by Evolveum.

the class PageDebugView method initViewButton.

private void initViewButton(Form mainForm) {
    List<String> propertyKeysList = Arrays.asList("PageDebugView.xmlViewButton", "PageDebugView.xmlJsonButton", "PageDebugView.xmlYamlButton");
    int selectedIndex = 0;
    if (PrismContext.LANG_JSON.equals(dataLanguage)) {
        selectedIndex = 1;
    } else if (PrismContext.LANG_YAML.equals(dataLanguage)) {
        selectedIndex = 2;
    }
    MultiStateHorizontalButton viewButtonPanel = new MultiStateHorizontalButton(ID_VIEW_BUTTON_PANEL, selectedIndex, propertyKeysList, PageDebugView.this) {

        @Override
        protected void onStateChanged(int index, AjaxRequestTarget target) {
            OperationResult result = new OperationResult(OPERATION_VALIDATE_OBJECT);
            Holder<PrismObject<ObjectType>> objectHolder = new Holder<>(null);
            try {
                validateObject(result, objectHolder);
                if (result.isAcceptable()) {
                    if (index == 1) {
                        dataLanguage = PrismContext.LANG_JSON;
                    } else if (index == 2) {
                        dataLanguage = PrismContext.LANG_YAML;
                    } else {
                        dataLanguage = PrismContext.LANG_XML;
                    }
                    PrismObject<ObjectType> updatedObject = objectHolder.getValue();
                    PrismContext context = getMidpointApplication().getPrismContext();
                    String objectStr = context.serializerFor(dataLanguage).serialize(updatedObject);
                    objectViewDto.setXml(objectStr);
                    setSelectedIndex(index);
                    addOrReplaceEditor();
                    target.add(mainForm);
                    target.add(getFeedbackPanel());
                } else {
                    showResult(result);
                    target.add(getFeedbackPanel());
                }
            } catch (Exception ex) {
                result.recordFatalError("Couldn't change the language.", ex);
                showResult(result);
                target.add(getFeedbackPanel());
            }
        }
    };
    viewButtonPanel.setOutputMarkupId(true);
    mainForm.add(viewButtonPanel);
}
Also used : MultiStateHorizontalButton(com.evolveum.midpoint.web.component.input.MultiStateHorizontalButton) PrismContext(com.evolveum.midpoint.prism.PrismContext) Holder(com.evolveum.midpoint.util.Holder) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) RestartResponseException(org.apache.wicket.RestartResponseException) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) PrismObject(com.evolveum.midpoint.prism.PrismObject)

Aggregations

Holder (com.evolveum.midpoint.util.Holder)45 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)27 PrismObject (com.evolveum.midpoint.prism.PrismObject)16 Task (com.evolveum.midpoint.task.api.Task)13 Test (org.testng.annotations.Test)13 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)12 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)9 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)8 QName (javax.xml.namespace.QName)8 SystemException (com.evolveum.midpoint.util.exception.SystemException)7 LensContext (com.evolveum.midpoint.model.impl.lens.LensContext)6 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)6 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)6 NotNull (org.jetbrains.annotations.NotNull)6 AbstractUninitializedCertificationTest (com.evolveum.midpoint.certification.test.AbstractUninitializedCertificationTest)5 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)5 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)5 Trace (com.evolveum.midpoint.util.logging.Trace)5 TraceManager (com.evolveum.midpoint.util.logging.TraceManager)5 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)5