[MRM-1942] Merge branch 'jpa' into master

Removing JDO and add JPA backend.
This commit is contained in:
Martin Stockhammer 2017-05-19 21:47:48 +02:00
commit 3e73762394
88 changed files with 3533 additions and 5113 deletions

127
pom.xml
View File

@ -71,13 +71,15 @@
</distributionManagement>
<properties>
<springVersion>4.2.1.RELEASE</springVersion>
<springVersion>4.3.5.RELEASE</springVersion>
<slf4jVersion>1.7.12</slf4jVersion>
<log4j2Version>2.8.2</log4j2Version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<gpg.useagent>true</gpg.useagent>
<cxf.version>3.0.3</cxf.version>
<openjpa.version>2.4.1</openjpa.version>
<!--
<redbackTestJdbcUrl>jdbc:derby:memory:users-test;create=true</redbackTestJdbcUrl>
<redbackTestJdbcDriver>org.apache.derby.jdbc.EmbeddedDriver</redbackTestJdbcDriver>
@ -144,11 +146,6 @@
<artifactId>redback-policy</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jdo</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-ldap</artifactId>
@ -181,7 +178,7 @@
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-jdo</artifactId>
<artifactId>redback-keys-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@ -216,7 +213,7 @@
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-jdo</artifactId>
<artifactId>redback-users-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@ -271,7 +268,7 @@
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-jdo</artifactId>
<artifactId>redback-rbac-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@ -299,6 +296,11 @@
<artifactId>redback-integrations-security</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jpa</artifactId>
<version>2.5-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
@ -385,35 +387,7 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback.components</groupId>
<artifactId>spring-jdo2</artifactId>
<version>2.2</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xmlParserAPIs</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Other -->
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<!-- must run at xalan 2.7.0, as ealier versions embed an ancient version
of bcel, which iterferes with the ability of jpox/jdo to run -->
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<!-- Xalan 2.7.0 requires xml-apis version 1.3.02+ -->
<version>1.3.03</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
@ -481,6 +455,11 @@
<artifactId>spring-core</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
@ -511,6 +490,16 @@
<artifactId>spring-test</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
@ -531,45 +520,6 @@
<artifactId>redback-rest-services</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>jpox</groupId>
<artifactId>jpox</artifactId>
<version>1.1.9-1</version>
<scope>compile</scope>
<exclusions>
<!-- targeting JDK 1.4 we don't need this -->
<exclusion>
<groupId>javax.sql</groupId>
<artifactId>jdbc-stdext</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>javax.resource</groupId>
<artifactId>connector</artifactId>
</exclusion>
<exclusion>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jpox</groupId>
<artifactId>jpox-ehcache</artifactId>
<version>1.1.9</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@ -685,22 +635,10 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jpox-maven-plugin</artifactId>
<version>1.1.7</version>
<dependencies>
<dependency>
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>6.0</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId>
@ -721,9 +659,9 @@
</configuration>
</plugin>
<plugin>
<groupId>org.apache.archiva.redback.components.modello</groupId>
<artifactId>jpox-modello-maven-plugin</artifactId>
<version>1.0</version>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>${openjpa.version}</version>
</plugin>
</plugins>
</pluginManagement>
@ -804,6 +742,7 @@
<exclude>build-number.txt</exclude>
<!-- IntelliJ IDEA files -->
<exclude>.idea/**</exclude>
<exclude>**/*.iml</exclude>
<!-- Eclipse files -->
<exclude>.project</exclude>
<exclude>.classpath</exclude>
@ -931,7 +870,7 @@
<descriptorRefs>
<descriptorRef>${sourceReleaseAssemblyDescriptor}</descriptorRef>
</descriptorRefs>
<tarLongFileFormat>gnu</tarLongFileFormat>
<tarLongFileMode>gnu</tarLongFileMode>
</configuration>
</execution>
</executions>

View File

@ -19,9 +19,9 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="true">
<bean name="authenticator#user-manager" class="org.apache.archiva.redback.authentication.users.UserManagerAuthenticator">
@ -35,4 +35,30 @@
<alias name="userManager#configurable" alias="userManager#default"/>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -19,9 +19,9 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="true">
<bean name="userManager#cached" class="org.apache.archiva.redback.users.cached.CachedUserManager">
@ -46,4 +46,37 @@
<alias name="userConfiguration#redback" alias="userConfiguration#default"/>
<alias name="userManager#configurable" alias="userManager#default"/>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -17,7 +17,8 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.archiva.redback</groupId>
@ -28,8 +29,8 @@
<name>Redback :: Commons</name>
<packaging>pom</packaging>
<modules>
<module>redback-common-jdo</module>
<module>redback-common-ldap</module>
<module>redback-common-test-resources</module>
<module>redback-common-jpa</module>
</modules>
</project>

View File

@ -1,116 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common</artifactId>
<version>2.7-SNAPSHOT</version>
</parent>
<artifactId>redback-common-jdo</artifactId>
<packaging>bundle</packaging>
<name>Redback :: JDO Common API</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback.components</groupId>
<artifactId>spring-jdo2</artifactId>
</dependency>
<dependency>
<groupId>jpox</groupId>
<artifactId>jpox</artifactId>
<scope>compile</scope>
<exclusions>
<!-- targeting JDK 1.4 we don't need this -->
<exclusion>
<groupId>javax.sql</groupId>
<artifactId>jdbc-stdext</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>javax.resource</groupId>
<artifactId>connector</artifactId>
</exclusion>
<exclusion>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-configuration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Export-Package>
org.apache.archiva.redback.common.jdo*;version=${project.version};-split-package:=merge-first
</Export-Package>
<Import-Package>
javax.annotation,
javax.inject;version="[1,2)",
javax.jdo;version="[2,3)",
org.apache.archiva.redback.components.jdo;version=${project.version},
org.apache.archiva.redback.configuration;version=${project.version},
org.apache.commons.lang;version="[2.6,3)",
org.codehaus.plexus.interpolation;version="[1.9,2)",
org.jpox*;version="[1.1,2)",
org.springframework.stereotype;version="[3,4)",
org.slf4j;resolution:=optional
</Import-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,132 +0,0 @@
package org.apache.archiva.redback.common.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.configuration.UserConfiguration;
import org.apache.commons.lang.StringUtils;
import org.codehaus.plexus.interpolation.InterpolationException;
import org.codehaus.plexus.interpolation.PropertiesBasedValueSource;
import org.codehaus.plexus.interpolation.StringSearchInterpolator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
/**
* UserConfigurableJdoFactory
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*/
@Service("jdoFactory#users")
public class UserConfigurableJdoFactory
extends DefaultConfigurableJdoFactory
{
private Logger log = LoggerFactory.getLogger( getClass() );
private UserConfiguration userConfiguration;
@Inject
public UserConfigurableJdoFactory(
@Named( value = "userConfiguration#default" ) UserConfiguration userConfiguration )
{
this.userConfiguration = userConfiguration;
}
private String getConfigString( String key, String currentValue, String defaultValue )
{
String valueFromSysProps = System.getProperty( "redback." + key );
if ( StringUtils.isNotEmpty( valueFromSysProps ) )
{
return valueFromSysProps;
}
String value = null;
if ( StringUtils.isNotEmpty( currentValue ) )
{
value = userConfiguration.getString( key, currentValue );
}
else
{
value = userConfiguration.getString( key, defaultValue );
}
// do some interpolation as we can have some ${plexus.home} etc...
StringSearchInterpolator interpolator = new StringSearchInterpolator();
interpolator.addValueSource( new PropertiesBasedValueSource( System.getProperties() ) );
try
{
return interpolator.interpolate( value );
}
catch ( InterpolationException e )
{
// ignore interpolation issue
log.warn( "skip issue during interpolation {}", e.getMessage() );
return value;
}
}
@PostConstruct
public void initialize()
{
String jdbcDriverName =
getConfigString( "jdbc.driver.name", super.getDriverName(), "org.apache.derby.jdbc.EmbeddedDriver" );
String jdbcUrl =
getConfigString( "jdbc.url", super.getUrl(), "jdbc:derby:${plexus.home}/database;create=true" );
String jdbcUsername = getConfigString( "jdbc.username", super.getUserName(), "sa" );
String jdbcPassword = getConfigString( "jdbc.password", super.getPassword(), "" );
super.setDriverName( jdbcDriverName );
super.setUrl( jdbcUrl );
super.setUserName( jdbcUsername );
super.setPassword( jdbcPassword );
if ( StringUtils.isEmpty( super.persistenceManagerFactoryClass ) )
{
super.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" );
}
if ( ( super.otherProperties == null ) || super.otherProperties.isEmpty() )
{
super.setProperty( "org.jpox.autoCreateSchema", "true" );
super.setProperty( "org.jpox.validateSchema", "false" );
super.setProperty( "org.jpox.validateTables", "false" );
super.setProperty( "org.jpox.validateConstraints", "false" );
super.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" );
super.setProperty( "org.jpox.rdbms.dateTimezone", "JDK_DEFAULT_TIMEZONE" );
}
super.initialize();
}
public UserConfiguration getUserConfiguration()
{
return userConfiguration;
}
public void setUserConfiguration( UserConfiguration userConfiguration )
{
this.userConfiguration = userConfiguration;
}
}

View File

@ -1,113 +0,0 @@
package org.apache.archiva.redback.common.jdo.test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.jdo.PersistenceManager;
import org.jpox.AbstractPersistenceManagerFactory;
import org.jpox.ClassLoaderResolver;
import org.jpox.plugin.ConfigurationElement;
import org.jpox.plugin.Extension;
import org.jpox.store.rdbms.RDBMSManager;
/**
* A extension to JPOX store manager that allows counting the SQL queries
*
* @author Carlos Sanchez
*/
public class StoreManagerDebug
extends RDBMSManager
{
private static int counter;
public StoreManagerDebug( ClassLoaderResolver clr, AbstractPersistenceManagerFactory pmf, String userName,
String password )
{
super( clr, pmf, userName, password );
}
/**
* This method will change JPOX store manager extension so it uses our class instead of whatever is configured in
* the plugin.xml
*
* @param pmf
*/
public static void setup( AbstractPersistenceManagerFactory pmf )
{
/* set our own Store Manager to allow counting SQL statements */
Extension[] extensions =
pmf.getPMFContext().getPluginManager().getExtensionPoint( "org.jpox.store_manager" ).getExtensions();
Extension e = extensions[0];
for ( ConfigurationElement element : e.getConfigurationElements() )
{
element.putAttribute( "class-name", StoreManagerDebug.class.getName() );
}
}
/**
* Get the currently configured store manager from JPOX. Will fail if
* {@link #setup(AbstractPersistenceManagerFactory)} is not called first.
*
* @param persistenceManager
* @return
*/
public static StoreManagerDebug getConfiguredStoreManager( PersistenceManager persistenceManager )
{
return (StoreManagerDebug) ( (org.jpox.PersistenceManager) persistenceManager ).getStoreManager();
}
@Override
public int[] executeStatementBatch( String stmt, PreparedStatement ps )
throws SQLException
{
counter++;
return super.executeStatementBatch( stmt, ps );
}
@Override
public ResultSet executeStatementQuery( String stmt, PreparedStatement ps )
throws SQLException
{
counter++;
return super.executeStatementQuery( stmt, ps );
}
@Override
public int executeStatementUpdate( String stmt, PreparedStatement ps )
throws SQLException
{
counter++;
return super.executeStatementUpdate( stmt, ps );
}
public void resetCounter()
{
counter = 0;
}
public int counter()
{
return counter;
}
}

View File

@ -1,35 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.common.jdo.UserConfigurableJdoFactory">
<constructor-arg>
<ref bean="userConfiguration#default"/>
</constructor-arg>
<!--
<property name="config" ref="userConfiguration#default"/>
-->
</bean>
</beans>

View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>redback-common</artifactId>
<groupId>org.apache.archiva.redback</groupId>
<version>2.5-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>redback-common-jpa</artifactId>
<packaging>jar</packaging>
<name>Redback :: JPA Common Package</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-model</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${openjpa.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="redback-jpa">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.apache.archiva.redback.users.jpa.model.JpaUser</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaOperation</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaResource</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaPermission</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaRole</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaUserAssignment</class>
<class>org.apache.archiva.redback.keys.jpa.model.JpaAuthenticationKey</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database"/>
<property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/>
<property name="openjpa.ConnectionUserName" value="sa"/>
<property name="openjpa.ConnectionPassword" value=""/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
<property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)" />
<property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
<property name="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.jdbc.DBDictionary" value="(disableSchemaFactoryColumnTypeErrors=true,BitTypeName=CHAR(1),BooleanTypeName=CHAR(1),BooleanRepresentation=STRING_YN)"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="redback-jpa">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<non-jta-data-source>java:comp/env/jdbc/users</non-jta-data-source>
<class>org.apache.archiva.redback.users.jpa.model.JpaUser</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaOperation</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaResource</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaPermission</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaRole</class>
<class>org.apache.archiva.redback.rbac.jpa.model.JpaUserAssignment</class>
<class>org.apache.archiva.redback.keys.jpa.model.JpaAuthenticationKey</class>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
<property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)" />
<property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
<property name="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.jdbc.DBDictionary" value="(disableSchemaFactoryColumnTypeErrors=true,BitTypeName=CHAR(1),BooleanTypeName=CHAR(1),BooleanRepresentation=STRING_YN)"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -130,7 +130,7 @@ ldap.bind.authenticator.enabled=false
#ldap.config.authentication.method=
# config parameter for the ConfigurableUserManager
user.manager.impl=jdo
user.manager.impl=jpa
# REST security settings

View File

@ -35,15 +35,15 @@
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-jdo</artifactId>
<artifactId>redback-users-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-jdo</artifactId>
<artifactId>redback-rbac-model</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-jdo</artifactId>
<artifactId>redback-keys-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@ -88,6 +88,10 @@
<artifactId>jul-to-slf4j</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -1,307 +0,0 @@
package org.apache.archiva.redback.management;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.keys.jdo.AuthenticationKeyDatabase;
import org.apache.archiva.redback.keys.jdo.io.stax.RedbackKeyManagementJdoStaxReader;
import org.apache.archiva.redback.keys.jdo.io.stax.RedbackKeyManagementJdoStaxWriter;
import org.apache.archiva.redback.rbac.Operation;
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.rbac.Role;
import org.apache.archiva.redback.rbac.jdo.RbacDatabase;
import org.apache.archiva.redback.rbac.jdo.io.stax.RbacJdoModelStaxReader;
import org.apache.archiva.redback.rbac.jdo.io.stax.RbacJdoModelStaxWriter;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rbac.Resource;
import org.apache.archiva.redback.rbac.UserAssignment;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.jdo.UserDatabase;
import org.apache.archiva.redback.users.jdo.io.stax.UsersManagementStaxReader;
import org.apache.archiva.redback.users.jdo.io.stax.UsersManagementStaxWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
/**
* JDO implementation of the data management tool.
*
* TODO do we really need JDO specifics here? Could optimize by going straight to JDOFactory
* TODO check whether this current method logs everything unnecessarily.
*/
@Service("dataManagementTool#jdo")
public class JdoDataManagementTool
implements DataManagementTool
{
private static final String USERS_XML_NAME = "users.xml";
private static final String KEYS_XML_NAME = "keys.xml";
private static final String RBAC_XML_NAME = "rbac.xml";
public void backupRBACDatabase( RBACManager manager, File backupDirectory )
throws RbacManagerException, IOException, XMLStreamException
{
RbacDatabase database = new RbacDatabase();
database.setRoles( manager.getAllRoles() );
database.setUserAssignments( manager.getAllUserAssignments() );
database.setPermissions( manager.getAllPermissions() );
database.setOperations( manager.getAllOperations() );
database.setResources( manager.getAllResources() );
RbacJdoModelStaxWriter writer = new RbacJdoModelStaxWriter();
Writer fileWriter = createWriter( backupDirectory, RBAC_XML_NAME, database.getModelEncoding() );
try
{
writer.write( fileWriter, database );
}
finally
{
IOUtils.closeQuietly( fileWriter );
}
}
public void backupUserDatabase( UserManager manager, File backupDirectory )
throws IOException, XMLStreamException, UserManagerException
{
UserDatabase database = new UserDatabase();
database.setUsers( manager.getUsers() );
UsersManagementStaxWriter writer = new UsersManagementStaxWriter();
Writer fileWriter = createWriter( backupDirectory, USERS_XML_NAME, database.getModelEncoding() );
try
{
writer.write( fileWriter, database );
}
finally
{
IOUtils.closeQuietly( fileWriter );
}
}
public void backupKeyDatabase( KeyManager manager, File backupDirectory )
throws IOException, XMLStreamException
{
try
{
manager.removeExpiredKeys();
}
catch ( KeyManagerException e )
{
throw new IOException( "Error removing expired keys" );
}
AuthenticationKeyDatabase database = new AuthenticationKeyDatabase();
database.setKeys( manager.getAllKeys() );
RedbackKeyManagementJdoStaxWriter writer = new RedbackKeyManagementJdoStaxWriter();
Writer fileWriter = createWriter( backupDirectory, KEYS_XML_NAME, database.getModelEncoding() );
try
{
writer.write( fileWriter, database );
}
finally
{
IOUtils.closeQuietly( fileWriter );
}
}
@SuppressWarnings("unchecked")
public void restoreRBACDatabase( RBACManager manager, File backupDirectory )
throws IOException, XMLStreamException, RbacManagerException
{
RbacJdoModelStaxReader reader = new RbacJdoModelStaxReader();
FileReader fileReader = new FileReader( new File( backupDirectory, RBAC_XML_NAME ) );
RbacDatabase database;
try
{
database = reader.read( fileReader );
}
finally
{
IOUtils.closeQuietly( fileReader );
}
Map<String, Permission> permissionMap = new HashMap<String, Permission>();
Map<String, Resource> resources = new HashMap<String, Resource>();
Map<String, Operation> operations = new HashMap<String, Operation>();
for ( Role role : (List<Role>) database.getRoles() )
{
// TODO: this could be generally useful and put into saveRole itself as long as the performance penalty isn't too harsh.
// Currently it always saves everything where it could pull pack the existing permissions, etc if they exist
List<Permission> permissions = new ArrayList<Permission>();
for ( Permission permission : role.getPermissions() )
{
if ( permissionMap.containsKey( permission.getName() ) )
{
permission = permissionMap.get( permission.getName() );
}
else if ( manager.permissionExists( permission ) )
{
permission = manager.getPermission( permission.getName() );
permissionMap.put( permission.getName(), permission );
}
else
{
Operation operation = permission.getOperation();
if ( operations.containsKey( operation.getName() ) )
{
operation = operations.get( operation.getName() );
}
else if ( manager.operationExists( operation ) )
{
operation = manager.getOperation( operation.getName() );
operations.put( operation.getName(), operation );
}
else
{
operation = manager.saveOperation( operation );
operations.put( operation.getName(), operation );
}
permission.setOperation( operation );
Resource resource = permission.getResource();
if ( resources.containsKey( resource.getIdentifier() ) )
{
resource = resources.get( resource.getIdentifier() );
}
else if ( manager.resourceExists( resource ) )
{
resource = manager.getResource( resource.getIdentifier() );
resources.put( resource.getIdentifier(), resource );
}
else
{
resource = manager.saveResource( resource );
resources.put( resource.getIdentifier(), resource );
}
permission.setResource( resource );
permission = manager.savePermission( permission );
permissionMap.put( permission.getName(), permission );
}
permissions.add( permission );
}
role.setPermissions( permissions );
manager.saveRole( role );
}
for ( UserAssignment userAssignment : (List<UserAssignment>) database.getUserAssignments() )
{
manager.saveUserAssignment( userAssignment );
}
}
@SuppressWarnings("unchecked")
public void restoreUsersDatabase( UserManager manager, File backupDirectory )
throws IOException, XMLStreamException, UserManagerException
{
UsersManagementStaxReader reader = new UsersManagementStaxReader();
FileReader fileReader = new FileReader( new File( backupDirectory, USERS_XML_NAME ) );
UserDatabase database;
try
{
database = reader.read( fileReader );
}
finally
{
IOUtils.closeQuietly( fileReader );
}
for ( User user : (List<User>) database.getUsers() )
{
manager.addUserUnchecked( user );
}
}
@SuppressWarnings("unchecked")
public void restoreKeysDatabase( KeyManager manager, File backupDirectory )
throws IOException, XMLStreamException
{
RedbackKeyManagementJdoStaxReader reader = new RedbackKeyManagementJdoStaxReader();
FileReader fileReader = new FileReader( new File( backupDirectory, KEYS_XML_NAME ) );
AuthenticationKeyDatabase database;
try
{
database = reader.read( fileReader );
}
finally
{
IOUtils.closeQuietly( fileReader );
}
for ( AuthenticationKey key : (List<AuthenticationKey>) database.getKeys() )
{
manager.addKey( key );
}
}
public void eraseRBACDatabase( RBACManager manager )
{
manager.eraseDatabase();
}
public void eraseUsersDatabase( UserManager manager )
{
manager.eraseDatabase();
}
public void eraseKeysDatabase( KeyManager manager )
{
manager.eraseDatabase();
}
private Writer createWriter( File directory, String file, String encoding )
throws FileNotFoundException
{
File f = new File( directory, file );
File parentFile = f.getParentFile();
parentFile.mkdirs();
FileOutputStream out = new FileOutputStream( f );
return new OutputStreamWriter( out, Charset.forName( encoding ) );
}
}

View File

@ -20,24 +20,24 @@ package org.apache.archiva.redback.management;
*/
import junit.framework.TestCase;
import org.apache.archiva.redback.common.jdo.UserConfigurableJdoFactory;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.rbac.Role;
import org.apache.archiva.redback.rbac.UserAssignment;
import org.apache.archiva.redback.tests.utils.RBACDefaults;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.tests.utils.RBACDefaults;
import org.apache.archiva.redback.users.User;
import org.custommonkey.xmlunit.XMLAssert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
@ -57,6 +57,8 @@ import java.util.List;
import java.util.Locale;
// @TODO: Investigate how to implement export with JPA
@Ignore("Currently no JPA implementation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" })
public class DataManagementTest
@ -68,20 +70,16 @@ public class DataManagementTest
private File targetDirectory;
@Inject
@Named(value = "jdoFactory#users")
UserConfigurableJdoFactory jdoFactory;
@Inject
@Named(value = "userManager#jdo")
@Named(value = "userManager#jpa")
UserManager userManager;
@Inject
@Named(value = "keyManager#jdo")
@Named(value = "keyManager#jpa")
KeyManager keyManager;
@Inject
@Named(value = "rbacManager#jdo")
@Named(value = "rbacManager#jpa")
RBACManager rbacManager;
@Before

View File

@ -20,33 +20,45 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder system-properties-mode="OVERRIDE"/>
<bean name="jdoFactory#users" class="org.apache.archiva.redback.common.jdo.UserConfigurableJdoFactory">
<constructor-arg>
<ref bean="userConfiguration#default"/>
</constructor-arg>
<!--
<property name="config" ref="userConfiguration#default"/>
-->
<!--
<property name="driverName" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="url" value="jdbc:derby:memory:users-test" />
-->
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
</bean>
<alias name="userConfiguration#redback" alias="userConfiguration#default"/>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -21,12 +21,10 @@ package org.apache.archiva.redback.integration.mail;
import junit.framework.TestCase;
import net.sf.ehcache.CacheManager;
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.policy.UserSecurityPolicy;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.jpox.SchemaTool;
import org.apache.archiva.redback.policy.UserSecurityPolicy;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -37,11 +35,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.net.URL;
import java.util.Map.Entry;
import java.util.Properties;
/**
* Test the Mailer class.
@ -67,9 +60,7 @@ public class MailGeneratorTest
@Named(value = "keyManager#memory")
private KeyManager keyManager;
@Inject
@Named(value = "jdoFactory#users")
DefaultConfigurableJdoFactory jdoFactory;
private Logger log = LoggerFactory.getLogger( getClass() );
@ -80,33 +71,6 @@ public class MailGeneratorTest
CacheManager.getInstance().clearAll();
super.setUp();
jdoFactory.setPassword( "" );
jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
Properties properties = jdoFactory.getProperties();
for ( Entry<Object, Object> entry : properties.entrySet() )
{
System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
}
SchemaTool.createSchemaTables( new URL[] { getClass()
.getResource( "/org/apache/archiva/redback/keys/jdo/package.jdo" ) }, new URL[] {}, null, false, null ); //$NON-NLS-1$
log.info( "jdoFactory driverName {} " , jdoFactory.getDriverName() );
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
}

View File

@ -20,28 +20,14 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder system-properties-mode="OVERRIDE"/>
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#custom-url" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="configs">
<list>
@ -57,4 +43,36 @@
<alias name="userConfiguration#redback" alias="userConfiguration#default"/>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -74,6 +74,10 @@
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-memory</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>

View File

@ -28,7 +28,7 @@ import org.apache.archiva.redback.authentication.TokenManager;
import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.keys.jdo.JdoAuthenticationKey;
import org.apache.archiva.redback.keys.jpa.model.JpaAuthenticationKey;
import org.apache.archiva.redback.keys.memory.MemoryAuthenticationKey;
import org.apache.archiva.redback.keys.memory.MemoryKeyManager;
import org.apache.archiva.redback.policy.AccountLockedException;
@ -101,7 +101,7 @@ public class DefaultLoginService
}
else
{
key = new JdoAuthenticationKey();
key = new JpaAuthenticationKey();
}
key.setKey( providedKey );

View File

@ -36,11 +36,11 @@ public class FakeCreateAdminServiceImpl
implements FakeCreateAdminService
{
@Inject
@Named( value = "rbacManager#jdo" )
@Named( value = "rbacManager#jpa" )
private RBACManager rbacManager;
@Inject
@Named( value = "userManager#jdo" )
@Named( value = "userManager#jpa" )
private UserManager userManager;
@Inject

View File

@ -16,5 +16,5 @@
# specific language governing permissions and limitations
# under the License.
#
user.manager.impl=jdo
rest.csrffilter.disableTokenValidation=true
user.manager.impl=jpa

View File

@ -19,9 +19,9 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<alias name="userConfiguration#redback" alias="userConfiguration#default"/>
@ -48,4 +48,36 @@
<alias name="userManager#configurable" alias="userManager#default"/>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -28,7 +28,7 @@
<name>Redback :: Key Management Providers</name>
<packaging>pom</packaging>
<modules>
<module>redback-keys-jdo</module>
<module>redback-keys-jpa</module>
<module>redback-keys-memory</module>
<module>redback-keys-cached</module>
</modules>

View File

@ -44,13 +44,17 @@
<groupId>org.apache.archiva.redback.components.cache</groupId>
<artifactId>spring-cache-ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-configuration</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-jdo</artifactId>
<artifactId>redback-keys-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>

View File

@ -43,7 +43,7 @@ public class CachedKeyManager
implements KeyManager
{
@Inject
@Named(value = "keyManager#jdo")
@Named(value = "keyManager#jpa")
private KeyManager keyImpl;
@Inject

View File

@ -20,25 +20,11 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
@ -60,4 +46,30 @@
<property name="timeToLiveSeconds" value="14400"/>
</bean>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -1,170 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-providers</artifactId>
<version>2.7-SNAPSHOT</version>
</parent>
<artifactId>redback-keys-jdo</artifactId>
<packaging>jar</packaging>
<name>Redback :: Key Management Provider :: JDO</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jdo</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.stax-utils</groupId>
<artifactId>stax-utils</artifactId>
<version>20060502</version>
<exclusions>
<exclusion>
<groupId>com.bea.xml</groupId>
<artifactId>jsr173-ri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/keys.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-java</id>
<goals>
<goal>java</goal>
<goal>stax-reader</goal>
<goal>stax-writer</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.archiva.redback.components.modello</groupId>
<artifactId>jpox-modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/keys.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-jpox</id>
<goals>
<goal>jpox-metadata-class</goal>
</goals>
</execution>
<execution>
<id>jpox-jdo-mapping</id>
<goals>
<goal>jpox-jdo-mapping</goal>
</goals>
<configuration>
<outputDirectory>${project.build.outputDirectory}/org/apache/archiva/redback/keys/jdo</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jpox-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,187 +0,0 @@
package org.apache.archiva.redback.keys.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.components.jdo.JdoFactory;
import org.apache.archiva.redback.components.jdo.RedbackJdoUtils;
import org.apache.archiva.redback.components.jdo.RedbackObjectNotFoundException;
import org.apache.archiva.redback.components.jdo.RedbackStoreException;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.AbstractKeyManager;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.apache.archiva.redback.keys.KeyNotFoundException;
import org.codehaus.plexus.util.StringUtils;
import org.jpox.PersistenceManagerFactoryImpl;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.util.Calendar;
import java.util.List;
/**
* JdoKeyManager
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*
*/
@Service( "keyManager#jdo" )
public class JdoKeyManager
extends AbstractKeyManager
{
@Inject
@Named( value = "jdoFactory#users" )
private JdoFactory jdoFactory;
private PersistenceManagerFactory pmf;
public AuthenticationKey createKey( String principal, String purpose, int expirationMinutes )
throws KeyManagerException
{
JdoAuthenticationKey authkey = new JdoAuthenticationKey();
authkey.setKey( super.generateUUID() );
authkey.setForPrincipal( principal );
authkey.setPurpose( purpose );
Calendar now = getNowGMT();
authkey.setDateCreated( now.getTime() );
if ( expirationMinutes >= 0 )
{
Calendar expiration = getNowGMT();
expiration.add( Calendar.MINUTE, expirationMinutes );
authkey.setDateExpires( expiration.getTime() );
}
return addKey( authkey );
}
public AuthenticationKey addKey( AuthenticationKey key )
{
return (AuthenticationKey) RedbackJdoUtils.addObject( getPersistenceManager(), key );
}
public void eraseDatabase()
{
RedbackJdoUtils.removeAll( getPersistenceManager(), JdoAuthenticationKey.class );
RedbackJdoUtils.removeAll( getPersistenceManager(), RedbackKeyManagementJdoModelloMetadata.class );
}
public AuthenticationKey findKey( String key )
throws KeyNotFoundException, KeyManagerException
{
if ( StringUtils.isEmpty( key ) )
{
throw new KeyNotFoundException( "Empty key not found." );
}
try
{
JdoAuthenticationKey authkey = (JdoAuthenticationKey) RedbackJdoUtils.getObjectById(
getPersistenceManager(), JdoAuthenticationKey.class, key );
if ( authkey == null )
{
throw new KeyNotFoundException( "Key [" + key + "] not found." );
}
assertNotExpired( authkey );
return authkey;
}
catch ( RedbackObjectNotFoundException e )
{
throw new KeyNotFoundException( e.getMessage() );
}
catch ( RedbackStoreException e )
{
throw new KeyManagerException(
"Unable to get " + JdoAuthenticationKey.class.getName() + "', key '" + key + "' from jdo store." );
}
}
public void deleteKey( AuthenticationKey authkey )
throws KeyManagerException
{
RedbackJdoUtils.removeObject( getPersistenceManager(), authkey );
}
public void deleteKey( String key )
throws KeyManagerException
{
try
{
AuthenticationKey authkey = findKey( key );
RedbackJdoUtils.removeObject( getPersistenceManager(), authkey );
}
catch ( KeyNotFoundException e )
{
// not found? nothing to do.
}
}
@SuppressWarnings( "unchecked" )
public List<AuthenticationKey> getAllKeys()
{
return RedbackJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoAuthenticationKey.class );
}
@PostConstruct
public void initialize()
{
pmf = jdoFactory.getPersistenceManagerFactory();
if ( pmf instanceof PersistenceManagerFactoryImpl )
{
PersistenceManagerFactoryImpl jpoxpmf = (PersistenceManagerFactoryImpl) pmf;
if ( !StringUtils.equals( "JDK_DEFAULT_TIMEZONE", jpoxpmf.getDateTimezone() ) )
{
throw new RuntimeException( "The JdoFactory property 'org.jpox.rdbms.dateTimezone' MUST BE "
+ "Set to 'JDK_DEFAULT_TIMEZONE' in order for jpox and JdoKeyManager to operate correctly." );
}
}
}
private PersistenceManager getPersistenceManager()
{
PersistenceManager pm = pmf.getPersistenceManager();
pm.getFetchPlan().setMaxFetchDepth( 5 );
return pm;
}
public String getId()
{
return "JDO Key Manager - " + this.getClass().getName();
}
public JdoFactory getJdoFactory()
{
return jdoFactory;
}
public void setJdoFactory( JdoFactory jdoFactory )
{
this.jdoFactory = jdoFactory;
}
}

View File

@ -1,89 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<model>
<id>redback-keys-jdo</id>
<name>RedbackKeyManagementJdo</name>
<version>1.0.1</version>
<description>Archiva Redback :: Key Management JDO Store.</description>
<defaults>
<default>
<key>package</key>
<value>org.apache.archiva.redback.keys.jdo</value>
</default>
</defaults>
<classes>
<class stash.storable="false" rootElement="true">
<name>AuthenticationKeyDatabase</name>
<version>1.0.1+</version>
<fields>
<field jpox.column="AUTH_KEYS">
<name>keys</name>
<version>1.0.1+</version>
<association>
<type>JdoAuthenticationKey</type>
<multiplicity>*</multiplicity>
</association>
</field>
</fields>
</class>
<class stash.storable="true" jpox.use-identifiers-as-primary-key="false">
<name>JdoAuthenticationKey</name>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.keys.AuthenticationKey</interface>
</interfaces>
<fields>
<field jpox.primary-key="true"
jpox.value-strategy="off"
jpox.persistence-modifier="persistent"
jpox.column="AUTHKEY">
<name>key</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>forPrincipal</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>purpose</name>
<version>1.0.0+</version>
<type>String</type>
</field>
<field xml.format="long">
<name>dateCreated</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
<field xml.format="long">
<name>dateExpires</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
</fields>
</class>
</classes>
</model>

View File

@ -1,102 +0,0 @@
package org.apache.archiva.redback.keys.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.keys.KeyManagerTestCase;
import org.jpox.SchemaTool;
import org.junit.Before;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
/**
* JdoKeyManagerTest
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*
*/
public class JdoKeyManagerTest
extends KeyManagerTestCase
{
@Inject
@Named(value = "jdoFactory#users")
DefaultConfigurableJdoFactory jdoFactory;
@Inject @Named(value = "keyManager#jdo")
KeyManager keyManager;
@Before
public void setUp()
throws Exception
{
super.setUp();
assertEquals( DefaultConfigurableJdoFactory.class.getName(), jdoFactory.getClass().getName() );
jdoFactory.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" ); //$NON-NLS-1$
jdoFactory.setDriverName( "org.hsqldb.jdbcDriver" ); //$NON-NLS-1$
jdoFactory.setUrl( "jdbc:hsqldb:mem:" + getName() ); //$NON-NLS-1$
jdoFactory.setUserName( "sa" ); //$NON-NLS-1$
jdoFactory.setPassword( "" ); //$NON-NLS-1$
jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.rdbms.dateTimezone", "JDK_DEFAULT_TIMEZONE" ); //$NON-NLS-1$ //$NON-NLS-2$
Properties properties = jdoFactory.getProperties();
for ( Map.Entry<Object,Object> entry : properties.entrySet() )
{
System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
}
SchemaTool.createSchemaTables( new URL[] { getClass()
.getResource( "/org/apache/archiva/redback/keys/jdo/package.jdo" ) }, new URL[] {}, null, false, null ); //$NON-NLS-1$
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
keyManager.eraseDatabase();
setKeyManager( keyManager );
}
}

View File

@ -1,48 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>
<bean name="commons-configuration" class="org.apache.archiva.redback.components.registry.commons.CommonsConfigurationRegistry">
</bean>
<alias name="commons-configuration" alias="test-conf"/>
</beans>

