Author: rareddy
Date: 2010-01-21 16:27:25 -0500 (Thu, 21 Jan 2010)
New Revision: 1769
Added:
branches/JCA/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
branches/JCA/runtime/src/main/java/org/teiid/services/AuthorizationServiceImpl.java
branches/JCA/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java
branches/JCA/runtime/src/main/java/org/teiid/services/MembershipServiceImpl.java
branches/JCA/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
branches/JCA/runtime/src/test/java/org/teiid/services/
branches/JCA/runtime/src/test/java/org/teiid/services/TestMembershipServiceImpl.java
branches/JCA/runtime/src/test/java/org/teiid/services/TestSessionServiceImpl.java
Removed:
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedBufferService.java
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedMetadataService.java
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/authorization/service/AuthorizationServiceImpl.java
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/membership/service/MembershipServiceImpl.java
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/session/service/SessionServiceImpl.java
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/membership/service/TestMembershipServiceImpl.java
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/session/service/TestSessionServiceImpl.java
Modified:
branches/JCA/build/kit-jboss-container/deploy/teiid-jboss-beans.xml
branches/JCA/build/kit-jboss-container/deployers/teiid-deployer-jboss-beans.xml
branches/JCA/engine/src/main/java/org/teiid/metadata/CompositeMetadataStore.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
branches/JCA/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java
Log:
TEIID-833: adding back temporary storage of the Metadata store to disk feature so that
index files or dynamic vdb metadata is persisted for repeated use
Modified: branches/JCA/build/kit-jboss-container/deploy/teiid-jboss-beans.xml
===================================================================
--- branches/JCA/build/kit-jboss-container/deploy/teiid-jboss-beans.xml 2010-01-21
19:42:30 UTC (rev 1768)
+++ branches/JCA/build/kit-jboss-container/deploy/teiid-jboss-beans.xml 2010-01-21
21:27:25 UTC (rev 1769)
@@ -28,12 +28,12 @@
</bean>
<!-- Teiid Services -->
- <bean name="AuthorizationService"
class="com.metamatrix.platform.security.authorization.service.AuthorizationServiceImpl">
+ <bean name="AuthorizationService"
class="org.teiid.services.AuthorizationServiceImpl">
<property name="VDBRepository"><inject
bean="VDBRepository"/></property>
<property name="useEntitlements"
class="java.lang.Boolean">false</property>
</bean>
- <bean name="SessionService"
class="com.metamatrix.platform.security.session.service.SessionServiceImpl">
+ <bean name="SessionService"
class="org.teiid.services.SessionServiceImpl">
<property name="VDBRepository"><inject
bean="VDBRepository"/></property>
<!-- Comma separated list of domains to be used -->
<property name="securityDomains">teiid-security</property>
@@ -41,7 +41,7 @@
<property name="sessionExpirationTimeLimit">0</property>
</bean>
- <bean name="BufferService"
class="com.metamatrix.dqp.embedded.services.EmbeddedBufferService">
+ <bean name="BufferService"
class="org.teiid.services.BufferServiceImpl">
<property name="contextCache"><inject
bean="ContextCache"/></property>
<property name="cacheFactory"><inject
bean="TeiidCache"/></property>
<property name="useDisk">true</property>
Modified: branches/JCA/build/kit-jboss-container/deployers/teiid-deployer-jboss-beans.xml
===================================================================
---
branches/JCA/build/kit-jboss-container/deployers/teiid-deployer-jboss-beans.xml 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/build/kit-jboss-container/deployers/teiid-deployer-jboss-beans.xml 2010-01-21
21:27:25 UTC (rev 1769)
@@ -4,9 +4,25 @@
<!-- Deployer specific Stuff -->
<bean name="VDBStructure"
class="org.teiid.deployers.VDBStructure" />
- <bean name="VDBParserDeployer"
class="org.teiid.deployers.VDBParserDeployer"/>
- <bean name="DynamicVDBDeployer"
class="org.teiid.deployers.DynamicVDBDeployer"/>
+ <bean name="VDBRepository"
class="org.teiid.deployers.VDBRepository"/>
+ <bean name="ConnectorManagerRepository"
class="org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository"/>
+
+ <bean name="VDBParserDeployer"
class="org.teiid.deployers.VDBParserDeployer">
+ <property name="objectSerializer"><inject
bean="ObjectSerializer"/></property>
+ </bean>
+
+ <bean name="DynamicVDBDeployer"
class="org.teiid.deployers.DynamicVDBDeployer">
+ <property name="objectSerializer"><inject
bean="ObjectSerializer"/></property>
+ <property name="VDBRepository"><inject
bean="VDBRepository"/></property>
+ <property name="connectorManagerRepository"><inject
bean="ConnectorManagerRepository"/></property>
+ </bean>
+
+
+ <bean name="ObjectSerializer"
class="org.teiid.deployers.ObjectSerializer">
+ <property
name="attachmentStoreRoot">${jboss.server.data.dir}/teiid</property>
+ </bean>
+
<bean name="VDBDeployer"
class="org.teiid.deployers.VDBDeployer">
<install bean="ManagedDeploymentCreator"
method="addAttachmentType">
<parameter>
@@ -23,13 +39,12 @@
</uninstall>
<property name="managedObjectFactory"><inject
bean="ManagedObjectFactory"/></property>
<property name="VDBRepository"><inject
bean="VDBRepository"/></property>
- <property name="connectorManagerRepository"><inject
bean="ConnectorManagerRepository"/></property>
<property name="contextCache"><inject
bean="ContextCache"/></property>
-
<depends>SystemVDBDeployer</depends>
</bean>
+
<bean name="SystemVDBDeployer"
class="org.teiid.deployers.SystemVDBDeployer">
<property name="VDBRepository"><inject
bean="VDBRepository"/></property>
</bean>
@@ -39,13 +54,10 @@
<property name="managedObjectFactory"><inject
bean="ManagedObjectFactory"/></property>
</bean>
- <bean name="VDBRepository"
class="org.teiid.deployers.VDBRepository"/>
- <bean name="ConnectorManagerRepository"
class="org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository"/>
<bean name="DQPManager"
class="org.teiid.dqp.internal.process.DQPManagementView">
<property name="connectorManagerRepository"><inject
bean="ConnectorManagerRepository"/></property>
</bean>
-
<!-- JBOSS Cache -->
<!-- Uncomment for JBoss Cache -->
<!--
Modified:
branches/JCA/engine/src/main/java/org/teiid/metadata/CompositeMetadataStore.java
===================================================================
---
branches/JCA/engine/src/main/java/org/teiid/metadata/CompositeMetadataStore.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/engine/src/main/java/org/teiid/metadata/CompositeMetadataStore.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -43,6 +43,11 @@
public class CompositeMetadataStore extends MetadataStore {
+ public CompositeMetadataStore(MetadataStore metadataStore) {
+ this.schemas.putAll(metadataStore.getSchemas());
+ this.datatypes.addAll(metadataStore.getDatatypes());
+ }
+
public CompositeMetadataStore(List<MetadataStore> metadataStores) {
for (MetadataStore metadataStore : metadataStores) {
this.schemas.putAll(metadataStore.getSchemas());
Deleted:
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedBufferService.java
===================================================================
---
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedBufferService.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedBufferService.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,186 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.dqp.embedded.services;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.Properties;
-
-import org.teiid.dqp.internal.cache.DQPContextCache;
-
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.cache.CacheFactory;
-import com.metamatrix.common.buffer.BufferManager;
-import com.metamatrix.common.buffer.StorageManager;
-import com.metamatrix.common.buffer.impl.BufferManagerImpl;
-import com.metamatrix.common.buffer.impl.FileStorageManager;
-import com.metamatrix.common.buffer.impl.MemoryStorageManager;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
-import com.metamatrix.dqp.service.BufferService;
-
-/**
- * Implement the BufferService for the DQP Embedded component. This implementation
- * may use either an all-memory model (which is prone to OutOfMemoryErrors) or
- * a mixed disk/memory model which requires use of a directory on the disk
- * for file service access.
- */
-public class EmbeddedBufferService implements BufferService, Serializable {
-
- // Instance
- private BufferManagerImpl bufferMgr;
- private File bufferDir;
- private boolean useDisk = true;
- private int memorySize = 64;
- private DQPContextCache contextCache;
- private int processorBatchSize = 2000;
- private int connectorBatchSize = 2000;
- private CacheFactory cacheFactory;
-
-
-
- /**
- * Clean the file storage directory on startup
- * @param dir
- * @since 4.3
- */
- void cleanDirectory(File file) {
- if (file.exists()) {
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- files[i].delete();
- }
- }
- }
-
- public void start(){
- try {
- // Set up buffer configuration properties
- Properties bufferProps = new Properties();
-
- bufferProps.setProperty(BufferManager.BUFFER_STORAGE_DIRECTORY,
bufferDir.getCanonicalPath());
- bufferProps.setProperty(BufferManager.PROCESSOR_BATCH_SIZE,
String.valueOf(processorBatchSize));
- bufferProps.setProperty(BufferManager.CONNECTOR_BATCH_SIZE,
String.valueOf(connectorBatchSize));
-
- // Construct and initialize the buffer manager
- this.bufferMgr = new BufferManagerImpl();
- this.bufferMgr.initialize(bufferProps);
-
- // If necessary, add disk storage manager
- if(useDisk) {
- // Get the properties for FileStorageManager and create.
- Properties fsmProps = new Properties();
- fsmProps.setProperty(BufferManager.BUFFER_STORAGE_DIRECTORY,
bufferDir.getCanonicalPath());
- StorageManager fsm = new FileStorageManager();
- fsm.initialize(fsmProps);
- this.bufferMgr.setStorageManager(fsm);
-
- // start the file storage manager in clean state
- // wise FileStorageManager is smart enough to clen up after itself
- cleanDirectory(bufferDir);
- } else {
- this.bufferMgr.setStorageManager(new MemoryStorageManager());
- }
-
- } catch(MetaMatrixComponentException e) {
- throw new MetaMatrixRuntimeException(e,
DQPEmbeddedPlugin.Util.getString("LocalBufferService.Failed_initializing_buffer_manager._8"));
//$NON-NLS-1$
- } catch(IOException e) {
- throw new MetaMatrixRuntimeException(e,
DQPEmbeddedPlugin.Util.getString("LocalBufferService.Failed_initializing_buffer_manager._8"));
//$NON-NLS-1$
- }
- }
-
- public void stop() {
- bufferMgr.shutdown();
-
- // Delete the buffer directory
- if (bufferDir != null) {
- cleanDirectory(bufferDir);
- bufferDir.delete();
- }
- }
-
- public BufferManager getBufferManager() {
- return this.bufferMgr;
- }
-
- @Override
- public DQPContextCache getContextCache() {
- return this.contextCache;
- }
-
- public void setContextCache(DQPContextCache cache) {
- this.contextCache = cache;
- }
-
- public void setUseDisk(boolean flag) {
- this.useDisk = flag;
- }
-
- public void setDiskDirectory(String dir) {
- this.bufferDir = new File(dir, "buffer");
- if (!bufferDir.exists()) {
- this.bufferDir.mkdirs();
- }
- }
-
- public void setBufferMemorySizeInMB(int size) {
- this.memorySize = size;
- }
-
- public void setProcessorBatchSize(int size) {
- this.processorBatchSize = size;
- }
- public void setConnectorBatchSize(int size) {
- this.connectorBatchSize = size;
- }
-
- public File getBufferDirectory() {
- return bufferDir;
- }
-
- public boolean isUseDisk() {
- return useDisk;
- }
-
- public int getBufferMemorySizeInMB() {
- return memorySize;
- }
-
- public int getProcessorBatchSize() {
- return processorBatchSize;
- }
-
- public int getConnectorBatchSize() {
- return connectorBatchSize;
- }
-
- @Override
- public CacheFactory getCacheFactory() {
- return this.cacheFactory;
- }
-
- public void setCacheFactory(CacheFactory cf) {
- this.cacheFactory = cf;
- }
-}
Deleted:
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedMetadataService.java
===================================================================
---
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedMetadataService.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedMetadataService.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,104 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.dqp.embedded.services;
-
-
-
-/**
- * @since 4.3
- */
-public class EmbeddedMetadataService {
-
-/*
-
-
- private TransformationMetadata loadMetadata(final VDBKey vdbID, final MetadataSource
runtimeSelector, DataService dataService) throws MetaMatrixComponentException {
-
- List<MetadataStore> metadataStores = new ArrayList<MetadataStore>();
- try {
- metadataStores.add(loadMetadataStore(runtimeSelector));
- Set<String> modelNames =
runtimeSelector.getConnectorMetadataModelNames();
- if (!modelNames.isEmpty()) {
- for (String modelName : modelNames) {
- MetadataStore connectorMetadata = null;
- String savedMetadata = "/runtime-inf/" + modelName.toLowerCase() +
".ser"; //$NON-NLS-1$ //$NON-NLS-2$
- if (runtimeSelector.cacheConnectorMetadata()) {
- connectorMetadata = loadMetadataStore(runtimeSelector, savedMetadata);
- }
- if (connectorMetadata == null) {
- connectorMetadata = dataService.getConnectorMetadata(vdbID.getName(),
vdbID.getVersion(), modelName, runtimeSelector.getModelInfo(modelName).getProperties());
- }
- if (runtimeSelector.cacheConnectorMetadata()) {
- saveMetadataStore(runtimeSelector, connectorMetadata, savedMetadata);
- }
- metadataStores.add(connectorMetadata);
- }
- }
- metadataStores.add(systemMetadataStore);
- } catch (IOException e) {
- throw new MetaMatrixComponentException(e);
- }
- // build a composite selector for the runtimeselectors of this vdb and system
vdb
- CompositeMetadataStore composite = new CompositeMetadataStore(metadataStores,
runtimeSelector);
- return new TransformationMetadata(composite);
- }
-
- private void saveMetadataStore(final MetadataSource runtimeSelector,
- MetadataStore connectorMetadata, String savedMetadata)
- throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(connectorMetadata);
- oos.close();
- runtimeSelector.saveFile(new ByteArrayInputStream(baos.toByteArray()), savedMetadata);
- }
-
- private MetadataStore loadMetadataStore(final MetadataSource vdb) throws IOException {
- String savedMetadata = "/runtime-inf/" + vdb.getName().toLowerCase() +
".vdb.ser"; //$NON-NLS-1$ //$NON-NLS-2$
- MetadataStore store = loadMetadataStore(vdb, savedMetadata);
- if (store == null) {
- store = new IndexMetadataFactory(vdb).getMetadataStore();
- saveMetadataStore(vdb, store, savedMetadata);
- }
- return store;
- }
-
- private MetadataStore loadMetadataStore(final MetadataSource runtimeSelector, String
savedMetadata) throws IOException {
- File f = runtimeSelector.getFile(savedMetadata);
- if (f != null) {
- ObjectInputStream ois = null;
- try {
- ois = new ObjectInputStream(new FileInputStream(f));
- return (MetadataStore)ois.readObject();
- } catch (Throwable e) {
- LogManager.logDetail(LogConstants.CTX_DQP, e, "invalid metadata in file",
savedMetadata); //$NON-NLS-1$
- } finally {
- if (ois != null) {
- ois.close();
- }
- }
- }
- return null;
- }
- */
-}
Deleted:
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/authorization/service/AuthorizationServiceImpl.java
===================================================================
---
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/authorization/service/AuthorizationServiceImpl.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/authorization/service/AuthorizationServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,472 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.platform.security.authorization.service;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.teiid.adminapi.AdminRoles;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.deployers.VDBRepository;
-import org.teiid.dqp.internal.process.DQPWorkContext;
-
-import com.metamatrix.admin.api.exception.security.InvalidSessionException;
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.security.AuthorizationMgmtException;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.core.log.MessageLevel;
-import com.metamatrix.core.util.LRUCache;
-import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
-import com.metamatrix.dqp.service.AuditMessage;
-import com.metamatrix.dqp.service.AuthorizationService;
-import com.metamatrix.dqp.util.LogConstants;
-import com.metamatrix.platform.security.api.AuthorizationActions;
-import com.metamatrix.platform.security.api.AuthorizationPermission;
-import com.metamatrix.platform.security.api.AuthorizationPoliciesHolder;
-import com.metamatrix.platform.security.api.AuthorizationPolicy;
-import com.metamatrix.platform.security.api.AuthorizationPolicyFactory;
-import com.metamatrix.platform.security.api.AuthorizationRealm;
-import com.metamatrix.platform.security.api.BasicAuthorizationPermission;
-import com.metamatrix.platform.security.api.BasicAuthorizationPermissionFactory;
-import com.metamatrix.platform.security.api.MetaMatrixPrincipal;
-import com.metamatrix.platform.security.api.MetaMatrixPrincipalName;
-import com.metamatrix.platform.security.api.SessionToken;
-import com.metamatrix.platform.security.api.StandardAuthorizationActions;
-import com.metamatrix.platform.security.util.RolePermissionFactory;
-import com.metamatrix.server.util.ServerAuditContexts;
-import com.metamatrix.vdb.runtime.VDBKey;
-
-/**
- * The Authorization Service is responsible for handling requests to determine
- * whether a Principal is entitled to perform a given action on a given resource
- * or set of resources.
- * <p>
- * Administration of the Authorization policies; creating/destroying Policies,
- * adding/deleting Principals and Permissions is available to Principals that
- * have the proper administrative role.
- * </p>
- */
-public class AuthorizationServiceImpl implements AuthorizationService, Serializable {
-
- private static final long serialVersionUID = 5399603007837606243L;
-
- /*
- * Configuration state
- */
- private boolean useEntitlements;
-
- protected LRUCache<VDBKey, Collection<AuthorizationPolicy>> policyCache =
new LRUCache<VDBKey, Collection<AuthorizationPolicy>>();
-
- // Permission factory is reusable and thread safe
- private static final BasicAuthorizationPermissionFactory PERMISSION_FACTORY = new
BasicAuthorizationPermissionFactory();
-
- private Collection<AuthorizationPolicy> adminPolicies =
AuthorizationPolicyFactory.buildDefaultAdminPolicies();
-
- private VDBRepository vdbRepository;
-
- @Override
- public Collection getInaccessibleResources(int action, Collection resources, int
context)
- throws MetaMatrixComponentException {
- AuthorizationRealm realm = getRealm(DQPWorkContext.getWorkContext());
- AuthorizationActions actions = getActions(action);
- Collection permissions = createPermissions(realm, resources, actions);
- String auditContext = getAuditContext(context);
- Collection inaccessableResources = Collections.EMPTY_LIST;
- try {
- inaccessableResources = getInaccessibleResources(auditContext, permissions);
- } catch (AuthorizationMgmtException e) {
- throw new MetaMatrixComponentException(e);
- }
-
- // Convert inaccessable resources from auth permissions to string resource names
- Collection inaccessableResourceNames = Collections.EMPTY_LIST;
- if ( inaccessableResources != null && inaccessableResources.size() > 0
) {
- inaccessableResourceNames = new ArrayList();
- for ( Iterator permItr = inaccessableResources.iterator(); permItr.hasNext();
) {
- AuthorizationPermission permission = (AuthorizationPermission)
permItr.next();
- inaccessableResourceNames.add(permission.getResourceName());
- }
- }
- return inaccessableResourceNames;
- }
-
- /**
- * Of those resources specified, return the subset for which the specified account
- * does <emph>NOT</emph> have authorization to access.
- * @param caller the session token of the principal that is calling this method
- * @param contextName the name of the context for the caller (@see AuditContext)
- * @param requests the permissions that detail the resources and the desired form of
access
- * @return the subset of <code>requests</code> that the account does
<i>not</i> have access to
- * @throws InvalidSessionException if the session token for this cache is not valid
- * @throws AuthorizationMgmtException if this service is unable to locate resources
required
- * for this operation
- */
- private Collection getInaccessibleResources(String contextName, Collection requests)
throws AuthorizationMgmtException {
-
- SessionToken caller = getSession();
-
- LogManager.logDetail(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,
new Object[]{"getInaccessibleResources(", caller, ", ", contextName,
", ", requests, ")"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
//$NON-NLS-4$
-
- List resources = new ArrayList();
- if (requests != null && ! requests.isEmpty()) {
- Iterator permItr = requests.iterator();
- while ( permItr.hasNext() ) {
-
resources.add(((AuthorizationPermission)permItr.next()).getResourceName());
- }
- }
-
- // Audit - request
- AuditMessage msg = new AuditMessage( contextName,
"getInaccessibleResources-request", caller.getUsername(), resources.toArray());
//$NON-NLS-1$
- LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
-
- if (isEntitled()){
- return Collections.EMPTY_LIST;
- }
-
- Collection results = new HashSet(requests);
- Collection policies = this.getPoliciesForPrincipal(getRequestedRealm(requests));
-
- Iterator policyIter = policies.iterator();
-
- while (policyIter.hasNext() && !results.isEmpty()) {
- Iterator requestIter = results.iterator();
- AuthorizationPolicy policy = (AuthorizationPolicy) policyIter.next();
- while (requestIter.hasNext()) {
- AuthorizationPermission request = (AuthorizationPermission)
requestIter.next();
- if (policy.implies(request)) {
- requestIter.remove();
- continue;
- }
- }
- }
-
- if (results.isEmpty()) {
- msg = new AuditMessage( contextName, "getInaccessibleResources-granted
all", caller.getUsername(), resources.toArray()); //$NON-NLS-1$
- LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
- } else {
- msg = new AuditMessage( contextName,
"getInaccessibleResources-denied", caller.getUsername(), resources.toArray());
//$NON-NLS-1$
- LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
- }
- return results;
- }
-
- /**
- * Query <code>requests</code> for the
<code>AuthorizationRealm</code> in
- * which they belong.
- * @param requests
- * @return The realm in which <i>all</i> the requests in the collection
- * belong.
- * @throws AuthorizationMgmtException if the request <i>do not all</i>
- * belong to the same realm.
- */
- private static AuthorizationRealm getRequestedRealm(final Collection requests)
- throws AuthorizationMgmtException {
- AuthorizationRealm theRealm = null;
- Iterator requestItr = requests.iterator();
- while (requestItr.hasNext()) {
- AuthorizationPermission aPerm = (AuthorizationPermission) requestItr.next();
- AuthorizationRealm aRealm = aPerm.getRealm();
- if ( theRealm != null ) {
- if ( ! theRealm.equals(aRealm) ) {
- throw new
AuthorizationMgmtException(DQPEmbeddedPlugin.Util.getString("AuthorizationServiceImpl.wrong_realms
")); //$NON-NLS-1$
- }
- } else {
- theRealm = aRealm;
- }
- }
- if ( theRealm == null ) {
- throw new
AuthorizationMgmtException(DQPEmbeddedPlugin.Util.getString("AuthorizationServiceImpl.Authorization_Realm_is_null"));
//$NON-NLS-1$
- }
- return theRealm;
- }
-
- @Override
- public boolean hasRole(String roleType, String roleName) throws
MetaMatrixComponentException {
-
- AuthorizationRealm realm = null;
-
- if (ADMIN_ROLE.equalsIgnoreCase(roleType)) {
- realm = RolePermissionFactory.getRealm();
- } else if (DATA_ROLE.equalsIgnoreCase(roleType)){
- realm = getRealm(DQPWorkContext.getWorkContext());
- } else {
- return false;
- }
-
- try {
- return hasPolicy(realm, roleName);
- } catch (AuthorizationMgmtException err) {
- throw new MetaMatrixComponentException(err);
- }
- }
-
- private boolean matchesPrincipal(Set<MetaMatrixPrincipalName> principals,
AuthorizationPolicy policy) {
- for (MetaMatrixPrincipalName principal : principals) {
- if (policy.getPrincipals().contains(principal)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean hasPolicy(AuthorizationRealm realm, String policyName) throws
AuthorizationMgmtException {
-
- if (isEntitled()) {
- return true;
- }
-
- Collection<AuthorizationPolicy> policies = getPoliciesForPrincipal(realm);
-
- HashSet applicablePolicies = new HashSet();
- applicablePolicies.add(policyName);
-
- if (realm == RolePermissionFactory.getRealm()) {
- if (AdminRoles.RoleName.ADMIN_PRODUCT.equals(policyName)) {
- applicablePolicies.add(AdminRoles.RoleName.ADMIN_SYSTEM);
- } else if (AdminRoles.RoleName.ADMIN_READONLY.equals(policyName)) {
- applicablePolicies.add(AdminRoles.RoleName.ADMIN_PRODUCT);
- applicablePolicies.add(AdminRoles.RoleName.ADMIN_SYSTEM);
- }
- }
-
- for (AuthorizationPolicy policy:policies) {
- if (applicablePolicies.contains(policy.getAuthorizationPolicyID().getDisplayName()))
{
- return true;
- }
- }
- return false;
- }
-
- /**
- * Return a collection of all policies for which this principal has authorization,
caching as needed.
- * Policies are returned for the principal and all groups in which the principal has
membership.
- * <br><strong>NOTE:</strong> This method only goes to the
authorization store when
- * <emph>none</emph> of the given principal's policies are found in
the cache.
- * @param user the user account for which access is being checked; may not be null
- * (this is not checked for, however)
- * @return All policies for which the principal is authenticated - may be empty but
never null.
- * @throws AuthorizationMgmtException if this service has trouble connecting to
services it uses.
- * @throws MetaMatrixComponentException
- */
- private Collection<AuthorizationPolicy>
getPoliciesForPrincipal(AuthorizationRealm realm)
- throws AuthorizationMgmtException {
-
- Set<AuthorizationPolicy> result = new HashSet<AuthorizationPolicy>();
- Set<MetaMatrixPrincipalName> userRoles = getUserRoles();
- if (userRoles.isEmpty()) {
- return result;
- }
-
- Collection<AuthorizationPolicy> policies = getPoliciesInRealm(realm);
-
- for (AuthorizationPolicy policy : policies) {
- if (matchesPrincipal(userRoles, policy)) {
- result.add(policy);
- continue;
- }
- }
- return result;
- }
-
-
- private Set<MetaMatrixPrincipalName> getUserRoles() {
- Set<MetaMatrixPrincipalName> roles = new
HashSet<MetaMatrixPrincipalName>();
- Set<Principal> principals =
DQPWorkContext.getWorkContext().getSubject().getPrincipals();
- for(Principal p: principals) {
- // this JBoss specific, but no code level dependencies
- if ((p instanceof Group) && p.getName().equals("Roles")){
- Group g = (Group)p;
- Enumeration rolesPrinciples = g.members();
- while(rolesPrinciples.hasMoreElements()) {
- roles.add(new
MetaMatrixPrincipalName(((Principal)rolesPrinciples.nextElement()).getName(),
MetaMatrixPrincipal.TYPE_GROUP));
- }
- }
- }
- return roles;
- }
-
- @Override
- public Collection<AuthorizationPolicy> getPoliciesInRealm(AuthorizationRealm
realm) throws AuthorizationMgmtException {
-
- Collection<AuthorizationPolicy> policies = null;
-
- VDBKey key = null;
-
- if (realm.getSubRealmName() != null) {
- // get data roles for the user
- key = new VDBKey(realm.getSuperRealmName(), realm.getSubRealmName());
- synchronized (this.policyCache) {
- policies = this.policyCache.get(key);
- if (policies == null ) {
- policies = getDataPolicies(realm);
- }
- this.policyCache.put(key, policies);
- }
- }
- else {
- // get admin roles
- policies = getAdminPolicies();
- }
- return policies;
- }
-
- private Collection<AuthorizationPolicy> getDataPolicies(AuthorizationRealm realm)
{
- Collection<AuthorizationPolicy> policies = null;
- VDBMetaData vdb = this.vdbRepository.getVDB(realm.getSuperRealmName(),
Integer.parseInt(realm.getSubRealmName()));
- AuthorizationPoliciesHolder holder =
vdb.getAttachment(AuthorizationPoliciesHolder.class);
-
- if (holder == null) {
- policies = Collections.emptyList();
- }
- else {
- policies = holder.getAuthorizationPolicies();
- //AuthorizationPolicyFactory.buildPolicies(vdb.getName(),
String.valueOf(vdb.getVersion()), vdb.getDataRoles());
- }
- return policies;
- }
-
- private Collection<AuthorizationPolicy> getAdminPolicies() {
- return adminPolicies;
- }
-
- @Override
- public void updatePoliciesInRealm(AuthorizationRealm realm,
Collection<AuthorizationPolicy> policies) throws AuthorizationMgmtException {
-
- if (realm.getSubRealmName() != null) {
- VDBKey key = new VDBKey(realm.getSuperRealmName(), realm.getSubRealmName());
- synchronized (this.policyCache) {
- policies = this.policyCache.get(key);
- if (policies != null) {
- this.policyCache.remove(key);
- }
- VDBMetaData vdb = this.vdbRepository.getVDB(realm.getSuperRealmName(),
Integer.parseInt(realm.getSubRealmName()));
- AuthorizationPoliciesHolder holder = new AuthorizationPoliciesHolder();
- holder.setAuthorizationPolicies(policies);
- vdb.addAttchment(AuthorizationPoliciesHolder.class, holder);
- //vdb.setDataRoles(AuthorizationPolicyFactory.exportPolicies(policies));
- this.policyCache.put(key, policies);
- }
- }
- else {
- // there is no admin API way to update the Admin Roles.
- this.adminPolicies = policies;
- }
- }
-
- protected boolean isEntitled(){
- if (DQPWorkContext.getWorkContext().getSubject() == null) {
-
LogManager.logDetail(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,new
Object[]{ "Automatically entitling principal",
DQPWorkContext.getWorkContext().getSessionToken().getUsername()}); //$NON-NLS-1$
- return true;
- }
- return false;
- }
-
- /**
- * Determine whether entitlements checking is enabled on the server.
- *
- * @return <code>true</code> iff server-side entitlements checking is
enabled.
- */
- @Override
- public boolean checkingEntitlements() {
- return useEntitlements;
- }
-
- /**
- * Create realm based on token
- * @param token Used to find info about this session
- * @return Realm to use (based on vdb name and version)
- */
- private AuthorizationRealm getRealm(DQPWorkContext context) {
- return new AuthorizationRealm(context.getVdbName(),
String.valueOf(context.getVdbVersion()));
- }
-
- private AuthorizationActions getActions(int actionCode) {
- switch(actionCode) {
- case AuthorizationService.ACTION_READ: return
StandardAuthorizationActions.DATA_READ;
- case AuthorizationService.ACTION_CREATE: return
StandardAuthorizationActions.DATA_CREATE;
- case AuthorizationService.ACTION_UPDATE: return
StandardAuthorizationActions.DATA_UPDATE;
- case AuthorizationService.ACTION_DELETE: return
StandardAuthorizationActions.DATA_DELETE;
- default: return StandardAuthorizationActions.DATA_READ;
- }
- }
-
- /**
- * Take a list of resources (Strings) and create a list of permissions
- * suitable for sending to the authorization service.
- * @param realm Realm to use
- * @param resources Collection of String, listing resources
- * @param actions Actions to check for
- * @return Collection of BasicAuthorizationPermission
- */
- private Collection createPermissions(AuthorizationRealm realm, Collection resources,
AuthorizationActions actions) {
- List permissions = new ArrayList(resources.size());
- Iterator iter = resources.iterator();
- while(iter.hasNext()) {
- String resource = (String) iter.next();
-
- BasicAuthorizationPermission permission =
- (BasicAuthorizationPermission) PERMISSION_FACTORY.create(resource, realm,
actions);
-
- permissions.add(permission);
- }
- return permissions;
- }
-
- private String getAuditContext(int auditCode) {
- switch(auditCode) {
- case AuthorizationService.CONTEXT_QUERY: return
ServerAuditContexts.CTX_QUERY;
- case AuthorizationService.CONTEXT_INSERT: return
ServerAuditContexts.CTX_INSERT;
- case AuthorizationService.CONTEXT_UPDATE: return
ServerAuditContexts.CTX_UPDATE;
- case AuthorizationService.CONTEXT_DELETE: return
ServerAuditContexts.CTX_DELETE;
- case AuthorizationService.CONTEXT_PROCEDURE: return
ServerAuditContexts.CTX_PROCEDURE;
- default: return ServerAuditContexts.CTX_QUERY;
- }
- }
-
- public void setVDBRepository(VDBRepository repo) {
- this.vdbRepository = repo;
- }
-
- public void setUseEntitlements(Boolean useEntitlements) {
- this.useEntitlements = useEntitlements.booleanValue();
- }
-
- @Override
- public boolean isCallerInRole(String roleName) throws AuthorizationMgmtException {
- LogManager.logTrace(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,
new Object[]{"isCallerInRole(", getSession(), roleName, ")"});
//$NON-NLS-1$ //$NON-NLS-2$
- return hasPolicy(RolePermissionFactory.getRealm(), roleName);
- }
-
- SessionToken getSession() {
- return DQPWorkContext.getWorkContext().getSessionToken();
- }
-}
Deleted:
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/membership/service/MembershipServiceImpl.java
===================================================================
---
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/membership/service/MembershipServiceImpl.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/membership/service/MembershipServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,222 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.platform.security.membership.service;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.teiid.ContainerHelper;
-import org.teiid.ContainerUtil;
-
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.util.LogConstants;
-import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
-import com.metamatrix.platform.security.api.Credentials;
-
-/**
- * This class serves as the primary implementation of the
- * Membership Service. Based on the security domains specified this class delegates the
responsibility of
- * authenticating user to those security domains in the order they are defined.
- */
-public class MembershipServiceImpl {
- public static final String AT = "@"; //$NON-NLS-1$
- private LoginContext loginContext;
- private String userName;
- private String securitydomain;
- private Object credentials;
-
- public void authenticateUser(String username, Credentials credential, String
applicationName, List<String> domains) throws LoginException {
-
- LogManager.logTrace(LogConstants.CTX_MEMBERSHIP, new Object[]
{"authenticateUser", username, applicationName}); //$NON-NLS-1$
-
- final String baseUsername = getBaseUsername(username);
- final char[] password = credential.getCredentialsAsCharArray();
-
- // If username specifies a domain (user@domain) only that domain is authenticated
against.
- // If username specifies no domain, then all domains are tried in order.
- for (String domain:getDomainsForUser(domains, username)) {
-
- try {
- CallbackHandler handler = new CallbackHandler() {
- @Override
- public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
- for (int i = 0; i < callbacks.length; i++) {
- if (callbacks[i] instanceof NameCallback) {
- NameCallback nc = (NameCallback)callbacks[i];
- nc.setName(baseUsername);
- } else if (callbacks[i] instanceof PasswordCallback) {
- PasswordCallback pc = (PasswordCallback)callbacks[i];
- pc.setPassword(password);
- credentials = password;
- } else {
- throw new UnsupportedCallbackException(callbacks[i], "Unrecognized
Callback");
- }
- }
- }
- };
-
- // this is the configured login for teiid
- this.loginContext = createLoginContext(domain,handler);
- this.loginContext.login();
- this.userName = baseUsername+AT+domain;
- this.securitydomain = domain;
-
- return;
- } catch (LoginException e) {
- LogManager.logDetail(LogConstants.CTX_MEMBERSHIP,e.getMessage());
- }
- }
- throw new
LoginException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.The_username_0_and/or_password_are_incorrect",
username ));
- }
-
- protected LoginContext createLoginContext(String domain, CallbackHandler handler)
throws LoginException {
- return new LoginContext(domain, handler);
- }
-
- public LoginContext getLoginContext() {
- return this.loginContext;
- }
-
- public String getUserName() {
- return this.userName;
- }
-
- public String getSecurityDomain() {
- return this.securitydomain;
- }
-
- public Object getSecurityContext() {
- Object sc = null;
- if (this.loginContext != null) {
- ContainerHelper helper =
ContainerUtil.lookup("teiid/container-helper");
- sc = helper.getSecurityContext(this.securitydomain);
- if ( sc == null){
- Subject subject = this.loginContext.getSubject();
- Principal principal = null;
- for(Principal p:subject.getPrincipals()) {
- if (this.userName.startsWith(p.getName())) {
- principal = p;
- break;
- }
- }
- return helper.createSecurityContext(this.securitydomain, principal,
credentials, subject);
- }
- }
- return sc;
- }
-
- static String getBaseUsername(String username) {
- if (username == null) {
- return username;
- }
-
- int index = getQualifierIndex(username);
-
- String result = username;
-
- if (index != -1) {
- result = username.substring(0, index);
- }
-
- //strip the escape character from the remaining ats
- return result.replaceAll("\\\\"+AT, AT); //$NON-NLS-1$
- }
-
- static String escapeName(String name) {
- if (name == null) {
- return name;
- }
-
- return name.replaceAll(AT, "\\\\"+AT); //$NON-NLS-1$
- }
-
- static String getDomainName(String username) {
- if (username == null) {
- return username;
- }
-
- int index = getQualifierIndex(username);
-
- if (index != -1) {
- return username.substring(index + 1);
- }
-
- return null;
- }
-
- static int getQualifierIndex(String username) {
- int index = username.length();
- while ((index = username.lastIndexOf(AT, --index)) != -1) {
- if (index > 0 && username.charAt(index - 1) != '\\') {
- return index;
- }
- }
-
- return -1;
- }
-
- private Collection<String> getDomainsForUser(List<String> domains, String
username) {
- // If username is null, return all domains
- if (username == null) {
- return domains;
- }
-
- String domain = getDomainName(username);
-
- if (domain == null) {
- return domains;
- }
-
- // ------------------------------------------
- // Handle usernames having @ sign
- // ------------------------------------------
- String domainHolder = null;
- for (String d:domains) {
- if(d.equalsIgnoreCase(domain)) {
- domainHolder = d;
- break;
- }
- }
-
- if (domainHolder == null) {
- return Collections.EMPTY_LIST;
- }
-
- LinkedList result = new LinkedList();
- result.add(domainHolder);
- return result;
- }
-}
Deleted:
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/session/service/SessionServiceImpl.java
===================================================================
---
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/session/service/SessionServiceImpl.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/session/service/SessionServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,317 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.platform.security.session.service;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.deployers.VDBRepository;
-
-import com.metamatrix.admin.api.exception.security.InvalidSessionException;
-import com.metamatrix.api.exception.security.SessionServiceException;
-import com.metamatrix.common.api.MMURL;
-import com.metamatrix.common.comm.api.ServerConnection;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.util.LogConstants;
-import com.metamatrix.core.util.ArgCheck;
-import com.metamatrix.core.util.StringUtil;
-import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
-import com.metamatrix.metadata.runtime.api.VirtualDatabaseException;
-import com.metamatrix.platform.security.api.Credentials;
-import com.metamatrix.platform.security.api.SessionToken;
-import com.metamatrix.platform.security.api.service.SessionService;
-import com.metamatrix.platform.security.membership.service.MembershipServiceImpl;
-
-/**
- * This class serves as the primary implementation of the Session Service.
- */
-public class SessionServiceImpl implements SessionService, Serializable {
- private static final long serialVersionUID = 3366022966048148299L;
-
- public static final String SECURITY_DOMAINS = "securitydomains";
//$NON-NLS-1$
-
- /*
- * Configuration state
- */
- private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
- private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
- private VDBRepository vdbRepository;
-
- private Map<Long, SessionMetadata> sessionCache = new
ConcurrentHashMap<Long, SessionMetadata>();
- private transient Timer sessionMonitor = new Timer("SessionMonitor",
true);
- private AtomicLong idSequence = new AtomicLong();
- private boolean isSecurityEnabled = false;
- private LinkedList<String> securityDomains = new LinkedList<String>();
-
-
- //
-----------------------------------------------------------------------------------
- // S E R V I C E - R E L A T E D M E T H O D S
- //
-----------------------------------------------------------------------------------
-
- private void monitorSessions() {
- long currentTime = System.currentTimeMillis();
- for (SessionMetadata info : sessionCache.values()) {
- try {
- if (currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5)
{
- LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
- closeSession(info.getSessionId());
- } else if (sessionExpirationTimeLimit > 0 && currentTime -
info.getCreatedTime() > sessionExpirationTimeLimit) {
- LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
- closeSession(info.getSessionId());
- }
- } catch (Exception e) {
- LogManager.logDetail(LogConstants.CTX_SESSION, e, "error running session
monitor, unable to monitor: " + info.getSessionId()); //$NON-NLS-1$
- }
- }
- }
-
- @Override
- public void closeSession(long sessionID) throws InvalidSessionException {
- LogManager.logDetail(LogConstants.CTX_SESSION, new Object[] {"closeSession",
sessionID}); //$NON-NLS-1$
- SessionMetadata info = this.sessionCache.remove(sessionID);
- if (info == null) {
- throw new
InvalidSessionException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
sessionID)); //$NON-NLS-1$
- }
-
- // try to log out of the context.
- try {
- LoginContext context = info.getAttachment(LoginContext.class);
- if (context != null) {
- context.logout();
- }
- } catch (LoginException e) {
- LogManager.logWarning(LogConstants.CTX_SESSION,e,"Exception terminitating
session"); //$NON-NLS-1$
- }
- }
-
- @Override
- public SessionMetadata createSession(String userName, Credentials credentials, String
applicationName, Properties properties)
- throws LoginException, SessionServiceException {
- ArgCheck.isNotNull(applicationName);
- ArgCheck.isNotNull(properties);
-
- Properties productInfo = new Properties();
-
- LoginContext loginContext = null;
- String securityDomain = "none";
- Object securityContext = null;
- if (this.isSecurityEnabled) {
- // Authenticate user...
- // if not authenticated, this method throws exception
- MembershipServiceImpl membership = authenticate(userName, credentials,
applicationName);
- loginContext = membership.getLoginContext();
- userName = membership.getUserName();
- securityDomain = membership.getSecurityDomain();
- securityContext = membership.getSecurityContext();
- }
-
- // Validate VDB and version if logging on to server product...
- VDBMetaData vdb = null;
- String vdbName = properties.getProperty(MMURL.JDBC.VDB_NAME);
- if (vdbName != null) {
- String vdbVersion = properties.getProperty(MMURL.JDBC.VDB_VERSION);
- try {
- if (vdbVersion == null) {
- vdb = this.vdbRepository.getActiveVDB(vdbName);
- }
- else {
- vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
- }
-
- // Reset product info with validated constants
- productInfo.put(MMURL.JDBC.VDB_NAME, vdb.getName());
- productInfo.put(MMURL.JDBC.VDB_VERSION, vdb.getVersion());
- } catch (VirtualDatabaseException e) {
- throw new
SessionServiceException(DQPEmbeddedPlugin.Util.getString("VDBService.VDB_does_not_exist._2",
vdbName, vdbVersion==null?"latest":vdbVersion)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- if (sessionMaxLimit > 0 && getActiveSessionsCount() >=
sessionMaxLimit) {
- throw new
SessionServiceException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.reached_max_sessions",
new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
- }
-
- long creationTime = System.currentTimeMillis();
-
- // Return a new session info object
- long id = idSequence.getAndIncrement();
- SessionMetadata newSession = new SessionMetadata();
- newSession.setSessionId(id);
- newSession.setUserName(userName);
- newSession.setCreatedTime(creationTime);
- newSession.setApplicationName(applicationName);
-
newSession.setClientHostName(properties.getProperty(MMURL.CONNECTION.CLIENT_HOSTNAME));
-
newSession.setIPAddress(properties.getProperty(MMURL.CONNECTION.CLIENT_IP_ADDRESS));
- newSession.setSecurityDomain(securityDomain);
- if (vdb != null) {
- newSession.setVDBName(vdb.getName());
- newSession.setVDBVersion(vdb.getVersion());
- }
-
- // these are local no need for monitoring.
- newSession.addAttchment(LoginContext.class, loginContext);
- newSession.addAttchment("SecurityContext", securityContext);
- newSession.addAttchment(VDBMetaData.class, vdb);
- newSession.addAttchment(SessionToken.class, new SessionToken(id, userName));
-
- this.sessionCache.put(newSession.getSessionId(), newSession);
- return newSession;
- }
-
- protected MembershipServiceImpl authenticate(String userName, Credentials credentials,
String applicationName)
- throws LoginException {
- MembershipServiceImpl membership = new MembershipServiceImpl();
- membership.authenticateUser(userName, credentials, applicationName,
this.securityDomains);
- return membership;
- }
-
- @Override
- public Collection<SessionMetadata> getActiveSessions() throws
SessionServiceException {
- return new ArrayList<SessionMetadata>(this.sessionCache.values());
- }
-
- @Override
- public SessionMetadata getActiveSession(long sessionID) {
- return this.sessionCache.get(sessionID);
- }
-
- @Override
- public int getActiveSessionsCount() throws SessionServiceException{
- return this.sessionCache.size();
- }
-
- @Override
- public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int
vdbVersion)
- throws SessionServiceException {
- if (VDBName == null || vdbVersion <= 0) {
- return Collections.emptyList();
- }
- ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
- for (SessionMetadata info : this.sessionCache.values()) {
- if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion ==
info.getVDBVersion()) {
- results.add(info);
- }
- }
- return results;
- }
-
- @Override
- public void pingServer(long sessionID) throws InvalidSessionException {
- SessionMetadata info = getSessionInfo(sessionID);
- info.setLastPingTime(System.currentTimeMillis());
- this.sessionCache.put(sessionID, info);
- }
-
- @Override
- public boolean terminateSession(long terminatedSessionID, long adminSessionID) {
- Object[] params = {adminSessionID, terminatedSessionID};
- LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
- try {
- closeSession(terminatedSessionID);
- return true;
- } catch (InvalidSessionException e) {
- LogManager.logWarning(LogConstants.CTX_SESSION,e,DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
new Object[] {e.getMessage()})); //$NON-NLS-1$
- return false;
- }
- }
-
- @Override
- public SessionMetadata validateSession(long sessionID) throws InvalidSessionException,
SessionServiceException {
- SessionMetadata info = getSessionInfo(sessionID);
- return info;
- }
-
- private SessionMetadata getSessionInfo(long sessionID)
- throws InvalidSessionException {
- SessionMetadata info = this.sessionCache.get(sessionID);
- if (info == null) {
- throw new
InvalidSessionException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
sessionID)); //$NON-NLS-1$
- }
- return info;
- }
-
- public void setSessionMaxLimit(Long limit) {
- this.sessionMaxLimit = limit.longValue();
- }
-
- public void setsessionExpirationTimeLimit(Long limit) {
- this.sessionExpirationTimeLimit = limit.longValue();
- }
-
- public void setSecurityDomains(String domainNameOrder) {
- if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
- isSecurityEnabled = true;
- }
- LogManager.logDetail(LogConstants.CTX_MEMBERSHIP, "Security Enabled: "
+ isSecurityEnabled); //$NON-NLS-1$
-
- if (isSecurityEnabled) {
- List domainNames = StringUtil.split(domainNameOrder, ",");
//$NON-NLS-1$
- Iterator domainNameItr = domainNames.iterator();
- while ( domainNameItr.hasNext() ) {
- String domainName = ((String) domainNameItr.next()).trim();
- this.securityDomains.addLast(domainName);
- }
- }
- }
-
- public void start() {
- this.sessionMonitor.schedule(new TimerTask() {
- @Override
- public void run() {
- monitorSessions();
- }
- }, 0, ServerConnection.PING_INTERVAL * 5);
- }
-
- public void stop(){
- this.sessionMonitor.cancel();
- this.sessionCache.clear();
- }
-
- @Override
- public void setLocalSession(long sessionID) {
- SessionMetadata info = this.sessionCache.get(sessionID);
- if (info != null) {
- info.setLastPingTime(Long.MAX_VALUE);
- }
- }
-
- public void setVDBRepository(VDBRepository repo) {
- this.vdbRepository = repo;
- }
-}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
===================================================================
---
branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -21,17 +21,31 @@
*/
package org.teiid.deployers;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+
+import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.vfs.spi.deployer.AbstractVFSParsingDeployer;
import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
import org.jboss.virtual.VirtualFile;
import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.connector.api.ConnectorException;
+import org.teiid.connector.metadata.runtime.MetadataStore;
+import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
+import org.teiid.metadata.CompositeMetadataStore;
+import com.metamatrix.core.CoreConstants;
import com.metamatrix.core.vdb.ModelType;
public class DynamicVDBDeployer extends AbstractVFSParsingDeployer<VDBMetaData> {
-
+ private VDBRepository vdbRepository;
+ private ConnectorManagerRepository connectorManagerRepository;
+ private ObjectSerializer serializer;
+
public DynamicVDBDeployer() {
super(VDBMetaData.class);
setSuffix("-vdb.xml");
@@ -50,6 +64,81 @@
def.setUrl(unit.getRoot().toURL().toExternalForm());
log.debug("VDB "+unit.getRoot().getName()+" has been parsed.");
+
+
+ ArrayList<MetadataStore> stores = new ArrayList<MetadataStore>();
+ for (ModelMetaData model:def.getModels()) {
+ if (model.getName().equals(CoreConstants.SYSTEM_MODEL)){
+ continue;
+ }
+ stores.add(buildDynamicMetadataStore(unit, def, model));
+ }
+
+ CompositeMetadataStore store = new CompositeMetadataStore(stores);
+ unit.addAttachment(CompositeMetadataStore.class, store);
+
return def;
}
+
+ private MetadataStore buildDynamicMetadataStore(VFSDeploymentUnit unit, VDBMetaData
vdb, ModelMetaData model) throws DeploymentException{
+ if (model.getConnectorBindingNames().isEmpty()) {
+ throw new DeploymentException(vdb.getName()+"-"+vdb.getVersion()+"
Can not be deployed because model {"+model.getName()+"} is not fully
configured.");
+ }
+
+ boolean cache =
"cached".equalsIgnoreCase(vdb.getPropertyValue("UseConnectorMetadata"));
+ File cacheFile = null;
+ if (cache) {
+ try {
+ cacheFile = buildCachedFileName(unit, vdb,model.getName());
+ if (cacheFile.exists()) {
+ return this.serializer.loadAttachment(cacheFile, MetadataStore.class);
+ }
+ } catch (IOException e) {
+ log.warn("invalid metadata in file = "+cacheFile.getAbsolutePath());
+ } catch (ClassNotFoundException e) {
+ log.warn("invalid metadata in file = "+cacheFile.getAbsolutePath());
+ }
+ }
+
+
+ Exception exception = null;
+ for (String connectorName: model.getConnectorBindingNames()) {
+ ConnectorManager cm =
this.connectorManagerRepository.getConnectorManager(connectorName);
+ if (cm == null) {
+ continue;
+ }
+ try {
+ MetadataStore store = cm.getMetadata(model.getName(),
this.vdbRepository.getBuiltinDatatypes(), model.getProperties());
+ if (cache) {
+ this.serializer.saveAttachment(cacheFile, store);
+ }
+ return store;
+ } catch (ConnectorException e) {
+ if (exception != null) {
+ exception = e;
+ }
+ } catch (IOException e) {
+ if (exception != null) {
+ exception = e;
+ }
+ }
+ }
+ throw new DeploymentException(vdb.getName()+"-"+vdb.getVersion()+"
Can not be deployed because model {"+model.getName()+"} can not retrive
metadata", exception);
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+
+ public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
+ this.connectorManagerRepository = repo;
+ }
+
+ public void setObjectSerializer(ObjectSerializer serializer) {
+ this.serializer = serializer;
+ }
+
+ private File buildCachedFileName(VFSDeploymentUnit unit, VDBMetaData vdb, String
modelName) throws IOException {
+ return this.serializer.getAttachmentPath(unit,
vdb.getName()+"_"+vdb.getVersion()+"_"+modelName);
+ }
}
Added: branches/JCA/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
(rev 0)
+++
branches/JCA/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,104 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.deployers;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.URISyntaxException;
+
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
+import org.jboss.logging.Logger;
+
+import com.metamatrix.core.util.FileUtils;
+
+public class ObjectSerializer {
+
+ private static final Logger log = Logger.getLogger(ObjectSerializer.class);
+
+ private static final String ATTACHMENT_SUFFIX = ".ser";
+
+ private String storagePath;
+
+ public void setAttachmentStoreRoot(String path) {
+ this.storagePath = path;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T loadAttachment(File attachmentsStore, Class<T> expected) throws
IOException, ClassNotFoundException {
+ if (log.isTraceEnabled()) {
+ log.trace("loadAttachment, attachmentsStore=" + attachmentsStore);
+ }
+
+ ObjectInputStream ois = null;
+ try {
+ ois = new ObjectInputStream(new FileInputStream(attachmentsStore));
+ return expected.cast(ois.readObject());
+ } finally {
+ if (ois != null) {
+ ois.close();
+ }
+ }
+ }
+
+ public void saveAttachment(File attachmentsStore, Object attachment) throws IOException
{
+ if (log.isTraceEnabled()) {
+ log.trace("saveAttachment, attachmentsStore=" + attachmentsStore + ",
attachment=" + attachment);
+ }
+
+ ObjectOutputStream oos = null;
+ try {
+ oos = new ObjectOutputStream(new FileOutputStream(attachmentsStore));
+ oos.writeObject(attachment);
+ } finally {
+ if (oos != null) {
+ oos.close();
+ }
+ }
+ }
+
+ public void removeAttachments(VFSDeploymentUnit vf) throws IOException {
+ String dirName = baseDirectory(vf);
+ FileUtils.removeDirectoryAndChildren(new File(dirName));
+ }
+
+ public File getAttachmentPath(VFSDeploymentUnit vf, String baseName) throws IOException
{
+
+ String dirName = baseDirectory(vf);
+
+ final String vfsPath = baseName + ATTACHMENT_SUFFIX;
+ File f = new File(dirName, vfsPath);
+ if (!f.getParentFile().exists()) {
+ f.getParentFile().mkdirs();
+ }
+ return f;
+ }
+
+ private String baseDirectory(VFSDeploymentUnit vf) throws IOException {
+ String fileName = vf.getRoot().getName();
+ String dirName = this.storagePath + File.separator + fileName + "-"+
vf.getRoot().getLastModified()+ File.separator;
+ return dirName;
+ }
+}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-01-21
19:42:30 UTC (rev 1768)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -21,9 +21,6 @@
*/
package org.teiid.deployers;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -39,11 +36,8 @@
import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.metadata.runtime.MetadataStore;
import org.teiid.dqp.internal.cache.DQPContextCache;
-import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.TransformationMetadata;
import org.teiid.metadata.index.IndexMetadataFactory;
@@ -57,7 +51,6 @@
private ManagedObjectFactory mof;
private VDBRepository vdbRepository;
private DQPContextCache contextCache;
- private ConnectorManagerRepository connectorManagerRepository;
public VDBDeployer() {
super(VDBMetaData.class);
@@ -75,29 +68,20 @@
this.vdbRepository.addVDB(deployment);
TransformationMetadata metadata = null;
-
+
+ // get the metadata store of the VDB (this is build in parse stage)
+ CompositeMetadataStore store = unit.getAttachment(CompositeMetadataStore.class);
+ this.vdbRepository.addMetadataStore(deployment, store);
+
// check if this is a VDB with index files, if there are then build the
TransformationMetadata
IndexMetadataFactory indexFactory = unit.getAttachment(IndexMetadataFactory.class);
if (indexFactory != null) {
- try {
- MetadataStore store = indexFactory.getMetadataStore();
- this.vdbRepository.addMetadataStore(deployment, store);
- Map<VirtualFile, Visibility> visibilityMap =
indexFactory.getEntriesPlusVisibilities();
- metadata = buildTransformationMetaData(deployment, visibilityMap, store);
- } catch (IOException e) {
- throw new DeploymentException(e);
- }
+ Map<VirtualFile, Visibility> visibilityMap =
indexFactory.getEntriesPlusVisibilities();
+ metadata = buildTransformationMetaData(deployment, visibilityMap, store);
}
else {
// this dynamic VDB
- ArrayList<MetadataStore> stores = new ArrayList<MetadataStore>();
- for (ModelMetaData model:deployment.getModels()) {
- if (model.getName().equals(CoreConstants.SYSTEM_MODEL)){
- continue;
- }
- stores.add(buildDynamicMetadataStore(deployment, model));
- }
- metadata = buildTransformationMetaData(deployment, null, stores.toArray(new
MetadataStore[stores.size()]));
+ metadata = buildTransformationMetaData(deployment, null, store);
}
// add the metadata objects as attachments
@@ -119,28 +103,6 @@
log.info("VDB = "+deployment + " deployed");
}
-
- private MetadataStore buildDynamicMetadataStore(VDBMetaData vdb, ModelMetaData model)
throws DeploymentException{
- if (model.getConnectorBindingNames().isEmpty()) {
- throw new DeploymentException(vdb.getName()+"-"+vdb.getVersion()+"
Can not be deployed because model {"+model.getName()+"} is not fully
configured.");
- }
-
- ConnectorException exception = null;
- for (String connectorName: model.getConnectorBindingNames()) {
- ConnectorManager cm =
this.connectorManagerRepository.getConnectorManager(connectorName);
- if (cm == null) {
- continue;
- }
- try {
- return cm.getMetadata(model.getName(), this.vdbRepository.getBuiltinDatatypes(),
model.getProperties());
- } catch (ConnectorException e) {
- if (exception != null) {
- exception = e;
- }
- }
- }
- throw new DeploymentException(vdb.getName()+"-"+vdb.getVersion()+"
Can not be deployed because model {"+model.getName()+"} can not retrive
metadata", exception);
- }
public boolean isFullyConfiguredVDB(VDBMetaData vdb) {
for(ModelMetaData m: vdb.getModels()) {
@@ -154,7 +116,7 @@
}
// does this need to be synchronized?
- private TransformationMetadata buildTransformationMetaData(VDBMetaData vdb,
Map<VirtualFile, Visibility> visibilityMap, MetadataStore... stores) throws
DeploymentException {
+ private TransformationMetadata buildTransformationMetaData(VDBMetaData vdb,
Map<VirtualFile, Visibility> visibilityMap, CompositeMetadataStore store) throws
DeploymentException {
// get the system VDB metadata store
MetadataStore systemStore =
this.vdbRepository.getMetadataStore(CoreConstants.SYSTEM_VDB, 1);
@@ -162,13 +124,7 @@
throw new DeploymentException("System.vdb needs to be loaded before any other
VDBs.");
}
- // build transformation metadata
- List<MetadataStore> metadataStores = new ArrayList<MetadataStore>();
- metadataStores.add(systemStore);
- for (MetadataStore s: stores) {
- metadataStores.add(s);
- }
- TransformationMetadata metadata = new TransformationMetadata(vdb.getName(),
vdb.getVersion(), new CompositeMetadataStore(metadataStores), visibilityMap);
+ TransformationMetadata metadata = new TransformationMetadata(vdb.getName(),
vdb.getVersion(), store, visibilityMap);
return metadata;
}
@@ -203,10 +159,6 @@
this.vdbRepository = repo;
}
- public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
- this.connectorManagerRepository = repo;
- }
-
@Override
public void undeploy(DeploymentUnit unit, VDBMetaData deployment) {
super.undeploy(unit, deployment);
@@ -214,7 +166,7 @@
this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion());
// remove any vdb specific context cache
this.contextCache.removeVDBScopedCache(deployment.getName(), deployment.getVersion());
-
+
log.info("VDB = "+deployment + " undeployed");
}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
===================================================================
---
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -21,6 +21,7 @@
*/
package org.teiid.deployers;
+import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@@ -32,6 +33,7 @@
import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.index.IndexConstants;
import org.teiid.metadata.index.IndexMetadataFactory;
@@ -44,7 +46,8 @@
* This file loads the ".def" file and "manifest" file inside a VDB
file.
*/
public class VDBParserDeployer extends BaseMultipleVFSParsingDeployer<VDBMetaData>
{
- protected Logger log = Logger.getLogger(getClass());
+ protected Logger log = Logger.getLogger(getClass());
+ private ObjectSerializer serializer;
public VDBParserDeployer() {
super(VDBMetaData.class, getCustomMappings(),
IndexConstants.NAME_DELIM_CHAR+IndexConstants.INDEX_EXT, IndexMetadataFactory.class);
@@ -114,6 +117,18 @@
if (imf != null) {
imf.addEntriesPlusVisibilities(visibilityMap);
unit.addAttachment(IndexMetadataFactory.class, imf);
+
+ // add the cached store.
+ CompositeMetadataStore store = null;
+ File cacheFileName = this.serializer.getAttachmentPath(unit,
def.getName()+"_"+def.getVersion());
+ if (cacheFileName.exists()) {
+ store = this.serializer.loadAttachment(cacheFileName,
CompositeMetadataStore.class);
+ }
+ else {
+ store = new CompositeMetadataStore(imf.getMetadataStore());
+ this.serializer.saveAttachment(cacheFileName,store);
+ }
+ unit.addAttachment(CompositeMetadataStore.class, store);
}
}
@@ -185,4 +200,8 @@
// any other file should be visible
return Visibility.PUBLIC;
}
+
+ public void setObjectSerializer(ObjectSerializer serializer) {
+ this.serializer = serializer;
+ }
}
Copied:
branches/JCA/runtime/src/main/java/org/teiid/services/AuthorizationServiceImpl.java (from
rev 1743,
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/authorization/service/AuthorizationServiceImpl.java)
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/services/AuthorizationServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/main/java/org/teiid/services/AuthorizationServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,472 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.services;
+
+import java.io.Serializable;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.adminapi.AdminRoles;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.dqp.internal.process.DQPWorkContext;
+
+import com.metamatrix.admin.api.exception.security.InvalidSessionException;
+import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.security.AuthorizationMgmtException;
+import com.metamatrix.common.log.LogManager;
+import com.metamatrix.core.log.MessageLevel;
+import com.metamatrix.core.util.LRUCache;
+import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
+import com.metamatrix.dqp.service.AuditMessage;
+import com.metamatrix.dqp.service.AuthorizationService;
+import com.metamatrix.dqp.util.LogConstants;
+import com.metamatrix.platform.security.api.AuthorizationActions;
+import com.metamatrix.platform.security.api.AuthorizationPermission;
+import com.metamatrix.platform.security.api.AuthorizationPoliciesHolder;
+import com.metamatrix.platform.security.api.AuthorizationPolicy;
+import com.metamatrix.platform.security.api.AuthorizationPolicyFactory;
+import com.metamatrix.platform.security.api.AuthorizationRealm;
+import com.metamatrix.platform.security.api.BasicAuthorizationPermission;
+import com.metamatrix.platform.security.api.BasicAuthorizationPermissionFactory;
+import com.metamatrix.platform.security.api.MetaMatrixPrincipal;
+import com.metamatrix.platform.security.api.MetaMatrixPrincipalName;
+import com.metamatrix.platform.security.api.SessionToken;
+import com.metamatrix.platform.security.api.StandardAuthorizationActions;
+import com.metamatrix.platform.security.util.RolePermissionFactory;
+import com.metamatrix.server.util.ServerAuditContexts;
+import com.metamatrix.vdb.runtime.VDBKey;
+
+/**
+ * The Authorization Service is responsible for handling requests to determine
+ * whether a Principal is entitled to perform a given action on a given resource
+ * or set of resources.
+ * <p>
+ * Administration of the Authorization policies; creating/destroying Policies,
+ * adding/deleting Principals and Permissions is available to Principals that
+ * have the proper administrative role.
+ * </p>
+ */
+public class AuthorizationServiceImpl implements AuthorizationService, Serializable {
+
+ private static final long serialVersionUID = 5399603007837606243L;
+
+ /*
+ * Configuration state
+ */
+ private boolean useEntitlements;
+
+ protected LRUCache<VDBKey, Collection<AuthorizationPolicy>> policyCache =
new LRUCache<VDBKey, Collection<AuthorizationPolicy>>();
+
+ // Permission factory is reusable and thread safe
+ private static final BasicAuthorizationPermissionFactory PERMISSION_FACTORY = new
BasicAuthorizationPermissionFactory();
+
+ private Collection<AuthorizationPolicy> adminPolicies =
AuthorizationPolicyFactory.buildDefaultAdminPolicies();
+
+ private VDBRepository vdbRepository;
+
+ @Override
+ public Collection getInaccessibleResources(int action, Collection resources, int
context)
+ throws MetaMatrixComponentException {
+ AuthorizationRealm realm = getRealm(DQPWorkContext.getWorkContext());
+ AuthorizationActions actions = getActions(action);
+ Collection permissions = createPermissions(realm, resources, actions);
+ String auditContext = getAuditContext(context);
+ Collection inaccessableResources = Collections.EMPTY_LIST;
+ try {
+ inaccessableResources = getInaccessibleResources(auditContext, permissions);
+ } catch (AuthorizationMgmtException e) {
+ throw new MetaMatrixComponentException(e);
+ }
+
+ // Convert inaccessable resources from auth permissions to string resource names
+ Collection inaccessableResourceNames = Collections.EMPTY_LIST;
+ if ( inaccessableResources != null && inaccessableResources.size() > 0
) {
+ inaccessableResourceNames = new ArrayList();
+ for ( Iterator permItr = inaccessableResources.iterator(); permItr.hasNext();
) {
+ AuthorizationPermission permission = (AuthorizationPermission)
permItr.next();
+ inaccessableResourceNames.add(permission.getResourceName());
+ }
+ }
+ return inaccessableResourceNames;
+ }
+
+ /**
+ * Of those resources specified, return the subset for which the specified account
+ * does <emph>NOT</emph> have authorization to access.
+ * @param caller the session token of the principal that is calling this method
+ * @param contextName the name of the context for the caller (@see AuditContext)
+ * @param requests the permissions that detail the resources and the desired form of
access
+ * @return the subset of <code>requests</code> that the account does
<i>not</i> have access to
+ * @throws InvalidSessionException if the session token for this cache is not valid
+ * @throws AuthorizationMgmtException if this service is unable to locate resources
required
+ * for this operation
+ */
+ private Collection getInaccessibleResources(String contextName, Collection requests)
throws AuthorizationMgmtException {
+
+ SessionToken caller = getSession();
+
+ LogManager.logDetail(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,
new Object[]{"getInaccessibleResources(", caller, ", ", contextName,
", ", requests, ")"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
//$NON-NLS-4$
+
+ List resources = new ArrayList();
+ if (requests != null && ! requests.isEmpty()) {
+ Iterator permItr = requests.iterator();
+ while ( permItr.hasNext() ) {
+
resources.add(((AuthorizationPermission)permItr.next()).getResourceName());
+ }
+ }
+
+ // Audit - request
+ AuditMessage msg = new AuditMessage( contextName,
"getInaccessibleResources-request", caller.getUsername(), resources.toArray());
//$NON-NLS-1$
+ LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
+
+ if (isEntitled()){
+ return Collections.EMPTY_LIST;
+ }
+
+ Collection results = new HashSet(requests);
+ Collection policies = this.getPoliciesForPrincipal(getRequestedRealm(requests));
+
+ Iterator policyIter = policies.iterator();
+
+ while (policyIter.hasNext() && !results.isEmpty()) {
+ Iterator requestIter = results.iterator();
+ AuthorizationPolicy policy = (AuthorizationPolicy) policyIter.next();
+ while (requestIter.hasNext()) {
+ AuthorizationPermission request = (AuthorizationPermission)
requestIter.next();
+ if (policy.implies(request)) {
+ requestIter.remove();
+ continue;
+ }
+ }
+ }
+
+ if (results.isEmpty()) {
+ msg = new AuditMessage( contextName, "getInaccessibleResources-granted
all", caller.getUsername(), resources.toArray()); //$NON-NLS-1$
+ LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
+ } else {
+ msg = new AuditMessage( contextName,
"getInaccessibleResources-denied", caller.getUsername(), resources.toArray());
//$NON-NLS-1$
+ LogManager.log(MessageLevel.INFO, LogConstants.CTX_AUDITLOGGING, msg);
+ }
+ return results;
+ }
+
+ /**
+ * Query <code>requests</code> for the
<code>AuthorizationRealm</code> in
+ * which they belong.
+ * @param requests
+ * @return The realm in which <i>all</i> the requests in the collection
+ * belong.
+ * @throws AuthorizationMgmtException if the request <i>do not all</i>
+ * belong to the same realm.
+ */
+ private static AuthorizationRealm getRequestedRealm(final Collection requests)
+ throws AuthorizationMgmtException {
+ AuthorizationRealm theRealm = null;
+ Iterator requestItr = requests.iterator();
+ while (requestItr.hasNext()) {
+ AuthorizationPermission aPerm = (AuthorizationPermission) requestItr.next();
+ AuthorizationRealm aRealm = aPerm.getRealm();
+ if ( theRealm != null ) {
+ if ( ! theRealm.equals(aRealm) ) {
+ throw new
AuthorizationMgmtException(DQPEmbeddedPlugin.Util.getString("AuthorizationServiceImpl.wrong_realms
")); //$NON-NLS-1$
+ }
+ } else {
+ theRealm = aRealm;
+ }
+ }
+ if ( theRealm == null ) {
+ throw new
AuthorizationMgmtException(DQPEmbeddedPlugin.Util.getString("AuthorizationServiceImpl.Authorization_Realm_is_null"));
//$NON-NLS-1$
+ }
+ return theRealm;
+ }
+
+ @Override
+ public boolean hasRole(String roleType, String roleName) throws
MetaMatrixComponentException {
+
+ AuthorizationRealm realm = null;
+
+ if (ADMIN_ROLE.equalsIgnoreCase(roleType)) {
+ realm = RolePermissionFactory.getRealm();
+ } else if (DATA_ROLE.equalsIgnoreCase(roleType)){
+ realm = getRealm(DQPWorkContext.getWorkContext());
+ } else {
+ return false;
+ }
+
+ try {
+ return hasPolicy(realm, roleName);
+ } catch (AuthorizationMgmtException err) {
+ throw new MetaMatrixComponentException(err);
+ }
+ }
+
+ private boolean matchesPrincipal(Set<MetaMatrixPrincipalName> principals,
AuthorizationPolicy policy) {
+ for (MetaMatrixPrincipalName principal : principals) {
+ if (policy.getPrincipals().contains(principal)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean hasPolicy(AuthorizationRealm realm, String policyName) throws
AuthorizationMgmtException {
+
+ if (isEntitled()) {
+ return true;
+ }
+
+ Collection<AuthorizationPolicy> policies = getPoliciesForPrincipal(realm);
+
+ HashSet applicablePolicies = new HashSet();
+ applicablePolicies.add(policyName);
+
+ if (realm == RolePermissionFactory.getRealm()) {
+ if (AdminRoles.RoleName.ADMIN_PRODUCT.equals(policyName)) {
+ applicablePolicies.add(AdminRoles.RoleName.ADMIN_SYSTEM);
+ } else if (AdminRoles.RoleName.ADMIN_READONLY.equals(policyName)) {
+ applicablePolicies.add(AdminRoles.RoleName.ADMIN_PRODUCT);
+ applicablePolicies.add(AdminRoles.RoleName.ADMIN_SYSTEM);
+ }
+ }
+
+ for (AuthorizationPolicy policy:policies) {
+ if (applicablePolicies.contains(policy.getAuthorizationPolicyID().getDisplayName()))
{
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return a collection of all policies for which this principal has authorization,
caching as needed.
+ * Policies are returned for the principal and all groups in which the principal has
membership.
+ * <br><strong>NOTE:</strong> This method only goes to the
authorization store when
+ * <emph>none</emph> of the given principal's policies are found in
the cache.
+ * @param user the user account for which access is being checked; may not be null
+ * (this is not checked for, however)
+ * @return All policies for which the principal is authenticated - may be empty but
never null.
+ * @throws AuthorizationMgmtException if this service has trouble connecting to
services it uses.
+ * @throws MetaMatrixComponentException
+ */
+ private Collection<AuthorizationPolicy>
getPoliciesForPrincipal(AuthorizationRealm realm)
+ throws AuthorizationMgmtException {
+
+ Set<AuthorizationPolicy> result = new HashSet<AuthorizationPolicy>();
+ Set<MetaMatrixPrincipalName> userRoles = getUserRoles();
+ if (userRoles.isEmpty()) {
+ return result;
+ }
+
+ Collection<AuthorizationPolicy> policies = getPoliciesInRealm(realm);
+
+ for (AuthorizationPolicy policy : policies) {
+ if (matchesPrincipal(userRoles, policy)) {
+ result.add(policy);
+ continue;
+ }
+ }
+ return result;
+ }
+
+
+ private Set<MetaMatrixPrincipalName> getUserRoles() {
+ Set<MetaMatrixPrincipalName> roles = new
HashSet<MetaMatrixPrincipalName>();
+ Set<Principal> principals =
DQPWorkContext.getWorkContext().getSubject().getPrincipals();
+ for(Principal p: principals) {
+ // this JBoss specific, but no code level dependencies
+ if ((p instanceof Group) && p.getName().equals("Roles")){
+ Group g = (Group)p;
+ Enumeration rolesPrinciples = g.members();
+ while(rolesPrinciples.hasMoreElements()) {
+ roles.add(new
MetaMatrixPrincipalName(((Principal)rolesPrinciples.nextElement()).getName(),
MetaMatrixPrincipal.TYPE_GROUP));
+ }
+ }
+ }
+ return roles;
+ }
+
+ @Override
+ public Collection<AuthorizationPolicy> getPoliciesInRealm(AuthorizationRealm
realm) throws AuthorizationMgmtException {
+
+ Collection<AuthorizationPolicy> policies = null;
+
+ VDBKey key = null;
+
+ if (realm.getSubRealmName() != null) {
+ // get data roles for the user
+ key = new VDBKey(realm.getSuperRealmName(), realm.getSubRealmName());
+ synchronized (this.policyCache) {
+ policies = this.policyCache.get(key);
+ if (policies == null ) {
+ policies = getDataPolicies(realm);
+ }
+ this.policyCache.put(key, policies);
+ }
+ }
+ else {
+ // get admin roles
+ policies = getAdminPolicies();
+ }
+ return policies;
+ }
+
+ private Collection<AuthorizationPolicy> getDataPolicies(AuthorizationRealm realm)
{
+ Collection<AuthorizationPolicy> policies = null;
+ VDBMetaData vdb = this.vdbRepository.getVDB(realm.getSuperRealmName(),
Integer.parseInt(realm.getSubRealmName()));
+ AuthorizationPoliciesHolder holder =
vdb.getAttachment(AuthorizationPoliciesHolder.class);
+
+ if (holder == null) {
+ policies = Collections.emptyList();
+ }
+ else {
+ policies = holder.getAuthorizationPolicies();
+ //AuthorizationPolicyFactory.buildPolicies(vdb.getName(),
String.valueOf(vdb.getVersion()), vdb.getDataRoles());
+ }
+ return policies;
+ }
+
+ private Collection<AuthorizationPolicy> getAdminPolicies() {
+ return adminPolicies;
+ }
+
+ @Override
+ public void updatePoliciesInRealm(AuthorizationRealm realm,
Collection<AuthorizationPolicy> policies) throws AuthorizationMgmtException {
+
+ if (realm.getSubRealmName() != null) {
+ VDBKey key = new VDBKey(realm.getSuperRealmName(), realm.getSubRealmName());
+ synchronized (this.policyCache) {
+ policies = this.policyCache.get(key);
+ if (policies != null) {
+ this.policyCache.remove(key);
+ }
+ VDBMetaData vdb = this.vdbRepository.getVDB(realm.getSuperRealmName(),
Integer.parseInt(realm.getSubRealmName()));
+ AuthorizationPoliciesHolder holder = new AuthorizationPoliciesHolder();
+ holder.setAuthorizationPolicies(policies);
+ vdb.addAttchment(AuthorizationPoliciesHolder.class, holder);
+ //vdb.setDataRoles(AuthorizationPolicyFactory.exportPolicies(policies));
+ this.policyCache.put(key, policies);
+ }
+ }
+ else {
+ // there is no admin API way to update the Admin Roles.
+ this.adminPolicies = policies;
+ }
+ }
+
+ protected boolean isEntitled(){
+ if (DQPWorkContext.getWorkContext().getSubject() == null) {
+
LogManager.logDetail(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,new
Object[]{ "Automatically entitling principal",
DQPWorkContext.getWorkContext().getSessionToken().getUsername()}); //$NON-NLS-1$
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Determine whether entitlements checking is enabled on the server.
+ *
+ * @return <code>true</code> iff server-side entitlements checking is
enabled.
+ */
+ @Override
+ public boolean checkingEntitlements() {
+ return useEntitlements;
+ }
+
+ /**
+ * Create realm based on token
+ * @param token Used to find info about this session
+ * @return Realm to use (based on vdb name and version)
+ */
+ private AuthorizationRealm getRealm(DQPWorkContext context) {
+ return new AuthorizationRealm(context.getVdbName(),
String.valueOf(context.getVdbVersion()));
+ }
+
+ private AuthorizationActions getActions(int actionCode) {
+ switch(actionCode) {
+ case AuthorizationService.ACTION_READ: return
StandardAuthorizationActions.DATA_READ;
+ case AuthorizationService.ACTION_CREATE: return
StandardAuthorizationActions.DATA_CREATE;
+ case AuthorizationService.ACTION_UPDATE: return
StandardAuthorizationActions.DATA_UPDATE;
+ case AuthorizationService.ACTION_DELETE: return
StandardAuthorizationActions.DATA_DELETE;
+ default: return StandardAuthorizationActions.DATA_READ;
+ }
+ }
+
+ /**
+ * Take a list of resources (Strings) and create a list of permissions
+ * suitable for sending to the authorization service.
+ * @param realm Realm to use
+ * @param resources Collection of String, listing resources
+ * @param actions Actions to check for
+ * @return Collection of BasicAuthorizationPermission
+ */
+ private Collection createPermissions(AuthorizationRealm realm, Collection resources,
AuthorizationActions actions) {
+ List permissions = new ArrayList(resources.size());
+ Iterator iter = resources.iterator();
+ while(iter.hasNext()) {
+ String resource = (String) iter.next();
+
+ BasicAuthorizationPermission permission =
+ (BasicAuthorizationPermission) PERMISSION_FACTORY.create(resource, realm,
actions);
+
+ permissions.add(permission);
+ }
+ return permissions;
+ }
+
+ private String getAuditContext(int auditCode) {
+ switch(auditCode) {
+ case AuthorizationService.CONTEXT_QUERY: return
ServerAuditContexts.CTX_QUERY;
+ case AuthorizationService.CONTEXT_INSERT: return
ServerAuditContexts.CTX_INSERT;
+ case AuthorizationService.CONTEXT_UPDATE: return
ServerAuditContexts.CTX_UPDATE;
+ case AuthorizationService.CONTEXT_DELETE: return
ServerAuditContexts.CTX_DELETE;
+ case AuthorizationService.CONTEXT_PROCEDURE: return
ServerAuditContexts.CTX_PROCEDURE;
+ default: return ServerAuditContexts.CTX_QUERY;
+ }
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+
+ public void setUseEntitlements(Boolean useEntitlements) {
+ this.useEntitlements = useEntitlements.booleanValue();
+ }
+
+ @Override
+ public boolean isCallerInRole(String roleName) throws AuthorizationMgmtException {
+ LogManager.logTrace(com.metamatrix.common.util.LogConstants.CTX_AUTHORIZATION,
new Object[]{"isCallerInRole(", getSession(), roleName, ")"});
//$NON-NLS-1$ //$NON-NLS-2$
+ return hasPolicy(RolePermissionFactory.getRealm(), roleName);
+ }
+
+ SessionToken getSession() {
+ return DQPWorkContext.getWorkContext().getSessionToken();
+ }
+}
Property changes on:
branches/JCA/runtime/src/main/java/org/teiid/services/AuthorizationServiceImpl.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: branches/JCA/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java (from
rev 1743,
branches/JCA/runtime/src/main/java/com/metamatrix/dqp/embedded/services/EmbeddedBufferService.java)
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,186 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.services;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Properties;
+
+import org.teiid.dqp.internal.cache.DQPContextCache;
+
+import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.cache.CacheFactory;
+import com.metamatrix.common.buffer.BufferManager;
+import com.metamatrix.common.buffer.StorageManager;
+import com.metamatrix.common.buffer.impl.BufferManagerImpl;
+import com.metamatrix.common.buffer.impl.FileStorageManager;
+import com.metamatrix.common.buffer.impl.MemoryStorageManager;
+import com.metamatrix.core.MetaMatrixRuntimeException;
+import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
+import com.metamatrix.dqp.service.BufferService;
+
+/**
+ * Implement the BufferService for the DQP Embedded component. This implementation
+ * may use either an all-memory model (which is prone to OutOfMemoryErrors) or
+ * a mixed disk/memory model which requires use of a directory on the disk
+ * for file service access.
+ */
+public class BufferServiceImpl implements BufferService, Serializable {
+
+ // Instance
+ private BufferManagerImpl bufferMgr;
+ private File bufferDir;
+ private boolean useDisk = true;
+ private int memorySize = 64;
+ private DQPContextCache contextCache;
+ private int processorBatchSize = 2000;
+ private int connectorBatchSize = 2000;
+ private CacheFactory cacheFactory;
+
+
+
+ /**
+ * Clean the file storage directory on startup
+ * @param dir
+ * @since 4.3
+ */
+ void cleanDirectory(File file) {
+ if (file.exists()) {
+ File[] files = file.listFiles();
+ for (int i = 0; i < files.length; i++) {
+ files[i].delete();
+ }
+ }
+ }
+
+ public void start(){
+ try {
+ // Set up buffer configuration properties
+ Properties bufferProps = new Properties();
+
+ bufferProps.setProperty(BufferManager.BUFFER_STORAGE_DIRECTORY,
bufferDir.getCanonicalPath());
+ bufferProps.setProperty(BufferManager.PROCESSOR_BATCH_SIZE,
String.valueOf(processorBatchSize));
+ bufferProps.setProperty(BufferManager.CONNECTOR_BATCH_SIZE,
String.valueOf(connectorBatchSize));
+
+ // Construct and initialize the buffer manager
+ this.bufferMgr = new BufferManagerImpl();
+ this.bufferMgr.initialize(bufferProps);
+
+ // If necessary, add disk storage manager
+ if(useDisk) {
+ // Get the properties for FileStorageManager and create.
+ Properties fsmProps = new Properties();
+ fsmProps.setProperty(BufferManager.BUFFER_STORAGE_DIRECTORY,
bufferDir.getCanonicalPath());
+ StorageManager fsm = new FileStorageManager();
+ fsm.initialize(fsmProps);
+ this.bufferMgr.setStorageManager(fsm);
+
+ // start the file storage manager in clean state
+ // wise FileStorageManager is smart enough to clen up after itself
+ cleanDirectory(bufferDir);
+ } else {
+ this.bufferMgr.setStorageManager(new MemoryStorageManager());
+ }
+
+ } catch(MetaMatrixComponentException e) {
+ throw new MetaMatrixRuntimeException(e,
DQPEmbeddedPlugin.Util.getString("LocalBufferService.Failed_initializing_buffer_manager._8"));
//$NON-NLS-1$
+ } catch(IOException e) {
+ throw new MetaMatrixRuntimeException(e,
DQPEmbeddedPlugin.Util.getString("LocalBufferService.Failed_initializing_buffer_manager._8"));
//$NON-NLS-1$
+ }
+ }
+
+ public void stop() {
+ bufferMgr.shutdown();
+
+ // Delete the buffer directory
+ if (bufferDir != null) {
+ cleanDirectory(bufferDir);
+ bufferDir.delete();
+ }
+ }
+
+ public BufferManager getBufferManager() {
+ return this.bufferMgr;
+ }
+
+ @Override
+ public DQPContextCache getContextCache() {
+ return this.contextCache;
+ }
+
+ public void setContextCache(DQPContextCache cache) {
+ this.contextCache = cache;
+ }
+
+ public void setUseDisk(boolean flag) {
+ this.useDisk = flag;
+ }
+
+ public void setDiskDirectory(String dir) {
+ this.bufferDir = new File(dir, "buffer");
+ if (!bufferDir.exists()) {
+ this.bufferDir.mkdirs();
+ }
+ }
+
+ public void setBufferMemorySizeInMB(int size) {
+ this.memorySize = size;
+ }
+
+ public void setProcessorBatchSize(int size) {
+ this.processorBatchSize = size;
+ }
+ public void setConnectorBatchSize(int size) {
+ this.connectorBatchSize = size;
+ }
+
+ public File getBufferDirectory() {
+ return bufferDir;
+ }
+
+ public boolean isUseDisk() {
+ return useDisk;
+ }
+
+ public int getBufferMemorySizeInMB() {
+ return memorySize;
+ }
+
+ public int getProcessorBatchSize() {
+ return processorBatchSize;
+ }
+
+ public int getConnectorBatchSize() {
+ return connectorBatchSize;
+ }
+
+ @Override
+ public CacheFactory getCacheFactory() {
+ return this.cacheFactory;
+ }
+
+ public void setCacheFactory(CacheFactory cf) {
+ this.cacheFactory = cf;
+ }
+}
Copied: branches/JCA/runtime/src/main/java/org/teiid/services/MembershipServiceImpl.java
(from rev 1743,
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/membership/service/MembershipServiceImpl.java)
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/services/MembershipServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/main/java/org/teiid/services/MembershipServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,222 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.services;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.teiid.ContainerHelper;
+import org.teiid.ContainerUtil;
+
+import com.metamatrix.common.log.LogManager;
+import com.metamatrix.common.util.LogConstants;
+import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
+import com.metamatrix.platform.security.api.Credentials;
+
+/**
+ * This class serves as the primary implementation of the
+ * Membership Service. Based on the security domains specified this class delegates the
responsibility of
+ * authenticating user to those security domains in the order they are defined.
+ */
+public class MembershipServiceImpl {
+ public static final String AT = "@"; //$NON-NLS-1$
+ private LoginContext loginContext;
+ private String userName;
+ private String securitydomain;
+ private Object credentials;
+
+ public void authenticateUser(String username, Credentials credential, String
applicationName, List<String> domains) throws LoginException {
+
+ LogManager.logTrace(LogConstants.CTX_MEMBERSHIP, new Object[]
{"authenticateUser", username, applicationName}); //$NON-NLS-1$
+
+ final String baseUsername = getBaseUsername(username);
+ final char[] password = credential.getCredentialsAsCharArray();
+
+ // If username specifies a domain (user@domain) only that domain is authenticated
against.
+ // If username specifies no domain, then all domains are tried in order.
+ for (String domain:getDomainsForUser(domains, username)) {
+
+ try {
+ CallbackHandler handler = new CallbackHandler() {
+ @Override
+ public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
+ for (int i = 0; i < callbacks.length; i++) {
+ if (callbacks[i] instanceof NameCallback) {
+ NameCallback nc = (NameCallback)callbacks[i];
+ nc.setName(baseUsername);
+ } else if (callbacks[i] instanceof PasswordCallback) {
+ PasswordCallback pc = (PasswordCallback)callbacks[i];
+ pc.setPassword(password);
+ credentials = password;
+ } else {
+ throw new UnsupportedCallbackException(callbacks[i], "Unrecognized
Callback");
+ }
+ }
+ }
+ };
+
+ // this is the configured login for teiid
+ this.loginContext = createLoginContext(domain,handler);
+ this.loginContext.login();
+ this.userName = baseUsername+AT+domain;
+ this.securitydomain = domain;
+
+ return;
+ } catch (LoginException e) {
+ LogManager.logDetail(LogConstants.CTX_MEMBERSHIP,e.getMessage());
+ }
+ }
+ throw new
LoginException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.The_username_0_and/or_password_are_incorrect",
username ));
+ }
+
+ protected LoginContext createLoginContext(String domain, CallbackHandler handler)
throws LoginException {
+ return new LoginContext(domain, handler);
+ }
+
+ public LoginContext getLoginContext() {
+ return this.loginContext;
+ }
+
+ public String getUserName() {
+ return this.userName;
+ }
+
+ public String getSecurityDomain() {
+ return this.securitydomain;
+ }
+
+ public Object getSecurityContext() {
+ Object sc = null;
+ if (this.loginContext != null) {
+ ContainerHelper helper =
ContainerUtil.lookup("teiid/container-helper");
+ sc = helper.getSecurityContext(this.securitydomain);
+ if ( sc == null){
+ Subject subject = this.loginContext.getSubject();
+ Principal principal = null;
+ for(Principal p:subject.getPrincipals()) {
+ if (this.userName.startsWith(p.getName())) {
+ principal = p;
+ break;
+ }
+ }
+ return helper.createSecurityContext(this.securitydomain, principal,
credentials, subject);
+ }
+ }
+ return sc;
+ }
+
+ static String getBaseUsername(String username) {
+ if (username == null) {
+ return username;
+ }
+
+ int index = getQualifierIndex(username);
+
+ String result = username;
+
+ if (index != -1) {
+ result = username.substring(0, index);
+ }
+
+ //strip the escape character from the remaining ats
+ return result.replaceAll("\\\\"+AT, AT); //$NON-NLS-1$
+ }
+
+ static String escapeName(String name) {
+ if (name == null) {
+ return name;
+ }
+
+ return name.replaceAll(AT, "\\\\"+AT); //$NON-NLS-1$
+ }
+
+ static String getDomainName(String username) {
+ if (username == null) {
+ return username;
+ }
+
+ int index = getQualifierIndex(username);
+
+ if (index != -1) {
+ return username.substring(index + 1);
+ }
+
+ return null;
+ }
+
+ static int getQualifierIndex(String username) {
+ int index = username.length();
+ while ((index = username.lastIndexOf(AT, --index)) != -1) {
+ if (index > 0 && username.charAt(index - 1) != '\\') {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+
+ private Collection<String> getDomainsForUser(List<String> domains, String
username) {
+ // If username is null, return all domains
+ if (username == null) {
+ return domains;
+ }
+
+ String domain = getDomainName(username);
+
+ if (domain == null) {
+ return domains;
+ }
+
+ // ------------------------------------------
+ // Handle usernames having @ sign
+ // ------------------------------------------
+ String domainHolder = null;
+ for (String d:domains) {
+ if(d.equalsIgnoreCase(domain)) {
+ domainHolder = d;
+ break;
+ }
+ }
+
+ if (domainHolder == null) {
+ return Collections.EMPTY_LIST;
+ }
+
+ LinkedList result = new LinkedList();
+ result.add(domainHolder);
+ return result;
+ }
+}
Property changes on:
branches/JCA/runtime/src/main/java/org/teiid/services/MembershipServiceImpl.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: branches/JCA/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
(from rev 1743,
branches/JCA/runtime/src/main/java/com/metamatrix/platform/security/session/service/SessionServiceImpl.java)
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,316 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.services;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.deployers.VDBRepository;
+
+import com.metamatrix.admin.api.exception.security.InvalidSessionException;
+import com.metamatrix.api.exception.security.SessionServiceException;
+import com.metamatrix.common.api.MMURL;
+import com.metamatrix.common.comm.api.ServerConnection;
+import com.metamatrix.common.log.LogManager;
+import com.metamatrix.common.util.LogConstants;
+import com.metamatrix.core.util.ArgCheck;
+import com.metamatrix.core.util.StringUtil;
+import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
+import com.metamatrix.metadata.runtime.api.VirtualDatabaseException;
+import com.metamatrix.platform.security.api.Credentials;
+import com.metamatrix.platform.security.api.SessionToken;
+import com.metamatrix.platform.security.api.service.SessionService;
+
+/**
+ * This class serves as the primary implementation of the Session Service.
+ */
+public class SessionServiceImpl implements SessionService, Serializable {
+ private static final long serialVersionUID = 3366022966048148299L;
+
+ public static final String SECURITY_DOMAINS = "securitydomains";
//$NON-NLS-1$
+
+ /*
+ * Configuration state
+ */
+ private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
+ private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
+ private VDBRepository vdbRepository;
+
+ private Map<Long, SessionMetadata> sessionCache = new
ConcurrentHashMap<Long, SessionMetadata>();
+ private transient Timer sessionMonitor = new Timer("SessionMonitor",
true);
+ private AtomicLong idSequence = new AtomicLong();
+ private boolean isSecurityEnabled = false;
+ private LinkedList<String> securityDomains = new LinkedList<String>();
+
+
+ //
-----------------------------------------------------------------------------------
+ // S E R V I C E - R E L A T E D M E T H O D S
+ //
-----------------------------------------------------------------------------------
+
+ private void monitorSessions() {
+ long currentTime = System.currentTimeMillis();
+ for (SessionMetadata info : sessionCache.values()) {
+ try {
+ if (currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5)
{
+ LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
+ closeSession(info.getSessionId());
+ } else if (sessionExpirationTimeLimit > 0 && currentTime -
info.getCreatedTime() > sessionExpirationTimeLimit) {
+ LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
+ closeSession(info.getSessionId());
+ }
+ } catch (Exception e) {
+ LogManager.logDetail(LogConstants.CTX_SESSION, e, "error running session
monitor, unable to monitor: " + info.getSessionId()); //$NON-NLS-1$
+ }
+ }
+ }
+
+ @Override
+ public void closeSession(long sessionID) throws InvalidSessionException {
+ LogManager.logDetail(LogConstants.CTX_SESSION, new Object[] {"closeSession",
sessionID}); //$NON-NLS-1$
+ SessionMetadata info = this.sessionCache.remove(sessionID);
+ if (info == null) {
+ throw new
InvalidSessionException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
sessionID)); //$NON-NLS-1$
+ }
+
+ // try to log out of the context.
+ try {
+ LoginContext context = info.getAttachment(LoginContext.class);
+ if (context != null) {
+ context.logout();
+ }
+ } catch (LoginException e) {
+ LogManager.logWarning(LogConstants.CTX_SESSION,e,"Exception terminitating
session"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public SessionMetadata createSession(String userName, Credentials credentials, String
applicationName, Properties properties)
+ throws LoginException, SessionServiceException {
+ ArgCheck.isNotNull(applicationName);
+ ArgCheck.isNotNull(properties);
+
+ Properties productInfo = new Properties();
+
+ LoginContext loginContext = null;
+ String securityDomain = "none";
+ Object securityContext = null;
+ if (this.isSecurityEnabled) {
+ // Authenticate user...
+ // if not authenticated, this method throws exception
+ MembershipServiceImpl membership = authenticate(userName, credentials,
applicationName);
+ loginContext = membership.getLoginContext();
+ userName = membership.getUserName();
+ securityDomain = membership.getSecurityDomain();
+ securityContext = membership.getSecurityContext();
+ }
+
+ // Validate VDB and version if logging on to server product...
+ VDBMetaData vdb = null;
+ String vdbName = properties.getProperty(MMURL.JDBC.VDB_NAME);
+ if (vdbName != null) {
+ String vdbVersion = properties.getProperty(MMURL.JDBC.VDB_VERSION);
+ try {
+ if (vdbVersion == null) {
+ vdb = this.vdbRepository.getActiveVDB(vdbName);
+ }
+ else {
+ vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
+ }
+
+ // Reset product info with validated constants
+ productInfo.put(MMURL.JDBC.VDB_NAME, vdb.getName());
+ productInfo.put(MMURL.JDBC.VDB_VERSION, vdb.getVersion());
+ } catch (VirtualDatabaseException e) {
+ throw new
SessionServiceException(DQPEmbeddedPlugin.Util.getString("VDBService.VDB_does_not_exist._2",
vdbName, vdbVersion==null?"latest":vdbVersion)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ if (sessionMaxLimit > 0 && getActiveSessionsCount() >=
sessionMaxLimit) {
+ throw new
SessionServiceException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.reached_max_sessions",
new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
+ }
+
+ long creationTime = System.currentTimeMillis();
+
+ // Return a new session info object
+ long id = idSequence.getAndIncrement();
+ SessionMetadata newSession = new SessionMetadata();
+ newSession.setSessionId(id);
+ newSession.setUserName(userName);
+ newSession.setCreatedTime(creationTime);
+ newSession.setApplicationName(applicationName);
+
newSession.setClientHostName(properties.getProperty(MMURL.CONNECTION.CLIENT_HOSTNAME));
+
newSession.setIPAddress(properties.getProperty(MMURL.CONNECTION.CLIENT_IP_ADDRESS));
+ newSession.setSecurityDomain(securityDomain);
+ if (vdb != null) {
+ newSession.setVDBName(vdb.getName());
+ newSession.setVDBVersion(vdb.getVersion());
+ }
+
+ // these are local no need for monitoring.
+ newSession.addAttchment(LoginContext.class, loginContext);
+ newSession.addAttchment("SecurityContext", securityContext);
+ newSession.addAttchment(VDBMetaData.class, vdb);
+ newSession.addAttchment(SessionToken.class, new SessionToken(id, userName));
+
+ this.sessionCache.put(newSession.getSessionId(), newSession);
+ return newSession;
+ }
+
+ protected MembershipServiceImpl authenticate(String userName, Credentials credentials,
String applicationName)
+ throws LoginException {
+ MembershipServiceImpl membership = new MembershipServiceImpl();
+ membership.authenticateUser(userName, credentials, applicationName,
this.securityDomains);
+ return membership;
+ }
+
+ @Override
+ public Collection<SessionMetadata> getActiveSessions() throws
SessionServiceException {
+ return new ArrayList<SessionMetadata>(this.sessionCache.values());
+ }
+
+ @Override
+ public SessionMetadata getActiveSession(long sessionID) {
+ return this.sessionCache.get(sessionID);
+ }
+
+ @Override
+ public int getActiveSessionsCount() throws SessionServiceException{
+ return this.sessionCache.size();
+ }
+
+ @Override
+ public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int
vdbVersion)
+ throws SessionServiceException {
+ if (VDBName == null || vdbVersion <= 0) {
+ return Collections.emptyList();
+ }
+ ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
+ for (SessionMetadata info : this.sessionCache.values()) {
+ if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion ==
info.getVDBVersion()) {
+ results.add(info);
+ }
+ }
+ return results;
+ }
+
+ @Override
+ public void pingServer(long sessionID) throws InvalidSessionException {
+ SessionMetadata info = getSessionInfo(sessionID);
+ info.setLastPingTime(System.currentTimeMillis());
+ this.sessionCache.put(sessionID, info);
+ }
+
+ @Override
+ public boolean terminateSession(long terminatedSessionID, long adminSessionID) {
+ Object[] params = {adminSessionID, terminatedSessionID};
+ LogManager.logInfo(LogConstants.CTX_SESSION, DQPEmbeddedPlugin.Util.getString(
"SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
+ try {
+ closeSession(terminatedSessionID);
+ return true;
+ } catch (InvalidSessionException e) {
+ LogManager.logWarning(LogConstants.CTX_SESSION,e,DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
new Object[] {e.getMessage()})); //$NON-NLS-1$
+ return false;
+ }
+ }
+
+ @Override
+ public SessionMetadata validateSession(long sessionID) throws InvalidSessionException,
SessionServiceException {
+ SessionMetadata info = getSessionInfo(sessionID);
+ return info;
+ }
+
+ private SessionMetadata getSessionInfo(long sessionID)
+ throws InvalidSessionException {
+ SessionMetadata info = this.sessionCache.get(sessionID);
+ if (info == null) {
+ throw new
InvalidSessionException(DQPEmbeddedPlugin.Util.getString("SessionServiceImpl.invalid_session",
sessionID)); //$NON-NLS-1$
+ }
+ return info;
+ }
+
+ public void setSessionMaxLimit(Long limit) {
+ this.sessionMaxLimit = limit.longValue();
+ }
+
+ public void setsessionExpirationTimeLimit(Long limit) {
+ this.sessionExpirationTimeLimit = limit.longValue();
+ }
+
+ public void setSecurityDomains(String domainNameOrder) {
+ if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
+ isSecurityEnabled = true;
+ }
+ LogManager.logDetail(LogConstants.CTX_MEMBERSHIP, "Security Enabled: "
+ isSecurityEnabled); //$NON-NLS-1$
+
+ if (isSecurityEnabled) {
+ List domainNames = StringUtil.split(domainNameOrder, ",");
//$NON-NLS-1$
+ Iterator domainNameItr = domainNames.iterator();
+ while ( domainNameItr.hasNext() ) {
+ String domainName = ((String) domainNameItr.next()).trim();
+ this.securityDomains.addLast(domainName);
+ }
+ }
+ }
+
+ public void start() {
+ this.sessionMonitor.schedule(new TimerTask() {
+ @Override
+ public void run() {
+ monitorSessions();
+ }
+ }, 0, ServerConnection.PING_INTERVAL * 5);
+ }
+
+ public void stop(){
+ this.sessionMonitor.cancel();
+ this.sessionCache.clear();
+ }
+
+ @Override
+ public void setLocalSession(long sessionID) {
+ SessionMetadata info = this.sessionCache.get(sessionID);
+ if (info != null) {
+ info.setLastPingTime(Long.MAX_VALUE);
+ }
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+}
Property changes on:
branches/JCA/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
branches/JCA/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java
===================================================================
---
branches/JCA/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -22,12 +22,13 @@
package com.metamatrix.dqp.service.buffer;
+import org.teiid.services.BufferServiceImpl;
+
import junit.framework.TestCase;
import com.metamatrix.common.buffer.impl.BufferManagerImpl;
import com.metamatrix.common.buffer.impl.FileStorageManager;
import com.metamatrix.core.util.UnitTestUtil;
-import com.metamatrix.dqp.embedded.services.EmbeddedBufferService;
public class TestLocalBufferService extends TestCase {
@@ -36,7 +37,7 @@
}
public void testMissingRequiredProperties() throws Exception {
- EmbeddedBufferService svc = new EmbeddedBufferService();
+ BufferServiceImpl svc = new BufferServiceImpl();
svc.setDiskDirectory(UnitTestUtil.getTestScratchPath()+"/teiid");
// These are defaults if none of the properties are set.
@@ -46,7 +47,7 @@
}
public void testCheckMemPropertyGotSet() throws Exception {
- EmbeddedBufferService svc = new EmbeddedBufferService();
+ BufferServiceImpl svc = new BufferServiceImpl();
svc.setDiskDirectory(UnitTestUtil.getTestScratchPath()+"/teiid/1");
svc.setBufferMemorySizeInMB(96);
svc.setUseDisk(true);
@@ -64,7 +65,7 @@
}
public void testCheckMemPropertyGotSet2() throws Exception {
- EmbeddedBufferService svc = new EmbeddedBufferService();
+ BufferServiceImpl svc = new BufferServiceImpl();
svc.setDiskDirectory(UnitTestUtil.getTestScratchPath()+"/teiid/1");
svc.setBufferMemorySizeInMB(96);
svc.setUseDisk(false);
Deleted:
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/membership/service/TestMembershipServiceImpl.java
===================================================================
---
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/membership/service/TestMembershipServiceImpl.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/membership/service/TestMembershipServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,75 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.platform.security.membership.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import junit.framework.TestCase;
-
-import org.mockito.Mockito;
-
-import com.metamatrix.platform.security.api.Credentials;
-
-public class TestMembershipServiceImpl extends TestCase {
-
-
- public void testBaseUsername() throws Exception {
-
- assertEquals("foo(a)bar.com",
MembershipServiceImpl.getBaseUsername("foo\\@bar.com(a)foo")); //$NON-NLS-1$
//$NON-NLS-2$
-
- assertEquals("foo",
MembershipServiceImpl.getDomainName("me\\@bar.com(a)foo")); //$NON-NLS-1$
//$NON-NLS-2$
-
- assertEquals(null, MembershipServiceImpl.getDomainName("@"));
//$NON-NLS-1$
-
- assertEquals("@",
MembershipServiceImpl.getBaseUsername("@")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private MembershipServiceImpl createMembershipService() throws Exception {
- MembershipServiceImpl membershipService = new MembershipServiceImpl() {
- public LoginContext createLoginContext(String domain, CallbackHandler handler) throws
LoginException {
- LoginContext context = Mockito.mock(LoginContext.class);
- return context;
- }
- };
- return membershipService;
- }
-
-
- public void testAuthenticate() throws Exception {
- MembershipServiceImpl ms = createMembershipService();
- List<String> domains = new ArrayList<String>();
- domains.add("testFile");
- ms.authenticateUser("user1", new
Credentials("pass1".toCharArray()), null, domains); //$NON-NLS-1$ //$NON-NLS-2$
-
- Mockito.verify(ms.getLoginContext()).login();
-
- assertEquals("user1@testFile", ms.getUserName()); //$NON-NLS-1$
- }
-
-
-}
Deleted:
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/session/service/TestSessionServiceImpl.java
===================================================================
---
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/session/service/TestSessionServiceImpl.java 2010-01-21
19:42:30 UTC (rev 1768)
+++
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/session/service/TestSessionServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -1,82 +0,0 @@
-package com.metamatrix.platform.security.session.service;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.Properties;
-
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.adminapi.impl.SessionMetadata;
-
-import com.metamatrix.admin.api.exception.security.InvalidSessionException;
-import com.metamatrix.platform.security.api.Credentials;
-import com.metamatrix.platform.security.membership.service.MembershipServiceImpl;
-
-public class TestSessionServiceImpl {
-
- public void validateSession(boolean securityEnabled) throws Exception {
- final MembershipServiceImpl impl = Mockito.mock(MembershipServiceImpl.class);
- Mockito.stub(impl.getUserName()).toReturn("steve@somedomain");
- Mockito.stub(impl.getLoginContext()).toReturn(Mockito.mock(LoginContext.class));
- final ArrayList<String> domains = new ArrayList<String>();
- domains.add("somedomain");
-
- SessionServiceImpl ssi = new SessionServiceImpl() {
- protected MembershipServiceImpl authenticate(String userName, Credentials credentials,
String applicationName)
- throws LoginException {
- impl.authenticateUser(userName, credentials, applicationName, domains);
- return impl;
- }
- };
-
- ssi.setSecurityDomains("somedomain");
-
- try {
- ssi.validateSession(1);
- fail("exception expected"); //$NON-NLS-1$
- } catch (InvalidSessionException e) {
-
- }
-
- SessionMetadata info = ssi.createSession("steve", null, "foo", new
Properties()); //$NON-NLS-1$ //$NON-NLS-2$
- if (securityEnabled) {
- Mockito.verify(impl).authenticateUser("steve", null, "foo",
domains);
- }
-
- long id1 = info.getSessionId();
- ssi.validateSession(id1);
-
- assertEquals(1, ssi.getActiveSessionsCount());
- assertEquals(0, ssi.getSessionsLoggedInToVDB("a", 1).size()); //$NON-NLS-1$
//$NON-NLS-2$
-
- ssi.closeSession(id1);
-
- try {
- ssi.validateSession(id1);
- fail("exception expected"); //$NON-NLS-1$
- } catch (InvalidSessionException e) {
-
- }
-
- try {
- ssi.closeSession(id1);
- fail("exception expected"); //$NON-NLS-1$
- } catch (InvalidSessionException e) {
-
- }
- }
-
- @Test public void testvalidateSession() throws Exception{
- validateSession(true);
- }
-
- @Test public void testvalidateSession2() throws Exception {
- validateSession(false);
- }
-
-}
Copied:
branches/JCA/runtime/src/test/java/org/teiid/services/TestMembershipServiceImpl.java (from
rev 1743,
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/membership/service/TestMembershipServiceImpl.java)
===================================================================
--- branches/JCA/runtime/src/test/java/org/teiid/services/TestMembershipServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/test/java/org/teiid/services/TestMembershipServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,76 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.services;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+import org.teiid.services.MembershipServiceImpl;
+
+import com.metamatrix.platform.security.api.Credentials;
+
+public class TestMembershipServiceImpl extends TestCase {
+
+
+ public void testBaseUsername() throws Exception {
+
+ assertEquals("foo(a)bar.com",
MembershipServiceImpl.getBaseUsername("foo\\@bar.com(a)foo")); //$NON-NLS-1$
//$NON-NLS-2$
+
+ assertEquals("foo",
MembershipServiceImpl.getDomainName("me\\@bar.com(a)foo")); //$NON-NLS-1$
//$NON-NLS-2$
+
+ assertEquals(null, MembershipServiceImpl.getDomainName("@"));
//$NON-NLS-1$
+
+ assertEquals("@",
MembershipServiceImpl.getBaseUsername("@")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ private MembershipServiceImpl createMembershipService() throws Exception {
+ MembershipServiceImpl membershipService = new MembershipServiceImpl() {
+ public LoginContext createLoginContext(String domain, CallbackHandler handler) throws
LoginException {
+ LoginContext context = Mockito.mock(LoginContext.class);
+ return context;
+ }
+ };
+ return membershipService;
+ }
+
+
+ public void testAuthenticate() throws Exception {
+ MembershipServiceImpl ms = createMembershipService();
+ List<String> domains = new ArrayList<String>();
+ domains.add("testFile");
+ ms.authenticateUser("user1", new
Credentials("pass1".toCharArray()), null, domains); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Mockito.verify(ms.getLoginContext()).login();
+
+ assertEquals("user1@testFile", ms.getUserName()); //$NON-NLS-1$
+ }
+
+
+}
Property changes on:
branches/JCA/runtime/src/test/java/org/teiid/services/TestMembershipServiceImpl.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: branches/JCA/runtime/src/test/java/org/teiid/services/TestSessionServiceImpl.java
(from rev 1743,
branches/JCA/runtime/src/test/java/com/metamatrix/platform/security/session/service/TestSessionServiceImpl.java)
===================================================================
--- branches/JCA/runtime/src/test/java/org/teiid/services/TestSessionServiceImpl.java
(rev 0)
+++
branches/JCA/runtime/src/test/java/org/teiid/services/TestSessionServiceImpl.java 2010-01-21
21:27:25 UTC (rev 1769)
@@ -0,0 +1,83 @@
+package org.teiid.services;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.Properties;
+
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.services.MembershipServiceImpl;
+import org.teiid.services.SessionServiceImpl;
+
+import com.metamatrix.admin.api.exception.security.InvalidSessionException;
+import com.metamatrix.platform.security.api.Credentials;
+
+public class TestSessionServiceImpl {
+
+ public void validateSession(boolean securityEnabled) throws Exception {
+ final MembershipServiceImpl impl = Mockito.mock(MembershipServiceImpl.class);
+ Mockito.stub(impl.getUserName()).toReturn("steve@somedomain");
+ Mockito.stub(impl.getLoginContext()).toReturn(Mockito.mock(LoginContext.class));
+ final ArrayList<String> domains = new ArrayList<String>();
+ domains.add("somedomain");
+
+ SessionServiceImpl ssi = new SessionServiceImpl() {
+ protected MembershipServiceImpl authenticate(String userName, Credentials credentials,
String applicationName)
+ throws LoginException {
+ impl.authenticateUser(userName, credentials, applicationName, domains);
+ return impl;
+ }
+ };
+
+ ssi.setSecurityDomains("somedomain");
+
+ try {
+ ssi.validateSession(1);
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (InvalidSessionException e) {
+
+ }
+
+ SessionMetadata info = ssi.createSession("steve", null, "foo", new
Properties()); //$NON-NLS-1$ //$NON-NLS-2$
+ if (securityEnabled) {
+ Mockito.verify(impl).authenticateUser("steve", null, "foo",
domains);
+ }
+
+ long id1 = info.getSessionId();
+ ssi.validateSession(id1);
+
+ assertEquals(1, ssi.getActiveSessionsCount());
+ assertEquals(0, ssi.getSessionsLoggedInToVDB("a", 1).size()); //$NON-NLS-1$
//$NON-NLS-2$
+
+ ssi.closeSession(id1);
+
+ try {
+ ssi.validateSession(id1);
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (InvalidSessionException e) {
+
+ }
+
+ try {
+ ssi.closeSession(id1);
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (InvalidSessionException e) {
+
+ }
+ }
+
+ @Test public void testvalidateSession() throws Exception{
+ validateSession(true);
+ }
+
+ @Test public void testvalidateSession2() throws Exception {
+ validateSession(false);
+ }
+
+}
Property changes on:
branches/JCA/runtime/src/test/java/org/teiid/services/TestSessionServiceImpl.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain