Search in sources :

Example 11 with IAction

use of org.pentaho.platform.api.action.IAction in project pentaho-platform by pentaho.

the class RuntimeContext method resolveComponent.

protected IComponent resolveComponent(final ISolutionActionDefinition actionDefinition, final String currentInstanceId, final String currentProcessId, final IPentahoSession currentSession) throws ClassNotFoundException, PluginBeanException, InstantiationException, IllegalAccessException {
    // try to create an instance of the component class specified in the
    // action document
    String componentAlias = actionDefinition.getComponentName().trim();
    String componentClassName = RuntimeContext.getComponentClassName(componentAlias, this);
    Element componentDefinition = (Element) actionDefinition.getComponentSection();
    setCurrentComponent(componentClassName);
    setCurrentActionDef(actionDefinition);
    IComponent component = null;
    Class componentClass = null;
    Object componentTmp = null;
    // Explicitly using the short name instead of the fully layed out class name
    if ((pluginManager != null) && (pluginManager.isBeanRegistered(componentAlias))) {
        if (RuntimeContext.debug) {
            // $NON-NLS-1$ //$NON-NLS-2$
            this.debug("Component alias " + componentAlias + " will be resolved by the plugin manager.");
        }
        componentTmp = pluginManager.getBean(componentAlias);
        if (RuntimeContext.debug) {
            // $NON-NLS-1$
            this.debug("Component found in a plugin, class is: " + componentTmp.getClass().getName());
        }
    }
    if (RuntimeContext.debug) {
        // $NON-NLS-1$ //$NON-NLS-2$
        this.debug("Component alias " + componentAlias + " will be resolved by the platform");
    }
    // Ok - the plugin didn't load - try the old route
    if (componentTmp == null) {
        componentClass = Class.forName(componentClassName);
        componentTmp = componentClass.newInstance();
    }
    if (componentTmp instanceof IComponent) {
        component = (IComponent) componentTmp;
    } else if (componentTmp instanceof IAction) {
        component = new ActionDelegate(componentTmp);
    } else {
        // Try this out...
        PojoComponent pc = new PojoComponent();
        pc.setPojo(componentTmp);
        component = pc;
    }
    component.setInstanceId(currentInstanceId);
    component.setActionName(getActionName());
    component.setProcessId(currentProcessId);
    // to the dom nodes.
    if (component instanceof IParameterResolver) {
        component.setActionDefinition(ActionFactory.getActionDefinition((Element) actionDefinition.getNode(), new ActionSequenceParameterMgr(this, currentSession, (IParameterResolver) component)));
    } else {
        component.setActionDefinition(ActionFactory.getActionDefinition((Element) actionDefinition.getNode(), new ActionSequenceParameterMgr(this, currentSession)));
    }
    // create a map of the top level component definition nodes and their text
    Map<String, String> componentDefinitionMap = new HashMap<String, String>();
    List elements = componentDefinition.elements();
    Element element;
    String name;
    String value;
    String customXsl = null;
    for (int idx = 0; idx < elements.size(); idx++) {
        element = (Element) elements.get(idx);
        name = element.getName();
        value = element.getText();
        // see if we have a target window for the output
        if ("target".equals(name)) {
            // $NON-NLS-1$
            setParameterTarget(value);
        } else if ("xsl".equals(name)) {
            // $NON-NLS-1$
            // setParameterXsl(value);
            customXsl = value;
        }
        componentDefinitionMap.put(element.getName(), element.getText());
    }
    if (customXsl != null) {
        setParameterXsl(customXsl);
    }
    component.setComponentDefinitionMap(componentDefinitionMap);
    component.setComponentDefinition(componentDefinition);
    component.setRuntimeContext(this);
    component.setSession(currentSession);
    component.setLoggingLevel(getLoggingLevel());
    component.setMessages(getMessages());
    return component;
}
Also used : IAction(org.pentaho.platform.api.action.IAction) HashMap(java.util.HashMap) IComponent(org.pentaho.platform.api.engine.IComponent) IRuntimeElement(org.pentaho.platform.api.repository.IRuntimeElement) Element(org.dom4j.Element) ActionDelegate(org.pentaho.platform.engine.services.solution.ActionDelegate) IParameterResolver(org.pentaho.platform.api.engine.IParameterResolver) List(java.util.List) ArrayList(java.util.ArrayList) ActionSequenceParameterMgr(org.pentaho.platform.engine.services.actionsequence.ActionSequenceParameterMgr) PojoComponent(org.pentaho.platform.engine.services.solution.PojoComponent)