View File

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>redback-keys-providers</artifactId>
<groupId>org.apache.archiva.redback</groupId>
<version>2.5-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>redback-keys-jpa</artifactId>
<packaging>jar</packaging>
<name>Redback :: Key Management Provider :: JPA</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-keys-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${openjpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<configuration>
<includes>**/model/*.class</includes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<!-- set the version to be the same as the level in your runtime -->
<version>${openjpa.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,176 @@
package org.apache.archiva.redback.keys.jpa;
/*
* Copyright 2001-2016 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.archiva.redback.keys.AbstractKeyManager;
import org.apache.archiva.redback.keys.AuthenticationKey;
import org.apache.archiva.redback.keys.KeyManagerException;
import org.apache.archiva.redback.keys.KeyNotFoundException;
import org.apache.archiva.redback.keys.jpa.model.JpaAuthenticationKey;
import org.codehaus.plexus.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Key Manager Implementation for JPA.
*
* Uses an injected Entity Manager.
*
* @author <a href="mailto:martin_s@apache.org">Martin Stockhammer</a>
*/
@Service( "keyManager#jpa" )
public class JpaKeyManager extends AbstractKeyManager {
@PersistenceContext(unitName = "redback-jpa")
EntityManager em;
// JpaUserManager is a singleton and initialization should be thread safe
private AtomicBoolean initialized = new AtomicBoolean(false);
public void setEntityManager(EntityManager em) {
this.em = em;
}
private EntityManager getEm() {
if (initialized.compareAndSet(false,true)) {
Query q = em.createQuery("SELECT COUNT(u.key) FROM JpaAuthenticationKey u");
boolean dbInit = q.getFirstResult()==0;
}
return em;
}
public String getId()
{
return "JPA Key Manager - " + this.getClass().getName();
}
@Override
@Transactional
public AuthenticationKey createKey( String principal, String purpose, int expirationMinutes )
throws KeyManagerException
{
JpaAuthenticationKey authkey = new JpaAuthenticationKey();
authkey.setKey( super.generateUUID() );
authkey.setForPrincipal( principal );
authkey.setPurpose( purpose );
Calendar now = getNowGMT();
authkey.setDateCreated( now.getTime() );
if ( expirationMinutes >= 0 )
{
Calendar expiration = getNowGMT();
expiration.add( Calendar.MINUTE, expirationMinutes );
authkey.setDateExpires( expiration.getTime() );
}
return addKey( authkey );
}
@Transactional
@Override
public AuthenticationKey addKey(AuthenticationKey key) {
final EntityManager em = getEm();
AuthenticationKey mergedKey = em.merge((JpaAuthenticationKey)key);
return mergedKey;
}
@Transactional
@Override
public void eraseDatabase()
{
final EntityManager em = getEm();
Query q = em.createQuery("DELETE FROM JpaAuthenticationKey k");
q.executeUpdate();
}
@Transactional
@Override
public AuthenticationKey findKey(final String key) throws KeyNotFoundException, KeyManagerException {
final EntityManager em = getEm();
if ( StringUtils.isEmpty( key ) )
{
throw new KeyNotFoundException( "Empty key not found." );
}
try
{
TypedQuery<JpaAuthenticationKey> q =
em.createQuery("SELECT k FROM JpaAuthenticationKey k WHERE k.key = :key",JpaAuthenticationKey.class);
q.setParameter("key",key);
JpaAuthenticationKey authkey = q.getSingleResult();
if ( authkey == null )
{
throw new KeyNotFoundException( "Key [" + key + "] not found." );
}
assertNotExpired( authkey );
return authkey;
} catch (NoResultException ex) {
throw new KeyNotFoundException("Key [" + key + "] not found.");
} catch (KeyNotFoundException ex) {
throw ex;
} catch (Throwable ex) {
log.error("Error while trying to retrieve JpaAuthenticationKey {}", key);
throw new KeyManagerException("Error while retrieving key "+key+": "+ex.getMessage(), ex);
}
}
@Transactional
@Override
protected void assertNotExpired(AuthenticationKey authkey) throws KeyManagerException {
super.assertNotExpired(authkey);
}
@Transactional
@Override
public void deleteKey(AuthenticationKey key) throws KeyManagerException {
final EntityManager em = getEm();
em.remove((JpaAuthenticationKey)key);
}
@Transactional
@Override
public void deleteKey(String key) throws KeyManagerException {
try {
JpaAuthenticationKey foundKey = (JpaAuthenticationKey)findKey(key);
em.remove(foundKey);
} catch (KeyNotFoundException ex) {
// Ignore
} catch (Exception ex) {
log.error("Error occured while trying to find key {}: {}", key, ex.getMessage());
throw new KeyManagerException("Error while retrieving key "+key, ex);
}
}
@Override
public List<AuthenticationKey> getAllKeys() {
final EntityManager em = getEm();
Query q= em.createQuery("SELECT x from JpaAuthenticationKey x");
return q.getResultList();
}
}

View File

@ -0,0 +1,108 @@
package org.apache.archiva.redback.keys.jpa.model;
/*
* Copyright 2001-2016 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.archiva.redback.keys.AuthenticationKey;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
* Authentication Key implementation for JPA.
*
* The table names are set to match the JDO tables.
*
* @author <a href="mailto:martin_s@apache.org">Martin Stockhammer</a>
*/
@javax.persistence.Entity
@Table(name="JDOAUTHENTICATIONKEY")
public class JpaAuthenticationKey implements AuthenticationKey {
@Column(name="AUTHKEY")
@Id
private String key;
@Column(name="FOR_PRINCIPAL")
private String forPrincipal;
@Column(name="PURPOSE")
private String purpose;
@Column(name="DATE_CREATED")
private Date dateCreated;
@Column(name="DATE_EXPIRES")
private Date dateExpires;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getForPrincipal() {
return forPrincipal;
}
public void setForPrincipal(String forPrincipal) {
this.forPrincipal = forPrincipal;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateExpires() {
return dateExpires;
}
public void setDateExpires(Date dateExpires) {
this.dateExpires = dateExpires;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaAuthenticationKey that = (JpaAuthenticationKey) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}

View File

@ -20,15 +20,14 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean name="rbacManager#jdo" class="org.apache.archiva.redback.rbac.jdo.JdoRbacManager" init-method="initialize">
<property name="jdo" ref="jdoTool"/>
</bean>
<context:annotation-config />
<context:component-scan base-package="org.apache.archiva.redback.keys.jpa" />
<bean id="jdoTool" class="org.apache.archiva.redback.rbac.jdo.JdoTool" init-method="initialize" lazy-init="true">
<property name="jdoFactory" ref="jdoFactory#users"/>
</bean>
</beans>

View File

@ -0,0 +1,65 @@
package org.apache.archiva.redback.keys.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.keys.KeyManager;
import org.apache.archiva.redback.keys.KeyManagerTestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManagerFactory;
/**
* JdoKeyManagerTest
*
* @author <a href="mailto:martin_s@apache.org">Martin Stockhammer</a>
*
*/
@Transactional
public class JpaKeyManagerTest
extends KeyManagerTestCase
{
@Inject
EntityManagerFactory entityManagerFactory;
@Inject
@Named(value = "keyManager#jpa")
KeyManager keyManager;
@Before
public void setUp()
throws Exception {
super.setUp();
super.setKeyManager(keyManager);
}
@Test
public void initialize() {
assertNotNull(keyManager);
}
}

View File

@ -0,0 +1,61 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.apache.archiva.redback.keys.jpa" />
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -23,10 +23,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.*;
/**
* KeyManagerTestCase
@ -115,11 +112,14 @@ public class KeyManagerTestCase
assertEquals( "bar", created2.getForPrincipal() );
assertEquals( "Something", created2.getPurpose() );
List<AuthenticationKey> keys = getKeyManager().getAllKeys();
System.out.println("foo key "+created1.getKey());
System.out.println("bar key "+created2.getKey());
List<AuthenticationKey> keys = new ArrayList(getKeyManager().getAllKeys());
Collections.sort( keys, new Comparator<AuthenticationKey>()
{
public int compare( AuthenticationKey key1, AuthenticationKey key2 )
{
System.out.println("Compare "+key2.getForPrincipal()+key2.getKey()+" - "+key1.getForPrincipal()+key1.getKey());
return key2.getForPrincipal().compareTo( key1.getForPrincipal() );
}
} );

View File

@ -28,7 +28,7 @@
<name>Redback :: RBAC Providers</name>
<packaging>pom</packaging>
<modules>
<module>redback-rbac-jdo</module>
<module>redback-rbac-jpa</module>
<module>redback-rbac-memory</module>
<module>redback-rbac-cached</module>
<module>redback-rbac-ldap</module>

View File

@ -66,7 +66,7 @@
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-jdo</artifactId>
<artifactId>redback-rbac-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>

View File

@ -54,7 +54,7 @@ public class CachedRbacManager
private Logger log = LoggerFactory.getLogger( getClass() );
@Inject
@Named( value = "rbacManager#jdo" )
@Named( value = "rbacManager#jpa" )
private RBACManager rbacImpl;
@Inject

View File

@ -19,24 +19,11 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="false">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
@ -80,5 +67,36 @@
<property name="timeToLiveSeconds" value="600"/>
</bean>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -1,156 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-providers</artifactId>
<version>2.7-SNAPSHOT</version>
</parent>
<artifactId>redback-rbac-jdo</artifactId>
<packaging>bundle</packaging>
<name>Redback :: RBAC Provider :: JDO</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-model</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jdo</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.stax-utils</groupId>
<artifactId>stax-utils</artifactId>
<version>20060502</version>
<exclusions>
<exclusion>
<groupId>com.bea.xml</groupId>
<artifactId>jsr173-ri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jpox</groupId>
<artifactId>jpox-ehcache</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/rbac-jdo.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-java</id>
<goals>
<goal>java</goal>
<!-- TODO: Move these to plexus-security-authorization-rbac-model -->
<goal>stax-reader</goal>
<goal>stax-writer</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.archiva.redback.components.modello</groupId>
<artifactId>jpox-modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/rbac-jdo.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-jpox</id>
<goals>
<goal>jpox-metadata-class</goal>
<goal>jpox-jdo-mapping</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jpox-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,711 +0,0 @@
package org.apache.archiva.redback.rbac.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.AbstractRBACManager;
import org.apache.archiva.redback.rbac.Operation;
import org.apache.archiva.redback.rbac.RBACManagerListener;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
import org.apache.archiva.redback.rbac.RbacPermanentException;
import org.apache.archiva.redback.rbac.Resource;
import org.apache.archiva.redback.rbac.Role;
import org.apache.archiva.redback.rbac.UserAssignment;
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.RBACObjectAssertions;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import java.util.Collection;
import java.util.List;
/**
* JdoRbacManager:
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
* @author Jesse McConnell
*
*/
@Service( "rbacManager#jdo" )
public class JdoRbacManager
extends AbstractRBACManager
implements RBACManagerListener
{
@Inject
private JdoTool jdo;
private boolean enableCache = true;
// private static final String ROLE_DETAIL = "role-child-detail";
private static final String ROLE_DETAIL = null;
// ----------------------------------------------------------------------
// Role methods
// ----------------------------------------------------------------------
/**
* Creates an implementation specific {@link Role}.
*
* Note: this method does not add the {@link Role} to the underlying store.
* a call to {@link #saveRole(Role)} is required to track the role created with this
* method call.
*
* @param name the name.
* @return the new {@link Role} object with an empty (non-null) {@link Role#getChildRoleNames()} object.
*/
public Role createRole( String name )
{
Role role;
try
{
role = getRole( name );
}
catch ( RbacManagerException e )
{
role = new JdoRole();
role.setName( name );
}
return role;
}
/**
* Method addRole
*
* @param role
*/
public Role saveRole( Role role )
throws RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( role );
return jdo.saveObject( role, new String[]{ ROLE_DETAIL } );
}
public boolean roleExists( Role role )
{
return jdo.objectExists( role );
}
public boolean roleExists( String name )
{
try
{
return jdo.objectExistsById( JdoRole.class, name );
}
catch ( RbacManagerException e )
{
return false;
}
}
/**
* @param roleName
* @return
* @throws RbacObjectNotFoundException
* @throws RbacManagerException
*/
public Role getRole( String roleName )
throws RbacObjectNotFoundException, RbacManagerException
{
return jdo.getObjectById( JdoRole.class, roleName, ROLE_DETAIL );
}
/**
* Method getRoles
*/
@SuppressWarnings( "unchecked" )
public List<Role> getAllRoles()
throws RbacManagerException
{
return (List<Role>) jdo.getAllObjects( JdoRole.class );
}
public void removeRole( Role role )
throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( role );
if ( role.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent role [" + role.getName() + "]" );
}
jdo.removeObject( role );
}
public void saveRoles( Collection<Role> roles )
throws RbacObjectInvalidException, RbacManagerException
{
if ( roles == null )
{
// Nothing to do.
return;
}
// This is done in JdoRbacManager as opposed to JdoTool as we need to assertValid() on each role and
// also wrap the entire collection into a single atomic save/makePersistent.
PersistenceManager pm = jdo.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
for ( Role role : roles )
{
if ( ( JDOHelper.getObjectId( role ) != null ) && !JDOHelper.isDetached( role ) )
{
// This is a fatal error that means we need to fix our code.
// Leave it as a JDOUserException, it's intentional.
throw new RbacManagerException( "Existing Role is not detached: " + role );
}
RBACObjectAssertions.assertValid( role );
pm.makePersistent( role );
}
tx.commit();
}
finally
{
jdo.rollbackIfActive( tx );
}
}
// ----------------------------------------------------------------------
// Permission methods
// ----------------------------------------------------------------------
/**
* Creates an implementation specific {@link Permission}.
*
* Note: this method does not add the {@link Permission} to the underlying store.
* a call to {@link #savePermission(Permission)} is required to track the permission created
* with this method call.
*
* @param name the name.
* @return the new Permission.
* @throws RbacManagerException
*/
public Permission createPermission( String name )
throws RbacManagerException
{
Permission permission;
try
{
permission = getPermission( name );
log.debug( "Create Permission [{}] Returning Existing.", name );
}
catch ( RbacObjectNotFoundException e )
{
permission = new JdoPermission();
permission.setName( name );
log.debug( "Create Permission [{}] New JdoPermission.", name );
}
return permission;
}
/**
* Creates an implementation specific {@link Permission} with specified {@link Operation},
* and {@link Resource} identifiers.
*
* Note: this method does not add the Permission, Operation, or Resource to the underlying store.
* a call to {@link #savePermission(Permission)} is required to track the permission, operation,
* or resource created with this method call.
*
* @param name the name.
* @param operationName the {@link Operation#setName(String)} value
* @param resourceIdentifier the {@link Resource#setIdentifier(String)} value
* @return the new Permission.
* @throws RbacManagerException
*/
public Permission createPermission( String name, String operationName, String resourceIdentifier )
throws RbacManagerException
{
Permission permission = new JdoPermission();
permission.setName( name );
Operation operation;
try
{
operation = getOperation( operationName );
}
catch ( RbacObjectNotFoundException e )
{
operation = new JdoOperation();
operation.setName( operationName );
}
permission.setOperation( operation );
Resource resource;
try
{
resource = getResource( resourceIdentifier );
}
catch ( RbacObjectNotFoundException e )
{
resource = new JdoResource();
resource.setIdentifier( resourceIdentifier );
}
permission.setResource( resource );
return permission;
}
public Permission savePermission( Permission permission )
throws RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( permission );
return jdo.saveObject( permission, null );
}
public boolean permissionExists( Permission permission )
{
return jdo.objectExists( permission );
}
public boolean permissionExists( String name )
{
try
{
return jdo.objectExistsById( JdoPermission.class, name );
}
catch ( RbacManagerException e )
{
return false;
}
}
public Permission getPermission( String permissionName )
throws RbacObjectNotFoundException, RbacManagerException
{
return jdo.getObjectById( JdoPermission.class, permissionName, null );
}
@SuppressWarnings( "unchecked" )
public List<Permission> getAllPermissions()
throws RbacManagerException
{
return (List<Permission>) jdo.getAllObjects( JdoPermission.class );
}
public void removePermission( Permission permission )
throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( permission );
if ( permission.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent permission [" + permission.getName() + "]" );
}
jdo.removeObject( permission );
}
// ----------------------------------------------------------------------
// Operation methods
// ----------------------------------------------------------------------
/**
* Creates an implementation specific {@link Operation}.
*
* Note: this method does not add the {@link Operation} to the underlying store.
* a call to {@link #saveOperation(Operation)} is required to track the operation created
* with this method call.
*
* @param name the name.
* @return the new Operation.
* @throws RbacManagerException
*/
public Operation createOperation( String name )
throws RbacManagerException
{
Operation operation;
try
{
operation = getOperation( name );
}
catch ( RbacObjectNotFoundException e )
{
operation = new JdoOperation();
operation.setName( name );
}
return operation;
}
public Operation saveOperation( Operation operation )
throws RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( operation );
return jdo.saveObject( operation, null );
}
public boolean operationExists( Operation operation )
{
return jdo.objectExists( operation );
}
public boolean operationExists( String name )
{
try
{
return jdo.objectExistsById( JdoOperation.class, name );
}
catch ( RbacManagerException e )
{
return false;
}
}
public Operation getOperation( String operationName )
throws RbacObjectNotFoundException, RbacManagerException
{
return jdo.getObjectById( JdoOperation.class, operationName, null );
}
@SuppressWarnings( "unchecked" )
public List<Operation> getAllOperations()
throws RbacManagerException
{
return (List<Operation>) jdo.getAllObjects( JdoOperation.class );
}
public void removeOperation( Operation operation )
throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( operation );
if ( operation.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent operation [" + operation.getName() + "]" );
}
jdo.removeObject( operation );
}
// ----------------------------------------------------------------------
// Resource methods
// ----------------------------------------------------------------------
/**
* Creates an implementation specific {@link Resource}.
*
* Note: this method does not add the {@link Resource} to the underlying store.
* a call to {@link #saveResource(Resource)} is required to track the resource created
* with this method call.
*
* @param identifier the identifier.
* @return the new Resource.
* @throws RbacManagerException
*/
public Resource createResource( String identifier )
throws RbacManagerException
{
Resource resource;
try
{
resource = getResource( identifier );
log.debug( "Create Resource [ {} ] Returning Existing.", identifier );
}
catch ( RbacObjectNotFoundException e )
{
resource = new JdoResource();
resource.setIdentifier( identifier );
log.debug( "Create Resource [ {} ] New JdoResource.", identifier );
}
return resource;
}
public Resource saveResource( Resource resource )
throws RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( resource );
return jdo.saveObject( resource, null );
}
public boolean resourceExists( Resource resource )
{
return jdo.objectExists( resource );
}
public boolean resourceExists( String identifier )
{
try
{
return jdo.objectExistsById( JdoResource.class, identifier );
}
catch ( RbacManagerException e )
{
return false;
}
}
public Resource getResource( String resourceIdentifier )
throws RbacObjectNotFoundException, RbacManagerException
{
return jdo.getObjectById( JdoResource.class, resourceIdentifier, null );
}
@SuppressWarnings( "unchecked" )
public List<Resource> getAllResources()
throws RbacManagerException
{
return (List<Resource>) jdo.getAllObjects( JdoResource.class );
}
public void removeResource( Resource resource )
throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( resource );
if ( resource.isPermanent() )
{
throw new RbacPermanentException(
"Unable to delete permanent resource [" + resource.getIdentifier() + "]" );
}
jdo.removeObject( resource );
}
// ----------------------------------------------------------------------
// User Assignment methods
// ----------------------------------------------------------------------
/**
* Creates an implementation specific {@link UserAssignment}.
*
* Note: this method does not add the {@link UserAssignment} to the underlying store.
* a call to {@link #saveUserAssignment(UserAssignment)} is required to track the user
* assignment created with this method call.
*
* @param principal the principal reference to the user.
* @return the new UserAssignment with an empty (non-null) {@link UserAssignment#getRoleNames()} object.
*/
public UserAssignment createUserAssignment( String principal )
{
UserAssignment ua;
try
{
ua = getUserAssignment( principal );
}
catch ( RbacManagerException e )
{
ua = new JdoUserAssignment();
ua.setPrincipal( principal );
}
return ua;
}
/**
* Method addUserAssignment
*
* @param userAssignment
*/
public UserAssignment saveUserAssignment( UserAssignment userAssignment )
throws RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( "Save User Assignment", userAssignment );
fireRbacUserAssignmentSaved( userAssignment );
return jdo.saveObject( userAssignment, new String[]{ ROLE_DETAIL } );
}
public boolean userAssignmentExists( String principal )
{
try
{
return jdo.objectExistsById( JdoUserAssignment.class, principal );
}
catch ( RbacManagerException e )
{
return false;
}
}
public boolean userAssignmentExists( UserAssignment assignment )
{
return jdo.objectExists( assignment );
}
public UserAssignment getUserAssignment( String principal )
throws RbacObjectNotFoundException, RbacManagerException
{
return jdo.getObjectById( JdoUserAssignment.class, principal, ROLE_DETAIL );
}
/**
* Method getAssignments
*/
@SuppressWarnings( "unchecked" )
public List<UserAssignment> getAllUserAssignments()
throws RbacManagerException
{
return (List<UserAssignment>) jdo.getAllObjects( JdoUserAssignment.class );
}
/**
* Method getUserAssignmentsForRoles
*/
@SuppressWarnings( "unchecked" )
public List<UserAssignment> getUserAssignmentsForRoles( Collection<String> roleNames )
throws RbacManagerException
{
return (List<UserAssignment>) jdo.getUserAssignmentsForRoles( JdoUserAssignment.class, null, roleNames );
}
/**
* Method removeAssignment
*
* @param userAssignment
*/
public void removeUserAssignment( UserAssignment userAssignment )
throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
{
RBACObjectAssertions.assertValid( userAssignment );
if ( userAssignment.isPermanent() )
{
throw new RbacPermanentException(
"Unable to delete permanent user assignment [" + userAssignment.getPrincipal() + "]" );
}
fireRbacUserAssignmentRemoved( userAssignment );
jdo.removeObject( userAssignment );
}
public void eraseDatabase()
{
// Must delete in order so that FK constraints don't get violated
jdo.removeAll( JdoRole.class );
jdo.removeAll( JdoPermission.class );
jdo.removeAll( JdoOperation.class );
jdo.removeAll( JdoResource.class );
jdo.removeAll( JdoUserAssignment.class );
jdo.removeAll( RbacJdoModelModelloMetadata.class );
}
@PostConstruct
public void initialize()
{
super.initialize();
jdo.setListener( this );
if ( enableCache )
{
jdo.enableCache( JdoRole.class );
jdo.enableCache( JdoOperation.class );
jdo.enableCache( JdoResource.class );
jdo.enableCache( JdoUserAssignment.class );
jdo.enableCache( JdoPermission.class );
}
}
public void rbacInit( boolean freshdb )
{
fireRbacInit( freshdb );
}
public void rbacPermissionRemoved( Permission permission )
{
fireRbacPermissionRemoved( permission );
}
public void rbacPermissionSaved( Permission permission )
{
fireRbacPermissionSaved( permission );
}
public void rbacRoleRemoved( Role role )
{
fireRbacRoleRemoved( role );
}
public void rbacRoleSaved( Role role )
{
fireRbacRoleSaved( role );
}
public void rbacUserAssignmentSaved( UserAssignment userAssignment )
{
fireRbacUserAssignmentSaved( userAssignment );
}
public void rbacUserAssignmentRemoved( UserAssignment userAssignment )
{
fireRbacUserAssignmentRemoved( userAssignment );
}
public JdoTool getJdo()
{
return jdo;
}
public void setJdo( JdoTool jdo )
{
this.jdo = jdo;
}
public boolean isEnableCache()
{
return enableCache;
}
public void setEnableCache( boolean enableCache )
{
this.enableCache = enableCache;
}
@Override
public boolean isFinalImplementation()
{
return true;
}
public String getDescriptionKey()
{
return "archiva.redback.rbacmanager.jdo";
}
public boolean isReadOnly()
{
return false;
}
}

