protected void executeQuery(final Statement statement, final String sql) throws SQLException { try { long start = 0; if (LOG.isDebugEnabled()) { start = System.currentTimeMillis(); LOG.debug("Execute script: \n[" + sql + "]"); } SecurityHelper.doPrivilegedSQLExceptionAction( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { statement.executeUpdate(sql); return null; } }); if (LOG.isDebugEnabled()) { LOG.debug( "Script " + sql + " executed in " + ((System.currentTimeMillis() - start) / 1000d) + " sec"); } } catch (SQLException e) { LOG.error("Query execution \"" + sql + "\" failed: " + JDBCUtils.getFullMessage(e), e); throw e; } }
/** Opens connection to database underlying a workspace. */ private static Connection getConnection(WorkspaceEntry wsEntry) throws DBCleanException { String dsName = getSourceNameParameter(wsEntry); DataSource ds; try { ds = (DataSource) new InitialContext().lookup(dsName); } catch (NamingException e) { throw new DBCleanException(e); } if (ds == null) { throw new DBCleanException("Data source " + dsName + " not found"); } final DataSource dsF = ds; Connection jdbcConn; try { jdbcConn = SecurityHelper.doPrivilegedSQLExceptionAction( new PrivilegedExceptionAction<Connection>() { public Connection run() throws Exception { return dsF.getConnection(); } }); } catch (SQLException e) { throw new DBCleanException(e); } return jdbcConn; }
/** * Execute script on database. Set auto commit mode if needed. * * @param scripts the scripts for execution * @throws SQLException */ protected void execute(List<String> scripts) throws SQLException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); // set needed auto commit mode boolean autoCommit = connection.getAutoCommit(); if (autoCommit != this.autoCommit) { connection.setAutoCommit(this.autoCommit); } Statement st = connection.createStatement(); try { for (String scr : scripts) { String sql = JDBCUtils.cleanWhitespaces(scr.trim()); if (!sql.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Execute script: \n[" + sql + "]"); } executeQuery(st, sql); } } } finally { try { st.close(); } catch (SQLException e) { LOG.error("Can't close the Statement." + e.getMessage()); } // restore previous auto commit mode if (autoCommit != this.autoCommit) { connection.setAutoCommit(autoCommit); } } }
/** * Cleans repository data from database. * * @param rEntry the repository configuration * @throws DBCleanException */ public static void cleanRepositoryData(RepositoryEntry rEntry) throws DBCleanException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); WorkspaceEntry wsEntry = rEntry.getWorkspaceEntries().get(0); boolean multiDB = getMultiDbParameter(wsEntry); if (multiDB) { for (WorkspaceEntry entry : rEntry.getWorkspaceEntries()) { cleanWorkspaceData(entry); } } else { Connection jdbcConn = getConnection(wsEntry); String dialect = resolveDialect(jdbcConn, wsEntry); boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE); try { jdbcConn.setAutoCommit(autoCommit); DBCleanerTool dbCleaner = getRepositoryDBCleaner(jdbcConn, rEntry); doClean(dbCleaner); } catch (SQLException e) { throw new DBCleanException(e); } finally { try { jdbcConn.close(); } catch (SQLException e) { LOG.error("Can not close connection", e); } } } }
private void registerComponents() throws RepositoryConfigurationException, RepositoryException { SecurityHelper.doPrivilegedAction( new PrivilegedAction<Void>() { public Void run() { registerComponentInstance(config); registerComponentImplementation(FileCleanerHolder.class); registerComponentImplementation(LockRemoverHolder.class); return null; } }); registerWorkspacesComponents(); registerRepositoryComponents(); }
/** {@inheritDoc} */ @Override protected Log getLogger(final String name) { Logger slf4jlogger = SecurityHelper.doPrivilegedAction( new PrivilegedAction<Logger>() { public Logger run() { return LoggerFactory.getLogger(name); } }); if (slf4jlogger instanceof LocationAwareLogger) { return new LocationAwareSLF4JExoLog((LocationAwareLogger) slf4jlogger); } else { return new SLF4JExoLog(slf4jlogger); } }
/** * Returns database cleaner for workspace. * * @param jdbcConn database connection which need to use * @param wsEntry workspace configuration * @return DBCleanerTool * @throws DBCleanException */ public static DBCleanerTool getWorkspaceDBCleaner(Connection jdbcConn, WorkspaceEntry wsEntry) throws DBCleanException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); String dialect = resolveDialect(jdbcConn, wsEntry); boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE); DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, wsEntry); return new DBCleanerTool( jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(), scripts.getRollbackingScripts()); }
public FtpServerImpl( FtpConfig configuration, CommandService commandService, RepositoryService repositoryService) throws Exception { this.configuration = configuration; this.repositoryService = repositoryService; InputStream commandStream = SecurityHelper.doPrivilegedAction( new PrivilegedAction<InputStream>() { public InputStream run() { return getClass().getResourceAsStream(COMMAND_PATH); } }); commandService.putCatalog(commandStream); commandCatalog = commandService.getCatalog(FtpConst.FTP_COMMAND_CATALOG); }
/** * RepositoryContainer constructor. * * @param parent container * @param config Repository configuration * @param addNamespacePlugins list of addNamespacePlugin * @throws RepositoryException container initialization error * @throws RepositoryConfigurationException configuration error * @throws PrivilegedActionException */ public RepositoryContainer( final ExoContainer parent, RepositoryEntry config, List<ComponentPlugin> addNamespacePlugins) throws RepositoryException, RepositoryConfigurationException { super(new MX4JComponentAdapterFactory(), parent); // Defaults: if (config.getAccessControl() == null) config.setAccessControl(AccessControlPolicy.OPTIONAL); this.config = config; this.addNamespacePlugins = addNamespacePlugins; this.name = config.getName(); try { SecurityHelper.doPrivilegedExceptionAction( new PrivilegedExceptionAction<Void>() { public Void run() throws RepositoryConfigurationException { context.setName(parent.getContext().getName() + "-" + name); try { parent.registerComponentInstance(name, RepositoryContainer.this); initAllWorkspaceComponentEntries(parent); registerComponents(); } catch (Throwable t) // NOSONAR { unregisterAllComponents(); parent.unregisterComponent(name); throw new RepositoryConfigurationException( "Can not register repository container " + name + " in parent container.", t); } return null; } }); } catch (PrivilegedActionException e) { Throwable ex = e.getCause(); if (ex instanceof RepositoryConfigurationException) { throw (RepositoryConfigurationException) ex; } else { throw new RepositoryConfigurationException(ex.getMessage(), ex); } } }
/** * Cleans workspace data from database. * * @param wsEntry workspace configuration * @throws DBCleanException */ public static void cleanWorkspaceData(WorkspaceEntry wsEntry) throws DBCleanException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); Connection jdbcConn = getConnection(wsEntry); String dialect = resolveDialect(jdbcConn, wsEntry); boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE); try { jdbcConn.setAutoCommit(autoCommit); DBCleanerTool dbCleaner = getWorkspaceDBCleaner(jdbcConn, wsEntry); doClean(dbCleaner); } catch (SQLException e) { throw new DBCleanException(e); } finally { try { jdbcConn.close(); } catch (SQLException e) { LOG.error("Can not close connection", e); } } }
/** * Returns the registry node which wraps a node of type "exo:registry" (the whole registry tree) * * @response {code} "entryStream" : the output stream corresponding registry node which wraps a * node of type "exo:registry" (the whole registry tree) {code} Example : {code:xml} <registry * xlinks:href="http://localhost:8080/portal/rest/registry/"> <GroovyScript2RestLoader * xlinks:href="http://localhost:8080/portal/rest/registry/exo:services/GroovyScript2RestLoader"/> * <Audit xlinks:href="http://localhost:8080/portal/rest/registry/exo:services/Audit"/> * </registry> {code} @LevelAPI Experimental */ @GET @Produces(MediaType.APPLICATION_XML) public Response getRegistry(@Context UriInfo uriInfo) { SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null); try { RegistryNode registryEntry = regService.getRegistry(sessionProvider); if (registryEntry != null) { Node registryNode = registryEntry.getNode(); NodeIterator registryIterator = registryNode.getNodes(); Document entry = SecurityHelper.doPrivilegedExceptionAction( new PrivilegedExceptionAction<Document>() { public Document run() throws Exception { return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } }); String fullURI = uriInfo.getRequestUri().toString(); XlinkHref xlinkHref = new XlinkHref(fullURI); Element root = entry.createElement(REGISTRY); xlinkHref.putToElement(root); while (registryIterator.hasNext()) { NodeIterator entryIterator = registryIterator.nextNode().getNodes(); while (entryIterator.hasNext()) { Node node = entryIterator.nextNode(); Element xmlNode = entry.createElement(node.getName()); xlinkHref.putToElement(xmlNode, node.getPath().substring(EXO_REGISTRY.length())); root.appendChild(xmlNode); } } entry.appendChild(root); return Response.ok(new DOMSource(entry), "text/xml").build(); } return Response.status(Response.Status.NOT_FOUND).build(); } catch (Exception e) { LOG.error("Get registry failed", e); throw new WebApplicationException(e); } }
@Override public void run() { while (enable) { Socket incoming = null; try { incoming = SecurityHelper.doPrivilegedExceptionAction( new PrivilegedExceptionAction<Socket>() { public Socket run() throws Exception { return serverSocket.accept(); } }); FtpClientSession clientSession = new FtpClientSessionImpl(ftpServer, incoming); clients.add(clientSession); LOG.info(">>> New client connected. Clients: " + clients.size()); } catch (Exception exc) { LOG.info("Unhandled exception. " + exc.getMessage(), exc); } } }
/** * Returns database cleaner for repository. * * @param jdbcConn database connection which need to use * @param rEntry repository configuration * @return DBCleanerTool * @throws DBCleanException */ public static DBCleanerTool getRepositoryDBCleaner(Connection jdbcConn, RepositoryEntry rEntry) throws DBCleanException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); WorkspaceEntry wsEntry = rEntry.getWorkspaceEntries().get(0); boolean multiDb = getMultiDbParameter(wsEntry); if (multiDb) { throw new DBCleanException( "It is not possible to create cleaner with common connection for multi database repository configuration"); } String dialect = resolveDialect(jdbcConn, wsEntry); boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE); DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, rEntry); return new DBCleanerTool( jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(), scripts.getRollbackingScripts()); }
/** * Adds the plugin. * * @param typesMap the types map */ public void addPlugin(final MimeTypeMap typesMap) { try { SecurityHelper.doPrivilegedIOExceptionAction( new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { for (String path : typesMap.getPaths()) { try { Scanner scanner = null; InputStream stream = configService.getInputStream(path); if (stream != null) { scanner = new Scanner(stream, "ISO-8859-1"); } if (scanner == null) { LOG.warn("Cannot read extended mimetypes from path " + path); } else { try { while (scanner.hasNextLine()) { processLine(scanner.nextLine()); } } finally { scanner.close(); } } } catch (IOException e) { throw new IOException( "Error loadinng extended mimetypes from path " + path + ": " + e.getMessage(), e); } } return null; } }); } catch (IOException e) { throw new InternalError("Unable to load extended mimetypes: " + e.toString()); } }
/** * Register workspace from configuration. * * @param wsConfig configuration * @throws RepositoryException initialization error * @throws RepositoryConfigurationException configuration error */ public void registerWorkspace(final WorkspaceEntry wsConfig) throws RepositoryException, RepositoryConfigurationException { // Need privileges to manage repository. SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); } try { SecurityHelper.doPrivilegedExceptionAction( new PrivilegedExceptionAction<Void>() { public Void run() throws RepositoryException, RepositoryConfigurationException { final boolean isSystem = config.getSystemWorkspaceName().equals(wsConfig.getName()); if (getWorkspaceContainer(wsConfig.getName()) != null) throw new RepositoryException( "Workspace " + wsConfig.getName() + " already registered"); final WorkspaceContainer workspaceContainer = new WorkspaceContainer(RepositoryContainer.this, wsConfig); registerComponentInstance(wsConfig.getName(), workspaceContainer); workspaceContainer.registerComponentInstance(wsConfig); workspaceContainer.registerComponentImplementation( StandaloneStoragePluginProvider.class); try { final Class<?> containerType = ClassLoading.forName( wsConfig.getContainer().getType(), RepositoryContainer.class); workspaceContainer.registerComponentImplementation(containerType); if (isSystem) { registerComponentInstance( new SystemDataContainerHolder( (WorkspaceDataContainer) workspaceContainer.getComponentInstanceOfType( WorkspaceDataContainer.class))); } } catch (ClassNotFoundException e) { throw new RepositoryConfigurationException( "Class not found for workspace data container " + wsConfig.getUniqueName() + " : " + e, e); } // cache type try { String className = wsConfig.getCache().getType(); if (className != null && className.length() > 0) { workspaceContainer.registerComponentImplementation( ClassLoading.forName(className, RepositoryContainer.class)); } else workspaceContainer.registerComponentImplementation( LinkedWorkspaceStorageCacheImpl.class); } catch (ClassNotFoundException e) { log.warn( "Workspace cache class not found " + wsConfig.getCache().getType() + ", will use default. Error : " + e.getMessage()); workspaceContainer.registerComponentImplementation( LinkedWorkspaceStorageCacheImpl.class); } if (workspaceContainer.getComponentInstanceOfType(RPCService.class) != null) { workspaceContainer.registerComponentImplementation(WorkspaceResumer.class); } if (workspaceContainer.getComponentInstanceOfType(QuotaManager.class) != null) { workspaceContainer.registerComponentImplementation(WorkspaceQuotaManager.class); } workspaceContainer.registerComponentImplementation( CacheableWorkspaceDataManager.class); workspaceContainer.registerComponentImplementation( LocalWorkspaceDataManagerStub.class); workspaceContainer.registerComponentImplementation(ObservationManagerRegistry.class); if (wsConfig.getLockManager() != null && wsConfig.getLockManager().getType() != null) { try { final Class<?> lockManagerType = ClassLoading.forName( wsConfig.getLockManager().getType(), RepositoryContainer.class); workspaceContainer.registerComponentImplementation(lockManagerType); } catch (ClassNotFoundException e) { throw new RepositoryConfigurationException( "Class not found for workspace lock manager " + wsConfig.getLockManager().getType() + ", container " + wsConfig.getUniqueName() + " : " + e, e); } } else { throw new RepositoryConfigurationException( "The configuration of lock manager is expected in container " + wsConfig.getUniqueName()); } // Query handler if (wsConfig.getQueryHandler() != null) { workspaceContainer.registerComponentImplementation(SearchManager.class); workspaceContainer.registerComponentImplementation(QueryManager.class); workspaceContainer.registerComponentImplementation(QueryManagerFactory.class); workspaceContainer.registerComponentInstance(wsConfig.getQueryHandler()); if (isSystem) { workspaceContainer.registerComponentImplementation(SystemSearchManager.class); } } // access manager if (wsConfig.getAccessManager() != null && wsConfig.getAccessManager().getType() != null) { try { final Class<?> am = ClassLoading.forName( wsConfig.getAccessManager().getType(), RepositoryContainer.class); workspaceContainer.registerComponentImplementation(am); } catch (ClassNotFoundException e) { throw new RepositoryConfigurationException( "Class not found for workspace access manager " + wsConfig.getAccessManager().getType() + ", container " + wsConfig.getUniqueName() + " : " + e, e); } } // initializer final Class<?> initilizerType; if (wsConfig.getInitializer() != null && wsConfig.getInitializer().getType() != null) { // use user defined try { initilizerType = ClassLoading.forName( wsConfig.getInitializer().getType(), RepositoryContainer.class); } catch (ClassNotFoundException e) { throw new RepositoryConfigurationException( "Class not found for workspace initializer " + wsConfig.getInitializer().getType() + ", container " + wsConfig.getUniqueName() + " : " + e, e); } } else { // use default initilizerType = ScratchWorkspaceInitializer.class; } workspaceContainer.registerComponentImplementation(initilizerType); workspaceContainer.registerComponentImplementation( TransactionableResourceManager.class); workspaceContainer.registerComponentImplementation(SessionFactory.class); final LocalWorkspaceDataManagerStub wsDataManager = (LocalWorkspaceDataManagerStub) workspaceContainer.getComponentInstanceOfType( LocalWorkspaceDataManagerStub.class); if (isSystem) { // system workspace systemDataManager = wsDataManager; registerComponentInstance(systemDataManager); } wsDataManager.setSystemDataManager(systemDataManager); if (!config.getWorkspaceEntries().contains(wsConfig)) config.getWorkspaceEntries().add(wsConfig); return null; } }); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (cause instanceof RepositoryConfigurationException) { throw (RepositoryConfigurationException) cause; } else if (cause instanceof RepositoryException) { throw (RepositoryException) cause; } else if (cause instanceof RuntimeException) { RuntimeException e = (RuntimeException) cause; int depth = 0; Throwable retval = e; while (retval.getCause() != null && depth < 100) { retval = retval.getCause(); if (retval instanceof RepositoryException) { throw new RepositoryException(retval.getMessage(), e); } else if (retval instanceof RepositoryConfigurationException) { throw new RepositoryConfigurationException(retval.getMessage(), e); } else if (retval instanceof NameNotFoundException) { throw new RepositoryException(retval.getMessage(), e); } depth++; } throw e; } else { throw new RepositoryException(cause); } } }
private void registerRepositoryComponents() throws RepositoryConfigurationException, RepositoryException { try { SecurityHelper.doPrivilegedExceptionAction( new PrivilegedExceptionAction<Void>() { public Void run() throws RepositoryConfigurationException, RepositoryException { if (getComponentInstanceOfType(QuotaManager.class) != null) { registerComponentImplementation(RepositoryQuotaManager.class); } registerComponentImplementation(RepositorySuspendController.class); registerComponentImplementation(RepositoryCheckController.class); registerComponentImplementation(IdGenerator.class); registerComponentImplementation(RepositoryIndexSearcherHolder.class); registerComponentImplementation(LocationFactory.class); registerComponentImplementation(ValueFactoryImpl.class); registerComponentInstance(new AddNamespacePluginHolder(addNamespacePlugins)); registerComponentImplementation(JCRNodeTypeDataPersister.class); registerComponentImplementation(NamespaceDataPersister.class); registerComponentImplementation(NamespaceRegistryImpl.class); registerComponentImplementation(NodeTypeManagerImpl.class); registerComponentImplementation(NodeTypeDataManagerImpl.class); registerComponentImplementation(DefaultAccessManagerImpl.class); registerComponentImplementation(SessionRegistry.class); String systemWsname = config.getSystemWorkspaceName(); WorkspaceEntry systemWsEntry = getWorkspaceEntry(systemWsname); if (systemWsEntry != null && systemWsEntry.getQueryHandler() != null) { SystemSearchManager systemSearchManager = (SystemSearchManager) getWorkspaceContainer(systemWsname) .getComponentInstanceOfType(SystemSearchManager.class); registerComponentInstance(new SystemSearchManagerHolder(systemSearchManager)); } try { final Class<?> authenticationPolicyClass = ClassLoading.forName( config.getAuthenticationPolicy(), RepositoryContainer.class); registerComponentImplementation(authenticationPolicyClass); } catch (ClassNotFoundException e) { throw new RepositoryConfigurationException( "Class not found for repository authentication policy: " + e, e); } // Repository final RepositoryImpl repository = new RepositoryImpl(RepositoryContainer.this); registerComponentInstance(repository); return null; } }); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (cause instanceof RepositoryConfigurationException) { throw (RepositoryConfigurationException) cause; } else if (cause instanceof RepositoryException) { throw (RepositoryException) cause; } else { throw new RepositoryException(cause); } } }
/** {@inheritDoc} */ public void removeMembershipEventListener(MembershipEventListener listener) { SecurityHelper.validateSecurityPermission(PermissionConstants.MANAGE_LISTENERS); listeners_.remove(listener); }
/** * Detect databse dialect using JDBC metadata. Based on code of * http://svn.jboss.org/repos/hibernate/core/trunk/core/src/main/java/org/hibernate/ * dialect/resolver/StandardDialectResolver.java * * @param metaData {@link DatabaseMetaData} * @return String * @throws SQLException if error occurs */ public static String detect(final DatabaseMetaData metaData) throws SQLException { final String databaseName = SecurityHelper.doPrivilegedSQLExceptionAction( new PrivilegedExceptionAction<String>() { public String run() throws Exception { return metaData.getDatabaseProductName(); } }); if ("HSQL Database Engine".equals(databaseName)) { return DialectConstants.DB_DIALECT_HSQLDB; } if ("H2".equals(databaseName)) { return DialectConstants.DB_DIALECT_H2; } if ("MySQL".equals(databaseName)) { return DialectConstants.DB_DIALECT_MYSQL; } if ("PostgreSQL".equals(databaseName)) { int majorVersion = metaData.getDatabaseMajorVersion(); int minorVersion = metaData.getDatabaseMinorVersion(); return (majorVersion > 9 || (majorVersion == 9 && minorVersion >= 1)) ? DialectConstants.DB_DIALECT_PGSQL_SCS : DialectConstants.DB_DIALECT_PGSQL; } if ("Apache Derby".equals(databaseName)) { return DialectConstants.DB_DIALECT_DERBY; } if ("ingres".equalsIgnoreCase(databaseName)) { return DialectConstants.DB_DIALECT_INGRES; } if (databaseName.startsWith("Microsoft SQL Server")) { return DialectConstants.DB_DIALECT_MSSQL; } if ("Sybase SQL Server".equals(databaseName) || "Adaptive Server Enterprise".equals(databaseName)) { return DialectConstants.DB_DIALECT_SYBASE; } if (databaseName.startsWith("Adaptive Server Anywhere")) { return DialectConstants.DB_DIALECT_SYBASE; } if (databaseName.startsWith("DB2/")) { return detectDB2Dialect(metaData); } if ("Oracle".equals(databaseName)) { return DialectConstants.DB_DIALECT_ORACLE; } return DialectConstants.DB_DIALECT_GENERIC; }