Example 12 with IAction

use of org.pentaho.platform.api.action.IAction in project pentaho-platform by pentaho.

the class LocalActionInvokerTest method invokeActionLocallyTest.

@Test
public void invokeActionLocallyTest() throws Exception {
    Map<String, Serializable> testMap = new HashMap<>();
    testMap.put(ActionUtil.QUARTZ_ACTIONCLASS, "one");
    testMap.put(ActionUtil.QUARTZ_ACTIONUSER, "two");
    IAction iaction = ActionUtil.createActionBean(ActionSequenceAction.class.getName(), null);
    ActionInvokeStatus actionInvokeStatus = (ActionInvokeStatus) defaultActionInvoker.invokeAction(iaction, "aUser", testMap);
    Assert.assertFalse(actionInvokeStatus.requiresUpdate());
}
Also used : Serializable(java.io.Serializable) ActionInvokeStatus(org.pentaho.platform.action.ActionInvokeStatus) IAction(org.pentaho.platform.api.action.IAction) HashMap(java.util.HashMap) ActionSequenceAction(org.pentaho.platform.plugin.action.builtin.ActionSequenceAction) Test(org.junit.Test)

Example 13 with IAction

use of org.pentaho.platform.api.action.IAction in project pentaho-platform by pentaho.

the class ActionAdapterQuartzJob method invokeAction.

/**
 * Invokes the {@link IAction} bean that is created from the provided {@code actionClassName} and {@code actionId} as
 * the provided {@code actionUser}. If the {@code IAction} execution fails as-is, the scheduler attempts to re-create
 * the job that will try to invoke the {@link IAction} again.
 *
 * @param actionClassName The class name of the {@link IAction} bean; used as a backup, if the {@code actionId} is not
 *                        available or vald
 * @param actionId        The bean id of the {@link IAction} requested to be invoked.
 * @param actionUser      The user invoking the {@link IAction}
 * @param context         the {@code JobExecutionContext}
 * @param params          the {@link Map} or parameters needed to invoke the {@link IAction}
 * @throws Exception when the {@code IAction} cannot be invoked for some reason.
 */