View File

@ -1,500 +0,0 @@
package org.apache.archiva.redback.rbac.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.RBACManagerListener;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
import org.apache.archiva.redback.rbac.Role;
import org.apache.archiva.redback.components.jdo.JdoFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.jdo.Extent;
import javax.jdo.JDOException;
import javax.jdo.JDOHelper;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.JDOUserException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.datastore.DataStoreCache;
import javax.jdo.listener.DeleteLifecycleListener;
import javax.jdo.listener.InstanceLifecycleEvent;
import javax.jdo.listener.StoreLifecycleListener;
import javax.jdo.spi.Detachable;
import javax.jdo.spi.PersistenceCapable;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* JdoTool - RBAC JDO Tools.
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*
*/
@Service("jdoTool")
public class JdoTool
implements DeleteLifecycleListener, StoreLifecycleListener
{
@Resource(name="jdoFactory#users")
private JdoFactory jdoFactory;
private PersistenceManagerFactory pmf;
private RBACManagerListener listener;
@PostConstruct
public void initialize()
{
pmf = jdoFactory.getPersistenceManagerFactory();
pmf.addInstanceLifecycleListener( this, null );
}
public static void dumpObjectState( PrintStream out, Object o )
{
final String STATE = "[STATE] ";
final String INDENT = " ";
if ( o == null )
{
out.println( STATE + "Object is null." );
return;
}
out.println( STATE + "Object " + o.getClass().getName() );
if ( !( o instanceof PersistenceCapable ) )
{
out.println( INDENT + "is NOT PersistenceCapable (not a jdo object?)" );
return;
}
out.println( INDENT + "is PersistenceCapable." );
if ( o instanceof Detachable )
{
out.println( INDENT + "is Detachable" );
}
out.println( INDENT + "is new : " + Boolean.toString( JDOHelper.isNew( o ) ) );
out.println( INDENT + "is transactional : " + Boolean.toString( JDOHelper.isTransactional( o ) ) );
out.println( INDENT + "is deleted : " + Boolean.toString( JDOHelper.isDeleted( o ) ) );
out.println( INDENT + "is detached : " + Boolean.toString( JDOHelper.isDetached( o ) ) );
out.println( INDENT + "is dirty : " + Boolean.toString( JDOHelper.isDirty( o ) ) );
out.println( INDENT + "is persistent : " + Boolean.toString( JDOHelper.isPersistent( o ) ) );
out.println( INDENT + "object id : " + JDOHelper.getObjectId( o ) );
}
public PersistenceManager getPersistenceManager()
{
PersistenceManager pm = pmf.getPersistenceManager();
pm.getFetchPlan().setMaxFetchDepth( -1 );
triggerInit();
return pm;
}
private boolean hasTriggeredInit = false;
@SuppressWarnings("unchecked")
public void triggerInit()
{
if ( !hasTriggeredInit )
{
hasTriggeredInit = true;
List<Role> roles = (List<Role>) getAllObjects( JdoRole.class );
listener.rbacInit( roles.isEmpty() );
}
}
public void enableCache( Class<?> clazz )
{
DataStoreCache cache = pmf.getDataStoreCache();
if ( cache.getClass().getName().equals( "org.jpox.cache.EhcacheClassBasedLevel2Cache" )
|| cache.getClass().getName().equals( "org.jpox.cache.EhcacheLevel2Cache" ) )
{
/* Ehcache adapters don't support pinAll, the caching is handled in the configuration */
return;
}
cache.pinAll( clazz, false ); // Pin all objects of type clazz from now on
}
public <T>T saveObject( T object )
{
return (T) saveObject( object, null );
}
public <T>T saveObject( T object, String[] fetchGroups )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
if ( ( JDOHelper.getObjectId( object ) != null ) && !JDOHelper.isDetached( object ) )
{
// This is a fatal error that means we need to fix our code.
// Leave it as a JDOUserException, it's intentional.
throw new JDOUserException( "Existing object is not detached: " + object, object );
}
if ( fetchGroups != null )
{
for ( int i = 0; i >= fetchGroups.length; i++ )
{
pm.getFetchPlan().addGroup( fetchGroups[i] );
}
}
pm.makePersistent( object );
object = (T) pm.detachCopy( object );
tx.commit();
return object;
}
finally
{
rollbackIfActive( tx );
}
}
public List<?> getAllObjects( Class<?> clazz )
{
return getAllObjects( clazz, null, null );
}
public List<?> getAllObjects( Class<?> clazz, String ordering )
{
return getAllObjects( clazz, ordering, null );
}
public List<?> getAllObjects( Class<?> clazz, String ordering, String fetchGroup )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Extent extent = pm.getExtent( clazz, true );
Query query = pm.newQuery( extent );
if ( ordering != null )
{
query.setOrdering( ordering );
}
if ( fetchGroup != null )
{
pm.getFetchPlan().addGroup( fetchGroup );
}
List<?> result = (List<?>) query.execute();
result = (List<?>) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollbackIfActive( tx );
}
}
public List<?> getUserAssignmentsForRoles( Class<?> clazz, String ordering, Collection<String> roleNames )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Extent extent = pm.getExtent( clazz, true );
Query query = pm.newQuery( extent );
if ( ordering != null )
{
query.setOrdering( ordering );
}
query.declareImports( "import java.lang.String" );
StringBuilder filter = new StringBuilder();
if ( roleNames.size() > 0 )
{
Iterator<String> i = roleNames.iterator();
filter.append( "this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
while ( i.hasNext() )
{
filter.append( " || this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
}
query.setFilter( filter.toString() );
}
List<?> result = (List<?>) query.execute();
result = (List<?>) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollbackIfActive( tx );
}
}
public <T>T getObjectById( Class<T> clazz, String id, String fetchGroup )
throws RbacObjectNotFoundException, RbacManagerException
{
if ( StringUtils.isEmpty( id ) )
{
throw new RbacObjectNotFoundException(
"Unable to get object '" + clazz.getName() + "' from jdo using null/empty id." );
}
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
if ( fetchGroup != null )
{
pm.getFetchPlan().addGroup( fetchGroup );
}
Object objectId = pm.newObjectIdInstance( clazz, id );
Object object = pm.getObjectById( objectId );
object = pm.detachCopy( object );
tx.commit();
return (T) object;
}
catch ( JDOObjectNotFoundException e )
{
throw new RbacObjectNotFoundException( "Unable to find RBAC Object '" + id + "' of type " +
clazz.getName() + " using fetch-group '" + fetchGroup + "'", e, id );
}
catch ( JDOException e )
{
throw new RbacManagerException( "Error in JDO during get of RBAC object id '" + id + "' of type " +
clazz.getName() + " using fetch-group '" + fetchGroup + "'", e );
}
finally
{
rollbackIfActive( tx );
}
}
public boolean objectExists( Object object )
{
return ( JDOHelper.getObjectId( object ) != null );
}
public boolean objectExistsById( Class<?> clazz, String id )
throws RbacManagerException
{
try
{
Object o = getObjectById( clazz, id, null );
return ( o != null );
}
catch ( RbacObjectNotFoundException e )
{
return false;
}
}
public <T>T removeObject( T o )
throws RbacManagerException
{
if ( o == null )
{
throw new RbacManagerException( "Unable to remove null object" );
}
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
o = (T) pm.getObjectById( pm.getObjectId( o ) );
pm.deletePersistent( o );
tx.commit();
return o;
}
finally
{
rollbackIfActive( tx );
}
}
public void rollbackIfActive( Transaction tx )
{
PersistenceManager pm = tx.getPersistenceManager();
try
{
if ( tx.isActive() )
{
tx.rollback();
}
}
finally
{
closePersistenceManager( pm );
}
}
public void closePersistenceManager( PersistenceManager pm )
{
try
{
pm.close();
}
catch ( JDOUserException e )
{
// ignore
}
}
public RBACManagerListener getListener()
{
return listener;
}
public void setListener( RBACManagerListener listener )
{
this.listener = listener;
}
public void postDelete( InstanceLifecycleEvent evt )
{
PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
if ( obj == null )
{
// Do not track null objects.
// These events are typically a product of an internal lifecycle event.
return;
}
if ( obj instanceof Role )
{
listener.rbacRoleRemoved( (Role) obj );
}
else if ( obj instanceof Permission )
{
listener.rbacPermissionRemoved( (Permission) obj );
}
}
public void preDelete( InstanceLifecycleEvent evt )
{
// ignore
}
public void postStore( InstanceLifecycleEvent evt )
{
PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
if ( obj instanceof Role )
{
listener.rbacRoleSaved( (Role) obj );
}
else if ( obj instanceof Permission )
{
listener.rbacPermissionSaved( (Permission) obj );
}
}
public void preStore( InstanceLifecycleEvent evt )
{
// ignore
}
public void removeAll( Class<?> aClass )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Query query = pm.newQuery( aClass );
query.deletePersistentAll();
tx.commit();
}
finally
{
rollbackIfActive( tx );
}
}
public JdoFactory getJdoFactory()
{
return jdoFactory;
}
public void setJdoFactory( JdoFactory jdoFactory )
{
this.jdoFactory = jdoFactory;
}
}

View File

@ -1,337 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<model jpox.mapping-in-package="true"
jpox.table-prefix="SECURITY_">
<!-- TODO: there is no reason this model is JDO specific. Shouldn't it be the basis for the various providers? It would dramatically reduce the code in -memory, for example -->
<id>rbac-jdo</id>
<name>RbacJdoModel</name>
<version>1.0.1</version>
<defaults>
<default>
<key>package</key>
<value>org.apache.archiva.redback.rbac.jdo</value>
</default>
</defaults>
<classes>
<class rootElement="true"
jpox.stashable="false">
<name>RbacDatabase</name>
<version>1.0.1+</version>
<fields>
<field jpox.column="RBAC_ROLES">
<name>roles</name>
<version>1.0.1+</version>
<association>
<type>JdoRole</type>
<multiplicity>*</multiplicity>
</association>
</field>
<field>
<name>permissions</name>
<version>1.0.1+</version>
<association>
<type>JdoPermission</type>
<multiplicity>*</multiplicity>
</association>
</field>
<field>
<name>operations</name>
<version>1.0.1+</version>
<association>
<type>JdoOperation</type>
<multiplicity>*</multiplicity>
</association>
</field>
<field>
<name>resources</name>
<version>1.0.1+</version>
<association>
<type>JdoResource</type>
<multiplicity>*</multiplicity>
</association>
</field>
<field>
<name>userAssignments</name>
<version>1.0.1+</version>
<association>
<type>JdoUserAssignment</type>
<multiplicity>*</multiplicity>
</association>
</field>
</fields>
</class>
<class jpox.stashable="true"
jpox.table="ROLES">
<name>JdoRole</name>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.rbac.Role</interface>
</interfaces>
<superClass>org.apache.archiva.redback.rbac.AbstractRole</superClass>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off">
<name>name</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>description</name>
<version>1.0.0+</version>
<type>String</type>
</field>
<field>
<name>assignable</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this role is available to be assigned to a user
</description>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this object is permanent.
</description>
</field>
<field jpox.persistence-modifier="persistent"
jpox.fetch-groups="role-child-detail"
jpox.join-table="ROLE_CHILDROLE_MAP">
<name>childRoleNames</name>
<version>1.0.0+</version>
<association stash.part="true"
jpox.join="true"
java.init="field"
jpox.dependent="false"
java.generate-break="false"
java.generate-create="false"
zjava.use-interface="org.apache.archiva.redback.rbac.Role">
<type>String</type>
<multiplicity>*</multiplicity>
</association>
<description>
roles that will inherit the permissions of this role
</description>
</field>
<field jpox.fetch-groups="role-child-detail"
jpox.join-table="ROLE_PERMISSION_MAP">
<name>permissions</name>
<version>1.0.0+</version>
<association stash.part="true"
xml.reference="true"
jpox.join="true"
jpox.dependent="false"
java.init="field"
java.generate-break="false"
java.generate-create="false"
java.use-interface="org.apache.archiva.redback.rbac.Permission">
<type>JdoPermission</type>
<multiplicity>*</multiplicity>
</association>
</field>
</fields>
</class>
<class jpox.stashable="true"
jpox.table="PERMISSIONS">
<name>JdoPermission</name>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.rbac.Permission</interface>
</interfaces>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off">
<name>name</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>description</name>
<version>1.0.0+</version>
<type>String</type>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this object is permanent.
</description>
</field>
<field jpox.indexed="true"
jpox.persistence-modifier="persistent"
jpox.column="RBAC_OPERATION">
<name>operation</name>
<version>1.0.0+</version>
<association stash.part="true"
xml.reference="true"
java.use-interface="org.apache.archiva.redback.rbac.Operation"
jpox.dependent="false">
<type>JdoOperation</type>
<multiplicity>1</multiplicity>
</association>
</field>
<field jpox.indexed="true"
jpox.persistence-modifier="persistent"
jpox.column="RBAC_RESOURCE">
<name>resource</name>
<version>1.0.0+</version>
<association stash.part="true"
xml.reference="true"
java.use-interface="org.apache.archiva.redback.rbac.Resource"
jpox.dependent="false">
<type>JdoResource</type>
<multiplicity>1</multiplicity>
</association>
</field>
</fields>
</class>
<class jpox.stashable="true"
jpox.table="OPERATIONS">
<name>JdoOperation</name>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.rbac.Operation</interface>
</interfaces>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off">
<name>name</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>description</name>
<version>1.0.0+</version>
<type>String</type>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this object is permanent.
</description>
</field>
<field>
<name>resourceRequired</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if the resource is required for authorization to be granted
</description>
</field>
</fields>
</class>
<class jpox.stashable="true"
jpox.table="RESOURCES">
<name>JdoResource</name>
<version>1.0.0+</version>
<description>
In RBAC terms, this is the entity which an operation is associated with that which permissions are based on.
</description>
<interfaces>
<interface>org.apache.archiva.redback.rbac.Resource</interface>
</interfaces>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off">
<name>identifier</name>
<version>1.0.0+</version>
<type>String</type>
<description>
The string identifier for a resource.
</description>
<identifier>true</identifier>
</field>
<field>
<name>pattern</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if the identifer is a pattern that is to be evaluated, for example x.* could match x.a or x.b and x.**
could match x.foo
</description>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this object is permanent.
</description>
</field>
</fields>
</class>
<class jpox.stashable="true"
jpox.table="USER_ASSIGNMENTS">
<name>JdoUserAssignment</name>
<description>binding of a principal to a role</description>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.rbac.UserAssignment</interface>
</interfaces>
<superClass>org.apache.archiva.redback.rbac.AbstractUserAssignment</superClass>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off">
<name>principal</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field jpox.column="LAST_UPDATED" xml.format="long">
<name>timestamp</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<description>
true if this object is permanent.
</description>
</field>
<field java.adder="false"
jpox.persistence-modifier="persistent"
jpox.indexed="false"
jpox.join-table="USERASSIGNMENT_ROLENAMES">
<name>roleNames</name>
<version>1.0.0+</version>
<association stash.part="true"
jpox.join="true"
java.init="field"
java.generate-break="false"
java.generate-create="false">
<type>String</type>
<multiplicity>*</multiplicity>
</association>
</field>
</fields>
</class>
</classes>
</model>

View File

