use of org.pentaho.platform.api.engine.IContentGenerator in project pentaho-platform by pentaho.
the class PentahoSystemPluginManager method registerContentGenerators.
private void registerContentGenerators(IPlatformPlugin plugin, ClassLoader loader, final GenericApplicationContext beanFactory) throws PlatformPluginRegistrationException {
// register the content generators
for (final IContentGeneratorInfo cgInfo : plugin.getContentGenerators()) {
// define the bean in the factory
BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(cgInfo.getClassname()).setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
// register bean with alias of content generator id (old way)
beanFactory.registerBeanDefinition(cgInfo.getId(), beanDef);
// register bean with alias of type (with default perspective) as well (new way)
beanFactory.registerAlias(cgInfo.getId(), cgInfo.getType());
PluginMessageLogger.add(Messages.getInstance().getString("PluginManager.USER_CONTENT_GENERATOR_REGISTERED", cgInfo.getId(), plugin.getId()));
final HashMap<String, Object> attributes = new HashMap<String, Object>();
attributes.put(PLUGIN_ID, plugin.getId());
attributes.put(CONTENT_TYPE, cgInfo.getType());
final IPentahoObjectRegistration referenceHandle = PentahoSystem.registerReference(new PrototypePentahoObjectReference.Builder<IContentGenerator>(IContentGenerator.class).creator(new IObjectCreator<IContentGenerator>() {
@Override
public IContentGenerator create(IPentahoSession session) {
return (IContentGenerator) beanFactory.getBean(cgInfo.getId());
}
}).attributes(attributes).build(), IContentGenerator.class);
registerReference(plugin.getId(), referenceHandle);
}
// The remaining operations require a beanFactory
if (beanFactory == null) {
return;
}
String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory.getBeanFactory(), IContentGenerator.class);
ArrayList<String> ids = new ArrayList<String>();
for (String beanName : names) {
ids.add(beanName);
Collections.addAll(ids, beanFactory.getAliases(beanName));
}
for (final String beanName : ids) {
final HashMap<String, Object> attributes = new HashMap<String, Object>();
attributes.put(PLUGIN_ID, plugin.getId());
attributes.put(CONTENT_TYPE, beanName);
final IPentahoObjectRegistration referenceHandle = PentahoSystem.registerReference(new PrototypePentahoObjectReference.Builder<IContentGenerator>(IContentGenerator.class).creator(new IObjectCreator<IContentGenerator>() {
@Override
public IContentGenerator create(IPentahoSession session) {
return (IContentGenerator) beanFactory.getBean(beanName);
}
}).attributes(attributes).build(), IContentGenerator.class);
registerReference(plugin.getId(), referenceHandle);
}
}
use of org.pentaho.platform.api.engine.IContentGenerator in project pentaho-platform by pentaho.
the class FileResourceTest method testDoIsParameterizable.
@Test
public void testDoIsParameterizable() throws Exception {
String path = "path";
doReturn(path).when(fileResource.fileService).idToPath(PATH_ID);
RepositoryFile mockRepositoryFile = mock(RepositoryFile.class);
doReturn(mockRepositoryFile).when(fileResource.repository).getFile(path);
doReturn(true).when(fileResource).hasParameterUi(mockRepositoryFile);
IContentGenerator mockContentGenerator = mock(IContentGenerator.class);
doReturn(mockContentGenerator).when(fileResource).getContentGenerator(mockRepositoryFile);
SimpleParameterProvider mockSimpleParameterProvider = mock(SimpleParameterProvider.class);
doReturn(mockSimpleParameterProvider).when(fileResource).getSimpleParameterProvider();
String repositoryPath = "repositoryPath";
doReturn(repositoryPath).when(mockRepositoryFile).getPath();
String encodedPath = "encodedPath";
doReturn(encodedPath).when(fileResource).encode(repositoryPath);
IPentahoSession mockPentahoSession = mock(IPentahoSession.class);
doReturn(mockPentahoSession).when(fileResource).getSession();
ByteArrayOutputStream mockByteArrayOutputStream = mock(ByteArrayOutputStream.class);
doReturn(mockByteArrayOutputStream).when(fileResource).getByteArrayOutputStream();
doReturn(1).when(mockByteArrayOutputStream).size();
String outputStreamToString = "outputStreamToString";
doReturn(outputStreamToString).when(mockByteArrayOutputStream).toString();
Document mockDocument = mock(Document.class);
doReturn(mockDocument).when(fileResource).parseText(outputStreamToString);
String selectNodesParam = "parameters/parameter";
List<Element> elements = new ArrayList<Element>();
doReturn(elements).when(mockDocument).selectNodes(selectNodesParam);
Element mockElement = mock(Element.class);
doReturn("output-target").when(mockElement).attributeValue("name");
doReturn("true").when(mockElement).attributeValue("is-mandatory");
// Test 1
String testString = fileResource.doIsParameterizable(PATH_ID);
assertEquals(Boolean.FALSE.toString(), testString);
// Test 2
elements.add(mockElement);
testString = fileResource.doIsParameterizable(PATH_ID);
assertEquals(Boolean.TRUE.toString(), testString);
// Test 3
doReturn("false").when(mockElement).attributeValue("is-mandatory");
testString = fileResource.doIsParameterizable(PATH_ID);
assertEquals(Boolean.TRUE.toString(), testString);
// Test 4
Element mockAttribElement = mock(Element.class);
doReturn(mockAttribElement).when(mockElement).selectSingleNode("attribute[@namespace='http://reporting.pentaho" + ".org/namespaces/engine/parameter-attributes/core' and @name='role']");
testString = fileResource.doIsParameterizable(PATH_ID);
assertEquals(Boolean.TRUE.toString(), testString);
verify(fileResource.fileService, times(4)).idToPath(PATH_ID);
verify(fileResource.repository, times(4)).getFile(path);
verify(fileResource, times(4)).hasParameterUi(mockRepositoryFile);
verify(fileResource, times(4)).getContentGenerator(mockRepositoryFile);
verify(mockContentGenerator, times(4)).setOutputHandler(any(SimpleOutputHandler.class));
verify(mockContentGenerator, times(4)).setMessagesList(anyList());
verify(fileResource, times(4)).getSimpleParameterProvider();
verify(mockRepositoryFile, times(4)).getPath();
verify(fileResource, times(4)).encode(repositoryPath);
verify(mockSimpleParameterProvider, times(4)).setParameter("path", encodedPath);
verify(mockSimpleParameterProvider, times(4)).setParameter("renderMode", "PARAMETER");
verify(mockContentGenerator, times(4)).setParameterProviders(anyMap());
verify(fileResource, times(4)).getSession();
verify(mockContentGenerator, times(4)).setSession(mockPentahoSession);
verify(mockContentGenerator, times(4)).createContent();
verify(fileResource, times(4)).getByteArrayOutputStream();
verify(mockDocument, times(4)).selectNodes(selectNodesParam);
verify(mockElement, times(3)).attributeValue("name");
verify(mockElement, times(3)).attributeValue("is-mandatory");
verify(mockAttribElement, times(1)).attributeValue("value");
}
use of org.pentaho.platform.api.engine.IContentGenerator in project pentaho-platform by pentaho.
the class AxisWebServiceManagerIT method testListingPageStyled.
@Test
public void testListingPageStyled() throws Exception {
MockServletContext context = new MockServletContext();
context.addResourcePaths("/", Arrays.asList("test-module/"));
context.addResourcePaths("/test-module/", Arrays.asList("themes.xml"));
context.addResourcePaths("/test-module/themes/onyx/", Arrays.asList("styles.css"));
File themesDotXML = new File(microPlatform.getFilePath() + "system/axis/themes.xml");
context.setResource("/test-module/themes.xml", themesDotXML.toURI().toURL());
context.setResourceAsStream("/test-module/themes.xml", new FileInputStream(themesDotXML));
File styleDotSCC = new File(microPlatform.getFilePath() + "system/axis/themes/onyx/styles.css");
context.setResource("/test-module/themes/onyx/styles.css", styleDotSCC.toURI().toURL());
context.setResourceAsStream("/test-module/themes/onyx/styles.css", new FileInputStream(styleDotSCC));
PentahoSystem.getApplicationContext().setContext(context);
IContentGenerator serviceLister = new StyledHtmlAxisServiceLister();
String html = ContentGeneratorUtil.getContentAsString(serviceLister);
System.out.println(html);
assertTrue("style is missing", html.contains("styles.css"));
}
use of org.pentaho.platform.api.engine.IContentGenerator in project pentaho-platform by pentaho.
the class DefaultPluginManagerIT method test9_ContentGenerationRegistration.
@SuppressWarnings("deprecation")
@Test
public void test9_ContentGenerationRegistration() throws ObjectFactoryException, PluginBeanException, PlatformInitializationException {
microPlatform.define(IPluginProvider.class, Tst9PluginProvider.class).start();
PluginMessageLogger.clear();
pluginManager.reload();
System.err.println(PluginMessageLogger.prettyPrint());
// see if we can get a content generator instance by id (old way)
assertNotNull("Could not get content generator test9 by id", pluginManager.getBean("test9id"));
assertNotNull("Could not get content generator test9b by id", pluginManager.getBean("test9bid"));
// see if we can get a content generator instance by type (new way)
assertNotNull("Could not get content generator test9 by id", pluginManager.getContentGenerator("test9type", null));
assertNotNull("Could not get content generator test9b by id", pluginManager.getContentGenerator("test9btype", null));
// see if we can access the content generator by type
IContentGenerator contentGenerator = pluginManager.getContentGeneratorForType("test9type", session);
assertNotNull("Should have gotten an instance of a cg for content type", contentGenerator);
assertTrue(contentGenerator instanceof ContentGenerator1);
}
use of org.pentaho.platform.api.engine.IContentGenerator in project pentaho-platform by pentaho.
the class GenericServlet method doGet.
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
if (showDeprecationMessage) {
String deprecationMessage = "GenericServlet is deprecated and should no longer be handling requests. More detail below..." + "\n | You have issued a {0} request to {1} from referer {2} " + "\n | Please consider using one of the following REST services instead:" + "\n | * GET /api/repos/<pluginId>/<path> to read files from a plugin public dir" + "\n | * POST|GET /api/repos/<pathId>/generatedContent to create content resulting from execution of a " + "repo file" + "\n | * POST|GET /api/repos/<pluginId>/<contentGeneratorId> to execute a content generator by name (RPC " + "compatibility service)" + "\n \\ To turn this message off, set init-param 'showDeprecationMessage' to false in the GenericServlet " + "declaration" + "";
String referer = StringUtils.defaultString(request.getHeader("Referer"), "");
logger.warn(MessageFormat.format(deprecationMessage, request.getMethod(), request.getRequestURL(), referer));
}
PentahoSystem.systemEntryPoint();
IOutputHandler outputHandler = null;
// BISERVER-2767 - grabbing the current class loader so we can replace it at the end
ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
try {
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
// $NON-NLS-1$
String contentGeneratorId = "";
// $NON-NLS-1$
String urlPath = "";
SimpleParameterProvider pathParams = new SimpleParameterProvider();
if (StringUtils.isEmpty(pathInfo)) {
logger.error(// $NON-NLS-1$
Messages.getInstance().getErrorString("GenericServlet.ERROR_0005_NO_RESOURCE_SPECIFIED"));
response.sendError(403);
return;
}
String path = pathInfo.substring(1);
int slashPos = path.indexOf('/');
if (slashPos != -1) {
// $NON-NLS-1$
pathParams.setParameter("path", pathInfo.substring(slashPos + 1));
contentGeneratorId = path.substring(0, slashPos);
} else {
contentGeneratorId = path;
}
// $NON-NLS-1$
urlPath = "content/" + contentGeneratorId;
IParameterProvider requestParameters = new HttpRequestParameterProvider(request);
// $NON-NLS-1$
pathParams.setParameter("query", request.getQueryString());
// $NON-NLS-1$
pathParams.setParameter("contentType", request.getContentType());
InputStream in = request.getInputStream();
// $NON-NLS-1$
pathParams.setParameter("inputstream", in);
// $NON-NLS-1$
pathParams.setParameter("httpresponse", response);
// $NON-NLS-1$
pathParams.setParameter("httprequest", request);
// $NON-NLS-1$
pathParams.setParameter("remoteaddr", request.getRemoteAddr());
if (PentahoSystem.debug) {
// $NON-NLS-1$
debug("GenericServlet contentGeneratorId=" + contentGeneratorId);
// $NON-NLS-1$
debug("GenericServlet urlPath=" + urlPath);
}
IPentahoSession session = getPentahoSession(request);
IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
if (pluginManager == null) {
OutputStream out = response.getOutputStream();
String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0001_BAD_OBJECT", // $NON-NLS-1$
IPluginManager.class.getSimpleName());
error(message);
out.write(message.getBytes());
return;
}
// TODO make doing the HTTP headers configurable per content generator
SimpleParameterProvider headerParams = new SimpleParameterProvider();
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = request.getHeader(name);
headerParams.setParameter(name, value);
}
String pluginId = pluginManager.getServicePlugin(pathInfo);
if (pluginId != null && pluginManager.isStaticResource(pathInfo)) {
boolean cacheOn = "true".equals(pluginManager.getPluginSetting(pluginId, "settings/cache", // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
"false"));
// $NON-NLS-1$
String maxAge = (String) pluginManager.getPluginSetting(pluginId, "settings/max-age", null);
allowBrowserCache(maxAge, pathParams);
String mimeType = MimeHelper.getMimeTypeFromFileName(pathInfo);
if (mimeType != null) {
response.setContentType(mimeType);
}
OutputStream out = response.getOutputStream();
// do we have this resource cached?
ByteArrayOutputStream byteStream = null;
if (cacheOn) {
byteStream = (ByteArrayOutputStream) cache.getFromRegionCache(CACHE_FILE, pathInfo);
}
if (byteStream != null) {
IOUtils.write(byteStream.toByteArray(), out);
return;
}
InputStream resourceStream = pluginManager.getStaticResource(pathInfo);
if (resourceStream != null) {
try {
byteStream = new ByteArrayOutputStream();
IOUtils.copy(resourceStream, byteStream);
// if cache is enabled, drop file in cache
if (cacheOn) {
cache.putInRegionCache(CACHE_FILE, pathInfo, byteStream);
}
// write it out
IOUtils.write(byteStream.toByteArray(), out);
return;
} finally {
IOUtils.closeQuietly(resourceStream);
}
}
logger.error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0004_RESOURCE_NOT_FOUND", pluginId, // $NON-NLS-1$
pathInfo));
response.sendError(404);
return;
}
// content generators defined in plugin.xml are registered with 2 aliases, one is the id, the other is type
// so, we can still retrieve a content generator by id, even though this is not the correct way to find
// it. the correct way is to look up a content generator by pluginManager.getContentGenerator(type,
// perspectiveName)
IContentGenerator contentGenerator = (IContentGenerator) pluginManager.getBean(contentGeneratorId);
if (contentGenerator == null) {
OutputStream out = response.getOutputStream();
String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", // $NON-NLS-1$
Encode.forHtml(contentGeneratorId));
error(message);
out.write(message.getBytes());
return;
}
// 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
Thread.currentThread().setContextClassLoader(pluginManager.getClassLoader(pluginId));
// String proxyClass = PentahoSystem.getSystemSetting( module+"/plugin.xml" ,
// "plugin/content-generators/"+contentGeneratorId,
// "content generator not found");
// see if this is an upload
// File uploading is a service provided by UploadFileServlet where appropriate protections
// are in place to prevent uploads that are too large.
// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// if (isMultipart) {
// requestParameters = new SimpleParameterProvider();
// // Create a factory for disk-based file items
// FileItemFactory factory = new DiskFileItemFactory();
//
// // Create a new file upload handler
// ServletFileUpload upload = new ServletFileUpload(factory);
//
// // Parse the request
// List<?> /* FileItem */items = upload.parseRequest(request);
// Iterator<?> iter = items.iterator();
// while (iter.hasNext()) {
// FileItem item = (FileItem) iter.next();
//
// if (item.isFormField()) {
// ((SimpleParameterProvider) requestParameters).setParameter(item.getFieldName(), item.getString());
// } else {
// String name = item.getName();
// ((SimpleParameterProvider) requestParameters).setParameter(name, item.getInputStream());
// }
// }
// }
response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
IMimeTypeListener listener = new HttpMimeTypeListener(request, response);
outputHandler = getOutputHandler(response, true);
outputHandler.setMimeTypeListener(listener);
IParameterProvider sessionParameters = new HttpSessionParameterProvider(session);
IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParameters);
parameterProviders.put(IParameterProvider.SCOPE_SESSION, sessionParameters);
// $NON-NLS-1$
parameterProviders.put("headers", headerParams);
// $NON-NLS-1$
parameterProviders.put("path", pathParams);
SimpleUrlFactory urlFactory = // $NON-NLS-1$ //$NON-NLS-2$
new SimpleUrlFactory(requestContext.getContextPath() + urlPath + "?");
List<String> messages = new ArrayList<String>();
contentGenerator.setOutputHandler(outputHandler);
contentGenerator.setMessagesList(messages);
contentGenerator.setParameterProviders(parameterProviders);
contentGenerator.setSession(session);
contentGenerator.setUrlFactory(urlFactory);
// String contentType = request.getContentType();
// contentGenerator.setInput(input);
contentGenerator.createContent();
if (PentahoSystem.debug) {
// $NON-NLS-1$
debug("Generic Servlet content generate successfully");
}
} catch (Exception e) {
StringBuffer buffer = new StringBuffer();
error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", request.getQueryString()), // $NON-NLS-1$
e);
List errorList = new ArrayList();
String msg = e.getMessage();
errorList.add(msg);
// $NON-NLS-1$
MessageFormatUtils.formatFailureMessage("text/html", null, buffer, errorList);
response.getOutputStream().write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));
} finally {
// reset the classloader of the current thread
Thread.currentThread().setContextClassLoader(origContextClassloader);
PentahoSystem.systemExitPoint();
}
}
Aggregations