protected void invokeAction(final String actionClassName, final String actionId, final String actionUser, final JobExecutionContext context, final Map<String, Serializable> params) throws Exception {
    final String workItemUid = ActionUtil.extractUid(params);
    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.SUBMITTED);
    // creates an instance of IActionInvoker, which knows how to invoke this IAction - if the IActionInvoker bean is
    // not defined through spring, fall back on the default action invoker
    final IActionInvoker actionInvoker = Optional.ofNullable(PentahoSystem.get(IActionInvoker.class)).orElse(getActionInvoker());
    // Instantiate the requested IAction bean
    final IAction actionBean = (IAction) ActionUtil.createActionBean(actionClassName, actionId);
    if (actionInvoker == null || actionBean == null) {
        final String failureMessage = Messages.getInstance().getErrorString(// $NON-NLS-1$
        "ActionAdapterQuartzJob.ERROR_0002_FAILED_TO_CREATE_ACTION", getActionIdentifier(null, actionClassName, actionId), StringUtil.getMapAsPrettyString(params));
        WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.FAILED, failureMessage);
        throw new LoggingJobExecutionException(failureMessage);
    }
    if (actionBean instanceof BlockoutAction) {
        params.put(IBlockoutManager.SCHEDULED_FIRE_TIME, context.getScheduledFireTime());
    }
    // Invoke the action and get the status of the invocation
    final IActionInvokeStatus status = actionInvoker.invokeAction(actionBean, actionUser, getSerializableMap(params));
    // Status may not be available for remote execution, which is expected
    if (status == null) {
        if (log.isWarnEnabled()) {
            log.warn(Messages.getInstance().getErrorString(// $NON-NLS-1$
            "ActionAdapterQuartzJob.WARN_0002_NO_STATUS", getActionIdentifier(actionBean, actionClassName, actionId), StringUtil.getMapAsPrettyString(params)));
        }
        return;
    }
    // exception
    if (!status.isExecutionSuccessful()) {
        // throw job exception
        throw new JobExecutionException(Messages.getInstance().getActionFailedToExecute(// $NON-NLS-1$
        actionBean.getClass().getName()));
    }
    final boolean requiresUpdate = status.requiresUpdate();
    final Throwable throwable = status.getThrowable();
    Object objsp = status.getStreamProvider();
    IBackgroundExecutionStreamProvider sp = null;
    if (objsp != null && IBackgroundExecutionStreamProvider.class.isAssignableFrom(objsp.getClass())) {
        sp = (IBackgroundExecutionStreamProvider) objsp;
    }
    final IBackgroundExecutionStreamProvider streamProvider = sp;
    // shallow copy
    final Map<String, Serializable> jobParams = new HashMap<String, Serializable>(params);
    final IScheduler scheduler = PentahoSystem.getObjectFactory().get(IScheduler.class, "IScheduler2", null);
    if (throwable != null) {
        Object restartFlag = jobParams.get(QuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG);
        if (restartFlag == null) {
            final SimpleJobTrigger trigger = new SimpleJobTrigger(new Date(), null, 0, 0);
            final Class<IAction> iaction = (Class<IAction>) actionBean.getClass();
            // recreate the job in the context of the original creator
            SecurityHelper.getInstance().runAsUser(actionUser, new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    if (streamProvider != null) {
                        // remove generated content
                        streamProvider.setStreamingAction(null);
                    }
                    QuartzJobKey jobKey = QuartzJobKey.parse(context.getJobDetail().getName());
                    String jobName = jobKey.getJobName();
                    jobParams.put(QuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG, Boolean.TRUE);
                    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.RESTARTED);
                    scheduler.createJob(jobName, iaction, jobParams, trigger, streamProvider);
                    log.warn("New RunOnce job created for " + jobName + " -> possible startup synchronization error");
                    return null;
                }
            });
        } else {
            log.warn("RunOnce already created, skipping");
        }
        throw new JobExecutionException(throwable);
    }
    scheduler.fireJobCompleted(actionBean, actionUser, params, streamProvider);
    if (requiresUpdate) {
        log.warn("Output path for job: " + context.getJobDetail().getName() + " has changed. Job requires update");
        try {
            final IJobTrigger trigger = scheduler.getJob(context.getJobDetail().getName()).getJobTrigger();
            final Class<IAction> iaction = (Class<IAction>) actionBean.getClass();
            // remove job with outdated/invalid output path
            scheduler.removeJob(context.getJobDetail().getName());
            // recreate the job in the context of the original creator
            SecurityHelper.getInstance().runAsUser(actionUser, new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    // remove generated content
                    streamProvider.setStreamingAction(null);
                    QuartzJobKey jobKey = QuartzJobKey.parse(context.getJobDetail().getName());
                    String jobName = jobKey.getJobName();
                    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.RESTARTED);
                    org.pentaho.platform.api.scheduler2.Job j = scheduler.createJob(jobName, iaction, jobParams, trigger, streamProvider);
                    log.warn("New Job: " + j.getJobId() + " created");
                    return null;
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(MessageFormat.format("Scheduling system successfully invoked action {0} as user {1} with params [ {2} ]", // $NON-NLS-1$
        actionBean.getClass().getName(), actionUser, QuartzScheduler.prettyPrintMap(params)));
    }
}
Also used : IBackgroundExecutionStreamProvider(org.pentaho.platform.api.scheduler2.IBackgroundExecutionStreamProvider) Serializable(java.io.Serializable) HashMap(java.util.HashMap) BlockoutAction(org.pentaho.platform.scheduler2.blockout.BlockoutAction) JobExecutionException(org.quartz.JobExecutionException) Job(org.quartz.Job) IAction(org.pentaho.platform.api.action.IAction) IActionInvoker(org.pentaho.platform.api.action.IActionInvoker) Date(java.util.Date) JobExecutionException(org.quartz.JobExecutionException) SimpleJobTrigger(org.pentaho.platform.api.scheduler2.SimpleJobTrigger) IActionInvokeStatus(org.pentaho.platform.api.action.IActionInvokeStatus) IJobTrigger(org.pentaho.platform.api.scheduler2.IJobTrigger) IScheduler(org.pentaho.platform.api.scheduler2.IScheduler)