@ -1,219 +0,0 @@
package org.apache.archiva.redback.rbac.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.common.jdo.test.StoreManagerDebug;
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.tests.AbstractRbacManagerTestCase;
import org.jpox.AbstractPersistenceManagerFactory;
import org.jpox.SchemaTool;
import org.junit.Before;
import org.springframework.test.annotation.DirtiesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
/**
* JdoRbacManagerTest:
*
* @author Jesse McConnell
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*/
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class JdoRbacManagerTest
extends AbstractRbacManagerTestCase
{
private StoreManagerDebug storeManager;
@Inject
@Named(value = "jdoFactory#users")
DefaultConfigurableJdoFactory jdoFactory;
@Inject
@Named(value = "rbacManager#jdo")
RBACManager rbacManager;
public static int EVENTCOUNT = 2;
@Override
public void assertEventCount()
{
assertEquals( EVENTCOUNT, eventTracker.initCount );
}
/**
* Creates a new RbacStore which contains no data.
*/
@Before
public void setUp()
throws Exception
{
super.setUp();
assertEquals( DefaultConfigurableJdoFactory.class.getName(), jdoFactory.getClass().getName() );
jdoFactory.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" ); //$NON-NLS-1$
jdoFactory.setDriverName(
System.getProperty( "jdo.test.driver", "org.hsqldb.jdbcDriver" ) ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setUrl(
System.getProperty( "jdo.test.url", "jdbc:hsqldb:mem:" + getName() ) ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setUserName( System.getProperty( "jdo.test.user", "sa" ) ); //$NON-NLS-1$
jdoFactory.setPassword( System.getProperty( "jdo.test.pass", "" ) ); //$NON-NLS-1$
jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.autoCreateTables", "true" );
jdoFactory.setProperty( "javax.jdo.option.RetainValues", "true" );
jdoFactory.setProperty( "javax.jdo.option.RestoreValues", "true" );
// jdoFactory.setProperty( "org.jpox.autoCreateColumns", "true" );
jdoFactory.setProperty( "org.jpox.validateTables", "true" );
jdoFactory.setProperty( "org.jpox.validateColumns", "true" );
jdoFactory.setProperty( "org.jpox.validateConstraints", "true" );
/* Enable the level 2 Ehcache class-based cache */
jdoFactory.setProperty( "org.jpox.cache.level2", "true" );
jdoFactory.setProperty( "org.jpox.cache.level2.type", "ehcacheclassbased" );
jdoFactory.setProperty( "org.jpox.cache.level2.configurationFile", "/ehcache.xml" ); // ehcache config
jdoFactory.setProperty( "org.jpox.cache.level2.cacheName", "default" ); // default cache name
Properties properties = jdoFactory.getProperties();
for ( Map.Entry<Object, Object> entry : properties.entrySet() )
{
System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
}
URL[] jdoFileUrls =
new URL[]{ getClass().getResource( "/org/apache/archiva/redback/rbac/jdo/package.jdo" ) }; //$NON-NLS-1$
if ( ( jdoFileUrls == null ) || ( jdoFileUrls[0] == null ) )
{
fail( "Unable to process test " + getName() + " - missing package.jdo." );
}
File propsFile = null; // intentional
boolean verbose = true;
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
/* set our own Store Manager to allow counting SQL statements */
StoreManagerDebug.setup( (AbstractPersistenceManagerFactory) pmf );
/* clean up the db */
SchemaTool.deleteSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose );
SchemaTool.createSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose, null );
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
setRbacManager( rbacManager );
/* save the store manager to access the queries executed */
JdoRbacManager rbacManager = (JdoRbacManager) getRbacManager();
storeManager = StoreManagerDebug.getConfiguredStoreManager( rbacManager.getJdo().getPersistenceManager() );
}
@Override
public void testGetAssignedRoles()
throws RbacManagerException
{
storeManager.resetCounter();
super.testGetAssignedRoles();
int counter = storeManager.counter();
/* without Level 2 cache: 15 queries */
/* with Level 2 cache: 8 queries */
assertEquals( "Number of SQL queries", 8, counter );
}
@Override
public void testGetAssignedPermissionsDeep()
throws RbacManagerException
{
super.testGetAssignedPermissionsDeep();
int counter = storeManager.counter();
/* without Level 2 cache: 26 queries */
/* with Level 2 cache: 10 queries */
assertEquals( "Number of SQL queries", 10, counter );
}
@Override
protected void afterSetup()
{
super.afterSetup();
storeManager.resetCounter();
}
@Override
public void testLargeApplicationInit()
throws RbacManagerException
{
this.clearCache();
super.testLargeApplicationInit();
}
@Override
public void testGetRolesDeep()
throws RbacManagerException
{
this.clearCache();
super.testGetRolesDeep();
}
@Override
public void testStoreInitialization()
throws Exception
{
this.clearCache();
rbacManager.eraseDatabase();
eventTracker.rbacInit( true );
super.testStoreInitialization();
assertEquals( EVENTCOUNT, eventTracker.initCount );
}
}

View File

@ -1,198 +0,0 @@
package org.apache.archiva.redback.rbac.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.xml.stream.XMLStreamException;
import junit.framework.TestCase;
import org.apache.archiva.redback.rbac.Operation;
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.Resource;
import org.apache.archiva.redback.rbac.jdo.io.stax.RbacJdoModelStaxReader;
import org.apache.archiva.redback.rbac.jdo.io.stax.RbacJdoModelStaxWriter;
/**
* Test the StAX reader and writer generated.
*/
public class RbacJdoModelStaxTest
extends TestCase
{
@SuppressWarnings("unchecked")
public void testStax()
throws IOException, XMLStreamException
{
RbacDatabase database = new RbacDatabase();
JdoRole role = new JdoRole();
role.setAssignable( true );
role.setDescription( "descriptor" );
role.setName( "name" );
role.setPermanent( true );
role.addChildRoleName( "childRole1" );
role.addChildRoleName( "childRole2" );
JdoPermission permission = new JdoPermission();
permission.setDescription( "permDesc" );
permission.setName( "permName" );
JdoOperation operation = new JdoOperation();
operation.setDescription( "opDesc" );
operation.setName( "opName" );
operation.setPermanent( true );
operation.setResourceRequired( true );
permission.setOperation( operation );
database.addOperation( operation );
JdoResource resource = new JdoResource();
resource.setIdentifier( "resId" );
resource.setPattern( true );
resource.setPermanent( true );
permission.setResource( resource );
database.addResource( resource );
permission.setPermanent( true );
role.addPermission( permission );
database.addPermission( permission );
database.addRole( role );
JdoUserAssignment assignment = new JdoUserAssignment();
assignment.setPermanent( false );
assignment.setPrincipal( "principal" );
assignment.setTimestamp( new Date() );
assignment.addRoleName( "name" );
database.addUserAssignment( assignment );
StringWriter w = new StringWriter();
new RbacJdoModelStaxWriter().write( w, database );
RbacDatabase newDatabase = new RbacJdoModelStaxReader().read( new StringReader( w.toString() ) );
List<JdoRole> expectedRoles = database.getRoles();
List<JdoRole> roles = newDatabase.getRoles();
assertEquals( expectedRoles.size(), roles.size() );
for ( JdoRole r : roles )
{
boolean found = false;
for ( JdoRole expectedRole : expectedRoles )
{
if ( expectedRole.getName().equals( r.getName() ) )
{
found = true;
assertRole( expectedRole, r );
}
}
if ( !found )
{
fail( "Couldn't find role: " + r.getName() );
}
}
List<JdoUserAssignment> expectedUserAssignments = database.getUserAssignments();
List<JdoUserAssignment> userAssignments = newDatabase.getUserAssignments();
assertEquals( expectedUserAssignments.size(), userAssignments.size() );
for ( JdoUserAssignment a : userAssignments )
{
boolean found = false;
for ( JdoUserAssignment expectedAssignment : expectedUserAssignments )
{
if ( expectedAssignment.getPrincipal().equals( a.getPrincipal() ) )
{
found = true;
assertUserAssignment( expectedAssignment, a );
}
}
if ( !found )
{
fail( "Couldn't find assignment: " + a.getPrincipal() );
}
}
}
@SuppressWarnings("unchecked")
private void assertRole( JdoRole expectedRole, JdoRole role )
{
assertEquals( expectedRole.getDescription(), role.getDescription() );
assertPermissions( expectedRole.getPermissions(), role.getPermissions() );
assertEquals( expectedRole.getChildRoleNames(), role.getChildRoleNames() );
}
private void assertUserAssignment( JdoUserAssignment expectedAssignment, JdoUserAssignment assignment )
{
SimpleDateFormat sdf = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z", Locale.US );
assertNotNull( expectedAssignment.getTimestamp() );
assertNotNull( assignment.getTimestamp() );
assertEquals( sdf.format( expectedAssignment.getTimestamp() ), sdf.format( assignment.getTimestamp() ) );
assertEquals( expectedAssignment.getRoleNames(), assignment.getRoleNames() );
}
private void assertPermissions( List<Permission> expectedPermissions, List<Permission> permissions )
{
assertEquals( expectedPermissions.size(), permissions.size() );
for ( Permission permission : permissions )
{
boolean found = false;
for ( Permission expectedPermission : expectedPermissions )
{
if ( expectedPermission.getName().equals( permission.getName() ) )
{
found = true;
assertPermission( expectedPermission, permission );
}
}
if ( !found )
{
fail( "Couldn't find permission: " + permission.getName() );
}
}
}
private void assertPermission( Permission expectedPermission, Permission permission )
{
assertEquals( expectedPermission.getDescription(), permission.getDescription() );
assertOperation( expectedPermission.getOperation(), permission.getOperation() );
assertResource( expectedPermission.getResource(), permission.getResource() );
}
private void assertResource( Resource expectedResource, Resource resource )
{
assertEquals( expectedResource.getIdentifier(), resource.getIdentifier() );
}
private void assertOperation( Operation expectedOperation, Operation operation )
{
assertEquals( expectedOperation.getName(), operation.getName() );
assertEquals( expectedOperation.getDescription(), operation.getDescription() );
}
}

View File

@ -1,90 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<!--
Redback EHCACHE config file that can be used with JPOX-Ehcache integration
For reference http://ehcache.sourceforge.net/documentation/configuration.html
-->
<!-- make default cache very short lived -->
<defaultCache
maxElementsInMemory="100"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU" />
<!--
cache Redback classes longer to avoid a lot of SQL queries
See REDBACK-227
-->
<cache name="org.apache.archiva.redback.rbac.jdo.JdoOperation"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="3000"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU" />
<cache name="org.apache.archiva.redback.rbac.jdo.JdoPermission"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="3000"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU" />
<cache name="org.apache.archiva.redback.rbac.jdo.JdoResource"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="3000"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU" />
<cache name="org.apache.archiva.redback.rbac.jdo.JdoRole"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="3000"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU" />
<cache name="org.apache.archiva.redback.rbac.jdo.JdoUserAssignment"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="3000"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU" />
</ehcache>

View File

@ -1,53 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
<prop key="org.jpox.cache.level2">true</prop>
<prop key="org.jpox.cache.level2.type">ehcacheclassbased</prop>
<prop key="org.jpox.cache.level2.configurationFile">/ehcache.xml</prop>
<prop key="org.jpox.cache.level2.cacheName">defaultfake</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>
<bean name="commons-configuration" class="org.apache.archiva.redback.components.registry.commons.CommonsConfigurationRegistry">
</bean>
<alias name="commons-configuration" alias="test-conf"/>
</beans>

View File

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>redback-rbac-providers</artifactId>
<groupId>org.apache.archiva.redback</groupId>
<version>2.5-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>redback-rbac-jpa</artifactId>
<packaging>jar</packaging>
<name>Redback :: RBAC Provider :: JPA</name>
<dependencies>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-model</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${openjpa.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<configuration>
<includes>**/model/*.class</includes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<!-- set the version to be the same as the level in your runtime -->
<version>${openjpa.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,488 @@
package org.apache.archiva.redback.rbac.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.*;
import org.apache.archiva.redback.rbac.jpa.model.*;
import org.apache.openjpa.persistence.Type;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by martin on 20.09.16.
*/
@Service("rbacManager#jpa")
public class JpaRbacManager extends AbstractRBACManager {
@PersistenceContext(unitName = "redback-jpa")
EntityManager em;
private AtomicBoolean initialized = new AtomicBoolean(false);
public void setEntityManager(EntityManager em) {
this.em = em;
}
@Override
public Role createRole(String name) {
JpaRole role = new JpaRole();
role.setName(name);
return role;
}
@Transactional
@Override
public Role saveRole(Role role) throws RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid( role );
final EntityManager em = getEm();
Role mergedRole = em.merge(role);
fireRbacRoleSaved(mergedRole);
for (Permission perm : mergedRole.getPermissions()) {
fireRbacPermissionSaved(perm);
}
return mergedRole;
}
@Transactional
@Override
public Map<String, List<Permission>> getAssignedPermissionMap(String principal) throws RbacManagerException {
return super.getAssignedPermissionMap(principal);
}
@Transactional
@Override
public Map<String, Role> getChildRoles(Role role) throws RbacManagerException {
return super.getChildRoles(role);
}
@Transactional
@Override
public void addChildRole(Role role, Role childRole) throws RbacObjectInvalidException, RbacManagerException {
super.addChildRole(role, childRole);
}
@Transactional
@Override
public void saveRoles(Collection<Role> roles) throws RbacObjectInvalidException, RbacManagerException {
if ( roles == null )
{
// Nothing to do.
return;
}
final EntityManager em = getEm();
List<Role> merged = new ArrayList<Role>();
for (Role role : roles ) {
RBACObjectAssertions.assertValid(role);
merged.add(em.merge(role));
}
for (Role role : merged) {
fireRbacRoleSaved(role);
}
}
@Override
public Role getRole(String roleName) throws RbacObjectNotFoundException, RbacManagerException {
final EntityManager em = getEm();
TypedQuery<JpaRole> q = em.createQuery("SELECT r FROM JpaRole r WHERE r.name = :rolename", JpaRole.class);
q.setParameter("rolename",roleName);
Role role;
try {
role = q.getSingleResult();
} catch (NoResultException ex) {
log.warn("Role {0} not found", roleName);
throw new RbacObjectNotFoundException("Role not found "+roleName);
}
return role;
}
@Override
public List<Role> getAllRoles() throws RbacManagerException {
final EntityManager em = getEm();
Query q = em.createQuery("SELECT r FROM JpaRole r");
return q.getResultList();
}
@Transactional
@Override
public void removeRole(Role role) throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(role);
if (!(role instanceof JpaRole)) {
throw new RbacObjectInvalidException("Role object is not instance of JpaRole");
}
if ( role.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent role [" + role.getName() + "]" );
}
final EntityManager em = getEm();
JpaRole myRole = em.find(JpaRole.class, role.getName());
if (myRole == null) {
throw new RbacObjectNotFoundException("Role not found "+role.getName());
}
myRole.setPermissions(new ArrayList<Permission>());
em.remove(myRole);
fireRbacRoleRemoved(myRole);
}
@Override
public Permission createPermission(String name) throws RbacManagerException {
JpaPermission permission = new JpaPermission();
permission.setName(name);
return permission;
}
@Override
public Permission createPermission(String name, String operationName, String resourceIdentifier) throws RbacManagerException {
JpaPermission permission = new JpaPermission();
permission.setName(name);
Operation op;
try {
op = getOperation(operationName);
} catch (RbacObjectNotFoundException ex) {
op = createOperation(operationName);
}
permission.setOperation(op);
Resource res;
try {
res = getResource(resourceIdentifier);
} catch (RbacObjectNotFoundException ex) {
res = createResource(resourceIdentifier);
}
permission.setResource(res);
return permission;
}
@Transactional
@Override
public Permission savePermission(Permission permission) throws RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(permission);
if (!(permission instanceof JpaPermission)) {
throw new RbacObjectInvalidException("The permission object ist not instance of JpaPermission");
}
final EntityManager em = getEm();
Permission savedPermission = em.merge(permission);
fireRbacPermissionSaved(savedPermission);
return savedPermission;
}
@Override
public Permission getPermission(String permissionName) throws RbacObjectNotFoundException, RbacManagerException {
final EntityManager em = getEm();
TypedQuery<Permission> q = em.createQuery("SELECT p FROM JpaPermission p WHERE p.name=:name", Permission.class);
q.setParameter("name",permissionName);
Permission res = q.getSingleResult();
if (res==null) {
throw new RbacObjectNotFoundException("Permission "+permissionName+" not found");
}
return res;
}
@Override
public List<Permission> getAllPermissions() throws RbacManagerException {
final EntityManager em = getEm();
TypedQuery<JpaPermission> q = em.createQuery("SELECT p FROM JpaPermission p",JpaPermission.class);
return (List<Permission>)(List<?>)q.getResultList();
}
@Transactional
@Override
public void removePermission(Permission permission) throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(permission);
if (!(permission instanceof JpaPermission)) {
throw new RbacObjectInvalidException("The permission object is not JpaPermission object");
}
if ( permission.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent permission [" + permission.getName() + "]" );
}
final EntityManager em = getEm();
JpaPermission p = em.find(JpaPermission.class, permission.getName());
if (p == null) {
throw new RbacObjectNotFoundException("Permission " + permission.getName() + " not found");
}
em.remove(p);
fireRbacPermissionRemoved(p);
}
@Override
public Operation createOperation(String name) throws RbacManagerException {
JpaOperation op = new JpaOperation();
op.setName(name);
return op;
}
@Transactional
@Override
public Operation saveOperation(Operation operation) throws RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(operation);
if (!(operation instanceof JpaOperation)) {
throw new RbacObjectInvalidException("Operation is not JpaOperation object");
}
final EntityManager em = getEm();
Operation savedOperation = em.merge(operation);
return savedOperation;
}
@Override
public Operation getOperation(String operationName) throws RbacObjectNotFoundException, RbacManagerException {
final EntityManager em = getEm();
Operation op = em.find(JpaOperation.class,operationName);
if(op==null) {
throw new RbacObjectNotFoundException("Operation "+operationName+" not found");
}
return op;
}
@Override
public List<Operation> getAllOperations() throws RbacManagerException {
final EntityManager em = getEm();
Query q = em.createQuery("SELECT o FROM JpaOperation o");
return q.getResultList();
}
@Transactional
@Override
public void removeOperation(Operation operation) throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(operation);
if (!(operation instanceof JpaOperation)) {
throw new RbacObjectInvalidException("Operation is not JpaOperation object");
}
if ( operation.isPermanent() )
{
throw new RbacPermanentException( "Unable to delete permanent operation [" + operation.getName() + "]" );
}
final EntityManager em = getEm();
JpaOperation op = em.find(JpaOperation.class, operation.getName());
if (op==null) {
throw new RbacObjectNotFoundException("Operation not found "+operation.getName());
}
em.remove(op);
}
@Override
public Resource createResource(String identifier) throws RbacManagerException {
JpaResource resource = new JpaResource();
resource.setIdentifier(identifier);
return resource;
}
@Transactional
@Override
public Resource saveResource(Resource resource) throws RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(resource);
if (!(resource instanceof JpaResource)) {
throw new RbacObjectInvalidException("Resource is not JpaResource");
}
final EntityManager em = getEm();
Resource savedResource = em.merge(resource);
return savedResource;
}
// Overriding to add the transactional attribute here
@Transactional
@Override
public Resource getGlobalResource()
throws RbacManagerException
{
return super.getGlobalResource();
}
@Override
public Resource getResource(String resourceIdentifier) throws RbacObjectNotFoundException, RbacManagerException {
final EntityManager em = getEm();
Resource r = em.find(JpaResource.class,resourceIdentifier);
if (r==null) {
throw new RbacObjectNotFoundException("Resource "+resourceIdentifier+" not found");
}
return r;
}
@Override
public List<Resource> getAllResources() throws RbacManagerException {
final EntityManager em = getEm();
TypedQuery<JpaResource> q = em.createQuery("SELECT r FROM JpaResource r",JpaResource.class);
return (List<Resource>)(List<?>)q.getResultList();
}
@Transactional
@Override
public void removeResource(Resource resource) throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(resource);
if (!(resource instanceof JpaResource)) {
throw new RbacObjectInvalidException("Resource is not JpaResource");
}
if (resource.isPermanent()) {
throw new RbacObjectInvalidException("Unable to delete permanent resource ["+resource.getIdentifier()+ "]");
}
final EntityManager em = getEm();
JpaResource res = em.find(JpaResource.class, resource.getIdentifier());
if (res==null) {
throw new RbacObjectNotFoundException("Resource "+resource.getIdentifier()+" not found");
}
em.remove(res);
}
@Override
public UserAssignment createUserAssignment(String principal) throws RbacManagerException {
JpaUserAssignment ua = new JpaUserAssignment();
ua.setPrincipal(principal);
return ua;
}
@Transactional
@Override
public UserAssignment saveUserAssignment(UserAssignment userAssignment) throws RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(userAssignment);
if (!(userAssignment instanceof JpaUserAssignment)) {
throw new RbacObjectInvalidException("Cannto save object that is not JpaUserAssignment");
}
final EntityManager em = getEm();
UserAssignment savedAssignment = em.merge(userAssignment);
fireRbacUserAssignmentSaved(savedAssignment);
return savedAssignment;
}
@Override
public UserAssignment getUserAssignment(String principal) throws RbacObjectNotFoundException, RbacManagerException {
final EntityManager em = getEm();
UserAssignment ua = em.find(JpaUserAssignment.class, principal);
if (ua==null) {
throw new RbacObjectNotFoundException("User assignment not found "+principal);
}
return ua;
}
@Override
public List<UserAssignment> getAllUserAssignments() throws RbacManagerException {
final EntityManager em = getEm();
Query q = em.createQuery("SELECT ua FROM JpaUserAssignment ua");
return q.getResultList();
}
@Override
public List<UserAssignment> getUserAssignmentsForRoles(Collection<String> roleNames) throws RbacManagerException {
try {
final EntityManager em = getEm();
Query q = em.createQuery("SELECT ua FROM JpaUserAssignment ua WHERE ua.roleNames IN :roles");
q.setParameter("roles", roleNames);
return q.getResultList();
} catch (Exception ex) {
log.error("Query failed: {}",ex.getMessage(),ex);
if (log.isDebugEnabled()) {
ex.printStackTrace();
}
throw new RbacManagerException(ex.getMessage(),ex);
}
}
@Transactional
@Override
public void removeUserAssignment(UserAssignment userAssignment) throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException {
RBACObjectAssertions.assertValid(userAssignment);
if (userAssignment.isPermanent()) {
throw new RbacObjectInvalidException("Cannot remove permanent object "+userAssignment.getPrincipal());
}
final EntityManager em = getEm();
JpaUserAssignment ua = em.find(JpaUserAssignment.class, userAssignment.getPrincipal());
if (ua==null) {
throw new RbacObjectNotFoundException("User assignment not found "+userAssignment.getPrincipal());
}
em.remove(ua);
fireRbacUserAssignmentRemoved(userAssignment);
}
@Transactional
@Override
public void eraseDatabase() {
final EntityManager em = getEm();
// Deletion is a bit tricky, because the JPA bulk delete queries do not cascade
// or keep foreign keys into account.
TypedQuery<JpaPermission> tqp = em.createQuery("SELECT r FROM JpaPermission r",JpaPermission.class);
for(JpaPermission p : tqp.getResultList()) {
p.setOperation(null);
p.setResource(null);
}
TypedQuery<JpaRole> tqr = em.createQuery("SELECT r FROM JpaRole r",JpaRole.class);
for (JpaRole r : tqr.getResultList()) {
r.getPermissions().clear();
}
em.flush();
TypedQuery<JpaOperation> tqo = em.createQuery("SELECT o FROM JpaOperation o",JpaOperation.class);
for(JpaOperation o : tqo.getResultList()) {
em.remove(o);
}
TypedQuery<JpaResource> tqre = em.createQuery("SELECT re FROM JpaResource re",JpaResource.class);
for(JpaResource re : tqre.getResultList()) {
em.remove(re);
}
for (JpaPermission p : tqp.getResultList()) {
em.remove(p);
}
for (JpaRole r : tqr.getResultList()) {
em.remove(r);
}
TypedQuery<JpaUserAssignment> tqu = em.createQuery("SELECT ua FROM JpaUserAssignment ua", JpaUserAssignment.class);
for(JpaUserAssignment ua : tqu.getResultList()) {
em.remove(ua);
}
em.flush();
em.clear();
}
@Override
public String getDescriptionKey() {
return "archiva.redback.rbacmanager.jpa";
}
@Override
public boolean isReadOnly() {
return false;
}
private EntityManager getEm() {
if (initialized.compareAndSet(false, true)) {
Query q = em.createQuery("SELECT COUNT(r.name) FROM JpaRole r");
boolean dbInit = q.getFirstResult()==0;
fireRbacInit(dbInit);
}
return em;
}
@Override
public boolean isFinalImplementation() {
return true;
}
}

