Search in sources :

Example 46 with IParameterProvider

use of org.pentaho.platform.api.engine.IParameterProvider in project pentaho-platform by pentaho.

the class DefaultChartBeansGenerator method createAndRunActionSequence.

protected void createAndRunActionSequence(final IPentahoSession pentahoSession, final Map<String, Object> params, final Map<String, Object> defaultParameterMap, String contentLinkingTemplate, final OutputStream out) {
    SimpleParameterProvider parameterProvider = new SimpleParameterProvider(params);
    // add the default parameter values
    for (Map.Entry<String, Object> entry : defaultParameterMap.entrySet()) {
        parameterProvider.setParameter(entry.getKey(), entry.getValue());
    }
    Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
    parameterProviders.put(IParameterProvider.SCOPE_REQUEST, parameterProvider);
    SimpleOutputHandler outputHandler = new SimpleOutputHandler(out, true);
    outputHandler.setOutputPreference(IOutputHandler.OUTPUT_TYPE_DEFAULT);
    ActionSequenceDocument doc = createActionSequenceDocument(defaultParameterMap.keySet(), contentLinkingTemplate);
    runActionSequence(pentahoSession, parameterProviders, outputHandler, doc);
    try {
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) HashMap(java.util.HashMap) SimpleOutputHandler(org.pentaho.platform.engine.core.output.SimpleOutputHandler) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) SimpleParameterProvider(org.pentaho.platform.engine.core.solution.SimpleParameterProvider) IActionSequenceDocument(org.pentaho.actionsequence.dom.IActionSequenceDocument) ActionSequenceDocument(org.pentaho.actionsequence.dom.ActionSequenceDocument)

Example 47 with IParameterProvider

use of org.pentaho.platform.api.engine.IParameterProvider in project pentaho-platform by pentaho.

the class GlobalOutputIT method testEmptyActionSequence.

public void testEmptyActionSequence() {
    startTest();
    List messages = new ArrayList();
    String instanceId = null;
    IPentahoSession session = new StandaloneSession("system");
    PentahoSessionHolder.setSession(session);
    ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class);
    solutionEngine.setLoggingLevel(ILogger.ERROR);
    solutionEngine.init(session);
    String baseUrl = PentahoSystem.getApplicationContext().getBaseUrl();
    HashMap parameterProviderMap = new HashMap();
    IPentahoUrlFactory urlFactory = new SimpleUrlFactory(baseUrl);
    try {
        File file = new File(getSolutionPath() + "/samples/platform/SetGlobalOutputTest.xaction");
        StringBuilder str = new StringBuilder();
        Reader reader = new FileReader(file);
        char[] buffer = new char[4096];
        int n = reader.read(buffer);
        while (n != -1) {
            str.append(buffer, 0, n);
            n = reader.read(buffer);
        }
        String xactionStr = str.toString();
        solutionEngine.setSession(session);
        IRuntimeContext runtimeContext = solutionEngine.execute(xactionStr, "SetGlobalOutputTest.xaction", "empty action sequence test", false, true, instanceId, false, parameterProviderMap, null, null, urlFactory, // $NON-NLS-1$ //$NON-NLS-2$
        messages);
        assertNotNull("RuntimeContext is null", runtimeContext);
        assertEquals("Action sequence execution failed", runtimeContext.getStatus(), IRuntimeContext.RUNTIME_STATUS_SUCCESS);
        IParameterProvider provider = PentahoSystem.getGlobalParameters();
        // $NON-NLS-1$
        String parameter = provider.getStringParameter("GLOBAL_TEST", null);
        assertNotNull(parameter);
        // $NON-NLS-1$
        assertEquals("This is a test", parameter);
    } catch (Exception e) {
        // we should not get here
        e.printStackTrace();
        assertTrue(e.getMessage(), false);
    }
}
Also used : ISolutionEngine(org.pentaho.platform.api.engine.ISolutionEngine) IPentahoUrlFactory(org.pentaho.platform.api.engine.IPentahoUrlFactory) StandaloneSession(org.pentaho.platform.engine.core.system.StandaloneSession) HashMap(java.util.HashMap) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ArrayList(java.util.ArrayList) Reader(java.io.Reader) FileReader(java.io.FileReader) IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) ArrayList(java.util.ArrayList) List(java.util.List) FileReader(java.io.FileReader) SimpleUrlFactory(org.pentaho.platform.util.web.SimpleUrlFactory) File(java.io.File) IRuntimeContext(org.pentaho.platform.api.engine.IRuntimeContext)

Example 48 with IParameterProvider

use of org.pentaho.platform.api.engine.IParameterProvider in project pentaho-platform by pentaho.

the class FileResource method doIsParameterizable.

/**
 * Determines whether a selected file supports parameters or not
 *
 * @param pathId Colon separated path for the repository file.
 *
 * @return ("true" or "false")
 * @throws FileNotFoundException
 */