Example 14 with IAction

use of org.pentaho.platform.api.action.IAction in project pentaho-platform by pentaho.

the class ActionRunnerTest method testCallThrowsException.

@Test
public void testCallThrowsException() throws Exception {
    Map<String, Serializable> paramsMap = createMapWithUserLocale();
    IAction actionBeanSpy = Mockito.spy(new TestAction());
    IBackgroundExecutionStreamProvider mockStreamProvider = Mockito.mock(IBackgroundExecutionStreamProvider.class);
    when(mockStreamProvider.getInputStream()).thenThrow(new Exception("something went wrong"));
    ActionRunner actionRunner = new ActionRunner(actionBeanSpy, "actionUser", paramsMap, mockStreamProvider);
    exception.expect(ActionInvocationException.class);
    actionRunner.call();
}
Also used : IBackgroundExecutionStreamProvider(org.pentaho.platform.api.scheduler2.IBackgroundExecutionStreamProvider) Serializable(java.io.Serializable) IAction(org.pentaho.platform.api.action.IAction) ExpectedException(org.junit.rules.ExpectedException) ActionInvocationException(org.pentaho.platform.api.action.ActionInvocationException) TestAction(org.pentaho.platform.util.bean.TestAction) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 15 with IAction

use of org.pentaho.platform.api.action.IAction in project pentaho-platform by pentaho.

the class ActionRunnerTest method testCallInvokesExecute.

@Test
public void testCallInvokesExecute() throws Exception {
    Map<String, Serializable> paramsMap = createMapWithUserLocale();
    IAction actionBeanSpy = Mockito.spy(new TestAction());
    ActionRunner actionRunner = new ActionRunner(actionBeanSpy, "actionUser", paramsMap, null);
    actionRunner.call();
    Mockito.verify(actionBeanSpy).execute();
    // Verify that, by default the isExecutionSuccessful returns true
    Assert.assertTrue(actionBeanSpy.isExecutionSuccessful());
}
Also used : Serializable(java.io.Serializable) IAction(org.pentaho.platform.api.action.IAction) TestAction(org.pentaho.platform.util.bean.TestAction) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

IAction (org.pentaho.platform.api.action.IAction)15 HashMap (java.util.HashMap)9 Serializable (java.io.Serializable)8 Test (org.junit.Test)8 IBackgroundExecutionStreamProvider (org.pentaho.platform.api.scheduler2.IBackgroundExecutionStreamProvider)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 TestAction (org.pentaho.platform.util.bean.TestAction)3 ArrayList (java.util.ArrayList)2 ActionInvokeStatus (org.pentaho.platform.action.ActionInvokeStatus)2 ActionInvocationException (org.pentaho.platform.api.action.ActionInvocationException)2 RepositoryFile (org.pentaho.platform.api.repository2.unified.RepositoryFile)2 IJobTrigger (org.pentaho.platform.api.scheduler2.IJobTrigger)2 ActionSequenceAction (org.pentaho.platform.plugin.action.builtin.ActionSequenceAction)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Date (java.util.Date)1 List (java.util.List)1 Element (org.dom4j.Element)1 ExpectedException (org.junit.rules.ExpectedException)1