View File

@ -0,0 +1,91 @@
package org.apache.archiva.redback.rbac.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.Operation;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created by martin on 25.09.16.
*/
@Entity
@Table(name="SECURITY_OPERATIONS")
public class JpaOperation implements Operation, Serializable {
@Id
@Column(name="NAME")
private String name;
@Column(name="DESCRIPTION")
private String description;
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaOperation that = (JpaOperation) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}

View File

@ -0,0 +1,123 @@
package org.apache.archiva.redback.rbac.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.Operation;
import org.apache.archiva.redback.rbac.Permission;
import org.apache.archiva.redback.rbac.Resource;
import org.apache.archiva.redback.rbac.jpa.JpaRbacManager;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by martin on 25.09.16.
*/
@Entity
@Table(name="SECURITY_PERMISSIONS")
public class JpaPermission implements Permission,Serializable {
@Id
@Column(name="NAME")
private String name;
@Column(name="DESCRIPTION")
private String description;
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(
name="OPERATION_NAME_OID",
referencedColumnName = "NAME"
)
private JpaOperation operation;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(
name="RESOURCE_IDENTIFIER_OID",
referencedColumnName = "IDENTIFIER"
)
private JpaResource resource;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
@Override
public Operation getOperation() {
return operation;
}
@Override
public void setOperation(Operation operation) {
this.operation = (JpaOperation)operation;
}
@Override
public Resource getResource() {
return resource;
}
@Override
public void setResource(Resource resource) {
this.resource = (JpaResource)resource;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaPermission that = (JpaPermission) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}

View File

@ -0,0 +1,91 @@
package org.apache.archiva.redback.rbac.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.Resource;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created by martin on 25.09.16.
*/
@Entity
@Table(name="SECURITY_RESOURCES")
public class JpaResource implements Resource, Serializable {
@Id
@Column(name="IDENTIFIER")
private String identifier;
@Column(name="PATTERN", nullable = false)
private Boolean pattern = false;
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@Override
public String getIdentifier() {
return identifier;
}
@Override
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
@Override
public boolean isPattern() {
return pattern;
}
@Override
public void setPattern(boolean pattern) {
this.pattern = pattern;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaResource that = (JpaResource) o;
return identifier.equals(that.identifier);
}
@Override
public int hashCode() {
return identifier.hashCode();
}
}

View File

@ -0,0 +1,176 @@
package org.apache.archiva.redback.rbac.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.AbstractRole;
import org.apache.archiva.redback.rbac.Permission;
import org.springframework.core.annotation.Order;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by martin on 25.09.16.
*/
@Entity
@Table(
name="SECURITY_ROLES"
)
public class JpaRole extends AbstractRole implements Serializable {
@Id
@Column(name="NAME")
private String name;
@Column(name="DESCRIPTION")
private String description;
@Column(name="ASSIGNABLE",nullable = false)
private Boolean assignable = false;
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@OrderColumn(name="INTEGER_IDX", nullable = false)
@JoinTable(
name="SECURITY_ROLE_PERMISSION_MAP",
joinColumns={ @JoinColumn(name="NAME_OID", referencedColumnName="NAME", nullable = false) },
inverseJoinColumns = {
@JoinColumn(name="NAME_EID",referencedColumnName = "NAME")
}
)
List<JpaPermission> permissions = new ArrayList<JpaPermission>();
@ElementCollection(fetch = FetchType.EAGER)
@OrderColumn(name="INTEGER_IDX",nullable = false)
@Column(name="STRING_ELE")
@CollectionTable(
name="SECURITY_ROLE_CHILDROLE_MAP",
joinColumns = {
@JoinColumn(name="NAME_OID",referencedColumnName = "NAME", nullable = false)
}
)
List<String> childRoleNames = new ArrayList<String>();
@Override
public void addPermission(Permission permission) {
if (permission instanceof JpaPermission) {
this.permissions.add((JpaPermission) permission);
}
}
@Override
public void addChildRoleName(String name) {
this.childRoleNames.add(name);
}
@Override
public List<String> getChildRoleNames() {
return childRoleNames;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getName() {
return name;
}
@Override
public List<Permission> getPermissions() {
// Maybe better to create a new list?
return (List<Permission>)(List<?>)permissions;
}
@Override
public boolean isAssignable() {
return assignable;
}
@Override
public void removePermission(Permission permission) {
this.permissions.remove(permission);
}
@Override
public void setAssignable(boolean assignable) {
this.assignable=assignable;
}
@Override
public void setChildRoleNames(List<String> names) {
this.childRoleNames.clear();
this.childRoleNames.addAll(names);
}
@Override
public void setDescription(String description) {
this.description=description;
}
@Override
public void setName(String name) {
this.name=name;
}
@Override
public void setPermissions(List<Permission> permissions) {
this.permissions.clear();
for (Permission p : permissions) {
if (p instanceof JpaPermission) {
permissions.add(p);
}
}
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent=permanent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
JpaRole jpaRole = (JpaRole) o;
return name.equals(jpaRole.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}

View File

@ -0,0 +1,121 @@
package org.apache.archiva.redback.rbac.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.AbstractUserAssignment;
import org.apache.archiva.redback.rbac.UserAssignment;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by Martin Stockhammer <martin_s@apache.org> on 26.09.16.
*/
@Entity
@Table(name="SECURITY_USER_ASSIGNMENTS")
public class JpaUserAssignment extends AbstractUserAssignment implements UserAssignment,Serializable {
@Id
@Column(name="PRINCIPAL")
private String principal;
@ElementCollection(fetch = FetchType.EAGER)
@Column(name="STRING_ELE")
@OrderColumn(name="INTEGER_IDX", nullable = false)
@CollectionTable(
name="SECURITY_USERASSIGNMENT_ROLENAMES",
joinColumns = {
@JoinColumn(name = "PRINCIPAL_OID", referencedColumnName = "PRINCIPAL", nullable = false)
}
)
private List<String> roleNames = new ArrayList<String>();
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@Column(name="LAST_UPDATED")
private Date timestamp;
@Override
public String getPrincipal() {
return principal;
}
@Override
public void setPrincipal(String principal) {
this.principal = principal;
}
@Override
public List<String> getRoleNames() {
return roleNames;
}
@Override
public void setRoleNames(List<String> roleNames) {
this.roleNames = roleNames;
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaUserAssignment that = (JpaUserAssignment) o;
return principal.equals(that.principal);
}
@Override
public int hashCode() {
return principal.hashCode();
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}

View File

@ -23,11 +23,8 @@
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">
<context:annotation-config />
<context:component-scan base-package="org.apache.archiva.redback.users.jdo"/>
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="org.apache.archiva.redback.rbac.jpa"/>
</beans>

View File

@ -0,0 +1,135 @@
package org.apache.archiva.redback.rbac.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rbac.RbacManagerException;
import org.apache.archiva.redback.tests.AbstractRbacManagerTestCase;
import org.junit.Before;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.io.InputStream;
import java.util.Properties;
/**
* JdoRbacManagerTest:
*
* @author Jesse McConnell
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*/
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional
public class JpaRbacManagerTest
extends AbstractRbacManagerTestCase
{
@Inject
@Named(value = "rbacManager#jpa")
RBACManager rbacManager;
public static int EVENTCOUNT = 2;
@Override
public void assertEventCount()
{
assertEquals( EVENTCOUNT, eventTracker.initCount );
}
/**
* Creates a new RbacStore which contains no data.
*/
@Before
public void setUp()
throws Exception
{
super.setUp();
// Properties props = new Properties();
// InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");
// assert is!=null;
// props.load(is);
// is.close();
// EntityManagerFactory emf = Persistence.createEntityManagerFactory("redback-jpa",props);
//
log.info("test setup");
// rbacManager.setEntityManager(emf.createEntityManager());
super.setRbacManager(rbacManager);
assertNotNull(rbacManager);
log.info("injected rbac manager "+rbacManager);
}
@Override
public void testGetAssignedRoles()
throws RbacManagerException
{
super.testGetAssignedRoles();
}
@Override
public void testGetAssignedPermissionsDeep()
throws RbacManagerException
{
super.testGetAssignedPermissionsDeep();
}
@Override
protected void afterSetup()
{
super.afterSetup();
}
@Override
public void testLargeApplicationInit()
throws RbacManagerException
{
this.clearCache();
super.testLargeApplicationInit();
}
@Override
public void testGetRolesDeep()
throws RbacManagerException
{
this.clearCache();
super.testGetRolesDeep();
}
@Override
public void testStoreInitialization()
throws Exception
{
this.clearCache();
rbacManager.eraseDatabase();
eventTracker.rbacInit( true );
super.testStoreInitialization();
assertEquals( EVENTCOUNT, eventTracker.initCount );
}
}

View File

@ -0,0 +1,67 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.apache.archiva.redback.rbac.jpa" />
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>
<bean name="commons-configuration" class="org.apache.archiva.redback.components.registry.commons.CommonsConfigurationRegistry">
</bean>
<alias name="commons-configuration" alias="test-conf"/>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -14,4 +14,4 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
jdbc.driver.name=org.hsqldb.jdbcDriver

View File

@ -72,10 +72,6 @@
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-jdo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-cached</artifactId>

View File

@ -20,11 +20,11 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="false">
<context:property-placeholder system-properties-mode="OVERRIDE"/>
@ -63,20 +63,6 @@
<alias name="ldapRoleMapper#test" alias="ldapRoleMapper#default"/>
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>
@ -123,5 +109,35 @@
<property name="timeToLiveSeconds" value="600"/>
</bean>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -19,23 +19,10 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
@ -47,6 +34,36 @@
<alias name="commons-configuration" alias="test-conf"/>
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -62,19 +62,10 @@
<groupId>org.apache.archiva.redback</groupId>
<scope>test</scope>
</dependency>
<dependency>
<artifactId>redback-rbac-jdo</artifactId>
<groupId>org.apache.archiva.redback</groupId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-model</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jdo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-rbac-cached</artifactId>

View File

@ -19,8 +19,7 @@ package org.apache.archiva.redback.role;
* under the License.
*/
import org.apache.archiva.redback.rbac.jdo.JdoRbacManager;
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.rbac.RBACManager;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
@ -28,8 +27,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
/**
* RoleManagerTest:
@ -41,38 +38,31 @@ import javax.jdo.PersistenceManagerFactory;
public class JpoxRoleManagerTest
extends AbstractRoleManagerTest
{
@Inject
@Named( value = "jdoFactory#users" )
DefaultConfigurableJdoFactory jdoFactory;
@Inject
@Named( value = "rbacManager#jdo" )
JdoRbacManager rbacManagerJdo;
@Inject @Named(value = "roleManager#jpox")
DefaultRoleManager roleManagerInjected;
@Inject
@Named(value = "rbacManager#jpa")
RBACManager rbacManager;
/**
* Creates a new RbacStore which contains no data.
*/
@Before
public void setUp()
throws Exception
throws Exception
{
super.setUp();
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
setRbacManager( rbacManagerJdo );
// rbacManager.setEntityManager(emf.createEntityManager());
super.setRbacManager(rbacManager);
assertNotNull(rbacManager);
setRoleManager( roleManagerInjected );
}
}

View File

@ -26,13 +26,13 @@
<bean name="roleModelProcessor" class="org.apache.archiva.redback.role.processor.DefaultRoleModelProcessor">
<property name="rbacManager" ref="rbacManager#jdo"/>
<property name="rbacManager" ref="rbacManager#jpa"/>
</bean>
<alias name="roleModelProcessor" alias="roleModelProcessor#jpox"/>
<bean name="roleTemplateProcessor" class="org.apache.archiva.redback.role.template.DefaultRoleTemplateProcessor">
<property name="rbacManager" ref="rbacManager#jdo"/>
<property name="rbacManager" ref="rbacManager#jpa"/>
</bean>
<alias name="roleTemplateProcessor" alias="roleTemplateProcessor#jpox"/>
@ -41,35 +41,10 @@
<property name="modelValidator" ref="roleModelValidator"/>
<property name="modelProcessor" ref="roleModelProcessor#jpox"/>
<property name="templateProcessor" ref="roleTemplateProcessor#jpox"/>
<property name="rbacManager" ref="rbacManager#jdo"/>
<property name="rbacManager" ref="rbacManager#jpa"/>
</bean>
<alias name="roleManager" alias="roleManager#jpox"/>
<bean name="rbacManager#jdo" class="org.apache.archiva.redback.rbac.jdo.JdoRbacManager">
<property name="jdo" ref="jdoTool"/>
<property name="enableCache" value="false"/>
</bean>
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-jpox-role-manager-test" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.transactionIsolation">READ_UNCOMMITTED</prop>
<prop key="org.jpox.poid.transactionIsolation">READ_UNCOMMITTED</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
<prop key="org.jpox.autoCreateSchema">true</prop>
<prop key="javax.jdo.option.RetainValues">true</prop>
<prop key="javax.jdo.option.RestoreValues">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>

View File

@ -19,25 +19,12 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="false">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
<prop key="org.jpox.autoCreateTables">true</prop>
</props>
</property>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
@ -72,4 +59,35 @@
<alias name="templateProcessor#memory" alias="roleTemplateProcessor"/>
-->
<!--
*** jpa init ***
Needed because of the dependency redback-user-cache -> redback-user-jpa
***
-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<!-- **** jpa init *** -->
</beans>

View File

@ -19,23 +19,37 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean name="jdoFactory#users" class="org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
<property name="persistenceManagerFactoryClass" value="org.jpox.PersistenceManagerFactoryImpl"/>
<property name="otherProperties">
<props>
<prop key="org.jpox.rdbms.dateTimezone">JDK_DEFAULT_TIMEZONE</prop>
</props>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
</bean>

View File

@ -36,8 +36,8 @@
<modules>
<module>redback-users-cached</module>
<module>redback-users-memory</module>
<module>redback-users-jdo</module>
<module>redback-users-ldap</module>
<module>redback-users-configurable</module>
<module>redback-users-jpa</module>
</modules>
</project>

View File

@ -51,14 +51,18 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-jdo</artifactId>
<artifactId>redback-users-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>

View File

@ -19,9 +19,9 @@
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="true">
<bean name="userManager#cached" class="org.apache.archiva.redback.users.cached.CachedUserManager">
@ -46,4 +46,30 @@
<alias name="userManager#configurable" alias="userManager#default"/>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -1,176 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-providers</artifactId>
<version>2.7-SNAPSHOT</version>
</parent>
<artifactId>redback-users-jdo</artifactId>
<packaging>jar</packaging>
<name>Redback :: Users Provider :: JDO</name>
<dependencies>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jdo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-policy</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.stax-utils</groupId>
<artifactId>stax-utils</artifactId>
<version>20060502</version>
<exclusions>
<exclusion>
<groupId>com.bea.xml</groupId>
<artifactId>jsr173-ri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/user.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-java</id>
<goals>
<goal>java</goal>
<goal>stax-reader</goal>
<goal>stax-writer</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.archiva.redback.components.modello</groupId>
<artifactId>jpox-modello-maven-plugin</artifactId>
<configuration>
<version>1.0.1</version>
<packageWithVersion>false</packageWithVersion>
<models>
<model>src/main/mdo/user.mdo</model>
</models>
</configuration>
<executions>
<execution>
<id>modello-jpox</id>
<goals>
<goal>jpox-metadata-class</goal>
</goals>
</execution>
<execution>
<id>jpox-jdo-mapping</id>
<goals>
<goal>jpox-jdo-mapping</goal>
</goals>
<configuration>
<outputDirectory>${project.build.outputDirectory}/org/apache/archiva/redback/users/jdo</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jpox-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,466 +0,0 @@
package org.apache.archiva.redback.users.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.components.jdo.JdoFactory;
import org.apache.archiva.redback.components.jdo.RedbackJdoUtils;
import org.apache.archiva.redback.components.jdo.RedbackObjectNotFoundException;
import org.apache.archiva.redback.components.jdo.RedbackStoreException;
import org.apache.archiva.redback.policy.UserSecurityPolicy;
import org.apache.archiva.redback.users.AbstractUserManager;
import org.apache.archiva.redback.users.PermanentUserException;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.archiva.redback.users.UserQuery;
import org.codehaus.plexus.util.StringUtils;
import org.jpox.JDOClassLoaderResolver;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import java.util.Date;
import java.util.List;
/**
* JdoUserManager
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*/
@Service("userManager#jdo")
public class JdoUserManager
extends AbstractUserManager
{
@Inject
@Named(value = "jdoFactory#users")
private JdoFactory jdoFactory;
@Inject
private UserSecurityPolicy userSecurityPolicy;
private PersistenceManagerFactory pmf;
public String getId()
{
return "jdo";
}
public boolean isReadOnly()
{
return false;
}
public UserQuery createUserQuery()
{
return new JdoUserQuery();
}
// ------------------------------------------------------------------
public User createUser( String username, String fullname, String email )
{
User user = new JdoUser();
user.setUsername( username );
user.setFullName( fullname );
user.setEmail( email );
user.setAccountCreationDate( new Date() );
return user;
}
public List<User> getUsers()
{
return getAllObjectsDetached( null );
}
public List<User> getUsers( boolean orderAscending )
{
String ordering = orderAscending ? "username ascending" : "username descending";
return getAllObjectsDetached( ordering );
}
@SuppressWarnings("unchecked")
private List<User> getAllObjectsDetached( String ordering )
{
return RedbackJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoUser.class, ordering, (String) null );
}
public List<User> findUsersByUsernameKey( String usernameKey, boolean orderAscending )
{
return findUsers( "username", usernameKey, orderAscending );
}
public List<User> findUsersByFullNameKey( String fullNameKey, boolean orderAscending )
{
return findUsers( "fullName", fullNameKey, orderAscending );
}
public List<User> findUsersByEmailKey( String emailKey, boolean orderAscending )
{
return findUsers( "email", emailKey, orderAscending );
}
@SuppressWarnings("unchecked")
public List<User> findUsersByQuery( UserQuery userQuery )
{
JdoUserQuery uq = (JdoUserQuery) userQuery;
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Extent extent = pm.getExtent( JdoUser.class, true );
Query query = pm.newQuery( extent );
String ordering = uq.getOrdering();
query.setOrdering( ordering );
query.declareImports( "import java.lang.String" );
query.declareParameters( uq.getParameters() );
query.setFilter( uq.getFilter() );
query.setRange( uq.getFirstResult(),
uq.getMaxResults() < 0 ? Long.MAX_VALUE : uq.getFirstResult() + uq.getMaxResults() );
List<User> result = (List<User>) query.executeWithArray( uq.getSearchKeys() );
result = (List<User>) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollback( tx );
}
}
@SuppressWarnings("unchecked")
private List<User> findUsers( String searchField, String searchKey, boolean ascendingUsername )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Extent extent = pm.getExtent( JdoUser.class, true );
Query query = pm.newQuery( extent );
String ordering = ascendingUsername ? "username ascending" : "username descending";
query.setOrdering( ordering );
query.declareImports( "import java.lang.String" );
query.declareParameters( "String searchKey" );
query.setFilter( "this." + searchField + ".toLowerCase().indexOf(searchKey.toLowerCase()) > -1" );
List<User> result = (List<User>) query.execute( searchKey );
result = (List<User>) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollback( tx );
}
}
public User addUser( User user )
throws UserManagerException
{
if ( !( user instanceof JdoUser ) )
{
throw new UserManagerException( "Unable to Add User. User object " + user.getClass().getName() +
" is not an instance of " + JdoUser.class.getName() );
}
if ( StringUtils.isEmpty( user.getUsername() ) )
{
throw new IllegalStateException(
Messages.getString( "user.manager.cannot.add.user.without.username" ) ); //$NON-NLS-1$
}
userSecurityPolicy.extensionChangePassword( user );
fireUserManagerUserAdded( user );
// TODO: find a better solution
// workaround for avoiding the admin from providing another password on the next login after the
// admin account has been created
// extensionChangePassword by default sets the password change status to false
if ( "admin".equals( user.getUsername() ) )
{
user.setPasswordChangeRequired( false );
}
else
{
user.setPasswordChangeRequired( true );
}
return (User) addObject( user );
}
public void deleteUser( String username )
throws UserManagerException
{
try
{
User user = findUser( username );
if ( user.isPermanent() )
{
throw new PermanentUserException( "Cannot delete permanent user [" + user.getUsername() + "]." );
}
fireUserManagerUserRemoved( user );
RedbackJdoUtils.removeObject( getPersistenceManager(), user );
}
catch ( UserNotFoundException e )
{
log.warn( "Unable to delete user {}, user not found.", username, e );
}
}
public void addUserUnchecked( User user )
throws UserManagerException
{
if ( !( user instanceof JdoUser ) )
{
throw new UserManagerException( "Unable to Add User. User object " + user.getClass().getName() +
" is not an instance of " + JdoUser.class.getName() );
}
if ( StringUtils.isEmpty( user.getUsername() ) )
{
throw new IllegalStateException(
Messages.getString( "user.manager.cannot.add.user.without.username" ) ); //$NON-NLS-1$
}
addObject( user );
}
public void eraseDatabase()
{
RedbackJdoUtils.removeAll( getPersistenceManager(), JdoUser.class );
RedbackJdoUtils.removeAll( getPersistenceManager(), UsersManagementModelloMetadata.class );
}
public User findUser( String username )
throws UserNotFoundException, UserManagerException
{
if ( StringUtils.isEmpty( username ) )
{
throw new UserNotFoundException( "User with empty username not found." );
}
return (User) getObjectById( username, null );
}
@Override
public User findUser( String username, boolean useCache )
throws UserNotFoundException, UserManagerException
{
return findUser( username );
}
public boolean userExists( String principal )
throws UserManagerException
{
try
{
findUser( principal );
return true;
}
catch ( UserNotFoundException ne )
{
return false;
}
}
public User updateUser( User user )
throws UserNotFoundException, UserManagerException
{
return updateUser( user, false );
}
public User updateUser( User user, boolean passwordChangeRequired )
throws UserNotFoundException, UserManagerException
{
if ( !( user instanceof JdoUser ) )
{
throw new UserManagerException( "Unable to Update User. User object " + user.getClass().getName() +
" is not an instance of " + JdoUser.class.getName() );
}
// If password is supplied, assume changing of password.
// TODO: Consider adding a boolean to the updateUser indicating a password change or not.
if ( StringUtils.isNotEmpty( user.getPassword() ) )
{
userSecurityPolicy.extensionChangePassword( user, passwordChangeRequired );
}
user = (User) updateObject( user );
fireUserManagerUserUpdated( user );
return user;
}
@PostConstruct
public void initialize()
{
JDOClassLoaderResolver d;
pmf = jdoFactory.getPersistenceManagerFactory();
}
public PersistenceManager getPersistenceManager()
{
PersistenceManager pm = pmf.getPersistenceManager();
pm.getFetchPlan().setMaxFetchDepth( -1 );
triggerInit();
return pm;
}
// ----------------------------------------------------------------------
// jdo utility methods
// ----------------------------------------------------------------------
private Object addObject( Object object )
{
return RedbackJdoUtils.addObject( getPersistenceManager(), object );
}
private Object getObjectById( String id, String fetchGroup )
throws UserNotFoundException, UserManagerException
{
try
{
return RedbackJdoUtils.getObjectById( getPersistenceManager(), JdoUser.class, id, fetchGroup );
}
catch ( RedbackObjectNotFoundException e )
{
throw new UserNotFoundException( e.getMessage() );
}
catch ( RedbackStoreException e )
{
throw new UserManagerException( "Unable to get object '" + JdoUser.class.getName() + "', id '" + id +
"', fetch-group '" + fetchGroup + "' from jdo store.", e );
}
}
private Object removeObject( Object o )
throws UserManagerException
{
if ( o == null )
{
throw new UserManagerException( "Unable to remove null object" );
}
RedbackJdoUtils.removeObject( getPersistenceManager(), o );
return o;
}
private Object updateObject( Object object )
throws UserNotFoundException, UserManagerException
{
try
{
return RedbackJdoUtils.updateObject( getPersistenceManager(), object );
}
catch ( RedbackStoreException e )
{
throw new UserManagerException(
"Unable to update the '" + object.getClass().getName() + "' object in the jdo database. Cause: " + e.getMessage(), e );
}
}
private void rollback( Transaction tx )
{
RedbackJdoUtils.rollbackIfActive( tx );
}
private boolean hasTriggeredInit = false;
public void triggerInit()
{
if ( !hasTriggeredInit )
{
hasTriggeredInit = true;
List<User> users = getAllObjectsDetached( null );
fireUserManagerInit( users.isEmpty() );
}
}
public JdoFactory getJdoFactory()
{
return jdoFactory;
}
public void setJdoFactory( JdoFactory jdoFactory )
{
this.jdoFactory = jdoFactory;
}
public UserSecurityPolicy getUserSecurityPolicy()
{
return userSecurityPolicy;
}
public boolean isFinalImplementation()
{
return true;
}
public String getDescriptionKey()
{
return "archiva.redback.usermanager.jdo";
}
}