@GET
@Path("{pathId : .+}/parameterizable")
@Produces(MediaType.TEXT_PLAIN)
@Facet(name = "Unsupported")
@StatusCodes({ @ResponseCode(code = 200, condition = "Successfully get the file or directory."), @ResponseCode(code = 404, condition = "Failed to find the file or resource.") })
public // have to accept anything for browsers to work
String doIsParameterizable(@PathParam("pathId") String pathId) throws FileNotFoundException {
    boolean hasParameterUi = false;
    RepositoryFile repositoryFile = getRepository().getFile(fileService.idToPath(pathId));
    if (repositoryFile != null) {
        try {
            hasParameterUi = hasParameterUi(repositoryFile);
        } catch (NoSuchBeanDefinitionException e) {
        // Do nothing.
        }
    }
    boolean hasParameters = false;
    if (hasParameterUi) {
        try {
            IContentGenerator parameterContentGenerator = getContentGenerator(repositoryFile);
            if (parameterContentGenerator != null) {
                ByteArrayOutputStream outputStream = getByteArrayOutputStream();
                parameterContentGenerator.setOutputHandler(new SimpleOutputHandler(outputStream, false));
                parameterContentGenerator.setMessagesList(new ArrayList<String>());
                Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
                SimpleParameterProvider parameterProvider = getSimpleParameterProvider();
                parameterProvider.setParameter("path", encode(repositoryFile.getPath()));
                parameterProvider.setParameter("renderMode", "PARAMETER");
                parameterProviders.put(IParameterProvider.SCOPE_REQUEST, parameterProvider);
                parameterContentGenerator.setParameterProviders(parameterProviders);
                parameterContentGenerator.setSession(getSession());
                parameterContentGenerator.createContent();
                if (outputStream.size() > 0) {
                    Document document = parseText(outputStream.toString());
                    // exclude all parameters that are of type "system", xactions set system params that have to be ignored.
                    @SuppressWarnings("rawtypes") List nodes = document.selectNodes("parameters/parameter");
                    for (int i = 0; i < nodes.size() && !hasParameters; i++) {
                        Element elem = (Element) nodes.get(i);
                        if (elem.attributeValue("name").equalsIgnoreCase("output-target") && elem.attributeValue("is-mandatory").equalsIgnoreCase("true")) {
                            hasParameters = true;
                            continue;
                        }
                        Element attrib = (Element) elem.selectSingleNode("attribute[@namespace='http://reporting.pentaho" + ".org/namespaces/engine/parameter-attributes/core' and @name='role']");
                        if (attrib == null || !"system".equals(attrib.attributeValue("value"))) {
                            hasParameters = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(getMessagesInstance().getString("FileResource.PARAM_FAILURE", e.getMessage()), e);
        }
    }
    return Boolean.toString(hasParameters);
}
Also used : HashMap(java.util.HashMap) Element(org.dom4j.Element) SimpleOutputHandler(org.pentaho.platform.engine.core.output.SimpleOutputHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.dom4j.Document) GeneralSecurityException(java.security.GeneralSecurityException) InvalidParameterException(java.security.InvalidParameterException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) UnifiedRepositoryAccessDeniedException(org.pentaho.platform.api.repository2.unified.UnifiedRepositoryAccessDeniedException) FileNotFoundException(java.io.FileNotFoundException) PlatformImportException(org.pentaho.platform.plugin.services.importer.PlatformImportException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ExportException(org.pentaho.platform.plugin.services.importexport.ExportException) DocumentException(org.dom4j.DocumentException) IllegalSelectorException(java.nio.channels.IllegalSelectorException) IOException(java.io.IOException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) IContentGenerator(org.pentaho.platform.api.engine.IContentGenerator) RepositoryFile(org.pentaho.platform.api.repository2.unified.RepositoryFile) List(java.util.List) ArrayList(java.util.ArrayList) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleParameterProvider(org.pentaho.platform.engine.core.solution.SimpleParameterProvider) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes) Facet(org.codehaus.enunciate.Facet)

Example 49 with IParameterProvider

use of org.pentaho.platform.api.engine.IParameterProvider in project pentaho-platform by pentaho.

the class FileResourceContentGenerator method createContent.

@Override
public void createContent(OutputStream out) throws Exception {
    // $NON-NLS-1$
    IParameterProvider pathParams = parameterProviders.get("path");
    IParameterProvider requestParams = parameterProviders.get(IParameterProvider.SCOPE_REQUEST);
    // $NON-NLS-1$
    RepositoryFile file = (RepositoryFile) pathParams.getParameter("file");
    ActionHarness harness = new ActionHarness(this);
    Iterator<?> iter = requestParams.getParameterNames();
    while (iter.hasNext()) {
        String paramName = (String) iter.next();
        harness.setValue(paramName, requestParams.getParameter(paramName));
    }
    this.setOutputStream(out);
    this.setRepositoryFile(file);
    this.execute();
}
Also used : IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) RepositoryFile(org.pentaho.platform.api.repository2.unified.RepositoryFile) ActionHarness(org.pentaho.platform.util.beans.ActionHarness)

Example 50 with IParameterProvider

use of org.pentaho.platform.api.engine.IParameterProvider in project pentaho-platform by pentaho.

the class GeneratorStreamingOutput method generateContent.

protected void generateContent(OutputStream outputStream, final MimeTypeCallback callback) throws Exception {
    try {
        httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding());
    } catch (Throwable t) {
        // $NON-NLS-1$
        logger.warn("could not set encoding, servlet-api is likely too old.  are we in a unit test?");
    }
    IOutputHandler outputHandler = new HttpOutputHandler(httpServletResponse, outputStream, true);
    outputHandler.setMimeTypeListener(new HttpMimeTypeListener(httpServletRequest, httpServletResponse) {

        /*
       * This content generator is setting the mimeType
       */
        @Override
        public void setMimeType(String mimeType) {
            try {
                if (!MIMETYPE_MUTABLE && GeneratorStreamingOutput.this.getMimeType() != null) {
                    mimeTrace(// $NON-NLS-1$
                    "Content generator is trying to set response mime type to [{0}], but mime type [{1}] has already been imposed. Content generator request to change mime type will be ignored.", mimeType, GeneratorStreamingOutput.this.getMimeType());
                    return;
                } else {
                    // $NON-NLS-1$
                    mimeTrace("Content generator is setting response mime type to [{0}]", mimeType);
                    if (callback != null) {
                        callback.setMimeType(mimeType);
                    }
                    GeneratorStreamingOutput.this.setMimeType(mimeType);
                }
            } catch (Throwable th) {
                mimeTrace("Failed to set mime type: {0}", th.getMessage());
                // $NON-NLS-1$
                logger.error(MessageFormat.format("Failed to set mime type: {0}", th.getMessage()));
            }
            super.setMimeType(mimeType);
        }
    });
    Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
    parameterProviders.put(IParameterProvider.SCOPE_REQUEST, createRequestParamProvider());
    parameterProviders.put(IParameterProvider.SCOPE_SESSION, createSessionParameterProvider());
    // $NON-NLS-1$
    parameterProviders.put("headers", createHeaderParamProvider());
    // $NON-NLS-1$
    parameterProviders.put("path", createPathParamProvider());
    String pluginId = contentGeneratorDescriptor.getPluginId();
    IPentahoUrlFactory urlFactory = new SimpleUrlFactory(PentahoRequestContextHolder.getRequestContext().getContextPath() + "api/repos/" + pluginId + "/" + contentGeneratorID + // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    "?");
    // set the classloader of the current thread to the class loader of
    // the plugin so that it can load its libraries
    // Note: we cannot ask the contentGenerator class for it's classloader,
    // since the cg may
    // actually be a proxy object loaded by main the WebAppClassloader
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(pluginMgr.getClassLoader(pluginId));
    try {
        contentGenerator.setOutputHandler(outputHandler);
        contentGenerator.setMessagesList(new ArrayList<String>());
        contentGenerator.setParameterProviders(parameterProviders);
        contentGenerator.setSession(PentahoSessionHolder.getSession());
        if (urlFactory != null) {
            contentGenerator.setUrlFactory(urlFactory);
        }
        contentGenerator.createContent();
    } finally {
        Thread.currentThread().setContextClassLoader(origContextClassloader);
    }
}
Also used : IPentahoUrlFactory(org.pentaho.platform.api.engine.IPentahoUrlFactory) HashMap(java.util.HashMap) HttpOutputHandler(org.pentaho.platform.web.http.HttpOutputHandler) IOutputHandler(org.pentaho.platform.api.engine.IOutputHandler) HttpMimeTypeListener(org.pentaho.platform.web.http.HttpMimeTypeListener) IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) SimpleUrlFactory(org.pentaho.platform.util.web.SimpleUrlFactory)

Aggregations

IParameterProvider (org.pentaho.platform.api.engine.IParameterProvider)57 HashMap (java.util.HashMap)27 SimpleParameterProvider (org.pentaho.platform.engine.core.solution.SimpleParameterProvider)21 ArrayList (java.util.ArrayList)14 List (java.util.List)11 Test (org.junit.Test)11 SimpleUrlFactory (org.pentaho.platform.util.web.SimpleUrlFactory)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 IOException (java.io.IOException)9 Iterator (java.util.Iterator)8 SimpleOutputHandler (org.pentaho.platform.engine.core.output.SimpleOutputHandler)8 HttpRequestParameterProvider (org.pentaho.platform.web.http.request.HttpRequestParameterProvider)8 MockHttpServletRequest (com.mockrunner.mock.web.MockHttpServletRequest)7 MockHttpServletResponse (com.mockrunner.mock.web.MockHttpServletResponse)7 IOutputHandler (org.pentaho.platform.api.engine.IOutputHandler)6 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)6 IRuntimeContext (org.pentaho.platform.api.engine.IRuntimeContext)6 RepositoryFile (org.pentaho.platform.api.repository2.unified.RepositoryFile)6 SimpleParameterSetter (org.pentaho.platform.engine.services.solution.SimpleParameterSetter)6 OutputStream (java.io.OutputStream)5