/** * Logs in with given username. * * @param username username of user * @param tenantId tenant to which this user belongs * @tenantAdmin true to add the tenant admin authority to the user's roles */ protected void login(final String username, final ITenant tenant, String[] roles) { StandaloneSession pentahoSession = new StandaloneSession(tenantedUserNameUtils.getPrincipleId(tenant, username)); pentahoSession.setAuthenticated( tenant.getId(), tenantedUserNameUtils.getPrincipleId(tenant, username)); PentahoSessionHolder.setSession(pentahoSession); pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenant.getId()); final String password = "******"; List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); for (String roleName : roles) { authList.add( new GrantedAuthorityImpl(tenantedRoleNameUtils.getPrincipleId(tenant, roleName))); } GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]); UserDetails userDetails = new User(username, password, true, true, true, true, authorities); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password, authorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(auth); SecurityHelper.getInstance().becomeUser(tenantedUserNameUtils.getPrincipleId(tenant, username)); SecurityContextHolder.getContext().setAuthentication(auth); }
protected void makeAuditRecord( final float time, final String messageType, final JobExecutionContext jobExecutionContext) { if (jobExecutionContext != null && jobExecutionContext.getJobDetail() != null) { final JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); AuditHelper.audit( PentahoSessionHolder.getSession() != null ? PentahoSessionHolder.getSession().getId() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER).toString() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER).toString() : null, jobExecutionContext.getJobDetail().getJobClass() != null ? jobExecutionContext.getJobDetail().getJobClass().getName() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID).toString() : null, messageType, jobDataMap.get("lineage-id") != null ? jobDataMap.get("lineage-id").toString() : null, null, time, null); //$NON-NLS-1$ } }
/** * Encapsulates the logic of registering import handlers, generating the manifest, and performing * the export */ public ZipExportProcessor(String path, IUnifiedRepository repository, boolean withManifest) { this.withManifest = withManifest; // set a default path at root if missing if (StringUtils.isEmpty(path)) { this.path = "/"; } else { this.path = path; } this.unifiedRepository = repository; this.exportHandlerList = new ArrayList<ExportHandler>(); this.exportManifest = new ExportManifest(); // set created by and create date in manifest information IPentahoSession session = PentahoSessionHolder.getSession(); Date todaysDate = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat(EXPORT_INFO_DATE_FORMAT); SimpleDateFormat timeFormat = new SimpleDateFormat(EXPORT_INFO_TIME_FORMAT); exportManifest.getManifestInformation().setExportBy(session.getName()); exportManifest .getManifestInformation() .setExportDate(dateFormat.format(todaysDate) + " " + timeFormat.format(todaysDate)); }
@BeforeClass public static void beforeClass() throws Exception { System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL"); PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL); FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK")); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); }
public static MasterReport createReport(final Serializable fileId) throws ResourceException, IOException { final ResourceManager resourceManager = new ResourceManager(); resourceManager.registerDefaults(); final HashMap helperObjects = new HashMap(); // add the runtime context so that PentahoResourceData class can get access // to the solution repo ResourceKey key = null; IUnifiedRepository unifiedRepository = PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession()); RepositoryFile repositoryFile = unifiedRepository.getFileById(fileId); if (repositoryFile != null) { key = resourceManager.createKey( RepositoryResourceLoader.SOLUTION_SCHEMA_NAME + RepositoryResourceLoader.SCHEMA_SEPARATOR + repositoryFile.getPath(), helperObjects); } else { key = resourceManager.createKey( RepositoryResourceLoader.SOLUTION_SCHEMA_NAME + RepositoryResourceLoader.SCHEMA_SEPARATOR + fileId, helperObjects); } final Resource resource = resourceManager.create(key, null, MasterReport.class); return (MasterReport) resource.getResource(); }
@Before public void setUp() throws Exception { repository = mock(IUnifiedRepository.class); session = mock(IPentahoSession.class); when(session.getName()).thenReturn("test"); PentahoSessionHolder.setSession(session); userSettings = new HashMap<String, Serializable>() { { put(USER_SETTING_NAME_1, USER_SETTING_VALUE_1); put(UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME, COMMON_USER_SETTING_VALUE); put(USER_SETTING_NAME_2, USER_SETTING_VALUE_2); put(UserSettingService.SETTING_PREFIX + USER_SETTING_NAME_3, USER_SETTING_VALUE_3); } }; globalSettings = new HashMap<String, Serializable>() { { put(GLOBAL_SETTING_NAME_1, GLOBAL_SETTING_VALUE_1); put( UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME, COMMON_GLOBAL_SETTING_VALUE); put(GLOBAL_SETTING_NAME_2, GLOBAL_SETTING_VALUE_2); put(UserSettingService.SETTING_PREFIX + GLOBAL_SETTING_NAME_3, GLOBAL_SETTING_VALUE_3); } }; when(repository.getFileMetadata(eq(USER_FOLDER_ID))).thenReturn(userSettings); when(repository.getFileMetadata(eq(TENANT_FOLDER_ID))).thenReturn(globalSettings); final RepositoryFile tenantRepositoryFile = mock(RepositoryFile.class); when(tenantRepositoryFile.getId()).thenReturn(TENANT_FOLDER_ID); when(repository.getFile(eq(ClientRepositoryPaths.getEtcFolderPath()))) .thenReturn(tenantRepositoryFile); final RepositoryFile userRepositoryFile = mock(RepositoryFile.class); when(userRepositoryFile.getId()).thenReturn(USER_FOLDER_ID); when(repository.getFile(eq(ClientRepositoryPaths.getUserHomeFolderPath(session.getName())))) .thenReturn(userRepositoryFile); securityHelper = mock(ISecurityHelper.class); when(securityHelper.runAsSystem(any(Callable.class))) .thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Callable callable = (Callable) invocation.getArguments()[0]; if (callable != null) { return callable.call(); } return null; } }); SecurityHelper.setMockInstance(securityHelper); userSettingService = new UserSettingService(repository); userSettingService.init(session); }
public static void mapPlatformRolesToMondrianRolesHelper(Util.PropertyList properties) throws PentahoAccessControlException { if (properties.get(RolapConnectionProperties.Role.name(), null) == null) { // Only if the action sequence/requester hasn't already injected a role in here do this. if (PentahoSystem.getObjectFactory().objectDefined(MDXConnection.MDX_CONNECTION_MAPPER_KEY)) { IConnectionUserRoleMapper mondrianUserRoleMapper = PentahoSystem.get( IConnectionUserRoleMapper.class, MDXConnection.MDX_CONNECTION_MAPPER_KEY, null); if (mondrianUserRoleMapper != null) { // Do role mapping String[] validMondrianRolesForUser = mondrianUserRoleMapper.mapConnectionRoles( PentahoSessionHolder.getSession(), properties.get(RolapConnectionProperties.Catalog.name())); if ((validMondrianRolesForUser != null) && (validMondrianRolesForUser.length > 0)) { StringBuffer buff = new StringBuffer(); String aRole = null; for (int i = 0; i < validMondrianRolesForUser.length; i++) { aRole = validMondrianRolesForUser[i]; // According to http://mondrian.pentaho.org/documentation/configuration.php // double-comma escapes a comma if (i > 0) { buff.append(","); // $NON-NLS-1$ } buff.append(aRole.replaceAll(",", ",,")); // $NON-NLS-1$//$NON-NLS-2$ } properties.put(RolapConnectionProperties.Role.name(), buff.toString()); } } } } }
protected String assembleRole(String catalog) { try { final IConnectionUserRoleMapper mondrianUserRoleMapper = PentahoSystem.get(IConnectionUserRoleMapper.class, "Mondrian-UserRoleMapper", null); if (mondrianUserRoleMapper != null) {} final String[] validMondrianRolesForUser = mondrianUserRoleMapper.mapConnectionRoles( PentahoSessionHolder.getSession(), "solution:" + catalog.replaceAll("solution/", "")); if ((validMondrianRolesForUser != null) && (validMondrianRolesForUser.length > 0)) { final StringBuffer buff = new StringBuffer(); for (int i = 0; i < validMondrianRolesForUser.length; i++) { final String aRole = validMondrianRolesForUser[i]; // According to http://mondrian.pentaho.org/documentation/configuration.php // double-comma escapes a comma if (i > 0) { buff.append(","); } buff.append(aRole.replaceAll(",", ",,")); } return buff.toString(); } else { return ""; } } catch (Exception e) { return ""; } }
@Before public void setUp() throws Exception { manager = new MockBackingRepositoryLifecycleManager(new MockSecurityHelper()); repo = context.mock(IUnifiedRepository.class); booter = new MicroPlatform("test-res/solution1"); booter.define(IPasswordService.class, Base64PasswordService.class, Scope.GLOBAL); booter.define(IDatabaseConnection.class, DatabaseConnection.class, Scope.GLOBAL); booter.define(IDatabaseDialectService.class, DatabaseDialectService.class, Scope.GLOBAL); booter.define(IMondrianCatalogService.class, MondrianCatalogHelper.class, Scope.GLOBAL); booter.define(ICacheManager.class, CacheManager.class, Scope.GLOBAL); booter.defineInstance(IUserRoleListService.class, context.mock(IUserRoleListService.class)); final IAuthorizationPolicy policy = context.mock(IAuthorizationPolicy.class); booter.defineInstance(IAuthorizationPolicy.class, policy); booter.defineInstance(IUnifiedRepository.class, repo); booter.setSettingsProvider(new SystemSettings()); booter.start(); context.checking( new Expectations() { { oneOf(policy); will(returnValue(false)); oneOf(policy); will(returnValue(false)); oneOf(policy); will(returnValue(false)); } }); PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); }
protected void login(final String username, final String tenantId, final boolean tenantAdmin) { StandaloneSession pentahoSession = new StandaloneSession(username); pentahoSession.setAuthenticated(username); pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenantId); final String password = "******"; List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); authList.add( new GrantedAuthorityImpl( MessageFormat.format(tenantAuthenticatedAuthorityNamePattern, tenantId))); if (tenantAdmin) { authList.add( new GrantedAuthorityImpl( MessageFormat.format(tenantAdminAuthorityNamePattern, tenantId))); } GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]); UserDetails userDetails = new User(username, password, true, true, true, true, authorities); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password, authorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(auth); manager.newTenant(); manager.newUser(); }
public static String postExecute( IRuntimeContext runtime, boolean debugMessages, boolean doWrapper, IOutputHandler outputHandler, Map<String, IParameterProvider> parameterProviders, HttpServletRequest request, HttpServletResponse response, List<?> messages, boolean deleteGeneratedFiles) throws Exception { StringBuffer buffer = new StringBuffer(); boolean hasResponse = outputHandler.isResponseExpected(); IContentItem responseContentItem = outputHandler.getOutputContentItem( IOutputHandler.RESPONSE, IOutputHandler.CONTENT, null, null); boolean success = (runtime != null && runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS); boolean printSuccess = (runtime != null) && success && (!hasResponse || debugMessages); boolean printError = (runtime != null) && !success && !response.isCommitted(); if (printSuccess || printError) { final String htmlMimeType = "text/html"; // $NON-NLS-1$ responseContentItem.setMimeType(htmlMimeType); response.setContentType(htmlMimeType); IMessageFormatter formatter = PentahoSystem.get(IMessageFormatter.class, PentahoSessionHolder.getSession()); if (printSuccess) { formatter.formatSuccessMessage(htmlMimeType, runtime, buffer, debugMessages, doWrapper); } else { response.resetBuffer(); formatter.formatFailureMessage(htmlMimeType, runtime, buffer, messages); } } // clear files which was generated during action execution // http://jira.pentaho.com/browse/BISERVER-12639 IUnifiedRepository unifiedRepository = PentahoSystem.get(IUnifiedRepository.class, null); if (unifiedRepository != null) { for (IContentItem contentItem : runtime.getOutputContentItems()) { if (contentItem != null) { try { contentItem.closeOutputStream(); if (deleteGeneratedFiles) { deleteContentItem(contentItem, unifiedRepository); } } catch (Exception e) { logger.warn( Messages.getInstance() .getString("XactionUtil.CANNOT_REMOVE_OUTPUT_FILE", contentItem.getPath()), e); } } } } return buffer.toString(); }
@BeforeClass public static void setUpClass() throws Exception { // folder cannot be deleted at teardown shutdown hooks have not yet necessarily completed // parent folder must match jcrRepository.homeDir bean property in // repository-test-override.spring.xml FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK")); PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL); }
/** * Creates and/or returns an internal folder called {@code .trash} located just below the user's * home folder. */ private Node getOrCreateTrashInternalFolderNode( final Session session, final PentahoJcrConstants pentahoJcrConstants) throws RepositoryException { IPentahoSession pentahoSession = PentahoSessionHolder.getSession(); String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY); Node userHomeFolderNode = (Node) session.getItem( ServerRepositoryPaths.getUserHomeFolderPath( new Tenant(tenantId, true), JcrStringHelper.fileNameEncode(PentahoSessionHolder.getSession().getName()))); if (userHomeFolderNode.hasNode(FOLDER_NAME_TRASH)) { return userHomeFolderNode.getNode(FOLDER_NAME_TRASH); } else { return userHomeFolderNode.addNode( FOLDER_NAME_TRASH, pentahoJcrConstants.getPHO_NT_INTERNALFOLDER()); } }
@Override public void createContent() throws Exception { this.session = PentahoSessionHolder.getSession(); this.repository = PentahoSystem.get(IUnifiedRepository.class, session); final RepositoryFile BIRTfile = (RepositoryFile) parameterProviders.get("path").getParameter("file"); final String ExecBIRTFilePath = "../webapps/birt/" + BIRTfile.getId() + ".rptdocument"; /* * Get BIRT report design from repository */ final File ExecBIRTFile = new File(ExecBIRTFilePath); if (!ExecBIRTFile.exists()) { final FileOutputStream fos = new FileOutputStream(ExecBIRTFilePath); try { final SimpleRepositoryFileData data = repository.getDataForRead(BIRTfile.getId(), SimpleRepositoryFileData.class); final InputStream inputStream = data.getInputStream(); final byte[] buffer = new byte[0x1000]; int bytesRead = inputStream.read(buffer); while (bytesRead >= 0) { fos.write(buffer, 0, bytesRead); bytesRead = inputStream.read(buffer); } } catch (final Exception e) { Logger.error(getClass().getName(), e.getMessage()); } finally { fos.close(); } } /* * Redirect to BIRT Viewer */ try { // Get informations about user context final IUserRoleListService service = PentahoSystem.get(IUserRoleListService.class); String roles = ""; final ListIterator<String> li = service.getRolesForUser(null, session.getName()).listIterator(); while (li.hasNext()) { roles = roles + li.next().toString() + ","; } // Redirect final HttpServletResponse response = (HttpServletResponse) this.parameterProviders.get("path").getParameter("httpresponse"); response.sendRedirect( "/birt/frameset?__document=" + BIRTfile.getId() + ".rptdocument&__showtitle=false&username="******"&userroles=" + roles + "&reportname=" + BIRTfile.getTitle()); } catch (final Exception e) { Logger.error(getClass().getName(), e.getMessage()); } }
@Test public void testUserWorkspace() { PentahoSessionHolder.setSession(new StandaloneSession("jerry")); WebResource webResource = resource(); String userWorkspaceDir = webResource.path("session/userWorkspaceDir").accept(TEXT_PLAIN).get(String.class); assertTrue(userWorkspaceDir != null); assertTrue(userWorkspaceDir.length() > 0); }
private static String callPlugin( final String pluginName, final String method, final Map<String, Object> parameters) throws ReportDataFactoryException { final IPentahoSession userSession = PentahoSessionHolder.getSession(); final IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, userSession); try { Object cdaBean = pluginManager.getBean("cda.api"); Class cdaBeanClass = cdaBean.getClass(); Class[] paramTypes; Object[] paramValues; Method m; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if ("listParameters".equals(method)) { IParameterProvider params = new SimpleParameterProvider(parameters); paramTypes = new Class[] { String.class, String.class, String.class, String.class, String.class, HttpServletResponse.class, HttpServletRequest.class }; m = cdaBeanClass.getMethod("listParameters", paramTypes); paramValues = new Object[7]; paramValues[0] = params.getStringParameter("path", null); paramValues[1] = params.getStringParameter("solution", ""); paramValues[2] = params.getStringParameter("file", ""); paramValues[3] = params.getStringParameter("outputType", "json"); paramValues[4] = params.getStringParameter("dataAccessId", "<blank>"); paramValues[5] = getResponse(outputStream); paramValues[6] = getRequest(parameters); m.invoke(cdaBean, paramValues); return outputStream.toString(); } else { paramTypes = new Class[] {HttpServletRequest.class}; m = cdaBeanClass.getMethod("doQueryInterPlugin", paramTypes); paramValues = new Object[1]; paramValues[0] = getRequest(parameters); return (String) m.invoke(cdaBean, paramValues); } } catch (Exception e) { throw new ReportDataFactoryException("Failed to acquire " + pluginName + " plugin: ", e); } }
public static MasterReport createReportByName(final String fullFilePathAndName) throws ResourceException, IOException { IUnifiedRepository unifiedRepository = PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession()); RepositoryFile repositoryFile = unifiedRepository.getFile(fullFilePathAndName); if (repositoryFile == null) { throw new IOException("File " + fullFilePathAndName + " not found in repository"); } else { return createReport(repositoryFile.getId()); } }
/** * @return the {@link IBackingRepositoryLifecycleManager} that this instance will use. If none has * been specified, it will default to getting the information from {@link PentahoSystem.get()} */ public ITenantManager getTenantManager() { // Check ... if we haven't been injected with a lifecycle manager, get one from PentahoSystem try { IPentahoObjectFactory objectFactory = PentahoSystem.getObjectFactory(); IPentahoSession pentahoSession = PentahoSessionHolder.getSession(); return (null != tenantManager ? tenantManager : objectFactory.get(ITenantManager.class, "tenantMgrProxy", pentahoSession)); } catch (ObjectFactoryException e) { return null; } }
protected void loginAsRepositoryAdmin() { StandaloneSession pentahoSession = new StandaloneSession(repositoryAdminUsername); pentahoSession.setAuthenticated(repositoryAdminUsername); final GrantedAuthority[] repositoryAdminAuthorities = new GrantedAuthority[] {}; final String password = "******"; UserDetails repositoryAdminUserDetails = new User( repositoryAdminUsername, password, true, true, true, true, repositoryAdminAuthorities); Authentication repositoryAdminAuthentication = new UsernamePasswordAuthenticationToken( repositoryAdminUserDetails, password, repositoryAdminAuthorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(repositoryAdminAuthentication); }
@BeforeClass public static void beforeClass() throws Exception { // BasicConfigurator.configure(); System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL"); Logger.getLogger("org").setLevel(Level.WARN); Logger.getLogger("org.pentaho").setLevel(Level.WARN); Logger.getLogger(RepositoryResource.class).setLevel(Level.DEBUG); // Logger.getLogger(RequestProxy.class).setLevel(Level.DEBUG); Logger.getLogger("MIME_TYPE").setLevel(Level.TRACE); PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL); FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK")); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); }
@Override public Set<String> getDomainIds() { final IPentahoSession session = PentahoSessionHolder.getSession(); final String domainKey = generateDomainIdCacheKeyForSession(session); Set<String> domainIds = (Set<String>) cacheManager.getFromRegionCache(CACHE_REGION, domainKey); if (domainIds != null) { // We've previously cached domainIds available for this session return domainIds; } // Domains are accessible by anyone. What they contain may be different so rely on the lookup to // be // session-specific. domainIds = delegate.getDomainIds(); cacheManager.putInRegionCache(CACHE_REGION, domainKey, new HashSet<String>(domainIds)); return domainIds; }
public MobileDashboard( IParameterProvider pathParams, DashboardDesignerContentGenerator generator) { super(pathParams, generator); IPentahoSession userSession = PentahoSessionHolder.getSession(); final ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class, userSession); final String absRoot = pathParams.hasParameter("root") ? !pathParams.getParameter("root").toString().isEmpty() ? "http://" + pathParams.getParameter("root").toString() : "" : ""; final boolean absolute = (!absRoot.isEmpty()) || pathParams.hasParameter("absolute") && pathParams.getParameter("absolute").equals("true"); final RenderMobileLayout layoutRenderer = new RenderMobileLayout(); final RenderComponents componentsRenderer = new RenderComponents(); try { final JSONObject json = (JSONObject) JsonUtils.readJsonFromInputStream( solutionRepository.getResourceInputStream(dashboardLocation, true)); json.put("settings", getWcdf().toJSON()); final JXPathContext doc = JXPathContext.newContext(json); final StringBuilder dashboardBody = new StringBuilder(); dashboardBody.append(layoutRenderer.render(doc)); dashboardBody.append(componentsRenderer.render(doc)); // set all dashboard members this.content = replaceTokens(dashboardBody.toString(), absolute, absRoot); this.header = renderHeaders(pathParams, this.content.toString()); this.loaded = new Date(); } catch (Exception e) { logger.error(e); } }
@SuppressWarnings("rawtypes") public static void createOutputFileName(RepositoryFile file, IOutputHandler outputHandler) { IPentahoSession userSession = PentahoSessionHolder.getSession(); ActionSequenceJCRHelper actionHelper = new ActionSequenceJCRHelper(userSession); IActionSequence actionSequence = actionHelper.getActionSequence( file.getPath(), PentahoSystem.loggingLevel, RepositoryFilePermission.READ); String fileName = "content"; // $NON-NLS-1$ if (actionSequence != null) { String title = actionSequence.getTitle(); if ((title != null) && (title.length() > 0)) { fileName = title; } else { String sequenceName = actionSequence.getSequenceName(); if ((sequenceName != null) && (sequenceName.length() > 0)) { fileName = sequenceName; } else { List actionDefinitionsList = actionSequence.getActionDefinitionsAndSequences(); int i = 0; boolean done = false; while ((actionDefinitionsList.size() > i) && (!done)) { IActionDefinition actionDefinition = (IActionDefinition) actionDefinitionsList.get(i); String componentName = actionDefinition.getComponentName(); if ((componentName != null) && (componentName.length() > 0)) { fileName = componentName; done = true; } else { ++i; } } } } } IMimeTypeListener mimeTypeListener = outputHandler.getMimeTypeListener(); if (mimeTypeListener != null) { mimeTypeListener.setName(fileName); } }
public static synchronized void initializePentahoSystem(String solutionPath) throws Exception { // this setting is useful only for running the integration tests from within IntelliJ // this same property is set for integration tests via the pom when running with mvn String folderPaths = "target/spoon/plugins"; File f = new File(folderPaths); System.setProperty("KETTLE_PLUGIN_BASE_FOLDERS", f.getAbsolutePath()); StandaloneApplicationContext appContext = new StandaloneApplicationContext(solutionPath, ""); PentahoSystem.setSystemSettingsService(new PathBasedSystemSettings()); if (solutionPath == null) { throw new MetaverseException( Messages.getString("ERROR.MetaverseInit.BadConfigPath", solutionPath)); } try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(MetaverseUtil.class.getClassLoader()); IPentahoObjectFactory pentahoObjectFactory = new StandaloneSpringPentahoObjectFactory(); pentahoObjectFactory.init(solutionPath, PentahoSystem.getApplicationContext()); PentahoSystem.registerObjectFactory(pentahoObjectFactory); // Restore context classloader Thread.currentThread().setContextClassLoader(cl); } catch (Exception e) { throw new MetaverseException(Messages.getString("ERROR.MetaverseInit.CouldNotInit"), e); } PentahoSystem.init(appContext); PentahoSessionHolder.setSession(new StandaloneSession()); registerKettlePlugins(); try { KettleEnvironment.init(); } catch (KettleException e) { e.printStackTrace(); } }
public static String postExecute( IRuntimeContext runtime, boolean debugMessages, boolean doWrapper, IOutputHandler outputHandler, Map<String, IParameterProvider> parameterProviders, HttpServletRequest request, HttpServletResponse response, List<?> messages) throws Exception { StringBuffer buffer = new StringBuffer(); boolean hasResponse = outputHandler.isResponseExpected(); IContentItem responseContentItem = outputHandler.getOutputContentItem( IOutputHandler.RESPONSE, IOutputHandler.CONTENT, null, null); boolean success = (runtime != null && runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS); boolean printSuccess = (runtime != null) && success && (!hasResponse || debugMessages); boolean printError = (runtime != null) && !success && !response.isCommitted(); if (printSuccess || printError) { final String htmlMimeType = "text/html"; // $NON-NLS-1$ responseContentItem.setMimeType(htmlMimeType); response.setContentType(htmlMimeType); IMessageFormatter formatter = PentahoSystem.get(IMessageFormatter.class, PentahoSessionHolder.getSession()); if (printSuccess) { formatter.formatSuccessMessage(htmlMimeType, runtime, buffer, debugMessages, doWrapper); } else { response.resetBuffer(); formatter.formatFailureMessage(htmlMimeType, runtime, buffer, messages); } } return buffer.toString(); }
@Override public Domain getDomain(final String id) { final IPentahoSession session = PentahoSessionHolder.getSession(); final CacheKey key = new CacheKey(session.getId(), id); Domain domain = (Domain) cacheManager.getFromRegionCache(CACHE_REGION, key); if (domain != null) { if (logger.isDebugEnabled()) { logger.debug("Found domain in cache: " + key); // $NON-NLS-1$ } return domain; } domain = delegate.getDomain(id); if (domain != null) { SecurityHelper helper = new SecurityHelper(); domain = helper.createSecureDomain(this, domain); // cache domain with the key we used to look it up, not whatever new id it might have now if (logger.isDebugEnabled()) { logger.debug("Caching domain by session: " + key); // $NON-NLS-1$ } cacheManager.putInRegionCache(CACHE_REGION, key, domain); } return domain; }
public Dashboard loadDashboard( String wcdfPath, boolean debug, boolean absolute, String scheme, String absRoot, boolean bypassCache, String alias) throws FileNotFoundException { String dashboardPath = getDashboardPath(wcdfPath); IPentahoSession userSession = PentahoSessionHolder.getSession(); XmlStructure structure = new XmlStructure(userSession); Dashboard dashboard = null; WcdfDescriptor wcdf = null; DashboardCacheKey key; /* * First we must figure out what dashboard we should * be handling. We do this by loading up its wcdf * descriptor. */ try { if (!wcdfPath.isEmpty() && wcdfPath.endsWith(".wcdf")) { wcdf = structure.loadWcdfDescriptor(wcdfPath); } else { /* We didn't receive a valid path. We're in preview mode. * TODO: Support mobile preview mode (must remove dependency on setStyle()) */ wcdf = new WcdfDescriptor(); if (wcdfPath != null && wcdfPath.endsWith(".cdfde")) { wcdf.setWcdfPath(wcdfPath); } wcdf.setStyle(CdfStyles.DEFAULTSTYLE); wcdf.setRendererType(Renderers.BLUEPRINT.toString()); bypassCache = true; // no cache for preview } } catch (IOException ioe) { logger.error(ioe); return null; } /* Next, if we're using the cache, we try to find * the dashboard in there. */ key = new DashboardCacheKey( dashboardPath, CdfStyles.getInstance().getResourceLocation(wcdf.getStyle()), debug); key.setAbs(absolute); key.setRoot(scheme, absRoot); if (!bypassCache) { dashboard = getDashboardFromCache(key); } /* If it's not there, or we're bypassing the cache, * we load it up, and cache the newly loaded dashboard. */ if (dashboard == null) { Cache cache = getCache(); try { switch (Renderers.valueOf(wcdf.getRendererType().toUpperCase())) { case MOBILE: dashboard = new MobileDashboard(wcdf, absolute, absRoot, debug, scheme); break; /* Until we consider it safe to assume that all dashboards have * their renderer type correctly identified, we'll have to default * to assuming they're blueprint-style dashboards. */ case BLUEPRINT: default: if (wcdf.isWidget()) { dashboard = new BlueprintWidget(wcdf, absolute, absRoot, debug, scheme, alias); } else { dashboard = new BlueprintDashboard(wcdf, absolute, absRoot, debug, scheme); } break; } } catch (IllegalArgumentException e) { logger.error("Bad renderer type: " + wcdf.getRendererType()); return null; } cache.put(new Element(key, dashboard)); } return dashboard; }
/** {@inheritDoc} */ public void permanentlyDeleteFile( final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable fileId) throws RepositoryException { Assert.notNull(fileId); Node fileNode = session.getNodeByIdentifier(fileId.toString()); // guard against using a file retrieved from a more lenient session inside a more strict session Assert.notNull(fileNode); // see if anything is referencing this node; if yes, then we cannot delete it as a // ReferentialIntegrityException // will result Set<RepositoryFile> referrers = new HashSet<RepositoryFile>(); PropertyIterator refIter = fileNode.getReferences(); if (refIter.hasNext()) { while (refIter.hasNext()) { // for each referrer property, march up the tree until we find the file node to which the // property belongs RepositoryFile referrer = getReferrerFile(session, pentahoJcrConstants, refIter.nextProperty()); if (referrer != null) { referrers.add(referrer); } } if (!referrers.isEmpty()) { RepositoryFile referee = JcrRepositoryFileUtils.nodeToFile( session, pentahoJcrConstants, pathConversionHelper, lockHelper, fileNode); throw new RepositoryFileDaoReferentialIntegrityException(referee, referrers); } } // technically, the node can be deleted while it is locked; however, we want to avoid an // orphaned lock token; // delete // it first if (fileNode.isLocked()) { Lock lock = session.getWorkspace().getLockManager().getLock(fileNode.getPath()); // don't need lock token anymore lockHelper.removeLockToken(session, pentahoJcrConstants, lock); } // if this file was non-permanently deleted, delete its containing folder too IPentahoSession pentahoSession = PentahoSessionHolder.getSession(); String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY); String trashFolder = ServerRepositoryPaths.getUserHomeFolderPath( new Tenant(tenantId, true), PentahoSessionHolder.getSession().getName()) + RepositoryFile.SEPARATOR + FOLDER_NAME_TRASH; Node parent = fileNode.getParent(); purgeHistory(fileNode, session, pentahoJcrConstants); if (fileNode.getPath().startsWith(trashFolder)) { // Remove the file and then the wrapper foler fileNode.remove(); parent.remove(); } else { fileNode.remove(); } }
@AfterClass public static void afterClass() { PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); }
protected void logout() { PentahoSessionHolder.removeSession(); SecurityContextHolder.getContext().setAuthentication(null); }