View File

@ -1,136 +0,0 @@
package org.apache.archiva.redback.users.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.users.AbstractUserQuery;
import org.apache.archiva.redback.users.UserQuery;
import org.codehaus.plexus.util.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class JdoUserQuery
extends AbstractUserQuery
{
/**
* Create the ordering string for use in {@link javax.jdo.Query#setOrdering(String)}
*
* @return the created filter
*/
public String getOrdering()
{
StringBuilder ordering = new StringBuilder();
if ( UserQuery.ORDER_BY_EMAIL.equals( getOrderBy() ) )
{
ordering.append( "email" );
}
else if ( UserQuery.ORDER_BY_FULLNAME.equals( getOrderBy() ) )
{
ordering.append( "fullName" );
}
else
{
ordering.append( "username" );
}
ordering.append( " " ).append( isAscending() ? "ascending" : "descending" );
return ordering.toString();
}
/**
* Create and return the filter string for use in {@link javax.jdo.Query#setFilter(String)}
*
* @return the query filter
*/
public String getFilter()
{
Set<String> terms = new HashSet<String>();
if ( getUsername() != null )
{
terms.add( "this.username.toLowerCase().indexOf(usernameKey.toLowerCase()) > -1" );
}
if ( getFullName() != null )
{
terms.add( "this.fullName.toLowerCase().indexOf(fullNameKey.toLowerCase()) > -1" );
}
if ( getEmail() != null )
{
terms.add( "this.email.toLowerCase().indexOf(emailKey.toLowerCase()) > -1" );
}
return StringUtils.join( terms.iterator(), " && " );
}
/**
* Return an array of parameters for user in {@link javax.jdo.Query#executeWithArray(Object[])}
*
* @return the parameter array
*/
public String[] getSearchKeys()
{
List<String> keys = new ArrayList<String>();
if ( getUsername() != null )
{
keys.add( getUsername() );
}
if ( getFullName() != null )
{
keys.add( getFullName() );
}
if ( getEmail() != null )
{
keys.add( getEmail() );
}
return keys.toArray( new String[keys.size()] );
}
/**
* Returns the parameters for use in {@link javax.jdo.Query#declareParameters(String)}
*
* @return the parameter list
*/
public String getParameters()
{
List<String> params = new ArrayList<String>();
if ( getUsername() != null )
{
params.add( "String usernameKey" );
}
if ( getFullName() != null )
{
params.add( "String fullNameKey" );
}
if ( getEmail() != null )
{
params.add( "String emailKey" );
}
return StringUtils.join( params.iterator(), ", " );
}
}

View File

@ -1,94 +0,0 @@
package org.apache.archiva.redback.users.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Localized Message Handling.
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.archiva.redback.users.jdo"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
/**
* Get a Message as-is from the Resource Bundle.
*
* @param key the key for the message to get.
* @return the value of the key, or "!key!" if the key is not found.
*/
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
/**
* Gets a Message from the Resource Bundle, with {1} and {2} style arguments.
*
* @param key the key for the message to get.
* @param arg the argument to pass in.
* @return the value of the key, or "!key!" if the key is not found.
*/
public static String getString( String key, Object arg )
{
return getString( key, new Object[] { arg } );
}
/**
* Gets a Message from the Resource Bundle, with {1} and {2} style arguments.
*
* @param key the key for the message to get.
* @param args the arguments to pass in.
* @return the value of the key, or "!key!" if the key is not found.
*/
public static String getString( String key, Object args[] )
{
try
{
String pattern = RESOURCE_BUNDLE.getString( key );
return MessageFormat.format( pattern, args );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
/**
* Prevent Instantiation.
*/
private Messages()
{
}
}

View File

@ -1,162 +0,0 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<model>
<id>redback-users-jdo</id>
<name>UsersManagement</name>
<version>1.0.1</version>
<description>Archiva Redback Users object model.</description>
<defaults>
<default>
<key>package</key>
<value>org.apache.archiva.redback.users.jdo</value>
</default>
</defaults>
<classes>
<class stash.storable="false" rootElement="true">
<name>UserDatabase</name>
<version>1.0.1+</version>
<fields>
<field>
<name>users</name>
<version>1.0.1+</version>
<association>
<type>JdoUser</type>
<multiplicity>*</multiplicity>
</association>
</field>
</fields>
</class>
<class stash.storable="true" jpox.use-identifiers-as-primary-key="false">
<name>JdoUser</name>
<version>1.0.0+</version>
<interfaces>
<interface>org.apache.archiva.redback.users.User</interface>
</interfaces>
<description></description>
<fields>
<field jpox.primary-key="true" jpox.value-strategy="off" jpox.persistence-modifier="persistent">
<name>username</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field jpox.column="USER_PASSWORD">
<name>password</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>encodedPassword</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>fullName</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field>
<name>email</name>
<version>1.0.0+</version>
<type>String</type>
<identifier>true</identifier>
</field>
<field xml.format="long">
<name>lastPasswordChange</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
<field xml.format="long">
<name>lastLoginDate</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
<field>
<name>countFailedLoginAttempts</name>
<version>1.0.0+</version>
<type>int</type>
</field>
<field>
<name>locked</name>
<version>1.0.0+</version>
<type>boolean</type>
<defaultValue>false</defaultValue>
<identifier>true</identifier>
</field>
<field>
<name>permanent</name>
<version>1.0.0+</version>
<type>boolean</type>
<defaultValue>false</defaultValue>
<identifier>true</identifier>
</field>
<field>
<name>validated</name>
<version>1.0.0+</version>
<type>boolean</type>
<defaultValue>false</defaultValue>
<identifier>true</identifier>
</field>
<field>
<name>passwordChangeRequired</name>
<version>1.0.0+</version>
<type>boolean</type>
<defaultValue>false</defaultValue>
<identifier>true</identifier>
</field>
<field>
<name>previousEncodedPasswords</name>
<version>1.0.0+</version>
<association stash.part="true">
<type>String</type>
<multiplicity>*</multiplicity>
</association>
</field>
<field xml.format="long">
<name>accountCreationDate</name>
<version>1.0.0+</version>
<type>Date</type>
</field>
</fields>
<codeSegments>
<codeSegment>
<version>1.0.0+</version>
<code><![CDATA[
public JdoUser()
{
// Intentionally initialize List to avoid JPOX NullPointerException Issues.
previousEncodedPasswords = new java.util.ArrayList<String>();
}
public String getUserManagerId()
{
return "jdo";
}
]]></code>
</codeSegment>
</codeSegments>
</class>
</classes>
</model>

View File

@ -1,117 +0,0 @@
package org.apache.archiva.redback.users.jdo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.components.jdo.DefaultConfigurableJdoFactory;
import org.apache.archiva.redback.common.jdo.test.StoreManagerDebug;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.provider.test.AbstractUserManagerTestCase;
import org.jpox.AbstractPersistenceManagerFactory;
import org.jpox.SchemaTool;
import org.junit.Before;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
/**
* JdoUserManagerTest
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
*/
public class JdoUserManagerTest
extends AbstractUserManagerTestCase
{
@Inject
@Named(value = "jdoFactory#users")
DefaultConfigurableJdoFactory jdoFactory;
@Inject
@Named(value = "userManager#jdo")
JdoUserManager jdoUserManager;
private StoreManagerDebug storeManager;
@Before
public void setUp()
throws Exception
{
super.setUp();
jdoFactory.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" ); //$NON-NLS-1$
jdoFactory.setDriverName( "org.hsqldb.jdbcDriver" ); //$NON-NLS-1$
jdoFactory.setUrl( "jdbc:hsqldb:mem:" + getName() ); //$NON-NLS-1$
jdoFactory.setUserName( "sa" ); //$NON-NLS-1$
jdoFactory.setPassword( "" ); //$NON-NLS-1$
jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
Properties properties = jdoFactory.getProperties();
for ( Map.Entry<?, ?> entry : properties.entrySet() )
{
System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
}
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
/* set our own Store Manager to allow counting SQL statements */
StoreManagerDebug.setup( (AbstractPersistenceManagerFactory) pmf );
SchemaTool.createSchemaTables(
new URL[]{ getClass().getResource( "/org/apache/archiva/redback/users/jdo/package.jdo" ) }, new URL[]{ },
null, false, null ); //$NON-NLS-1$
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
setUserManager( jdoUserManager );
/* save the store manager to access the queries executed */
JdoUserManager userManager = (JdoUserManager) getUserManager();
storeManager = StoreManagerDebug.getConfiguredStoreManager( userManager.getPersistenceManager() );
}
protected void assertCleanUserManager()
throws UserManagerException
{
// database cleanup
( (JdoUserManager) getUserManager() ).eraseDatabase();
super.assertCleanUserManager();
}
}

View File

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>redback-users-providers</artifactId>
<groupId>org.apache.archiva.redback</groupId>
<version>2.5-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>redback-users-jpa</artifactId>
<packaging>jar</packaging>
<name>Redback :: Users Provider :: JPA</name>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-policy</artifactId>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-common-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${openjpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.archiva.redback</groupId>
<artifactId>redback-users-tests</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<configuration>
<includes>**/model/*.class</includes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<!-- set the version to be the same as the level in your runtime -->
<version>${openjpa.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,352 @@
package org.apache.archiva.redback.users.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.policy.UserSecurityPolicy;
import org.apache.archiva.redback.users.*;
import org.apache.archiva.redback.users.jpa.model.JpaUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by martin on 20.09.16.
*/
@Service("userManager#jpa")
public class JpaUserManager extends AbstractUserManager {
@PersistenceContext(unitName = "redback-jpa")
EntityManager em;
@Inject
private UserSecurityPolicy userSecurityPolicy;
// JpaUserManager is a singleton and initialization should be thread safe
private AtomicBoolean initialized = new AtomicBoolean(false);
public void setEntityManager(EntityManager em) {
this.em = em;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public String getId() {
return "jpa";
}
private EntityManager getEm() {
if (initialized.compareAndSet(false,true)) {
Query q = em.createQuery("SELECT COUNT(u.username) FROM JpaUser u");
boolean dbInit = q.getFirstResult()==0;
fireUserManagerInit(dbInit);
}
return em;
}
@Override
public User createUser(String username, String fullName, String emailAddress) throws UserManagerException {
JpaUser user = new JpaUser();
user.setUsername(username);
user.setFullName(fullName);
user.setEmail(emailAddress);
return user;
}
@Override
public UserQuery createUserQuery() {
return new JpaUserQuery();
}
@Override
public List<User> getUsers() throws UserManagerException {
final EntityManager em = getEm();
Query q= em.createQuery("SELECT x from JpaUser x");
return q.getResultList();
}
@Override
public List<User> getUsers(boolean orderAscending) throws UserManagerException {
final EntityManager em = getEm();
final String orderFlag = orderAscending ? "ASC" : "DESC";
Query q = em.createQuery("SELECT u FROM JpaUser u ORDER BY u.username "+orderFlag);
return q.getResultList();
}
@Transactional
@Override
public User addUser(User user) throws UserManagerException {
EntityManager em = getEm();
if ( !( user instanceof JpaUser ) )
{
throw new UserManagerException( "Unable to Add User. User object " + user.getClass().getName() +
" is not an instance of " + JpaUser.class.getName() );
}
if ( StringUtils.isEmpty( user.getUsername() ) )
{
throw new IllegalStateException(
Messages.getString( "user.manager.cannot.add.user.without.username" ) ); //$NON-NLS-1$
}
userSecurityPolicy.extensionChangePassword( user );
fireUserManagerUserAdded( user );
// TODO: find a better solution
// workaround for avoiding the admin from providing another password on the next login after the
// admin account has been created
// extensionChangePassword by default sets the password change status to false
if ( "admin".equals( user.getUsername() ) )
{
user.setPasswordChangeRequired( false );
}
else
{
user.setPasswordChangeRequired( true );
}
if (user.getLastPasswordChange()==null) {
user.setLastPasswordChange(new Date());
}
em.persist((JpaUser)user);
return user;
}
@Transactional
@Override
public User updateUser(User user) throws UserNotFoundException, UserManagerException {
return updateUser(user, false);
}
@Override
public User findUser(String username) throws UserNotFoundException, UserManagerException {
if (username==null) {
throw new UserNotFoundException("Username was <null>");
}
final EntityManager em = getEm();
TypedQuery<JpaUser> q = em.createQuery("SELECT u FROM JpaUser u WHERE LOWER(u.username)=:uname", JpaUser.class);
q.setParameter("uname",username.toLowerCase());
User result;
try {
result = q.getSingleResult();
} catch (NoResultException ex ) {
throw new UserNotFoundException(ex);
}
return result;
}
@Override
public User findUser(String username, boolean useCache) throws UserNotFoundException, UserManagerException {
return findUser(username);
}
@Override
public List<User> findUsersByUsernameKey(String usernameKey, boolean orderAscending) throws UserManagerException {
return findUsers("username",usernameKey,"username",orderAscending);
}
@Override
public List<User> findUsersByFullNameKey(String fullNameKey, boolean orderAscending) throws UserManagerException {
return findUsers("fullName",fullNameKey,"username",orderAscending);
}
@Override
public List<User> findUsersByEmailKey(String emailKey, boolean orderAscending) throws UserManagerException {
return findUsers("email",emailKey,"username", orderAscending);
}
@Override
public List<User> findUsersByQuery(final UserQuery queryParam) throws UserManagerException {
final EntityManager em = getEm();
final JpaUserQuery query = (JpaUserQuery)queryParam;
String orderByAttribute = "";
if (UserQuery.ORDER_BY_EMAIL.equals(query.getOrderBy())) {
orderByAttribute="email";
} else if (UserQuery.ORDER_BY_FULLNAME.equals(query.getOrderBy())) {
orderByAttribute="fullName";
} else if (UserQuery.ORDER_BY_USERNAME.equals(query.getOrderBy())) {
orderByAttribute="username";
} else {
throw new IllegalArgumentException("Unknown order attribute "+query.getOrderBy());
}
StringBuilder sb = new StringBuilder("SELECT u FROM JpaUser u ");
if (query.hasUsername()||query.hasFullName()||query.hasEmail()) {
sb.append("WHERE ");
}
boolean checkBefore = false;
if (query.hasUsername()) {
sb.append("LOWER(u.username) LIKE :username ");
checkBefore=true;
}
if (query.hasEmail()) {
if (checkBefore) {
sb.append("AND ");
}
checkBefore=true;
sb.append("LOWER(u.email) LIKE :email ");
}
if (query.hasFullName()) {
if (checkBefore) {
sb.append("AND ");
}
sb.append("LOWER(u.fullName) LIKE :fullname ");
}
if (query.getOrderBy()!=null && !"".equals(query.getOrderBy())) {
sb.append("ORDER BY u.").append(orderByAttribute).append(query.isAscending() ? " ASC" : " DESC");
}
TypedQuery<User> q = em.createQuery(sb.toString(), User.class);
if (query.hasUsername()) {
q.setParameter("username", "%"+query.getUsername().toLowerCase()+"%");
}
if (query.hasEmail()) {
q.setParameter("email", "%"+query.getEmail().toLowerCase()+"%");
}
if (query.hasFullName()) {
q.setParameter("fullname", "%"+query.getFullName().toLowerCase()+"%");
}
q.setFirstResult((int)query.getFirstResult()).setMaxResults((int)query.getMaxResults());
return q.getResultList();
}
private List<User> findUsers(final String attribute, final String pattern,
final String orderAttribute, final boolean orderAscending) {
final EntityManager em = getEm();
StringBuilder sb = new StringBuilder("SELECT u FROM JpaUser u WHERE LOWER(u.");
sb.append(attribute).append(") LIKE :patternvalue ORDER BY u.").append(orderAttribute);
sb.append(orderAscending ? " ASC" : " DESC");
TypedQuery<User> q = em.createQuery(sb.toString(),User.class);
q.setParameter("patternvalue","%"+pattern.toLowerCase()+"%");
return q.getResultList();
}
@Override
public boolean userExists(String principal) throws UserManagerException {
EntityManager em = getEm();
JpaUser user = em.find(JpaUser.class, principal);
return user != null;
}
@Transactional
@Override
public void deleteUser(String username) throws UserNotFoundException, UserManagerException {
final EntityManager em = getEm();
User u = findUser(username);
if (u.isPermanent()) {
throw new PermanentUserException("User "+username+" cannot be deleted");
}
em.remove(u);
fireUserManagerUserRemoved(u);
}
@Transactional
@Override
public void addUserUnchecked(User user) throws UserManagerException {
log.info("addUserUnchecked "+user.getUsername());
if ( !( user instanceof JpaUser ) )
{
throw new UserManagerException( "Unable to Add User. User object " + user.getClass().getName() +
" is not an instance of " + JpaUser.class.getName() );
}
if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getUsername() ) )
{
throw new IllegalStateException(
Messages.getString( "user.manager.cannot.add.user.without.username" ) ); //$NON-NLS-1$
}
TypedQuery<JpaUser> q = em.createQuery("SELECT u FROM JpaUser u", JpaUser.class);
for (JpaUser u : q.getResultList()) {
log.info("USER FOUND: "+u.getUsername());
}
log.info("NEW USER "+user.getUsername());
em.persist((JpaUser)user);
}
@Transactional
@Override
public void eraseDatabase() {
EntityManager em = getEm();
TypedQuery<JpaUser> q = em.createQuery("SELECT u FROM JpaUser u", JpaUser.class);
for (JpaUser u : q.getResultList()) {
u.getPreviousEncodedPasswords().clear();
}
em.flush();
Query qd = em.createQuery("DELETE FROM JpaUser u");
qd.executeUpdate();
em.clear();
}
@Transactional
@Override
public User updateUser(User user, boolean passwordChangeRequired) throws UserNotFoundException, UserManagerException {
if ( !( user instanceof JpaUser ) )
{
throw new UserManagerException( "Unable to update user. User object " + user.getClass().getName() +
" is not an instance of " + JpaUser.class.getName() );
}
if ( StringUtils.isNotEmpty( user.getPassword() ) )
{
userSecurityPolicy.extensionChangePassword( user, passwordChangeRequired );
}
JpaUser jpaUser = (JpaUser) user;
final EntityManager em = getEm();
jpaUser = em.merge(jpaUser);
fireUserManagerUserUpdated(jpaUser);
return jpaUser;
}
@Override
public String getDescriptionKey() {
return "archiva.redback.usermanager.jpa";
}
@Override
public boolean isFinalImplementation() {
return true;
}
// Override to add transactional annotation
@Transactional
@Override
public User createGuestUser() throws UserManagerException {
return super.createGuestUser();
}
}

View File

@ -0,0 +1,123 @@
package org.apache.archiva.redback.users.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.users.UserQuery;
import java.util.Arrays;
/**
* Created by martin on 23.09.16.
*/
public class JpaUserQuery implements UserQuery {
private String username;
private String email;
private String fullName;
private long firstResult=0;
private long maxResults=Integer.MAX_VALUE;
private boolean ascending=true;
private String orderBy="username";
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
public boolean hasUsername() {
return username != null && !"".equals(username);
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
public boolean hasEmail() {
return email!=null && !"".equals(email);
}
@Override
public String getFullName() {
return fullName;
}
@Override
public void setFullName(String fullName) {
this.fullName = fullName;
}
public boolean hasFullName() {
return fullName!=null && !"".equals(fullName);
}
@Override
public long getFirstResult() {
return firstResult;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
@Override
public long getMaxResults() {
return maxResults;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
@Override
public boolean isAscending() {
return ascending;
}
@Override
public void setAscending(boolean ascending) {
this.ascending = ascending;
}
@Override
public String getOrderBy() {
return orderBy;
}
@Override
public void setOrderBy(String orderBy) {
if (!UserQuery.ALLOWED_ORDER_FIELDS.contains(orderBy)) {
throw new IllegalArgumentException("Order attribute not allowed: "+orderBy);
}
this.orderBy = orderBy;
}
}

View File

@ -0,0 +1,259 @@
package org.apache.archiva.redback.users.jpa.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.openjpa.persistence.ExternalValues;
import org.apache.openjpa.persistence.Type;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by martin on 20.09.16.
*/
@Entity
@Table(name="JDOUSER")
public class JpaUser implements org.apache.archiva.redback.users.User {
@Id
@Column(name="USERNAME")
private String username;
@Column(name="FULL_NAME")
private String fullName;
@Column(name="EMAIL")
private String email;
@Column(name="ENCODED_PASSWORD")
private String encodedPassword;
@Column(name="LAST_PASSWORD_CHANGE")
private Date lastPasswordChange;
@ElementCollection(fetch = FetchType.EAGER)
@OrderColumn(name="INTEGER_IDX", nullable = false)
@Column(name="STRING_ELE", nullable = false)
@CollectionTable(name="JDOUSER_PREVIOUSENCODEDPASSWORDS",
joinColumns = @JoinColumn(name = "USERNAME_OID", nullable = false, referencedColumnName = "USERNAME")
)
private List<String> previousEncodedPasswords = new ArrayList<String>();
@Column(name="PERMANENT", nullable = false)
private Boolean permanent = false;
@Column(name="LOCKED", nullable = false)
private Boolean locked = false;
@Column(name="PASSWORD_CHANGE_REQUIRED", nullable = false)
private Boolean passwordChangeRequired = false;
@Column(name="VALIDATED", nullable = false)
private Boolean validated = false;
@Column(name="COUNT_FAILED_LOGIN_ATTEMPTS",nullable = false)
private int countFailedLoginAttempts = 0;
@Column(name="ACCOUNT_CREATION_DATE")
private Date accountCreationDate;
@Column(name="LAST_LOGIN_DATE")
private Date lastLoginDate;
@Column(name="USER_PASSWORD")
private String rawPassword;
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String name) {
this.username = name;
}
@Override
public String getFullName() {
return fullName;
}
@Override
public void setFullName(String name) {
this.fullName = name;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String address) {
this.email = address;
}
@Override
public String getPassword() {
return rawPassword;
}
@Override
public void setPassword(String rawPassword) {
this.rawPassword = rawPassword;
}
@Override
public String getEncodedPassword() {
return encodedPassword;
}
@Override
public void setEncodedPassword(String encodedPassword) {
this.encodedPassword = encodedPassword;
}
@Override
public Date getLastPasswordChange() {
return lastPasswordChange;
}
@Override
public void setLastPasswordChange(Date passwordChangeDate) {
this.lastPasswordChange = passwordChangeDate;
}
@Override
public List<String> getPreviousEncodedPasswords() {
if (previousEncodedPasswords==null) {
setPreviousEncodedPasswords(new ArrayList<String>());
}
assert previousEncodedPasswords != null;
return previousEncodedPasswords;
}
@Override
public void setPreviousEncodedPasswords(List<String> encodedPasswordList) {
if (previousEncodedPasswords==null) {
previousEncodedPasswords = new ArrayList<String>();
}
previousEncodedPasswords.clear();
previousEncodedPasswords.addAll(encodedPasswordList);
}
@Override
public void addPreviousEncodedPassword(String encodedPassword) {
if (previousEncodedPasswords==null) {
previousEncodedPasswords = new ArrayList<String>();
}
previousEncodedPasswords.add(encodedPassword);
}
@Override
public boolean isPermanent() {
return permanent;
}
@Override
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
@Override
public boolean isLocked() {
return locked;
}
@Override
public void setLocked(boolean locked) {
this.locked = locked;
}
@Override
public boolean isPasswordChangeRequired() {
return passwordChangeRequired;
}
@Override
public void setPasswordChangeRequired(boolean changeRequired) {
this.passwordChangeRequired = changeRequired;
}
@Override
public boolean isValidated() {
return validated;
}
@Override
public void setValidated(boolean valid) {
this.validated = valid;
}
@Override
public int getCountFailedLoginAttempts() {
return countFailedLoginAttempts;
}
@Override
public void setCountFailedLoginAttempts(int count) {
this.countFailedLoginAttempts = count;
}
@Override
public Date getAccountCreationDate() {
return accountCreationDate;
}
@Override
public void setAccountCreationDate(Date date) {
this.accountCreationDate = date;
}
@Override
public Date getLastLoginDate() {
return lastLoginDate;
}
@Override
public void setLastLoginDate(Date date) {
this.lastLoginDate = date;
}
@Override
public String getUserManagerId() {
return "jpa";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JpaUser jpaUser = (JpaUser) o;
return username.equals(jpaUser.username);
}
@Override
public int hashCode() {
return username.hashCode();
}
}

View File

@ -24,9 +24,8 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="org.apache.archiva.redback.users.jpa" />
<context:annotation-config />
<context:component-scan base-package="org.apache.archiva.redback.keys.jdo"/>
</beans>

View File

@ -0,0 +1,94 @@
package org.apache.archiva.redback.users.jpa;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.redback.policy.UserSecurityPolicy;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.archiva.redback.users.jpa.model.JpaUser;
import org.apache.archiva.redback.users.provider.test.AbstractUserManagerTestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
*
* Test for the JPA User Manager
*
* @author <a href="mailto:martin_s@apache.org">Martin Stockhammer</a>
*/
@Transactional
public class JpaUserManagerTest extends AbstractUserManagerTestCase {
Log log = LogFactory.getLog(JpaUserManagerTest.class);
@Inject
@Named("userManager#jpa")
UserManager jpaUserManager;
@Inject
EntityManagerFactory entityManagerFactory;
@Inject
private UserSecurityPolicy securityPolicy;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
assertNotNull(jpaUserManager);
super.setUserManager(jpaUserManager);
log.info("injected usermanager "+jpaUserManager);
}
@Test
public void testInit() {
assertNotNull(jpaUserManager);
jpaUserManager.initialize();
}
}

View File

@ -21,21 +21,14 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.apache.archiva.redback.users.jpa" />
<bean name="jdoFactory#users" class="org.apache.archiva.redback.common.jdo.UserConfigurableJdoFactory">
<constructor-arg>
<ref bean="userConfiguration#default"/>
</constructor-arg>
<!--property name="userConfiguration" ref="userConfiguration#default"/-->
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:redback-users-tests" />
<property name="userName" value="sa"/>
<property name="password" value=""/>
</bean>
<bean name="userConfiguration#default" class="org.apache.archiva.redback.configuration.DefaultUserConfiguration">
<property name="registry" ref="test-conf"/>
@ -55,4 +48,33 @@
<alias name="commons-configuration" alias="test-conf"/>
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-hsqldb.xml" />
<property name="jpaPropertyMap">
<map>
<entry key="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:redback_database" />
<entry key="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<entry key="openjpa.ConnectionUserName" value="sa" />
<entry key="openjpa.ConnectionPassword" value="" />
<entry key="openjpa.Log" value="DefaultLevel=TRACE, Runtime=TRACE, Tool=INFO, SQL=TRACE" />
<entry key="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<entry key="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict"/>
</map>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>

View File

@ -14,5 +14,4 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
user.manager.cannot.add.user.without.username=User.username must be supplied on an .addUser() request.
user.manager.cannot.add.user.without.password=User.password must be supplied on an .addUser() request.

View File

@ -97,10 +97,12 @@ public class AbstractUserManagerTestCase
throws UserManagerException
{
assertNotNull(userManager);
getUserManager().eraseDatabase();
getEventTracker().userManagerInit( true );
assertNotNull( getUserManager() );
assertNotNull(userManager.getUsers());
assertEquals( "New UserManager should contain no users. " + userManager.getUsers(), 0,
userManager.getUsers().size() );
}