Subversion Repositories linid-dm

Compare Revisions

Rev 501 → Rev 503

/branches/Tapestry-5.4-beta/T5-java-codingstyle.txt New file
0,0 → 1,148
This file define the common rules and convention about the organization of the Java
code of Tapestry Pages and Components.
 
This classes consist of several kind of block.
Each kind of block must be preceded by an *visible* comment,
as show here after. The order of blocks is madatory.
Block may be omitted if there is no such code in the class, or let
empty so that everybody is sur that there no such kind of code
in the class.
 
Aa easy copy&past :
 
/* ***********************************************************
* Parameters
************************************************************ */
 
/* ***********************************************************
* Injected services
************************************************************ */
 
/* ***********************************************************
* Injected components
************************************************************ */
/* ***********************************************************
* Properties & ASO, etc
************************************************************ */
/* ==== END OF PROPERTIES ==== */
/* ***********************************************************
* Phase processing
************************************************************ */
/* ***********************************************************
* Event handlers&processing
************************************************************ */
 
/* ***********************************************************
* Helpers
************************************************************ */
/* ***********************************************************
* Helpers
************************************************************ */
/* ***********************************************************
* Getters & Setters
************************************************************ */
Details in Kinds of block :
 
Parameters
===========
* Comment to copy&paste before :
 
/* ***********************************************************
* Parameters
************************************************************ */
* description
Parameter are component parameters : private attributes with
@Parameter annotation.
 
Injection
==========
* Comment to copy&paste before :
 
/* ***********************************************************
* Injected services (properties, etc)
************************************************************ */
 
* description
Here goes injected service, properties, environnemental, etc.
One may define a block by kind of injection.
Each kind of injection should be set in after "Injected ".
 
Properties
===========
* Comment to copy&paste before :
 
/* ***********************************************************
* Properties
************************************************************ */
 
* description
Here goes attribute that are not parameters. These
attribute may be managed (with @Persist annotation, for ex).
 
Phase processing
=================
* Comment to copy&paste before :
 
/* ***********************************************************
* Phase processing
************************************************************ */
 
* description
Here goes method that deals with rendering phases, as describes here :
http://tapestry.apache.org/tapestry5/tapestry-core/guide/rendering.html
(such as method annotated with @setupRender, etc).
 
 
Events handling
================
* Comment to copy&paste before :
 
/* ***********************************************************
* Event handlers&processing
************************************************************ */
 
* description
Here goes event handling and methods alike ( onActivate, onPassivate).
 
Helpers
========
* Comment to copy&paste before :
 
/* ***********************************************************
* Helpers
************************************************************ */
* description
Here goes (private or protected) methods used elsewhere in the code as helper.
 
 
Javascript
=============
* Comment to copy&paste before :
 
/* ***********************************************************
* Javascript
************************************************************ */
* description
Here goes method that should render Javascript code. For now, Javascript
support in T5 is somewhat strange, so we have to do it by hand.
 
 
8/Getters / Setters
* Comment to copy&paste before :
 
/* ***********************************************************
* Getters & Setters
************************************************************ */
 
* description
Getters and setters for code used in template.
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/ldap/repository/TestLdapEntryRepository.java New file
0,0 → 1,108
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.repository;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.ldap.LdapName;
 
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.linid.dm.ldap.repository.LdapEntryRepository;
 
public class TestLdapEntryRepository {
 
private static LdapEntryRepository entryRepository;
@BeforeClass
public static void setUpBeforeClass() {
entryRepository = new DefaultLdapEntryRepository();
}
 
@AfterClass
public static void tearDownAfterClass() {
}
 
@Before
public void setUp() {
}
 
@After
public void tearDown() {
}
 
@Test
public final void testGetDnPath() throws InvalidNameException {
String root = "ou=example,ou=org";
LdapName rootDn = new LdapName(root);
LdapName badRootDn = new LdapName("ou=bad,ou=root");
LdapName emptyRootDn = new LdapName("");
LdapName childDn = new LdapName("uid=foo,ou=bar,ou=example,ou=org");
LdapName emptyChildDn = new LdapName("");
LdapName childEqualsRootDn = new LdapName("ou=example,ou=org");
List<Name> path = entryRepository.getDnPath(rootDn, childDn);
List<Name> referencePath = new ArrayList<Name>();
referencePath.add(new LdapName(root));
referencePath.add(new LdapName("ou=bar,"+root));
referencePath.add(new LdapName("uid=foo,ou=bar,"+root));
Assert.assertArrayEquals(referencePath.toArray(), path.toArray());
path = entryRepository.getDnPath(rootDn, childEqualsRootDn);
referencePath = new ArrayList<Name>();
referencePath.add(new LdapName(root));
Assert.assertArrayEquals(referencePath.toArray(), path.toArray());
 
path = entryRepository.getDnPath(rootDn, emptyChildDn);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
path = entryRepository.getDnPath(emptyRootDn, childDn);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
path = entryRepository.getDnPath(emptyRootDn, emptyChildDn);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
path = entryRepository.getDnPath(badRootDn, childDn);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
path = entryRepository.getDnPath(null, childDn);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
 
path = entryRepository.getDnPath(rootDn, null);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
 
path = entryRepository.getDnPath(null, null);
Assert.assertArrayEquals(new Object[]{}, path.toArray());
}
 
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/ldap/repository/LdapRepositoryModule.java New file
0,0 → 1,68
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.repository;
 
import java.util.Properties;
 
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.SubModule;
import org.linid.dm.ldap.core.LdapFacadeFactory;
import org.linid.dm.ldap.postprocessing.PostProcessingModule;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.repository.LdapEntryRepository;
import org.linid.dm.authorization.AuthorizationModule;
import org.springframework.core.io.ClassPathResource;
 
@SubModule({PostProcessingModule.class})
public class LdapRepositoryModule {
private static final String CONFIG_FILE = "configuration.properties";
public static LdapEntryRepository build(
@InjectService("facadeFactory") LdapFacadeFactory facadeFactory,
@InjectService("entryPostProcessor") EntryPostProcessor postProcessor,
@InjectService("entryTypeAnalyzer") EntryTypeAnalyzer typeAnalyzer,
@InjectService("ldapRepositoryAuthzModule") AuthorizationModule authorizationModule){
DefaultLdapEntryRepository repository = new DefaultLdapEntryRepository();
repository.setLdapFacadeFactory(facadeFactory);
repository.setEntryPostProcessor(postProcessor);
repository.setEntryTypeAnalyzer(typeAnalyzer);
repository.setAuthorizationModule(authorizationModule);
/*
* TODO : build a SymbolProvider for properties files.
*/
Properties properties = new Properties();
try {
properties.load(new ClassPathResource(CONFIG_FILE).getInputStream() );
} catch (Exception e) {
throw new RuntimeException("The file '"+CONFIG_FILE+"' use to retrieve configuration properties has not been found");
}
repository.setUserDnTemplate(properties.getProperty("ldap.user.dn"));
return repository;
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/ldap/repository/DefaultLdapEntryRepository.java New file
0,0 → 1,57
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.repository;
 
import javax.naming.Name;
 
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.core.LdapFacadeFactory;
import org.linid.dm.ldap.repository.service.impl.AbstractLdapEntryRepository;
 
/**
* A default implementation for the Entries Repository,
* witch is based upon the LdapFacade with proxied authentication
* for the User LdapFAcade. It's seem to be one the most tricky
* case, so that's why I choose to implement it.
* @author LINAGORA
*/
public class DefaultLdapEntryRepository extends AbstractLdapEntryRepository {
 
private LdapFacadeFactory ldapFacadeFactory;
@Override
protected LdapFacade getLdapFacade(Name authDn) {
if(null == authDn) {
return this.ldapFacadeFactory.getAnonymousFacade();
} else {
return this.ldapFacadeFactory.getUserFacade(authDn);
}
}
 
public void setLdapFacadeFactory(LdapFacadeFactory ldapFacadeFactory) {
this.ldapFacadeFactory = ldapFacadeFactory;
}
 
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/app1/pages/ListEditor.java New file
0,0 → 1,86
package org.linid.dm.wui.app1.pages;
 
import java.util.ArrayList;
import java.util.List;
 
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.linid.dm.data.SimplePerson;
 
public class ListEditor {
 
@Persist @Property
private List<SimplePerson> people;
 
@Persist @Property
private List<String> indexes;
@Property
private String index;
public SimplePerson getCurrentPerson() {
return people.get(indexes.indexOf(index));
}
public void setCurrentPerson(SimplePerson p) {
people.set(indexes.indexOf(index), p);
}
void onActivate() {
if(null != people)
for(int i = 0; i < people.size(); i++) {
System.out.println(i + " -> " + people.get(i));
}
}
void setupRender() {
if(null == people) {
people = new ArrayList<SimplePerson>();
indexes = new ArrayList<String>();
}
}
public ValueEncoder<String> getListEncoder() {
return new ValueEncoder<String>() {
 
public String toValue(String key) { return key; }
 
public String toClient(String value) { return value; }
};
}
 
Object onAddRow() {
SimplePerson sp = new SimplePerson();
people.add(sp);
String s = new StringBuilder().append(Math.random()).toString();
indexes.add(s);
System.out.println("index:" + s +" add "+sp);
return s;
}
void onRemoveRow(String key) {
int i = indexes.indexOf(key);
System.out.println("inRemove index: " + key);
// System.out.println(sp);
indexes.remove(i);
people.remove(i);
}
@Persist @Property(write=false)
private List<SimplePerson> result;
@Property
private SimplePerson sp;
void onSuccessFromForm() {
this.result = new ArrayList<SimplePerson>();
for(SimplePerson s:people) {
result.add(s);
}
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/app1/pages/WrappedListEditor.java New file
0,0 → 1,77
package org.linid.dm.wui.app1.pages;
 
import java.util.ArrayList;
import java.util.List;
 
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Cached;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import org.linid.dm.data.IdBeanWrapper;
import org.linid.dm.data.SimplePerson;
 
public class WrappedListEditor {
@Persist @Property(write=false)
private List<IdBeanWrapper<Integer, SimplePerson>> people;
 
@Property
private IdBeanWrapper<Integer, SimplePerson> person;
void onActivate() {
if(null != people)
for(int i = 0; i < people.size(); i++) {
System.out.println(i + ":" + people.get(i));
}
}
void setupRender() {
if(null == people) {
people = new ArrayList<IdBeanWrapper<Integer,SimplePerson>>();
}
}
public ValueEncoder<IdBeanWrapper<Integer, SimplePerson>> getListEncoder() {
return new ValueEncoder<IdBeanWrapper<Integer, SimplePerson>>() {
 
public String toClient(IdBeanWrapper<Integer, SimplePerson> value) {
throw new RuntimeException("uinimplemented");
}
 
public IdBeanWrapper<Integer, SimplePerson> toValue(
String clientValue) {
throw new RuntimeException("uinimplemented");
}
};
}
 
Object onAddRow() {
IdBeanWrapper<Integer, SimplePerson> b =
new IdBeanWrapper<Integer, SimplePerson>(people.size(),new SimplePerson());
people.add(b);
return b;
}
void onRemoveRow(IdBeanWrapper<Integer, SimplePerson> b) {
//key and index are the same thing
people.remove(b.getId().intValue());
}
@Inject
private BeanModelSource source;
@Inject
private ComponentResources resources;
@Cached
public BeanModel<SimplePerson> getModel() {
return source.createEditModel(SimplePerson.class, resources.getMessages());
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/app1/pages/EditEntry.java New file
0,0 → 1,31
package org.linid.dm.wui.app1.pages;
 
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.linid.dm.data.IELdapEntryFactory;
import org.linid.dm.wui.entrymapping.EntryBean;
import org.linid.dm.wui.entrymapping.EntryBeanFactory;
 
public class EditEntry {
 
@Inject
private EntryBeanFactory beanFactory;
@Persist @Property
private EntryBean entry;
void setupRender() {
if(null == this.entry) {
this.entry = beanFactory.newBean(IELdapEntryFactory.newPerson(getActorDn()));
}
}
public String getActorDn() {
return "sn=smith,ou=people,dc=test,dc=org";
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/app1/pages/Index.java New file
0,0 → 1,6
package org.linid.dm.wui.app1.pages;
 
 
public class Index {
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/app1/services/AppModule.java New file
0,0 → 1,121
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.app1.services;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Properties;
 
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.SubModule;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestFilter;
import org.apache.tapestry5.services.RequestHandler;
import org.apache.tapestry5.services.Response;
import org.linid.dm.authorization.AuthorizationModule;
import org.linid.dm.authorization.AuthorizationType;
import org.linid.dm.wui.t5lib.WuiCommonModule;
import org.slf4j.Logger;
 
/**
* This module is automatically included as part of the Tapestry IoC Registry,
* it's a good place to configure and extend Tapestry, or to place your own
* services.
*/
@SubModule( {WuiCommonModule.class})
public class AppModule {
public void contributeApplicationDefaults( MappedConfiguration<String, String> configuration) {
configuration.add("tapestry.supported-locales", "en");
}
 
public RequestFilter buildTimingFilter(final Logger log) {
return new RequestFilter() {
public boolean service(Request request, Response response, RequestHandler handler) throws IOException {
long startTime = System.currentTimeMillis();
log.info(String.format("%s (XHR:%s) : %s", request.getMethod(), request.isXHR(), request.getPath()));
try {
return handler.service(request, response);
} finally {
long elapsed = System.currentTimeMillis() - startTime;
 
log.info(String.format("Request time: %d ms", elapsed));
}
}
};
}
 
/**
* This is a contribution to the RequestHandler service configuration. This
* is how we extend Tapestry using the timing filter. A common use for this
* kind of filter is transaction management or security.
*/
public void contributeRequestHandler(
OrderedConfiguration<RequestFilter> configuration,
@InjectService("TimingFilter") final RequestFilter timingFilter) {
configuration.add("Timing", timingFilter);
}
/* ****************************
* Properties symbol provider *
**************************** */
public void contributePropertiesSymbolProvider(Configuration<String> configuration) {
configuration.add("classpath:configuration_test.properties");
}
/* *****************************************
* Defaults services implementation for that
* test application
******************************************* */
/*
* A kind authorization module that always say OK
*/
public static AuthorizationModule buildWuiAuthzModule() {
return new AuthorizationModule() {
public boolean eval(String principalDN, String targetDN, EnumSet<AuthorizationType> rights, Properties otherVars) {
return true;
}
public boolean eval(String principalDN, String targetDN, EnumSet<AuthorizationType> rights) {
return true;
}
public List<String> eval(String principalDN, String targetDN, EnumSet<AuthorizationType> rights, String... attributeIds) {
return Arrays.asList(attributeIds);
}
public List<String> eval(String principalDN, String targetDN, EnumSet<AuthorizationType> rights, Collection<String> attributeIds) {
List<String> a = new ArrayList<String>();
a.addAll(attributeIds);
return a;
}
};
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/wui/AbstractWuiTapestryTest.java New file
0,0 → 1,45
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */package org.linid.dm.wui;
 
import org.linid.dm.wui.t5lib.WuiCommonModule;
import org.mockito.MockitoAnnotations;
 
import com.formos.tapestry.testify.core.TapestryTester;
import com.formos.tapestry.testify.junit4.TapestryTest;
 
public abstract class AbstractWuiTapestryTest extends TapestryTest {
 
protected static final TapestryTester SHARED_TESTER = new TapestryTester("wui", WuiCommonModule.class);
 
public AbstractWuiTapestryTest() {
super(SHARED_TESTER);
}
@Override
protected void setUpForAllTestMethods() throws Exception {
MockitoAnnotations.initMocks(this);
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/data/SimplePerson.java New file
0,0 → 1,61
package org.linid.dm.data;
 
import java.util.Date;
 
public class SimplePerson {
 
public enum Sex { MALE, FEMALE, NONE }
private String name;
private Date birthdate;
private Boolean hasChildren;
private Sex sex;
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Date getBirthdate() {
return birthdate;
}
 
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
 
public Boolean getHasChildren() {
return hasChildren;
}
 
public void setHasChildren(Boolean hasChildren) {
this.hasChildren = hasChildren;
}
 
public Sex getSex() {
return sex;
}
 
public void setSex(Sex sex) {
this.sex = sex;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("{name:").append(name).append("}");
sb.append("{sex:").append(sex).append("}");
sb.append("{date:").append(birthdate).append("}");
sb.append("{has:").append(hasChildren).append("}");
sb.append("]");
return sb.toString();
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/data/IdBeanWrapper.java New file
0,0 → 1,66
package org.linid.dm.data;
 
import java.io.Serializable;
 
public class IdBeanWrapper<I extends Serializable, V> {
 
private I id;
private V value;
public IdBeanWrapper(I id, V value) {
this.id = id;
this.value = value;
}
public IdBeanWrapper() {
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(!(o instanceof IdBeanWrapper)) return false;
IdBeanWrapper<?, ?> other = (IdBeanWrapper<?, ?>)o;
if(null == id) {
if(null == other.getId()) {
//do not compare values
return true;
} else {
return false;
}
}
return id.equals(other.getId());
}
@Override
public int hashCode() {
if(null == id) return super.hashCode();
return id.hashCode();
}
 
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(id).append("->");
sb.append(value.toString());
sb.append("]");
return sb.toString();
}
public I getId() {
return id;
}
 
public void setId(I id) {
this.id = id;
}
 
public V getValue() {
return value;
}
 
public void setValue(V value) {
this.value = value;
}
}
/branches/Tapestry-5.4-beta/src/test/java/org/linid/dm/data/IELdapEntryFactory.java New file
0,0 → 1,70
package org.linid.dm.data;
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
import javax.naming.InvalidNameException;
 
import org.linid.dm.eschema.IESchemaAttributeDefinition;
import org.linid.dm.eschema.IESchemaClassDefinition;
import org.linid.dm.ldap.eschema.ESchemaAttributeDefinition;
import org.linid.dm.ldap.eschema.ESchemaClassDefinition;
import org.linid.dm.ldap.objects.impl.ELdapEntry;
import org.linid.dm.utils.CaseInsensitiveSet;
 
/**
* This is a simpler way to get IELdapEntries
* than to fully set-up a real repository
*/
public class IELdapEntryFactory {
public static ESchemaClassDefinition newPersonSchema() {
List<IESchemaAttributeDefinition> attrs = new ArrayList<IESchemaAttributeDefinition>();
ESchemaAttributeDefinition uid = ESchemaAttributeDefinition.defaultESchemaAttribute("uid");
uid.setMandatory(true);
uid.setMultiValued(false);
ESchemaAttributeDefinition cn = ESchemaAttributeDefinition.defaultESchemaAttribute("cn");
ESchemaAttributeDefinition sn = ESchemaAttributeDefinition.defaultESchemaAttribute("sn");
ESchemaAttributeDefinition invisible = ESchemaAttributeDefinition.defaultESchemaAttribute("invisible");
invisible.setVisible(false);
invisible.setShownAtCreation(false);
attrs.add(uid);
attrs.add(cn);
attrs.add(sn);
attrs.add(invisible);
ESchemaClassDefinition clazz = new ESchemaClassDefinition("person");
clazz.setAttributeDefinition(attrs);
Set<String> opt = new CaseInsensitiveSet();
opt.add("cn");
opt.add("sn");
opt.add("invisible");
clazz.setOptionalAttributeNames(opt);
Set<String> req = new CaseInsensitiveSet();
req.add("uid");
clazz.setRequiredAttributeNames(req);
return clazz;
}
/**
* Create a "person" entry bean, that is:
* - an ID
* @return the person entry bean
*/
public static ELdapEntry newPerson(String dn) {
Set<IESchemaClassDefinition> clazz = new HashSet<IESchemaClassDefinition>();
clazz.add(newPersonSchema());
ELdapEntry entry = new ELdapEntry(clazz);
try {
entry.setDn(dn);
} catch (InvalidNameException e) {
throw new RuntimeException(e);
}
return entry;
}
}
/branches/Tapestry-5.4-beta/src/test/resources/configuration_test.properties New file
0,0 → 1,18
#Ldap Configuration
#Standard LDAP"url to your server, for instance: ldap://localhost:389/dc=base,dc=org
ldap.url=ldap://localhost:1389
ldap.base=dc=bpi,dc=fr
#Complete root dn, for instance: uid=root,dc=base,dc=org
ldap.root.dn=cn=proxy-enabled-manager
#Root password
ldap.root.password = secret
 
#User used for proxy connection
ldap.proxyuser.dn=cn=proxy-enabled-manager
ldap.proxyuser.password=secret
 
##########
# WUI #
##########
#display debug information in pages
display.debug.info=false
/branches/Tapestry-5.4-beta/src/test/resources/eschema/default/placeholder.txt --- branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/WrappedListEditor.tml (revision 0) +++ branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/WrappedListEditor.tml (revision 503) @@ -0,0 +1,39 @@ + + + Test home page + + + +

Test list editor

+ +
+ + + +
+ +
+ +
+ + remove +
+ + + + + + + \ No newline at end of file
/branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/EditEntry.tml New file
0,0 → 1,13
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
<head>
<title>Test home page</title>
</head>
<body>
<h3>Test entry edition</h3>
 
<form t:type="wui-commons/ldapentry/EntryBeanEditor" principaldn="actordn" source="entry" />
 
</body>
 
</html>
/branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/Index.tml New file
0,0 → 1,13
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
 
<head>
<title>Test home page</title>
</head>
<body>
<h1>Hello test page !</h1>
 
 
</body>
 
</html>
/branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/SimplePeopleEditBlock.tml New file
0,0 → 1,15
<t:container xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p="tapestry:parameter">
 
<t:block t:id="simpleperson">
<t:if test="simpleperson">
<!--
<t:wui-commons.search.criterioneditor t:criterion="criterion" />
-->
<p:else>
Can not edit the object.
</p:else>
</t:if>
</t:block>
</t:container>
/branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/TestTree.tml New file
0,0 → 1,14
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
 
<head>
<title>Test tree with delegates</title>
</head>
<body>
<h1>Tree with delegate</h1>
 
<t:wui-commons.treedelegate source="node" />
 
</body>
 
</html>
/branches/Tapestry-5.4-beta/src/test/resources/org/linid/dm/wui/app1/pages/ListEditor.tml New file
0,0 → 1,43
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
<head>
<title>Test home page</title>
</head>
<body>
<h3>Test list editor</h3>
 
<form t:type="form">
<!--
<t:wui-common.listeditor
object="people"
propertiesClass="literal:org.linid.dm.data.SimplePerson"
dataType="simplepeople"
model="model"
/>
-->
<div t:type="ajaxformloop"
t:id="peopleEditor"
t:source="indexes"
t:encoder="listEncoder"
t:value="index"
>
<t:beaneditor object="currentPerson" />
<t:removerowlink>remove</t:removerowlink>
</div>
<t:submit />
</form>
<hr/>
<t:if test="result">
<ul>
<li t:type="loop" t:source="result" t:value="sp">${sp}</li>
</ul>
</t:if>
</body>
 
</html>
/branches/Tapestry-5.4-beta/src/test/resources/applicationContext-test-common.xml New file
0,0 → 1,45
<?xml version="1.0" encoding="UTF-8"?>
<!--
This library is part of LinID Directory Manager project,
http://linid.org/
 
LinID Directory Manager is a free software subjected to the
** GNU Affero Public License ** as published by the
Free Software Foundation, ** version 3 ** of the license.
 
By application to section 7 in the GNU Affero GPLv3,
dynamic and static links do not extend license to other
softwares.
 
You can redistribute and/or modify since you respect
the term of the license.
 
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
 
You should have received a copy of the GNU Affero General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
Copyright (C) 2008-2013 Linagora http://linagora.com/
-->
 
<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-2.0.xsd"
default-autowire="no">
 
<!-- We do not use autowiring for documentation generation purpose.
A lot of copy/paste, but it's the prize to maintain a valid doc -->
 
<!-- Use external propeties file for environment dependant configuration -->
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configuration_test.properties</value>
</list>
</property>
</bean>
</beans>
/branches/Tapestry-5.4-beta/src/test/resources/applicationContext-ldapFacades.xml New file
0,0 → 1,128
<?xml version="1.0" encoding="UTF-8"?>
<!--
This library is part of LinID Directory Manager project,
http://linid.org/
 
LinID Directory Manager is a free software subjected to the
** GNU Affero Public License ** as published by the
Free Software Foundation, ** version 3 ** of the license.
 
By application to section 7 in the GNU Affero GPLv3,
dynamic and static links do not extend license to other
softwares.
 
You can redistribute and/or modify since you respect
the term of the license.
 
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
 
You should have received a copy of the GNU Affero General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
Copyright (C) 2008-2013 Linagora http://linagora.com/
-->
 
<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-2.0.xsd"
default-autowire="no">
 
<!-- We do not use autowiring to avoid too much wizardry.
A lot of copy/paste, but it's the prize to maintain a understable sources -->
 
<!-- **************************************************************** -->
<!-- DAO beans -->
<!-- **************************************************************** -->
 
<!-- class definition DAO -->
<bean id="classDefinitionDao" class="org.linid.dm.dao.eschema.xstream.XstreamESchemaClassDao" init-method="init">
<property name="eschemaPersistenceDirectory" value="/tmp/xstream"/>
<property name="eschemaRootSourceDirectory" value="classpath:eschema" />
</bean>
 
<!-- LDAP DAO configuration -->
<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="${ldap.url}" />
<!-- <property name="base" value="${ldap.base}" /> -->
<property name="userDn" value="${ldap.root.dn}" />
<property name="password" value="${ldap.root.password}" />
<!-- We do not use context binding with Acegi because we want to be indenpendant from LDAP from auth -->
<!-- <property name="authenticationSource"><ref local="acegiAuthenticationSource" /></property> -->
</bean>
 
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg><ref local="contextSource" /></constructor-arg>
</bean>
 
<!-- We do not use context binding with Acegi because we want to be indenpendant from LDAP from auth -->
<!-- <bean id="acegiAuthenticationSource" class="org.springframework.ldap.core.support.authentication.AcegiAuthenticationSource"/> -->
 
<!-- different Facade and the facade Factory -->
<!-- an anonymous context, singleton -->
<bean id="anonymousLdapContextSource" class="org.linid.dm.dao.ldap.ProxyAuthzContextSource">
<property name="url" value="${ldap.url}" />
<property name="anonymousReadOnly" value="true" />
</bean>
<bean id="anonymousLdapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="anonymousLdapContextSource" />
</bean>
<bean id="anonymousLdapFacade" class="org.linid.dm.dao.ldap.DefaultLdapFacade">
<property name="classDefinitionDao"><ref local="classDefinitionDao"/></property>
<property name="contextSource"><ref local="anonymousLdapContextSource"/></property>
<property name="ldapTemplate"><ref local="anonymousLdapTemplate" /></property>
<property name="stringBaseName" value="${ldap.base}"/>
</bean>
 
<!-- Root authenticated Ldap template -->
<bean id="wuiLdapContextSource" class="org.linid.dm.dao.ldap.ProxyAuthzContextSource">
<property name="url" value="${ldap.url}" />
<!-- <property name="base" value="" /> -->
<!-- We have to use a special manager to enable proxy auth -->
<!-- <property name="userName" value="cn=manager" /> -->
<property name="userDn" value="${ldap.root.dn}" />
<property name="password" value="${ldap.root.password}" />
<!-- We do not use context binding with Acegi because we want to be indenpendant from LDAP from auth -->
<!-- <property name="authenticationSource"><ref local="acegiAuthenticationSource" /></property> -->
</bean>
<bean id="wuiLdapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="wuiLdapContextSource" />
</bean>
<bean id="wuiLdapFacade" class="org.linid.dm.dao.ldap.DefaultLdapFacade">
<property name="classDefinitionDao"><ref local="classDefinitionDao"/></property>
<property name="contextSource"><ref local="wuiLdapContextSource"/></property>
<property name="ldapTemplate"><ref local="wuiLdapTemplate"/></property>
<property name="stringBaseName" value="${ldap.base}"/>
</bean>
<!-- Authenticated LDAP facade, created on demand -->
<bean id="userLdapFacade" class="org.linid.dm.dao.ldap.DefaultLdapFacade" init-method="init" scope="prototype">
<property name="stringBaseName" value="${ldap.base}"/>
<property name="classDefinitionDao"><ref local="classDefinitionDao"/></property>
<property name="contextSource">
<bean class="org.linid.dm.dao.ldap.ProxyAuthzContextSource" scope="prototype">
<property name="url" value="${ldap.url}" />
<!-- <property name="base" value="" /> -->
<!-- We have to use a special manager to enable proxy auth -->
<!-- <property name="userName" value="cn=manager" /> -->
<!-- <property name="userDn" value="${ldap.proxyuser.dn}" />
<property name="password" value="${ldap.proxyuser.password}" />-->
<!-- We do not use context binding with Acegi because we want to be indenpendant from LDAP from auth -->
<!-- <property name="authenticationSource"><ref local="acegiAuthenticationSource" /></property> -->
</bean>
</property>
<property name="ldapTemplate">
<!-- authenticated Ldap template, created on demand -->
<bean id="userLdapContextSource" class="org.springframework.ldap.core.LdapTemplate" scope="prototype">
<!-- this is awful, but I do not know how to refer the same prototype bean two times without the creation of a new one bean -->
<constructor-arg><ref local="anonymousLdapContextSource"/></constructor-arg>
</bean>
</property>
</bean>
 
<bean id="facadeFactory" class="org.linid.dm.dao.ldap.DefaultLdapFacadeFactory"/>
 
</beans>
/branches/Tapestry-5.4-beta/src/test/webapp-app1/WEB-INF/app.properties New file
0,0 → 1,4
#==========================
# Strings in the webapp
#==========================
 
/branches/Tapestry-5.4-beta/src/test/webapp-app1/WEB-INF/web.xml New file
0,0 → 1,36
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>LinID Directory Manager test</display-name>
 
<context-param>
<param-name>tapestry.app-package</param-name>
<param-value>org.linid.dm.wui.app1</param-value>
</context-param>
 
<!-- spring bean definition -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml,classpath*:lqlRules*.xml</param-value>
</context-param>
<!-- tapestry filter -->
<filter>
<filter-name>app</filter-name>
<!-- Special filter that adds in a T5 IoC module derived from the Spring WebApplicationContext. -->
<filter-class>org.apache.tapestry5.spring.TapestrySpringFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>app</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
/branches/Tapestry-5.4-beta/src/main/java/META-INF/MANIFEST.MF New file
0,0 → 1,3
Manifest-Version: 1.0
Class-Path:
 
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/ConfigurableLdapFacadeManager.java New file
0,0 → 1,94
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
import java.util.List;
 
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.exception.InvalidLdapConfiguration;
 
public interface ConfigurableLdapFacadeManager {
 
/**
* List all available connection configuration for this manager
* @return the list of configuraiton, never null
*/
List<LdapConfiguration> listAvailableConfiguration();
 
/**
* Retrieve the configuration with the given ID,
* or null if none match.
* @param configurationId
* @return
*/
LdapConfiguration get(String configurationId);
/**
* @return the current configuration in use or null if none
*/
LdapConfiguration getCurrentConfiguration();
 
/**
* @return the current connected ldap facade or null if none
*/
public abstract LdapFacade getCurrentLdapFacade();
 
/**
* Open a connection that will be used by the repository.
* All previously opened connection will be closed before
* the new connection is made available.
*/
public abstract void useConnection(String configurationId) throws InvalidLdapConfiguration;
 
/**
* Disonnect the current Ldap facade
*/
public abstract void disconnect();
 
/**
* Check if there is a currently available connection
* for the repository
*/
public abstract boolean isConnected();
/**
* @return connections list for the current session
*/
public LdapConfigurationDao getLdapConfigurationRepository();
 
/**
* Store configuration on disk
*/
public void storeConfigurations();
 
/**
* Restore in memory all configurations stored on disk
*/
public void resetConfigurations();
 
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/TestLdapConnection.java New file
0,0 → 1,40
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.data.TestLdapConnectionResult;
 
public interface TestLdapConnection {
 
TestLdapConnectionResult testConnection(String host, int port);
TestLdapConnectionResult testConnection(String host, int port, boolean useLDAPS);
TestLdapConnectionResult testConnection(LdapConfiguration configuration);
TestLdapConnectionResult testAuthentication(String host, int port, String dn, String password);
TestLdapConnectionResult testAuthentication(String host, int port, boolean useLDAPS, String dn, String password);
TestLdapConnectionResult testAuthentication(LdapConfiguration configuration);
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/LdapUtils.java New file
0,0 → 1,47
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
import org.springframework.ldap.core.support.LdapContextSource;
 
public interface LdapUtils {
 
LdapContextSource newLdapContextSource(String ldapUrl);
LdapContextSource newLdapContextSource(String ldapUrl,String userDn, String password);
 
LdapContextSource newLdapContextSource(String host, int port);
 
LdapContextSource newLdapContextSource(String host, int port, String userDn, String password);
 
LdapContextSource newLdapContextSource(String host, int port, boolean useLDAPS);
 
LdapContextSource newLdapContextSource(String host, int port, boolean useLDAPS, String userDn, String password);
 
String buildLdapUrl(String host, int port);
 
String buildLdapUrl(String host, int port, boolean useLDAPS);
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/TestLdapConnectionImpl.java New file
0,0 → 1,93
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service.impl;
 
import javax.naming.directory.DirContext;
 
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.data.TestLdapConnectionResult;
import org.linid.dm.ldap.repository.service.LdapUtils;
import org.linid.dm.ldap.repository.service.TestLdapConnection;
import org.springframework.ldap.AuthenticationException;
import org.springframework.ldap.core.support.LdapContextSource;
 
public class TestLdapConnectionImpl implements TestLdapConnection {
 
private final LdapUtils ldapUtils;
public TestLdapConnectionImpl(final LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
public TestLdapConnectionResult testAuthentication(String host, int port, String dn, String password) {
return testLdapContextSource(host, port, false, dn, password);
}
 
public TestLdapConnectionResult testAuthentication(String host, int port, boolean useLDAPS, String dn, String password) {
return testLdapContextSource(host, port, useLDAPS, dn, password);
}
 
public TestLdapConnectionResult testConnection(String host, int port) {
return testConnection(host, port, false);
}
 
public TestLdapConnectionResult testConnection(String host, int port, boolean useLDAPS) {
TestLdapConnectionResult t = testLdapContextSource(host, port, useLDAPS, null, null);
if(TestLdapConnectionResult.BAD_CONNECTION == t) {
return t;
} else {
return TestLdapConnectionResult.SUCCESS;
}
}
 
private TestLdapConnectionResult testLdapContextSource(String host, int port, boolean useLDAPS, String dn, String password) {
LdapContextSource ctxSrc = ldapUtils.newLdapContextSource(host, port, useLDAPS, dn, password);
DirContext ctx = null;
try {
ctxSrc.afterPropertiesSet();
ctx = ctxSrc.getReadWriteContext();
} catch (AuthenticationException e) {
return TestLdapConnectionResult.BAD_AUTHENTICATION;
} catch (Exception e) {
return TestLdapConnectionResult.BAD_CONNECTION;
} finally {
org.springframework.ldap.support.LdapUtils.closeContext(ctx);
}
return TestLdapConnectionResult.SUCCESS;
}
 
public TestLdapConnectionResult testAuthentication(LdapConfiguration configuration) {
return testAuthentication(
configuration.getLdapHost(), configuration.getLdapPort(), configuration.isUseLDAPS(),
configuration.getBindDn(), configuration.getBindPwd()
);
}
 
public TestLdapConnectionResult testConnection(LdapConfiguration configuration) {
return testConnection(configuration.getLdapHost(), configuration.getLdapPort(), configuration.isUseLDAPS());
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/LdapUtilsImpl.java New file
0,0 → 1,83
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service.impl;
 
import org.apache.commons.lang3.StringUtils;
import org.linid.dm.ldap.repository.service.LdapUtils;
import org.springframework.ldap.core.support.LdapContextSource;
 
public class LdapUtilsImpl implements LdapUtils {
public static final String LDAP_SCHEME = "ldap://";
public static final String LDAPS_SCHEME = "ldaps://";
public String buildLdapUrl(String host, int port) {
return buildLdapUrl(host, port, false);
}
 
public String buildLdapUrl(String host, int port, boolean useLDAPS) {
StringBuilder sb = new StringBuilder();
if (useLDAPS) {
sb.append(LDAPS_SCHEME);
} else {
sb.append(LDAP_SCHEME);
}
sb.append(StringUtils.trim(host));
sb.append(":").append(port).append("/");
return sb.toString();
}
 
public LdapContextSource newLdapContextSource(String ldapUrl) {
return this.newLdapContextSource(ldapUrl, null, null);
}
 
public LdapContextSource newLdapContextSource(String ldapUrl, String userDn, String password) {
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl(ldapUrl);
if(!StringUtils.isEmpty(userDn)) ctxSrc.setUserDn(userDn);
if(!StringUtils.isEmpty(password)) ctxSrc.setPassword(password);
return ctxSrc;
}
 
public LdapContextSource newLdapContextSource(String host, int port) {
return this.newLdapContextSource(this.buildLdapUrl(host, port), null,null);
}
 
public LdapContextSource newLdapContextSource(String host, int port,
boolean useLDAPS) {
return this.newLdapContextSource(this.buildLdapUrl(host, port, useLDAPS), null,null);
}
 
public LdapContextSource newLdapContextSource(String host, int port,String userDn, String password) {
return this.newLdapContextSource(this.buildLdapUrl(host, port), userDn,password);
}
 
@Override
public LdapContextSource newLdapContextSource(String host, int port,
boolean useLDAPS, String userDn, String password) {
return this.newLdapContextSource(this.buildLdapUrl(host, port, useLDAPS), userDn,password);
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/AbstractLdapEntryRepository.java New file
0,0 → 1,500
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.repository.service.impl;
 
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map.Entry;
 
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapName;
 
import org.linid.dm.authorization.AuthorizationException;
import org.linid.dm.authorization.AuthorizationModule;
import org.linid.dm.authorization.AuthorizationType;
import org.linid.dm.ldap.SizeLimitExceededExceptionWithPartialResults;
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.ldap.objects.IELdapAttribute;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer.ActionType;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.repository.LdapEntryRepository;
 
/**
* this class is the central access point for LdapEntries.
* It handle cache pb, thread pb, etc.
* Each time an LdapEntry has to be retrieve or modified,
* you HAVE TO use this repository.
*/
public abstract class AbstractLdapEntryRepository implements LdapEntryRepository {
 
private EntryPostProcessor entryPostProcessor;
 
private EntryTypeAnalyzer entryTypeAnalyzer;
 
/**
* The actual authorization module
*/
private AuthorizationModule authorizationModule;
 
public AbstractLdapEntryRepository() {
}
 
public AbstractLdapEntryRepository(
EntryPostProcessor entryPostProcessor,
EntryTypeAnalyzer entryTypeAnalyzer,
AuthorizationModule authorizationModule) {
this.entryPostProcessor = entryPostProcessor;
this.entryTypeAnalyzer = entryTypeAnalyzer;
this.authorizationModule = authorizationModule;
}
 
/**
* Template to construct user DN from there login name
* @return the template string
*/
private String userDnTemplate;
 
protected abstract LdapFacade getLdapFacade(Name authDn);
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#create(javax.naming.Name, org.linid.dm.ldap.objects.IELdapEntry)
*/
public IELdapEntry create(Name authDn, IELdapEntry entry, Name targetCreateDn) throws NameAlreadyBoundException, AuthorizationException, PostProcessingException {
//for creation, the right is look on the parentDN
LdapName parentDn = new LdapName(entry.getDn().getRdns());
try {
parentDn.remove(parentDn.size()-1);
} catch (InvalidNameException e) {
// Should not happen, but in this case parentDn = entry.getDn() is ok
}
 
/*
if(!targetCreateDn.endsWith(parentDn)) {
throw new AuthorizationException("You do not have sufficient rights to create this entry:" + entry.toString());
}
*/
 
/* TODO :
* SO, we have a pb to create entries of a specific type in a branch.
* In fact, we should be able to match on the target create dn.
*/
if(!this.authorizationModule.eval(authDn.toString(), targetCreateDn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.CREATE))) {
//TODO : log
throw new AuthorizationException("You do not have sufficient rights to create this entry:" + entry.toString());
}
 
IELdapEntry postProcessedEntry =this.postProcess(entry,ActionType.preCreate);
if(null == entry.getModifications()) {
throw new PostProcessingException("An error happen during post processing.");
}
this.getLdapFacade(authDn).createSubcontext(postProcessedEntry);
return this.postProcess(postProcessedEntry,ActionType.postCreate);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#get(javax.naming.Name, javax.naming.Name)
*/
public IELdapEntry get(Name authDn, Name dn) throws AuthorizationException {
if(null == dn)
return null;
if(!this.authorizationModule.eval(authDn == null ? null : authDn.toString(), dn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.READ)))
throw new AuthorizationException("DN '"+authDn+"' has not sufficient rights to access entry '"+dn+"'");
IELdapEntry entry = null;
entry = this.getLdapFacade(authDn).lookup(dn);
return entry;
}
 
@Override
public IELdapEntry get(Name authDn, Name dn, String[] attrs) throws AuthorizationException {
if(null == dn)
return null;
if(!this.authorizationModule.eval(authDn == null ? null : authDn.toString(), dn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.READ)))
throw new AuthorizationException("DN '"+authDn+"' has not sufficient rights to access entry '"+dn+"'");
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.OBJECT_SCOPE);
scs.setReturningAttributes(attrs);
List<IELdapEntry> entries = this.getLdapFacade(authDn).search(dn, "(objectClass=*)", scs );
if (entries == null || entries.size() == 0) {
return null;
} else {
return entries.get(0);
}
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#delete(javax.naming.Name, javax.naming.Name)
*/
public void delete(Name authDn, Name dn) throws AuthorizationException, PostProcessingException {
this.delete(authDn, dn, false);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#delete(javax.naming.Name, javax.naming.Name, boolean)
*/
public void delete(Name authDn, Name dn, boolean recursive) throws AuthorizationException, PostProcessingException {
IELdapEntry toDeleteEntry = get(authDn, dn);
IELdapEntry preProcessedEntry = this.postProcess(toDeleteEntry, ActionType.preDelete);
if(null == preProcessedEntry) {
throw new PostProcessingException("An error happen during post processing.");
}
//TODO: maybe we should check subentries in case of recursive delete
if(!this.authorizationModule.eval(authDn.toString(), dn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.DELETE))) {
throw new AuthorizationException("You do not have sufficient rights to delete the entry matching DN: "+dn.toString());
}
this.getLdapFacade(authDn).destroySubcontext(dn, recursive);
this.postProcess(preProcessedEntry, ActionType.postDelete);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#update(javax.naming.Name, org.linid.dm.ldap.objects.IELdapEntry)
*/
public void update(Name authDn, IELdapEntry input) throws AuthorizationException,PostProcessingException {
/*
* post process the entry
*/
if(null == input) {
return;
}
IELdapEntry entry = this.postProcess(input, ActionType.preUpdate);
if(null == entry || null == entry.getModifications()) {
throw new PostProcessingException("An error happen during post processing.");
}
 
//build the ModificationItems Array from the modification map
List<ModificationItem> modifications = new ArrayList<ModificationItem>();
for(Entry<String, Integer> item : entry.getModifications().entrySet()) {
ModificationItem modificationItem;
if(DirContext.REMOVE_ATTRIBUTE == item.getValue()) {
modificationItem = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(item.getKey()));
} else {
IELdapAttribute attribute;
attribute = entry.getAttribute(item.getKey());
if(null == attribute) {
throw new RuntimeException("An attribute marked as modified is not in the entry");
}
Attribute modifierAttribute = new BasicAttribute(item.getKey());
for(IByteString value : attribute.getValues() ) {
if(null != value.stringValue() && !"".equals(value.stringValue())) {
modifierAttribute.add(value.stringValue());
} else if(null != value.value()) {
modifierAttribute.add(value.value());
}
}
modificationItem = new ModificationItem(item.getValue(), modifierAttribute);
}
modifications.add(modificationItem);
}
 
//process the update.
ModificationItem[] modificationItems = modifications.toArray(new ModificationItem[modifications.size()]);
 
/*
* Validate that authDn has the rights to modify each of the attributes
*/
for(ModificationItem item : modificationItems) {
if(input.getModifications().containsKey(item.getAttribute().getID())
&& this.authorizationModule.eval(authDn.toString(), entry.getDn().toString(), EnumSet.<AuthorizationType>of(AuthorizationType.MODIFY), item.getAttribute().getID()).size() != 1) {
throw new AuthorizationException("You do not have sufficient rights to modify the attribute: '" +item.getAttribute().getID()+"' for entry "+input.getDn().toString());
}
}
//TODO : the exception hierarchy is a mess !!
this.getLdapFacade(authDn).modifyAttributes(entry.getDn(), modificationItems);
this.postProcess(input, ActionType.postUpdate);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#move(javax.naming.Name, javax.naming.Name, javax.naming.Name)
*/
public void move(Name authDn, Name fromDn, Name toDn) throws AuthorizationException {
if(!this.authorizationModule.eval(authDn.toString(), fromDn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.DELETE)) ||
!this.authorizationModule.eval(authDn.toString(), toDn.toString(), EnumSet.<AuthorizationType>of(AuthorizationType.CREATE))) {
throw new AuthorizationException("You do not have sufficient rights to move the entry mathcing DN:"+fromDn.toString()+"");
}
this.getLdapFacade(authDn).rename(fromDn, toDn);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getAllChildren(javax.naming.Name, javax.naming.Name)
*
*/
public List<IELdapEntry> getAllChildren(Name authDn, Name dn) {
List<IELdapEntry> allChildren = null;
try {
allChildren = this.getLdapFacade(authDn).fetchChildren(dn);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
return this.getAuthzEntries(authDn, allChildren);
}
 
@Override
public List<IELdapEntry> getAllChildren(Name authDn, Name dn, String[] attrs) {
List<IELdapEntry> allChildren = null;
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.SUBTREE_SCOPE);
scs.setReturningAttributes(attrs);
try {
allChildren = this.getLdapFacade(authDn).search(dn, "(objectClass=*)", scs);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
return this.getAuthzEntries(authDn, allChildren);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getDirectChildren(javax.naming.Name, javax.naming.Name)
*/
public List<IELdapEntry> getDirectChildren(Name authDn, Name dn) {
List<IELdapEntry> directChildren = null;
try {
directChildren = this.getLdapFacade(authDn).searchOneLevelScope(dn, "objectClass=*");
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
return this.getAuthzEntries(authDn, directChildren);
}
 
@Override
public List<IELdapEntry> getDirectChildren(Name authDn, Name dn,
String[] attrs) {
List<IELdapEntry> directChildren = null;
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.ONELEVEL_SCOPE);
scs.setReturningAttributes(attrs);
try {
directChildren = this.getLdapFacade(authDn).search(dn, "(objectClass=*)", scs);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
return this.getAuthzEntries(authDn, directChildren);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#search(javax.naming.Name, javax.naming.Name, java.lang.String, int)
*/
public List<IELdapEntry> search(Name authDn, Name dn, String filter, int scope) {
List<IELdapEntry> entries = null;
switch (scope) {
case SearchControls.ONELEVEL_SCOPE :
try {
entries = this.getLdapFacade(authDn).searchOneLevelScope(dn, filter);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
break;
case SearchControls.OBJECT_SCOPE:
try {
entries = this.getLdapFacade(authDn).searchBaseLevel(dn, filter);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
break;
case SearchControls.SUBTREE_SCOPE:
try {
entries = this.getLdapFacade(authDn).fetchChildren(dn, filter);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
break;
default:
break;
}
 
return this.getAuthzEntries(authDn, entries);
}
 
public List<IELdapEntry> search(Name authDn, Name dn, String filter, SearchControls scs) {
List<IELdapEntry> entries = null;
 
try {
entries = this.getLdapFacade(authDn).search(dn, filter, scs);
} catch (SizeLimitExceededExceptionWithPartialResults e) {
throw this.getAuthzSizeLimitExceededExceptionWithPartialResults(authDn, e);
}
 
return this.getAuthzEntries(authDn, entries);
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getBase()
*/
public Name getBase() {
return this.getLdapFacade(null).getBaseName();
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getUserDnTemplate()
*/
public String getUserDnTemplate() {
return this.userDnTemplate;
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#setUserDnTemplate(java.lang.String)
*/
public void setUserDnTemplate(String userDnTemplate) {
this.userDnTemplate = userDnTemplate;
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getDnPath(javax.naming.Name, javax.naming.Name)
*/
public List<Name> getDnPath(Name fromRootDn, Name toChildDn) {
/* note : the order of rdns on path.getRdns() is opposite of path.toString() : base dn is in first place */
List<Name> path = new ArrayList<Name>();
 
if(null == fromRootDn || fromRootDn.isEmpty()
|| null == toChildDn || toChildDn.isEmpty()
|| !toChildDn.startsWith(fromRootDn)) {
return path;
}
 
//remove common rdn//
Name copyChildDn = (Name)toChildDn.clone();
Name copyRootDn = (Name)fromRootDn.clone();
 
for(int i = 0; i < copyRootDn.size(); i++) {
try {
copyChildDn.remove(0);
} catch (InvalidNameException e) {
return path;
}
}
//build the path, constructing at each turn a new dn
path.add(fromRootDn);
for(int i = 0; i< copyChildDn.size(); i++ ) {
try {
copyRootDn.add(copyChildDn.get(i));
LdapName currentName = (LdapName)copyRootDn.clone();
path.add(currentName);
} catch (InvalidNameException e) {
break;
}
}
return path;
}
 
/**
* This method handle the post processing of an entry,
* when it is edited
* @param entry
* @return
* @throws PostProcessingException
*/
private IELdapEntry postProcess(IELdapEntry entry, ActionType actionType) throws PostProcessingException {
IELdapEntry specialized = entryTypeAnalyzer.getSpecializedEntry(entry, actionType);
/*
* we don't post process non specialized entry
*/
if(null == specialized) {
//no accurate post processing, return the input
return entry;
} else {
return entryPostProcessor.process(specialized);
}
}
 
/* (non-Javadoc)
* @see org.linid.dm.ldap.repository.impl.LdapEntryRepository#getDnPath(javax.naming.Name)
*/
public List<Name> getDnPath(Name toChildDn) {
return this.getDnPath(this.getBase(), toChildDn);
}
 
/**
* Filter entries using authorization module
* @param authDn Principal DN
* @param entries Entries to filter
* @return authorized entries
*/
private List<IELdapEntry> getAuthzEntries(Name authDn, List<IELdapEntry> entries) {
List<IELdapEntry> authzEntries = null;
if(null != entries) {
authzEntries = new ArrayList<IELdapEntry>();
for(IELdapEntry entry : entries) {
if(this.authorizationModule.eval(authDn == null ? null : authDn.toString(), entry.getDn().toString(), EnumSet.<AuthorizationType>of(AuthorizationType.READ))){
authzEntries.add(entry);
}
}
}
return authzEntries;
}
 
/**
* Create SizeLimitExceededExceptionWithPartialResults exception
* with filtered entries
* @param authDn Principal DN
* @param e Initial exception
* @return exception
*/
private SizeLimitExceededExceptionWithPartialResults getAuthzSizeLimitExceededExceptionWithPartialResults(Name authDn, SizeLimitExceededExceptionWithPartialResults e) {
List<IELdapEntry>entries = e.getPartialResults();
SizeLimitExceededExceptionWithPartialResults exception = new SizeLimitExceededExceptionWithPartialResults((javax.naming.SizeLimitExceededException) e.getCause());
exception.setPartialResults(this.getAuthzEntries(authDn, entries));
return exception;
}
 
/**
* Define the Entry post processor service used to handle
* post processing, business actions
* @param postProcessor
*/
public void setEntryPostProcessor(EntryPostProcessor postProcessor) {
this.entryPostProcessor = postProcessor;
}
 
/**
* Define the type analyzer used to associate entry with a
* specialized type and post process / validate them
* adequately.
* @param typeAnalyzer
*/
public void setEntryTypeAnalyzer(EntryTypeAnalyzer typeAnalyzer) {
this.entryTypeAnalyzer = typeAnalyzer;
}
 
/**
* The authz module used by the repository to handle authz upon entries
* @param authorizationModule the actual authorization module to use to manage
* authz in the repo.
*/
public void setAuthorizationModule(AuthorizationModule authorizationModule) {
this.authorizationModule = authorizationModule;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/AuthenticatedLdapEntryRepositoryImpl.java New file
0,0 → 1,37
package org.linid.dm.ldap.repository.service.impl;
 
import javax.naming.Name;
 
import org.linid.dm.authorization.AuthorizationModule;
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
 
public class AuthenticatedLdapEntryRepositoryImpl extends
AbstractLdapEntryRepository {
 
private final LdapFacade ldapFacade;
public AuthenticatedLdapEntryRepositoryImpl(
EntryPostProcessor entryPostProcessor,
EntryTypeAnalyzer entryTypeAnalyzer,
AuthorizationModule authorizationModule,
LdapFacade ldapFacade) {
super(entryPostProcessor, entryTypeAnalyzer, authorizationModule);
this.ldapFacade = ldapFacade;
}
 
/**
* return the authn LdapFacade if the auth dn match
* {@code AuthenticatedLdapEntryRepository#getAuthDn()}
*/
@Override
protected LdapFacade getLdapFacade(Name authDn) {
return this.ldapFacade;
}
 
// public Name getAuthDn() {
// return this.ldapFacade.getAuthDn();
// }
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/InMemoryLdapConfigDao.java New file
0,0 → 1,91
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
**********************************************************/
package org.linid.dm.ldap.repository.service.impl;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.linid.dm.NoSuchElement;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.service.LdapConfigurationDao;
 
public class InMemoryLdapConfigDao implements LdapConfigurationDao {
private final Map<String, LdapConfiguration> repos;
public InMemoryLdapConfigDao() {
this.repos = new HashMap<String, LdapConfiguration>();
}
 
public List<LdapConfiguration> findAll() {
List<LdapConfiguration> config = new ArrayList<LdapConfiguration>();
for(LdapConfiguration c: repos.values()) {
config.add(c.clone());
}
return config;
}
 
public void mergeAll(List<LdapConfiguration> configurations) {
repos.clear();
for (LdapConfiguration configuration: configurations) {
save(configuration);
}
}
 
public LdapConfiguration get(String configId) throws NoSuchElement {
LdapConfiguration config = this.repos.get(configId);
if(null == config) {
throw new NoSuchElement();
} else {
return config.clone();
}
}
 
public LdapConfiguration save(LdapConfiguration config) {
LdapConfiguration c = config.clone();
if(StringUtils.isEmpty(c.getId())) c.setId(freshId());
repos.put(c.getId(),c);
return c.clone();
}
 
public void delete(String id) {
this.repos.remove(id);
}
 
private String freshId() {
String id = new StringBuilder().append(new Double(Math.random()*1000000000000l).longValue()).toString();
try {
this.get(id);
//ok, so our fresh id is not so fresh, loop
return this.freshId();
} catch (NoSuchElement e) {
return id;
}
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/SwitchableConnectionLdapEntryRepositoryImpl.java New file
0,0 → 1,264
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service.impl;
 
import java.util.List;
 
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.services.Request;
import org.linid.dm.NoSuchElement;
import org.linid.dm.authorization.AuthorizationModule;
import org.linid.dm.dao.eschema.ESchemaClassDao;
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.data.TestLdapConnectionResult;
import org.linid.dm.ldap.repository.exception.InvalidLdapConfiguration;
import org.linid.dm.ldap.repository.service.ConfigurableLdapEntryRepository;
import org.linid.dm.ldap.repository.service.LdapConfigurationDao;
import org.linid.dm.ldap.repository.service.LdapConnectionManager;
import org.linid.dm.ldap.repository.service.LdapUtils;
import org.linid.dm.ldap.repository.service.TestLdapConnection;
 
public class SwitchableConnectionLdapEntryRepositoryImpl
extends AbstractLdapEntryRepository
implements ConfigurableLdapEntryRepository {
public static final String CURRENT_LDAP_CONFIGURATION = "org.linid.dm.currentLdapConfiguration";
public static final String LDAP_CONFIGURATION_REPOSITORY = "org.linid.dm.ldapConfigurationRepository";
public static final String CONNECTION_MANAGER = "org.linid.dm.connectionManager";
 
private final Object mutex = new Object();
final private TestLdapConnection testLdapConnection;
final private ESchemaClassDao schemaClassDao;
final private LdapUtils ldapUtils;
final private LdapConfigurationDao diskConfigurationDao;
private Request request;
public SwitchableConnectionLdapEntryRepositoryImpl(
EntryPostProcessor entryPostProcessor,
EntryTypeAnalyzer entryTypeAnalyzer,
AuthorizationModule authorizationModule,
LdapConfigurationDao diskConfigurationDao,
TestLdapConnection testLdapConnection,
ESchemaClassDao schemaClassDao,
LdapUtils ldapUtils,
Request request
) {
super(entryPostProcessor, entryTypeAnalyzer, authorizationModule);
this.diskConfigurationDao = diskConfigurationDao;
this.testLdapConnection = testLdapConnection;
this.schemaClassDao = schemaClassDao;
this.ldapUtils = ldapUtils;
this.request = request;
}
 
/*
* we have to store the current connection and not just the
* configuration ID so that we can show to the user the
* actual configuration used to create the connection,
* even if the configuration was modified since that time.
*/
private LdapConfiguration getCurrentLdapConfiguration() {
Object attr = request.getSession(true).getAttribute(CURRENT_LDAP_CONFIGURATION);
if (attr != null && attr instanceof LdapConfiguration) {
return (LdapConfiguration)attr;
}
LdapConfiguration configuration = new LdapConfiguration();
setCurrentLdapConfiguration(configuration);
return configuration;
}
private void setCurrentLdapConfiguration(LdapConfiguration configuration) {
request.getSession(true).setAttribute(CURRENT_LDAP_CONFIGURATION, configuration);
}
public LdapConfigurationDao getLdapConfigurationRepository() {
Object attr = request.getSession(true).getAttribute(LDAP_CONFIGURATION_REPOSITORY);
if (attr != null && attr instanceof LdapConfigurationDao) {
return (LdapConfigurationDao)attr;
}
LdapConfigurationDao repository = new InMemoryLdapConfigDao();
repository.mergeAll(diskConfigurationDao.findAll());
setLdapConfigurationRepository(repository);
return repository;
}
private void setLdapConfigurationRepository(LdapConfigurationDao repository) {
request.getSession(true).setAttribute(LDAP_CONFIGURATION_REPOSITORY, repository);
}
private LdapConnectionManager getConnectionManager() {
Object attr = request.getSession(true).getAttribute(CONNECTION_MANAGER);
if (attr != null && attr instanceof LdapConnectionManager) {
return (LdapConnectionManager)attr;
}
LdapConnectionManager manager = new LdapConnectionManagerImpl(testLdapConnection, schemaClassDao, ldapUtils);
setConnectionManager(manager);
return manager;
}
private void setConnectionManager(LdapConnectionManager manager) {
request.getSession(true).setAttribute(CONNECTION_MANAGER, manager);
}
/**
* Return the manager Dn for the
* current repository
* @return null if no connection is currently chosen
*/
public Name getAuthDn() {
synchronized (mutex) {
if(null == this.getCurrentLdapFacade()) {
return null;
} else {
try {
return new LdapName(this.getCurrentLdapConfiguration().getBindDn());
} catch (InvalidNameException e) {
return null;
}
}
}
}
 
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#listAvailableConfiguration()
*/
public List<LdapConfiguration> listAvailableConfiguration() {
return this.getLdapConfigurationRepository().findAll();
}
public LdapConfiguration get(String configurationId) {
try {
return this.getLdapConfigurationRepository().get(configurationId);
} catch (NoSuchElement e) {
return null;
}
}
 
 
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#getCurrentConfiguration()
*/
public LdapConfiguration getCurrentConfiguration() {
if (this.getCurrentLdapConfiguration() != null) {
return this.getCurrentLdapConfiguration().clone();
} else {
return null;
}
}
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#getCurrentLdapFacade()
*/
public LdapFacade getCurrentLdapFacade() {
synchronized (mutex) {
if (null == this.getCurrentLdapConfiguration()) {
return null;
}
if (null == this.getCurrentLdapConfiguration().getId()) {
return null;
}
else return this.getConnectionManager().get(getCurrentLdapConfiguration());
}
}
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#useConnection(java.lang.String)
*/
public void useConnection(String configurationId) throws InvalidLdapConfiguration {
LdapConfiguration configuration;
try {
configuration = this.getLdapConfigurationRepository().get(configurationId);
} catch (NoSuchElement e) {
throw new InvalidLdapConfiguration("No such configuration ID");
}
if(TestLdapConnectionResult.SUCCESS != this.testLdapConnection.testAuthentication(configuration)) {
throw new InvalidLdapConfiguration("Bad configuration. Check the connection parameters.");
}
 
synchronized (mutex) {
this.getConnectionManager().closeAllConnections();
this.getConnectionManager().open(configuration);
this.setCurrentLdapConfiguration(configuration);
}
}
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#disconnect()
*/
public void disconnect() {
if(null != this.getCurrentLdapConfiguration()) {
this.getConnectionManager().close(getCurrentLdapConfiguration());
}
}
/* (non-Javadoc)
* @see org.linid.dm.console.services.impl.ConfigurableLdapFacadeManager#isConnected()
*/
public boolean isConnected() {
synchronized (mutex) {
return null != getCurrentLdapFacade();
}
}
/**
* In this implementation, we enforce that the parameter
* has to be the result of {@code AuthenticatedLdapEntryRepository#getAuthDn()}
*/
@Override
protected LdapFacade getLdapFacade(Name authDn) {
if(null == authDn)
throw new IllegalArgumentException("Auth DN must be provided");
synchronized (mutex) {
if(null == getCurrentLdapFacade())
throw new RuntimeException("You must open a connection before trying to use the repository");
try {
if(!authDn.equals(new LdapName(getCurrentLdapConfiguration().getBindDn())))
throw new RuntimeException("The provided auth dn does not match the current connection. Check the given auth dn");
} catch (InvalidNameException e) {
throw new RuntimeException("The provided auth dn does not match the current connection. Check the given auth dn");
}
return getCurrentLdapFacade();
}
}
public void storeConfigurations() {
diskConfigurationDao.mergeAll(getLdapConfigurationRepository().findAll());
}
public void resetConfigurations() {
request.getSession(true).invalidate();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/LdapConnectionManagerImpl.java New file
0,0 → 1,122
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
**********************************************************/
 
package org.linid.dm.ldap.repository.service.impl;
 
import java.util.HashMap;
import java.util.Map;
 
import org.linid.dm.dao.eschema.ESchemaClassDao;
import org.linid.dm.dao.ldap.DefaultLdapFacade;
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.data.TestLdapConnectionResult;
import org.linid.dm.ldap.repository.exception.InvalidLdapConfiguration;
import org.linid.dm.ldap.repository.service.LdapConnectionManager;
import org.linid.dm.ldap.repository.service.LdapUtils;
import org.linid.dm.ldap.repository.service.TestLdapConnection;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
 
public class LdapConnectionManagerImpl implements LdapConnectionManager {
 
private final Map<String, LdapFacade> connections;
private final TestLdapConnection testLdapConnection;
private final LdapUtils ldapUtils;
/*
* TODO : List of EschemaClassDao
* in a future version, we may want to have
* one EschemaClassDao by connection.
* For now, all connection share the same
* metadatas
*/
private final ESchemaClassDao eschemaClassDao;
public LdapConnectionManagerImpl(
final TestLdapConnection testLdapConnection,
final ESchemaClassDao schemaClassDao,
final LdapUtils ldapUtils
) {
this.connections = new HashMap<String, LdapFacade>();
this.testLdapConnection = testLdapConnection;
this.eschemaClassDao = schemaClassDao;
this.ldapUtils = ldapUtils;
}
public synchronized void close(LdapConfiguration configuration) {
if(null != configuration && null != configuration.getId()) {
close(configuration.getId());
}
}
public synchronized void closeAllConnections() {
for(String id : connections.keySet()) {
close(id);
}
}
//be careful to use this method in the scope of a synchronized call
private void close(String configurationId) {
if(this.connections.containsKey(configurationId)) {
LdapFacade facade = this.connections.get(configurationId);
if(null != facade) {
this.connections.remove(configurationId);
facade.destroy();
}
}
}
 
public synchronized void open(LdapConfiguration conf) throws InvalidLdapConfiguration {
if(null == conf || null == conf.getId()) throw new InvalidLdapConfiguration("Configuration can not be null");
if(TestLdapConnectionResult.SUCCESS !=
testLdapConnection.testConnection(conf.getLdapHost(), conf.getLdapPort(), conf.isUseLDAPS()))
throw new InvalidLdapConfiguration("Bad configuration");
 
LdapContextSource ctxSrc = this.ldapUtils.newLdapContextSource(
conf.getLdapHost(), conf.getLdapPort(), conf.isUseLDAPS(), conf.getBindDn(), conf.getBindPwd());
LdapTemplate template = new LdapTemplate(ctxSrc);
try {
ctxSrc.afterPropertiesSet();
template.afterPropertiesSet();
} catch (Exception e) {
throw new InvalidLdapConfiguration(e);
}
DefaultLdapFacade facade = new DefaultLdapFacade();
facade.setClassDefinitionDao(this.eschemaClassDao);
facade.setLdapTemplate(template);
facade.setContextSource(ctxSrc);
facade.init();
connections.put(conf.getId(), facade);
}
 
public synchronized LdapFacade get(LdapConfiguration configuration) {
return this.connections.get(configuration.getId());
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/impl/XstreamLdapConfigDao.java New file
0,0 → 1,149
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service.impl;
 
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.linid.dm.NoSuchElement;
import org.linid.dm.dao.eschema.xstream.XstreamESchemaClassDao;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.service.LdapConfigurationDao;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.util.Assert;
 
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlMap;
 
public class XstreamLdapConfigDao implements LdapConfigurationDao {
private final XStream xstream;
private final Map<String, LdapConfiguration> repos;
private final Map<String, String> passwords;
 
public XstreamLdapConfigDao(final String persistencePath) {
this.xstream = new XStream(new DomDriver("UTF-8"));
this.xstream.omitField(LdapConfiguration.class, "bindPwd");
this.repos = createPersistenceMapAndDir(persistencePath);
this.passwords = Collections.synchronizedMap(new HashMap<String, String>());
}
@SuppressWarnings("unchecked")
private Map<String, LdapConfiguration> createPersistenceMapAndDir(String path) {
File persistenceDirectoryPath = new File(path);
if(persistenceDirectoryPath.exists()) {
Assert.isTrue(persistenceDirectoryPath.isDirectory(),"You must specify a directory as persistence back-end for xmlPersistenceDirectory property");
Assert.isTrue(persistenceDirectoryPath.canWrite(),"You must have write access to the directory specified for xmlPersistenceDirectory property");
} else {
if(!persistenceDirectoryPath.mkdirs()) {
throw new RuntimeException("Error when creating directory '" + persistenceDirectoryPath + "' for metadata persistence, abort.");
}
}
PersistenceStrategy strategy;
try {
/*
* The new version of persistence (xstream > 1.3.1) save the
* file with key that look like: key_classname@key.xml.
* We do not want to have something like that.
*/
strategy = new FilePersistenceStrategy(persistenceDirectoryPath,this.xstream);
} catch (Exception e) {
throw new InvalidPropertyException(XstreamESchemaClassDao.class, "xmlPersistenceDirectory",
"Error when tying to use directory '"+persistenceDirectoryPath+"' as persistence back end.");
}
return Collections.synchronizedMap(new XmlMap(strategy));
}
 
public List<LdapConfiguration> findAll() {
List<LdapConfiguration> config = new ArrayList<LdapConfiguration>();
for(LdapConfiguration c: repos.values()) {
config.add(c.clone(passwords));
}
return config;
}
public synchronized void mergeAll(List<LdapConfiguration> configurations) {
List<String> ids = new ArrayList<String>();
for (LdapConfiguration configuration: configurations) {
LdapConfiguration c = configuration.clone(passwords);
String id = c.getId();
if (id != null) {
ids.add(id);
repos.put(c.getId(), c);
}
}
for (Iterator<String> iter = repos.keySet().iterator(); iter.hasNext();) {
String id = iter.next();
if (!ids.contains(id)) {
iter.remove();
}
}
}
 
public LdapConfiguration get(String configId) throws NoSuchElement {
LdapConfiguration config = this.repos.get(configId);
if(null == config) {
throw new NoSuchElement();
} else {
return config.clone(passwords);
}
}
 
public LdapConfiguration save(LdapConfiguration config) {
passwords.put(config.getId(), config.getBindPwd());
LdapConfiguration c = config.clone(passwords);
if(StringUtils.isEmpty(c.getId())) c.setId(freshId());
repos.put(c.getId(),c);
return c.clone(passwords);
}
 
public void delete(String id) {
this.repos.remove(id);
}
 
private String freshId() {
String id = new StringBuilder().append(new Double(Math.random()*1000000000000l).longValue()).toString();
try {
this.get(id);
//ok, so our fresh id is not so fresh, loop
return this.freshId();
} catch (NoSuchElement e) {
return id;
}
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/ConfigurableLdapEntryRepository.java New file
0,0 → 1,40
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
/**
* Syntatic sugar interface that denotes
* an Ldap entry repository for which the
* Ldap back-end can be defined at run-time.
*
* We one uses this kind of repository, a special
* attention HAS to be paid onto context switch,
* and more precisely on how the pending connection
* are handled when the switch occures.
*
*/
public interface ConfigurableLdapEntryRepository
extends AuthenticatedLdapEntryRepository, ConfigurableLdapFacadeManager {}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/AuthenticatedLdapEntryRepository.java New file
0,0 → 1,47
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
**********************************************************/
 
package org.linid.dm.ldap.repository.service;
 
import javax.naming.Name;
 
import org.linid.dm.ldap.repository.LdapEntryRepository;
 
 
/**
* Repository that is known to have an authenticated context
* and expose the user DN to use with it.
*/
public interface AuthenticatedLdapEntryRepository extends LdapEntryRepository {
 
/**
* Return the authenticated user dn for the
* LDAP context used.
* This dn should be use in other method of {@code LdapEntryRepository}
* as "auth dn" parameter
* @return
*/
Name getAuthDn();
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/LdapConnectionManager.java New file
0,0 → 1,76
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
import javax.naming.NamingException;
 
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
import org.linid.dm.ldap.repository.exception.InvalidLdapConfiguration;
 
/**
*
* Manage Ldap connection based on {@code LdapConfiguration}
* Implementation should be very careful about resources
* disposal and multi-threading issues.
*/
public interface LdapConnectionManager {
 
/**
* Open or reopen the connection
* for the given configuration.
* The returned object is ONLY a reference
* to the facade that may be destroyed
* on close call.
* @return the connection for the configuration
* @throws NamingException if the given configuration is not valid
*/
void open(LdapConfiguration configuration) throws InvalidLdapConfiguration;
/**
* Return the connection associated with this configuration is one
* exists.
* BE CAREFUL !! No reference should be maintains toward the returned
* LdapFacade, since it is the responsability of the manager to
* close them and make them available.
*/
LdapFacade get(LdapConfiguration configuration);
/**
* Close the connection link to that configuration,
* if exists.
* If no opened connection exists for the given configuration,
* does nothing
*
*/
void close(LdapConfiguration configuration);
/**
* Close all opened connection
*/
void closeAllConnections();
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/service/LdapConfigurationDao.java New file
0,0 → 1,45
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.ldap.repository.service;
 
import java.util.List;
 
import org.linid.dm.NoSuchElement;
import org.linid.dm.ldap.repository.data.LdapConfiguration;
 
public interface LdapConfigurationDao {
 
List<LdapConfiguration> findAll();
void mergeAll(List<LdapConfiguration> configurations);
LdapConfiguration save(LdapConfiguration config);
LdapConfiguration get(String configId) throws NoSuchElement;
 
void delete(String id);
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/LdapEntryRepository.java New file
0,0 → 1,162
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.repository;
 
import java.util.List;
 
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.SearchControls;
 
import org.linid.dm.authorization.AuthorizationException;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
 
public interface LdapEntryRepository {
/*
* the repository allows CRUD operations
*/
/** create an entry
* @return the post-processed entry
*/
IELdapEntry create(Name authDn, IELdapEntry entry, Name targetCreateDn) throws NameAlreadyBoundException, AuthorizationException, PostProcessingException;
 
/**
* Returns an Entry with the specified username, if exists and authDn has sufficient rights to read it,
* null otherwise
*/
IELdapEntry get(Name authDn, Name dn) throws AuthorizationException;
 
/**
* Returns an Entry with the specified username, if exists and authDn has sufficient rights to read it,
* null otherwise
*/
IELdapEntry get(Name authDn, Name dn, String[] attrs) throws AuthorizationException;
 
/** delete an entry
*/
void delete(Name authDn, Name dn) throws AuthorizationException, PostProcessingException;
 
/** delete an entry with recursive possibility
*/
void delete(Name authDn, Name dn, boolean recursive) throws AuthorizationException, PostProcessingException;
/** update an entry
*/
void update(Name authDn, IELdapEntry input) throws AuthorizationException, PostProcessingException;
 
/** move an entry from dn to newDn
*/
void move(Name authDn, Name fromDn, Name toDn) throws AuthorizationException;
 
/**
* Retrieve all the subtree of entries for the target dn,
* as seen through the prism of authorizations of authDn
* @param authDn
* @param dn
* @return the full subtree of entries fo dn
*/
List<IELdapEntry> getAllChildren(Name authDn, Name dn);
 
/**
* Retrieve all the subtree of entries for the target dn,
* as seen through the prism of authorizations of authDn
* @param authDn
* @param dn
* @param attrs array containing attributes to search for
* @return the full subtree of entries fo dn
*/
List<IELdapEntry> getAllChildren(Name authDn, Name dn, String[] attrs);
 
/**
* Retrieve the direct children for entry dn,
* as seen through the prism of authorizations of authDn
* @param authDn
* @param dn
* @return
*/
List<IELdapEntry> getDirectChildren(Name authDn, Name dn);
 
/**
* Retrieve the direct children for entry dn,
* as seen through the prism of authorizations of authDn
* @param authDn
* @param dn
* @param attrs array containing attributes to search for
* @return
*/
List<IELdapEntry> getDirectChildren(Name authDn, Name dn, String[] attrs);
 
/**
* A search with common parameters
* @param authDn
* @param dn
* @param filter
* @param scope
* @return
*/
List<IELdapEntry> search(Name authDn, Name dn, String filter, int scope);
/**
* A search fully parametrizable
* @param authDn
* @param dn
* @param filter
* @param searchcontrol
* @return
*/
List<IELdapEntry> search(Name authDn, Name dn, String filter, SearchControls scs);
 
/** retrieve the base dn */
Name getBase();
 
String getUserDnTemplate();
 
void setUserDnTemplate(String userDnTemplate);
 
/**
* This method build the path of dn from the (given) root dn to
* the target child dn. Only a basic <b>syntaxique</b> validation is made :
* - toChildDn end with fromRootDn,
* - toChildDn is null or empty
* - fromRootDn is null or empty
* In each of these cases, the function return an empty List.
* @return the list of DN builing the path, from rootDn to childDn or an emptyl if childDn does not contain rootDn
*/
List<Name> getDnPath(Name fromRootDn, Name toChildDn);
 
/**
* This method build the path of dn from the configured base DN to
* the target child dn. Only a basic <b>syntaxique</b> validation is made :
* - toChildDn end with base DN,
* - toChildDn can not be null or empty
* - base DN can not be null or empty
* In each of these cases, the function return an empty List.
* @return the list of DN builing the path, from rootDn to childDn or an emptyl if childDn does not contain rootDn
*/
List<Name> getDnPath(Name toChildDn);
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/TestLdapConnectionResult.java New file
0,0 → 1,10
/**
*
*/
package org.linid.dm.ldap.repository.data;
 
public enum TestLdapConnectionResult {
SUCCESS,
BAD_CONNECTION,
BAD_AUTHENTICATION
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/LdapConnection.java New file
0,0 → 1,77
package org.linid.dm.ldap.repository.data;
 
import org.apache.commons.lang3.StringUtils;
import org.linid.dm.ldap.core.Identifiable;
import org.linid.dm.ldap.core.LdapFacade;
 
 
/**
* A stateful object that maintains a match
* between an LDAP configuration and an LDAP facade
*/
public class LdapConnection implements Identifiable, Cloneable {
private String id;
 
private LdapConfiguration ldapConfiguration;
private LdapFacade facade;
 
@Override
public boolean equals(Object obj) {
if(obj == this) return true;
if(null == obj) return false;
if(!(obj instanceof LdapConnection)) return false;
LdapConnection other = (LdapConnection)obj;
return (null == this.id && null == other.getId())
|| this.id.equals(other.getId());
}
@Override
public int hashCode() {
if(StringUtils.isEmpty(this.id)) return super.hashCode();
else return this.id.hashCode();
}
 
/*
* Open or reopen a connection with the given
* configuration
*/
public void open() {
if(null != this.facade) {
facade.destroy();
}
facade = null;
}
public String getId() {
return id;
}
 
public void setId(String id) {
this.id = id;
}
 
public LdapConfiguration getLdapConfiguration() {
return ldapConfiguration;
}
 
public void setLdapConfiguration(LdapConfiguration ldapConfiguration) {
this.ldapConfiguration = ldapConfiguration;
}
 
public LdapFacade getFacade() {
return facade;
}
 
public void setFacade(LdapFacade facade) {
this.facade = facade;
}
public String getDescription() {
return toString();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/OpenLDAPVersionComparator.java New file
0,0 → 1,29
package org.linid.dm.ldap.repository.data;
 
import java.util.Comparator;
 
public class OpenLDAPVersionComparator implements Comparator<String> {
 
public int compare(String a, String b) {
return compare(OpenLDAPVersion.searchValueOf(a), OpenLDAPVersion.searchValueOf(b));
}
public int compare(OpenLDAPVersion a, OpenLDAPVersion b) {
if(a == OpenLDAPVersion.UNKNOWN || b == OpenLDAPVersion.UNKNOWN) {
throw new IllegalArgumentException("Parameter version must not be UNKNOWN !");
}
if(a == OpenLDAPVersion.TRUNK) {
if(b == OpenLDAPVersion.TRUNK) {
return 0;
} else {
return new VersionComparator().compare("99999", b.getName());
}
} else {
if(b == OpenLDAPVersion.TRUNK) {
return new VersionComparator().compare(a.getName(), "99999");
} else {
return new VersionComparator().compare(a.getName(), b.getName());
}
}
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/LdapConfiguration.java New file
0,0 → 1,158
package org.linid.dm.ldap.repository.data;
 
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.beaneditor.Validate;
import org.linid.dm.ldap.core.Identifiable;
 
public class LdapConfiguration implements Cloneable, Identifiable {
 
/*
* TODO : let the user select the Eschema Class Dao
* for each Ldap Configuration
*/
private String id;
@Validate("required")
private String serverName;
@Validate("required")
private String ldapHost;
@Validate("required")
private int ldapPort;
private boolean useLDAPS;
private String bindDn;
private boolean mustSavePassword;
 
private String bindPwd;
private String savedPassword;
@Override
public LdapConfiguration clone() {
try {
return (LdapConfiguration)super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public LdapConfiguration clone(Map<String, String> passwords) {
LdapConfiguration c = clone();
if (c.isMustSavePassword()) {
c.setBindPwd(c.getSavedPassword());
} else {
c.setBindPwd(passwords.get(c.getId()));
}
return c;
}
@Override
public boolean equals(Object obj) {
if(obj == this) return true;
if(null == obj) return false;
if(!(obj instanceof LdapConfiguration)) return false;
LdapConfiguration other = (LdapConfiguration)obj;
if (null == this.id && null != other.getId()) {
return false;
}
return (null == this.id && null == other.getId())
|| this.id.equals(other.getId());
}
@Override
public int hashCode() {
if(StringUtils.isEmpty(this.id)) return super.hashCode();
else return this.id.hashCode();
}
 
public String getId() {
return id;
}
 
public void setId(String id) {
this.id = id;
}
 
public String getServerName() {
return serverName;
}
 
public void setServerName(String serverName) {
this.serverName = serverName;
}
 
public String getLdapHost() {
return ldapHost;
}
 
public void setLdapHost(String ldapHost) {
this.ldapHost = ldapHost;
}
 
public int getLdapPort() {
return ldapPort;
}
 
public void setLdapPort(int ldapPort) {
this.ldapPort = ldapPort;
}
public boolean isUseLDAPS() {
return useLDAPS;
}
public void setUseLDAPS(boolean useLDAPS) {
this.useLDAPS = useLDAPS;
}
 
public String getBindDn() {
return bindDn;
}
 
public void setBindDn(String bindDn) {
this.bindDn = bindDn;
}
 
public boolean isMustSavePassword() {
return mustSavePassword;
}
 
public void setMustSavePassword(boolean mustSavePassword) {
this.mustSavePassword = mustSavePassword;
}
 
public String getBindPwd() {
if (bindPwd == null || bindPwd.length() == 0) {
bindPwd = this.getSavedPassword();
}
return bindPwd;
}
 
public void setBindPwd(String bindPwd) {
this.bindPwd = bindPwd;
if (mustSavePassword) {
this.setSavedPassword(bindPwd);
} else {
this.setSavedPassword(null);
}
}
 
public String getSavedPassword() {
return savedPassword;
}
 
public void setSavedPassword(String bindPwdToSave) {
this.savedPassword = bindPwdToSave;
}
 
public String getDescription() {
return toString();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/OpenLDAPVersion.java New file
0,0 → 1,29
package org.linid.dm.ldap.repository.data;
 
 
public enum OpenLDAPVersion {
 
_2_4("2.4"),
_2_5("2.5"),
TRUNK("2.X"),
UNKNOWN("Unknown");
private String name;
OpenLDAPVersion(String version) {
name = version;
}
public String getName() {
return name;
}
public static OpenLDAPVersion searchValueOf(String value) {
for(OpenLDAPVersion version: OpenLDAPVersion.values()) {
if(value.equalsIgnoreCase(version.getName())) {
return version;
}
}
return OpenLDAPVersion.UNKNOWN;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/data/VersionComparator.java New file
0,0 → 1,271
package org.linid.dm.ldap.repository.data;
 
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Java XPCOM Bindings.
*
* The Initial Developer of the Original Code is
* IBM Corporation.
* Portions created by the Initial Developer are Copyright (C) 2005
* IBM Corporation. All Rights Reserved.
*
* Contributor(s):
* Javier Pedemonte (jhpedemonte@gmail.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
 
import java.util.Comparator;
import java.util.Enumeration;
import java.util.StringTokenizer;
 
/**
* Version strings are dot-separated sequences of version-parts.
* <p>
* A version-part consists of up to four parts, all of which are optional: <br>
* <code>
* &lt;number-a&gt;&lt;string-b&gt;&lt;number-c&gt;
* &lt;string-d (everything else)&gt;
* </code>
* <p>
* A version-part may also consist of a single asterisk "*" which indicates
* "infinity".
* <p>
* Numbers are base-10, and are zero if left out. Strings are compared bytewise.
* <p>
* For additional backwards compatibility, if "string-b" is "+" then "number-a"
* is incremented by 1 and "string-b" becomes "pre".
* <p>
*
* <pre>
* 1.0pre1
* &lt; 1.0pre2
* &lt; 1.0 == 1.0.0 == 1.0.0.0
* &lt; 1.1pre == 1.1pre0 == 1.0+
* &lt; 1.1pre1a
* &lt; 1.1pre1
* &lt; 1.1pre10a
* &lt; 1.1pre10
* </pre>
*
* Although not required by this interface, it is recommended that numbers
* remain within the limits of a signed char, i.e. -127 to 128.
*/
public class VersionComparator implements Comparator<String> {
 
/**
* Compare two version strings
*
* @param A
* a version string
* @param B
* a version string
* @return a value less than 0 if A < B; the value 0 if A == B; or a value
* greater than 0 if A > B
*/
public int compare(String A, String B) {
int result;
String a = A, b = B;
 
do {
VersionPart va = new VersionPart();
VersionPart vb = new VersionPart();
a = parseVersionPart(a, va);
b = parseVersionPart(b, vb);
 
result = compareVersionPart(va, vb);
if (result != 0) {
break;
}
} while (a != null || b != null);
 
return result;
}
 
private class VersionPart {
int numA = 0;
String strB;
int numC = 0;
String extraD;
}
 
private static String parseVersionPart(String aVersion, VersionPart result) {
if (aVersion == null || aVersion.length() == 0) {
return aVersion;
}
 
StringTokenizer tok = new StringTokenizer(aVersion.trim(), ".");
String part = tok.nextToken();
 
if (part.equals("*")) {
result.numA = Integer.MAX_VALUE;
result.strB = "";
} else {
VersionPartTokenizer vertok = new VersionPartTokenizer(part);
try {
result.numA = Integer.parseInt(vertok.nextToken());
} catch (NumberFormatException e) {
// parsing error; default to zero like 'strtol' C function
result.numA = 0;
}
 
if (vertok.hasMoreElements()) {
String str = vertok.nextToken();
 
// if part is of type "<num>+"
if (str.charAt(0) == '+') {
result.numA++;
result.strB = "pre";
} else {
// else if part is of type "<num><alpha>..."
result.strB = str;
 
if (vertok.hasMoreTokens()) {
try {
result.numC = Integer.parseInt(vertok.nextToken());
} catch (NumberFormatException e) {
// parsing error; default to zero like 'strtol' C
// function
result.numC = 0;
}
if (vertok.hasMoreTokens()) {
result.extraD = vertok.getRemainder();
}
}
}
}
}
 
if (tok.hasMoreTokens()) {
// return everything after "."
return aVersion.substring(part.length() + 1);
}
return null;
}
 
private int compareVersionPart(VersionPart va, VersionPart vb) {
int res = compareInt(va.numA, vb.numA);
if (res != 0) {
return res;
}
 
res = compareString(va.strB, vb.strB);
if (res != 0) {
return res;
}
 
res = compareInt(va.numC, vb.numC);
if (res != 0) {
return res;
}
 
return compareString(va.extraD, vb.extraD);
}
 
private int compareInt(int n1, int n2) {
return n1 - n2;
}
 
private int compareString(String str1, String str2) {
// any string is *before* no string
if (str1 == null) {
return (str2 != null) ? 1 : 0;
}
 
if (str2 == null) {
return -1;
}
 
return str1.compareTo(str2);
}
 
}
 
/**
* Specialized tokenizer for Mozilla version strings. A token can consist of one
* of the four sections of a version string: <code>
* &lt;number-a&gt;&lt;string-b&gt;&lt;number-c&gt;
* &lt;string-d (everything else)&gt;</code>.
*/
class VersionPartTokenizer implements Enumeration<String> {
 
String part;
 
public VersionPartTokenizer(String aPart) {
part = aPart;
}
 
public boolean hasMoreElements() {
return part.length() != 0;
}
 
public boolean hasMoreTokens() {
return part.length() != 0;
}
 
public String nextElement() {
if (part.matches("[\\+\\-]?[0-9].*")) {
// if string starts with a number...
int index = 0;
if (part.charAt(0) == '+' || part.charAt(0) == '-') {
index = 1;
}
 
while (index < part.length() && Character.isDigit(part.charAt(index))) {
index++;
}
 
String numPart = part.substring(0, index);
part = part.substring(index);
return numPart;
} else {
// ... or if this is the non-numeric part of version string
int index = 0;
while (index < part.length() && !Character.isDigit(part.charAt(index))) {
index++;
}
 
String alphaPart = part.substring(0, index);
part = part.substring(index);
return alphaPart;
}
}
 
public String nextToken() {
return nextElement();
}
 
/**
* Returns what remains of the original string, without tokenization. This
* method is useful for getting the <code>&lt;string-d (everything else)&gt;
* </code> section of a version string.
*
* @return remaining version string
*/
public String getRemainder() {
return part;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/repository/exception/InvalidLdapConfiguration.java New file
0,0 → 1,22
package org.linid.dm.ldap.repository.exception;
 
public class InvalidLdapConfiguration extends Exception {
 
private static final long serialVersionUID = -1861670689513220618L;
 
public InvalidLdapConfiguration() {
super();
}
 
public InvalidLdapConfiguration(String message, Throwable cause) {
super(message, cause);
}
 
public InvalidLdapConfiguration(String message) {
super(message);
}
 
public InvalidLdapConfiguration(Throwable cause) {
super(cause);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/PostProcessingException.java New file
0,0 → 1,59
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing;
 
/**
* this is the top level exception that should be raised
* if an error succeed somewhere in the post processing
* of the entry.
*
* These exception have to be reported to higher level
* of the application. Typically, such an exception
* is raised in the repository when the user process a modification.
* Then, the exception is caught by the form that add an error and
* show it to the end user.
*/
public class PostProcessingException extends Exception {
 
 
private static final long serialVersionUID = -785992846887775780L;
 
public PostProcessingException() {
super();
}
 
public PostProcessingException(String arg0) {
super(arg0);
}
 
public PostProcessingException(Throwable arg0) {
super(arg0);
}
 
public PostProcessingException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/analyze/impl/MatchAllAnalizer.java New file
0,0 → 1,41
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.analyze.impl;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.analyze.entrytype.DefaultEntry;
 
/**
* this analyzer match all entries and transform them
* in {@link DefaultEntry}
*/
public class MatchAllAnalizer implements EntryTypeAnalyzer {
 
public IELdapEntry getSpecializedEntry(IELdapEntry entry, ActionType actionType) {
return new DefaultEntry(entry);
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/analyze/impl/PersonAnalizer.java New file
0,0 → 1,40
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.analyze.impl;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.analyze.entrytype.PersonEntry;
 
public class PersonAnalizer implements EntryTypeAnalyzer{
 
public IELdapEntry getSpecializedEntry(IELdapEntry entry, ActionType actionType) {
if(PersonEntry.isPersonEntry(entry))
return new PersonEntry(entry);
else
return null;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/analyze/entrytype/DefaultEntry.java New file
0,0 → 1,40
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.analyze.entrytype;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ELdapEntry;
 
public class DefaultEntry extends ELdapEntry {
private static final long serialVersionUID = 1L;
 
/**
* copy constructor
*/
public DefaultEntry(IELdapEntry entry) {
super(entry);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/analyze/entrytype/PersonEntry.java New file
0,0 → 1,82
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.analyze.entrytype;
 
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ELdapEntry;
 
/**
* This class is an examle of the kind of class used to
* specialized Entry before injecting them in the
* strategy dispatcher.
*/
public class PersonEntry extends ELdapEntry {
 
private static final long serialVersionUID = 1L;
 
/**
* Find if the entry is a PersonEntry based on business rules
* Here, the business rule is really simple, but it give an idea.
*/
public static boolean isPersonEntry(IELdapEntry entry) {
if(null == entry || null == entry.getDn())
return false;
/*
* decide rule : an entry is a person if and only if it's a sub object of
* dn "ou=person,dc=linid,dc=org" and the
* rdn id is "uid"
* It's a demo rule
*/
LdapName personGroup = null ;
try {
personGroup = new LdapName("ou=People,dc=linid,dc=org");
} catch (InvalidNameException e) {
return false;
}
if( !entry.getDn().startsWith(personGroup)) {
return false;
}
Rdn rdn = entry.getDn().getRdn(entry.getDn().size()-1);
if("uid".equals(rdn.getType())) {
return true;
} else {
return false;
}
}
/**
* this class can only be used has a copy constructor
* The aim of it is to specialize Entry Type so that
* specific rule may be applied.
*/
public PersonEntry(IELdapEntry source) {
super(source);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/analyze/EntryTypeAnalyzer.java New file
0,0 → 1,48
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.analyze;
 
import org.linid.dm.ldap.objects.IELdapEntry;
 
public interface EntryTypeAnalyzer {
 
public enum ActionType { preUpdate, postUpdate, preCreate, postCreate, preDelete, postDelete }
/**
* This method identify the given entry.
* If the entry is of the type of the implementation,
*
* ** CONVENTION **
* The method MUST return a non null entry of
* correct type if the entry is of the handled type, and Null
* otherwise.
* This behaviour is required as the different implementation
* will be called in a chain of command pattern.
* @param entry
* @return the correct, specialized entry if it is of the kink of the class,
* null otherwise.
*/
IELdapEntry getSpecializedEntry(IELdapEntry entry, ActionType actionType);
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/FieldPostProcessingException.java New file
0,0 → 1,104
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing;
 
import java.util.ArrayList;
import java.util.List;
 
/**
* This is top level exception for post processing error linked to a particular
* field or list of fields. it allows to specify witch field are on fault to
* process the exception with relevant behavior.
*/
public class FieldPostProcessingException extends PostProcessingException {
List<String> fieldNames;
private static final long serialVersionUID = 8274871210907889996L;
 
 
public FieldPostProcessingException(String arg0, Throwable arg1, List<String> fields) {
super(arg0, arg1);
this.fieldNames = fields;
}
public FieldPostProcessingException(String arg0, Throwable arg1) {
super(arg0, arg1);
this.fieldNames = new ArrayList<String>();
}
 
public FieldPostProcessingException() {
this(null,(Throwable)null);
}
 
public FieldPostProcessingException(String arg0) {
this(arg0,(Throwable)null);
}
 
public FieldPostProcessingException(Throwable arg0) {
this(null,arg0);
}
 
public FieldPostProcessingException(String arg0, List<String> fields) {
this(arg0,null,fields);
}
 
public FieldPostProcessingException(String arg0, String field) {
this(arg0,(Throwable)null);
this.fieldNames.add(field);
}
 
public List<String> getFieldNames() {
return this.fieldNames;
}
 
public void setFieldNames(List<String> fieldNames) {
this.fieldNames = fieldNames;
}
/**
* This method is an helper to facilitate the manipulation of only
* one field
* @return
*/
public String getFieldName() {
if(null == this.fieldNames)
return null;
return this.fieldNames.get(0);
}
public void setFieldName(String field) {
if(null == this.fieldNames) {
this.fieldNames = new ArrayList<String>();
}
if(null == this.fieldNames.get(0)) {
this.fieldNames.add(field);
} else {
this.fieldNames.set(0, field);
}
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/PostProcessUtils.java New file
0,0 → 1,76
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline;
 
import java.util.Map;
import java.util.Map.Entry;
 
import javax.naming.directory.DirContext;
 
import org.apache.commons.logging.Log;
import org.linid.dm.ldap.objects.IELdapEntry;
 
public class PostProcessUtils {
 
public static void logModifications(IELdapEntry entry, Log logger) {
if(null == entry || null == logger) {
throw new IllegalArgumentException("Arguments can not be null");
}
StringBuilder sb = new StringBuilder();
if(logger.isInfoEnabled()) {
sb.append("Modifications items:");
}
Map<String, Integer> modifications = entry.getModifications();
if(null != modifications && modifications.size() >0) {
//sort the modifications item by attribute name
 
for (Entry<String, Integer> item : modifications.entrySet()) {
sb.append("[").append(item.getKey()).append(":");
switch (item.getValue()) {
case DirContext.ADD_ATTRIBUTE:
sb.append("add");
break;
case DirContext.REMOVE_ATTRIBUTE:
sb.append("remove");
break;
case DirContext.REPLACE_ATTRIBUTE:
sb.append("replace");
break;
default:
sb.append("unknow operation");
break;
}
sb.append("]\n");
}
} else {
if(logger.isInfoEnabled()) {
sb.append(" no modification items.");
}
}
if(logger.isInfoEnabled()) {
logger.info(sb.toString());
}
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/EntryPostProcessor.java New file
0,0 → 1,37
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
 
/**
* This interface specify a service that takes part of the
* entry postprocessing pipeline.
* It is tightly coupled with {@link IProcessEntryFilter}
*/
public interface EntryPostProcessor {
IELdapEntry process(IELdapEntry input) throws PostProcessingException;
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/filters/ThrowException.java New file
0,0 → 1,41
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline.filters;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.FieldPostProcessingException;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
 
/**
* This filter log the modification map of the post processed entry
*/
public class ThrowException implements EntryPostProcessorFilter {
 
public IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException {
throw new FieldPostProcessingException("Exception throwed by post processor filer", "email");
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/filters/LogTransformation.java New file
0,0 → 1,62
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline.filters;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
import org.linid.dm.ldap.postprocessing.pipeline.PostProcessUtils;
 
/**
* This filter log the modification map of the post processed entry
*/
public class LogTransformation implements EntryPostProcessorFilter {
private static final Log logger = LogFactory.getLog(LogTransformation.class);
private String message;
/**
* Default constructor
*/
public LogTransformation() {
}
/**
* A constructor that add a message in front of each log lines
* @param message the message to begin line with
*/
public LogTransformation(String message) {
this.message = message;
}
public IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException {
logger.info(message);
PostProcessUtils.logModifications(input, logger);
return delegate.process(input);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/filters/CreateDisplayName.java New file
0,0 → 1,114
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline.filters;
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.linid.dm.ldap.UnknownAttributeException;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.ldap.objects.IELdapAttribute;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ByteString;
import org.linid.dm.ldap.objects.impl.ELdapAttribute;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
 
/**
* step : build the displayname from sn and givenName
* replace just the 'first' value if several available
* Do that only if modification contains at least sn or cn
* and if sn and givenName are not null
*/
public class CreateDisplayName implements EntryPostProcessorFilter {
private String separator = " ";
private boolean snFirst;
public CreateDisplayName withSeparator(String separator) {
this.separator = separator;
return this;
}
public CreateDisplayName snFirst() {
this.snFirst = true;
return this;
}
public CreateDisplayName snFirst(boolean first) {
this.snFirst = first;
return this;
}
public IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException {
if(null == input || null == input.getModifications()) {
return input;
}
Map<String, Integer> modifications = input.getModifications();
if((modifications.containsKey("givenName") || modifications.containsKey("sn")) ) {
IELdapAttribute first, second;
if(snFirst) {
first = input.getAttribute("sn");
second = input.getAttribute("givenName");
} else {
first =input.getAttribute("givenName");
second = input.getAttribute("sn");
}
StringBuilder sb = new StringBuilder();
if(null != first && null != first.getValue()) {
sb.append(first.getValue().stringValue()).append(separator);
}
if(null != second && null != second.getValue()) {
sb.append(second.getValue().stringValue());
}
IByteString displayNameValue = new ByteString(sb.toString());
IELdapAttribute dispayName = input.getAttribute("displayName");
if(null != dispayName && !dispayName.isEmpty()) {
Set<IByteString> values = dispayName.getValues();
List<IByteString> newValues = new ArrayList<IByteString>(values);
newValues.set(0, displayNameValue);
dispayName.setValues(new HashSet<IByteString>(newValues));
} else {
dispayName = new ELdapAttribute("displayName");
dispayName.setValue(displayNameValue);
}
try {
input.setAttribute(dispayName);
} catch (UnknownAttributeException e) {
throw new PostProcessingException(e);
}
}
return delegate.process(input);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/filters/CreateEmail.java New file
0,0 → 1,91
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline.filters;
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.linid.dm.ldap.UnknownAttributeException;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.ldap.objects.IELdapAttribute;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ByteString;
import org.linid.dm.ldap.objects.impl.ELdapAttribute;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
 
/**
* step : build the email from lower(sn_cn) @ baz.com
* replace just the 'first' value if several available
* Do that only if modification contains at least sn or cn
* and if sn and cn are not null
*/
public class CreateEmail implements EntryPostProcessorFilter {
private String domain;
public CreateEmail(String domain) {
this.domain = domain;
}
 
public IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException {
if(null == input || null == input.getModifications()) {
return input;
}
Map<String, Integer> modifications = input.getModifications();
if((modifications.containsKey("cn") || modifications.containsKey("sn"))
&& null != input.getAttribute("cn") && !input.getAttribute("cn").isEmpty()
&& null != input.getAttribute("sn") && !input.getAttribute("sn").isEmpty() ) {
StringBuilder sb = new StringBuilder(input.getAttribute("sn").getValue().stringValue());
sb.append("_").append(input.getAttribute("cn").getValue().stringValue());
sb.append("@" + this.domain);
IByteString emailValue = new ByteString(sb.toString());
IELdapAttribute email = input.getAttribute("mail");
if(null != email && !email.isEmpty()) {
Set<IByteString> values = input.getAttribute("mail").getValues();
List<IByteString> newValues = new ArrayList<IByteString>(values);
newValues.set(0, emailValue);
email.setValues(new HashSet<IByteString>(newValues));
} else {
email = new ELdapAttribute("mail");
email.setValue(emailValue);
}
try {
input.setAttribute(email);
} catch (UnknownAttributeException e) {
//log ? throw the exception ?
return null;
}
}
return delegate.process(input);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/filters/CapitalizeFirstLetter.java New file
0,0 → 1,93
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline.filters;
 
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
import javax.naming.directory.DirContext;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linid.dm.ldap.UnknownAttributeException;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.ldap.objects.IELdapAttribute;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ByteString;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
import org.linid.dm.utils.CaseInsensitiveSet;
 
/**
* This filter log the modification map of the post processed entry
*/
public class CapitalizeFirstLetter implements EntryPostProcessorFilter {
private static final Log logger = LogFactory.getLog(CapitalizeFirstLetter.class);
private static final Set<String> capitalizeAttributes = new CaseInsensitiveSet();
static {
capitalizeAttributes.add("cn");
capitalizeAttributes.add("sn");
}
public IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException {
 
if(null == input || null == input.getModifications()) {
return input;
}
Map<String, Integer> modifications = input.getModifications();
if((modifications.containsKey("cn") || modifications.containsKey("sn"))
&& null != input.getAttribute("cn") && !input.getAttribute("cn").isEmpty()
&& null != input.getAttribute("sn") && !input.getAttribute("sn").isEmpty() ) {
for(String id : capitalizeAttributes) {
if(modifications.keySet().contains(id) && DirContext.REPLACE_ATTRIBUTE == modifications.get(id)) {
try {
input.setAttribute(capitalize(input.getAttribute(id)));
} catch (UnknownAttributeException e) {
logger.error("An attribute mark as replaced is not in attribute list", e);
return null;
}
}
}
}
return delegate.process(input);
}
private IELdapAttribute capitalize(IELdapAttribute attribute) {
Set<IByteString> values = new HashSet<IByteString>();
for(IByteString bs : attribute.getValues()) {
String newVallue = bs.stringValue();
values.add(new ByteString(StringUtils.capitalize(newVallue.toLowerCase())));
}
attribute.setValues(values);
return attribute;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/TerminatorPostProcessor.java New file
0,0 → 1,38
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline;
 
import org.linid.dm.ldap.objects.IELdapEntry;
 
/**
* This service does nothing and is just used
* to terminate the pipeline of filter.
*/
public class TerminatorPostProcessor implements EntryPostProcessor {
public IELdapEntry process(IELdapEntry entry) {
return entry;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/pipeline/EntryPostProcessorFilter.java New file
0,0 → 1,43
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing.pipeline;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.postprocessing.PostProcessingException;
 
/**
* This interface is the unit token used to build
* pipeline of filter, and thus full post processing
*
*/
public interface EntryPostProcessorFilter {
/**
* Post process the entry and delegate to another step of post processing
* @param input
* @param delegate
* @return
*/
IELdapEntry process(IELdapEntry input, EntryPostProcessor delegate) throws PostProcessingException;
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/ldap/postprocessing/PostProcessingModule.java New file
0,0 → 1,179
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.ldap.postprocessing;
 
import java.util.List;
import java.util.Map;
 
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.services.ChainBuilder;
import org.apache.tapestry5.ioc.services.PipelineBuilder;
import org.apache.tapestry5.ioc.services.StrategyBuilder;
import org.apache.tapestry5.ioc.util.StrategyRegistry;
import org.linid.dm.ldap.postprocessing.analyze.EntryTypeAnalyzer;
import org.linid.dm.ldap.postprocessing.analyze.entrytype.DefaultEntry;
import org.linid.dm.ldap.postprocessing.analyze.entrytype.PersonEntry;
import org.linid.dm.ldap.postprocessing.analyze.impl.MatchAllAnalizer;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.EntryPostProcessorFilter;
import org.linid.dm.ldap.postprocessing.pipeline.TerminatorPostProcessor;
import org.linid.dm.ldap.postprocessing.pipeline.filters.CapitalizeFirstLetter;
import org.linid.dm.ldap.postprocessing.pipeline.filters.CreateDisplayName;
import org.linid.dm.ldap.postprocessing.pipeline.filters.CreateEmail;
import org.linid.dm.ldap.postprocessing.pipeline.filters.LogTransformation;
import org.slf4j.Logger;
 
/**
*
* The goal of this module is to handle configuration of the post processing
* features of WUI. When a user is about to update/create/delete/move an entry,
* one should want to be sure that the modification will compliant with business
* rules. For that, the framework may have to modify the request.
*
*commons, simple example are : - string normalization : capitalize first
* letter of CN, forbid some character, replace some other, etc - attribute auto
* creation : for example, automatically create an email given the name and the
* section of an user
*
* To achieve such a goal, this module apply three patterns : - a chain of
* command that specialize the entry to a class of set ; - a strategy pattern
* that, given an entry class, will choose the type of post-process rules to
* apply ; - a chain of commands (or filter ?) that apply the list of commands
* on the entry
*
*/
public class PostProcessingModule {
 
/**
* The default service that specialized an entry so that it will be usable
* in the strategy pattern.
*
* @param commands
* a contributed configuration list of commands
* @param chainBuilder
* the tapestry chain of command auto builder
* @return the specialized entry if the chain found one, null otherwise
*/
public static EntryTypeAnalyzer build(List<EntryTypeAnalyzer> commands,
@InjectService("ChainBuilder") ChainBuilder chainBuilder) {
return chainBuilder.build(EntryTypeAnalyzer.class, commands);
}
 
/**
* The configuration of chain of command that specialize the type of entry
*
* @param configuration
*/
public static void contributeEntryTypeAnalyzer(
OrderedConfiguration<EntryTypeAnalyzer> configuration) {
// Example of the PersonAnalyzer contribution
// configuration.add("PersonAnalyzer", new PersonAnalizer());
configuration.add("DefaultAnalyzer", new MatchAllAnalizer(), "after:*");
}
 
/**
* This is an example of a little more complex filter chain. We see that we
* use default post processor service as a termination service, what show
* that we are able to pipeline already defined post processor pipe in our
* new pipe (think at a more specialized entry that only need some more post
* processing than it's parent, it would be a mess to have to redefine all
* the pipe).
*
* @param builder
* @param defaultPostProcessor
* @param configuration
* @param serviceLog
* @return
*/
public static EntryPostProcessor buildPersonPostProcessor(
@InjectService("PipelineBuilder") PipelineBuilder builder,
@InjectService("DefaultPostProcessor") EntryPostProcessor defaultPostProcessor,
List<EntryPostProcessorFilter> configuration, Logger serviceLog) {
return builder.build(serviceLog, EntryPostProcessor.class,
EntryPostProcessorFilter.class, configuration,
defaultPostProcessor);
}
 
/**
* Exemple of the PersonPostProcessor. To activate it, uncomment the
* PersonDataType Analyzer
*
* @param configuration
*/
public static void contributePersonPostProcessor(
OrderedConfiguration<EntryPostProcessorFilter> configuration) {
configuration.add("log", new LogTransformation("Entry post processor log:"));
configuration.add("capitalize", new CapitalizeFirstLetter(), "after:log");
configuration.add("email", new CreateEmail("foo.bar"), "after:capitalize");
configuration.add("displayName", new CreateDisplayName().withSeparator(" ").snFirst(), "after:capitalize");
/*
* This filter is an example of a filter that always raise a post
* processing exception
*/
// configuration.add("exception", new ThrowException(), "after:email");
}
 
public static void contributeDefaultPostProcessor(
OrderedConfiguration<EntryPostProcessorFilter> configuration) {
configuration.add("log", new LogTransformation(
"Default post processor log:"));
}
 
public static EntryPostProcessor buildDefaultPostProcessor(
@InjectService("PipelineBuilder") PipelineBuilder builder,
List<EntryPostProcessorFilter> configuration, Logger serviceLog) {
return builder.build(serviceLog, EntryPostProcessor.class,
EntryPostProcessorFilter.class, configuration,
new TerminatorPostProcessor());
}
 
/**
* The strategy decider for a given entry this is the default post processor
* that should be called in Tapestry pages/components
*
* @param configuration
* @param builder
* @return
*/
@SuppressWarnings("rawtypes")
public static EntryPostProcessor build(
Map<Class, EntryPostProcessor> configuration,
@InjectService("StrategyBuilder") StrategyBuilder builder) {
StrategyRegistry<EntryPostProcessor> registry = StrategyRegistry
.newInstance(EntryPostProcessor.class, configuration);
return builder.build(registry);
}
 
@SuppressWarnings("rawtypes")
public static void contributeEntryPostProcessor(
MappedConfiguration<Class, EntryPostProcessor> configuration,
@InjectService("PersonPostProcessor") EntryPostProcessor personPostProcessor,
@InjectService("DefaultPostProcessor") EntryPostProcessor defaultPostProcessor) {
configuration.add(PersonEntry.class, personPostProcessor);
configuration.add(DefaultEntry.class, defaultPostProcessor);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/SimplePropertyEditBlocks.java New file
0,0 → 1,246
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.Select;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.services.PropertyEditContext;
import org.apache.tapestry5.util.AbstractSelectModel;
import org.linid.dm.wui.model.AttributeEditContext;
import org.linid.dm.wui.t5lib.data.DropDownList;
 
/**
* Create a simple dropdown select from a list of String
*
* @author LINAGORA
*/
public class SimplePropertyEditBlocks {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
@Component(parameters = { "value=selected",
"encoder=valueEncoderForSelected", "validate=prop:selectValidator",
"label=prop:context.label", "model=selectModelForDropDownList",
"clientId=prop:context.propertyId" })
private Select select;
 
public SelectModel getSelectModelForDropDownList() {
return new IntValueSelectModel(((DropDownList) this.context
.getPropertyValue()).getOptions());
}
 
public int getSelected() {
return ((DropDownList) this.context.getPropertyValue()).getSelected();
}
 
public void setSelected(int value) {
((DropDownList) this.context.getPropertyValue()).setSelected(value);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getSelectValidator() {
return context.getValidator(select);
}
 
@Component(parameters = { "value=attributeSelected",
"validate=prop:attributeSelectValidator",
"label=prop:context.label", "model=attributeSelectModel",
"clientId=prop:context.propertyId" })
private Select attributeSelect;
 
public SelectModel getAttributeSelectModel() {
List<String> options = new ArrayList<String>(
((AttributeEditContext) this.context).getPossibleValues());
Collections.sort(options);
return new StringValueSelectModel(options);
}
 
public String getAttributeSelected() {
return (String) this.context.getPropertyValue();
}
 
public void setAttributeSelected(String value) {
this.context.setPropertyValue(value);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getAttributeSelectValidator() {
return context.getValidator(attributeSelect);
}
 
/**
* A simple translator from/to integer
*
* @return The translator for Integer type
*/
@SuppressWarnings("rawtypes")
public ValueEncoder getValueEncoderForSelected() {
return new ValueEncoder() {
public String toClient(Object value) {
return ((Integer) value).toString();
}
 
public Object toValue(String clientValue) {
return new Integer(clientValue);
}
};
}
/* simple value option model class */
private class ValueOptionModel implements OptionModel {
Map<String, String> attributes;
Object value;
String label;
boolean disabled;
 
public ValueOptionModel(Object value, String label, boolean disabled,
Map<String, String> attrs) {
this.value = value;
this.label = label;
this.disabled = disabled;
this.attributes = attrs;
}
 
public Map<String, String> getAttributes() {
return this.attributes;
}
 
public String getLabel() {
return this.label;
}
 
public Object getValue() {
return this.value;
}
 
public boolean isDisabled() {
return this.disabled;
}
}
 
/*
* ---------------------- simple select model class with integer
* index--------------------
*/
/* the selectmodel to transform the list of value to a select element */
public class IntValueSelectModel extends AbstractSelectModel {
 
private List<OptionModel> optionModels;
 
public IntValueSelectModel(List<String> options) {
optionModels = new ArrayList<OptionModel>();
for (int i = 0; i < options.size(); i++) {
optionModels.add(new ValueOptionModel(new Integer(i), options
.get(i), false, null));
}
}
 
/*
* No option group in this select model example
*
* @see org.apache.tapestry5.SelectModel#getOptionGroups()
*/
public List<OptionGroupModel> getOptionGroups() {
return null;
}
 
public List<OptionModel> getOptions() {
return this.optionModels;
}
}
 
/*
* ---------------------- simple select model class with value =
* label--------------------
*/
/* the selectmodel to transform the list of value to a select element */
public class StringValueSelectModel extends AbstractSelectModel {
 
private List<OptionModel> optionModels;
 
public StringValueSelectModel(List<String> options) {
optionModels = new ArrayList<OptionModel>();
for (String s : options) {
optionModels.add(new ValueOptionModel(s, s, false, null));
}
}
 
/*
* No option group in this select model example
*
* @see org.apache.tapestry5.SelectModel#getOptionGroups()
*/
public List<OptionGroupModel> getOptionGroups() {
return null;
}
 
public List<OptionModel> getOptions() {
return this.optionModels;
}
}
 
/*
* Non editable text Displayer
*/
 
@Component(parameters = { "value=context.propertyValue",
"label=prop:context.label", "translate=prop:textfieldtranslator",
"clientId=prop:context.propertyId" })
private TextField nonEditableTextField;
 
public FieldTranslator<?> getTextFieldTranslator() {
return context.getTranslator(nonEditableTextField);
}
 
/*
* Non editable text Displayer
*/
 
@Component(parameters = { "value=context.propertyValue",
"label=prop:context.label", "translate=prop:hiddentranslator",
"clientId=prop:context.propertyId" })
private TextField hiddenField;
 
public FieldTranslator<?> getHiddenTranslator() {
return context.getTranslator(hiddenField);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/PasswordDisplayBlock.java New file
0,0 → 1,43
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
 
public class PasswordDisplayBlock {
private static final String HIDDEN_PASSWORD = "*****";
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
 
public String getValue() {
return HIDDEN_PASSWORD;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/URLDisplayBlock.java New file
0,0 → 1,54
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.t5lib.components.URLDisplayer;
 
/**
* Display an urk with a link
*
* @author Raph
*/
public class URLDisplayBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
@Component(parameters = {
"value=prop:context.propertyValue"
// "label=prop:context.label",
// "clientId=prop:context.propertyId",
// "displayLink=prop:parameters.displayLink"
})
private URLDisplayer urlDisplayer;
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/LdapValueDisplayerBlock.java New file
0,0 → 1,75
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.model.AttributeOutputContext;
import org.linid.dm.wui.model.LdapValueSelectParameters;
import org.linid.dm.wui.t5lib.components.LdapValueDisplayer;
import org.springframework.context.ApplicationContext;
 
/**
* Block to use an LdapValueDisplayer
* To configure with LdapValueSelectParameters
*
* @author Raph
*/
public class LdapValueDisplayerBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
@InjectService("ApplicationContext")
private ApplicationContext applicationContext;
 
@Component(parameters = {
"principalDn=prop:principalDn",
"searchBase=prop:parameters.searchBase",
"searchScope=prop:parameters.searchScope",
"searchFilterAttr=prop:parameters.searchFilterAttr",
"searchFilterValue=prop:context.propertyValue",
// "label=prop:context.label",
"displayParameters=prop:parameters.displayParameters",
"clientId=prop:context.propertyId"
})
private LdapValueDisplayer ldapValueDisplayer;
public LdapValueSelectParameters getParameters() {
String bean = ((AttributeOutputContext) context).getTypeConfigurationBean();
return (LdapValueSelectParameters) applicationContext.getBean(bean);
}
public String getPrincipalDn() {
return ((AttributeOutputContext) context).getPrincipalDn();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/SearchCriterionEditBlock.java New file
0,0 → 1,45
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.wui.model.SearchCriterion;
 
public class SearchCriterionEditBlock {
@Environmental
private PropertyEditContext context;
public SearchCriterion getCriterion() {
if(context.getPropertyValue() instanceof SearchCriterion) {
return (SearchCriterion)context.getPropertyValue();
}
return null;
}
public void setCriterion(SearchCriterion criterion) {
this.context.setPropertyValue(criterion);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/CheckBoxesEditBlock.java New file
0,0 → 1,164
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.Checklist;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.internal.services.StringValueEncoder;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PropertyEditContext;
import org.apache.tapestry5.util.AbstractSelectModel;
import org.linid.dm.wui.entrymapping.pipeline.filters.AggregateCheckBoxesValues;
import org.linid.dm.wui.model.AttributeEditContext;
 
/**
* Block for list of checkbox
*/
 
 
 
public class CheckBoxesEditBlock {
 
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
@Component(parameters = { "selected=selected", "encoder=encoder", "model=model"})
private Checklist checklist;
 
@Inject
private Messages messages;
private List<String> selected;
public List<String> getSelected() {
String fromcontext = (String) this.context.getPropertyValue();
//the selected values come like this: AAAA#BBBB#CCCC
//see AggregateCheckBoxesValues
if (fromcontext != null) {
selected = new ArrayList<String>(Arrays.asList(fromcontext.split(AggregateCheckBoxesValues.CHARACTER_SEP)));
} else {
selected = new ArrayList<String>();
}
return selected;
}
public void setSelected(List<String> elements){
this.selected = elements;
StringBuilder out = new StringBuilder();
for (String o : selected)
{
out.append(o);
out.append(AggregateCheckBoxesValues.CHARACTER_SEP);
}
this.context.setPropertyValue(out.toString());
}
public ValueEncoder<String> getEncoder() {
return new StringValueEncoder();
}
 
public SelectModel getModel() {
AttributeEditContext attrEditContext = (AttributeEditContext) this.context;
Set<String> valuesFromEsSchema = attrEditContext.getPossibleValues();
Map<String,String> map = new HashMap<String,String>();
String currentValue;
String currentLabel;
for (String oneValueFromEsSchema : valuesFromEsSchema) {
currentValue = oneValueFromEsSchema.substring(oneValueFromEsSchema.indexOf("{")+1, oneValueFromEsSchema.indexOf("}"));
if(messages.contains(currentValue)){
//get the label from the application bundle.
currentLabel = messages.get(currentValue);
} else {
//get the label from the shema
currentLabel = oneValueFromEsSchema.substring(oneValueFromEsSchema.indexOf("}")+1);
}
map.put(currentValue, currentLabel) ;
}
return new CheckBoxesSelectModel(map);
}
public class CheckBoxesSelectModel extends AbstractSelectModel {
private Map<String,String> checkboxValues;
 
public CheckBoxesSelectModel(Map<String,String> checkboxValues) {
this.checkboxValues = checkboxValues;
}
@Override
public List<OptionGroupModel> getOptionGroups() {
return null;
}
 
@Override
public List<OptionModel> getOptions() {
List<OptionModel> options = new ArrayList<OptionModel>();
for (Map.Entry<String, String> entry : checkboxValues.entrySet()) {
options.add(new OptionModelImpl(entry.getValue(), entry.getKey())); //label and and unique value for html checkbox
}
return options;
}
}
}
 
 
 
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/FileEditBlock.java New file
0,0 → 1,152
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.io.File;
import java.io.FilenameFilter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Mixins;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.ldap.repository.service.ConfigurableLdapFacadeManager;
 
/**
* Create a simple dropdown select from a list of String
*
* @author LINAGORA
*/
public class FileEditBlock {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
@Inject
private ConfigurableLdapFacadeManager facadeManager;
 
@Component(parameters = { "value=context.propertyValue",
"label=prop:context.label",
"translate=prop:filetranslator",
"clientId=prop:context.propertyId"})
@Mixins({"jquery/Autocomplete"})
private TextField fileCompletion;
 
public FieldTranslator<?> getFileTranslator() {
return context.getTranslator(fileCompletion);
}
 
public String getFileCompletion() {
return (String) this.context.getPropertyValue();
}
 
public void setFileCompletion(String value) {
this.context.setPropertyValue(value);
}
@Persist
private Map<String, Boolean> hostIsLocalhost;
 
private boolean isLocallyDeployed() {
if (hostIsLocalhost == null) {
hostIsLocalhost = new HashMap<String, Boolean>();
}
String host = facadeManager.getCurrentConfiguration().getLdapHost();
if (hostIsLocalhost.containsKey(host)) {
return hostIsLocalhost.get(host);
}
boolean isLocalhost;
try {
InetAddress address = InetAddress.getByName(host);
isLocalhost = address.isLoopbackAddress();
} catch (UnknownHostException e) {
isLocalhost = false;
}
hostIsLocalhost.put(host, isLocalhost);
return isLocalhost;
}
private static final int MAX_SIZE = 20;
 
/**
* Prepend prefix on each table value
* @param prefix the prefix
* @param params the values table
* @return the prefixed values table
*/
public List<String> prepend(String prefix, String[] params) {
if(params != null) {
int max = (params.length < MAX_SIZE ? params.length : MAX_SIZE);
List<String> returns = new ArrayList<String>(max);
for(int i = 0; i < max; i++) {
returns.add(prefix + params[i]);
}
return returns;
} else {
return new ArrayList<String>();
}
}
/**
* Provide the files / directories listing on the application server local filesystem
* @param partial the written path
* @return the list of values available to select on client side
*/
public List<String> onProvideCompletions(String partial) {
if( !isLocallyDeployed() ) {
return null;
} else if( partial.lastIndexOf( File.separator ) == -1 ) {
return prepend( partial, new File(partial).list() );
} else if( partial.lastIndexOf( File.separator ) == 0 && partial.length()==1 ) {
return prepend( "/", new File("/").list() );
} else if ( new File(partial).isDirectory() ) {
if (partial.endsWith("/")) {
return prepend( partial, new File(partial).list() );
} else {
return prepend( partial + File.separator, new File(partial).list() );
}
} else {
String prefix = partial.substring( 0, partial.lastIndexOf( File.separator ) );
final String suffix = partial.substring( partial.lastIndexOf( File.separator) + 1 );
return prepend( prefix + File.separator, new File(prefix).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(suffix);
}
}) );
}
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/DnSelectorEditBlock.java New file
0,0 → 1,101
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Value;
import org.apache.tapestry5.services.PropertyEditContext;
 
/**
* Create a simple dropdown select from a list of String
*
* @author Sebastien Bahloul <seb@lsc-project.org>
*/
public class DnSelectorEditBlock {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
@Inject @Path("../../components/ldapentry/plus-16x16.png")
private Asset plusIcon;
public Asset getPlusIcon() {
return plusIcon;
}
@SuppressWarnings("unused")
private String dn;
@Inject @Value("${ldap.base}")
private String rootDn;
public String getRootDn() {
return rootDn;
}
public String getLdapFacadePrincipal() {
/* FIXME: should return principal */
return rootDn;
}
/** Distinguish Name selector */
@Component(parameters = { "value=prop:dn",
"label=prop:context.label",
"validate=prop:dnValidator",
"translate=prop:dntranslator",
"clientId=prop:context.propertyId"})
private TextField dnSelector;
// @SuppressWarnings("unused")
// @Component
// private Window dnSelectorWindow;
public String getDn() {
return (String) this.context.getPropertyValue();
}
 
public void setDn(String dn) {
this.context.setPropertyValue(dn);
}
 
public FieldTranslator<?> getDnTranslator() {
return context.getTranslator(dnSelector);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getDnValidator() {
return context.getValidator(dnSelector);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/PasswordEditBlock.java New file
0,0 → 1,142
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.internal.services.CompositeFieldValidator;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.FieldValidatorSource;
import org.apache.tapestry5.services.PropertyEditContext;
 
/**
* Create a simple dropdown select from a list of String
*
* @author LINAGORA
*/
public class PasswordEditBlock {
@Environmental
private PropertyEditContext context;
 
@Inject
private FieldValidatorSource fieldValidatorSource;
 
@Inject
private Locale locale;
 
public PropertyEditContext getContext() {
return context;
}
 
/*
* Password validation field
*/
/*
* This editor verify that two password have the same input. It create two
* field that are backed by only one property
*/
@Component(parameters = { "value=passwordValue",
"label=prop:context.label", "translate=prop:passwordtranslator",
"validate=prop:passwordValidator",
"clientId=prop:context.propertyId" })
private PasswordField password;
 
@Persist("flash")
private String verifyPasswordValue;
@Persist("flash")
private boolean firstPasswordSet;
 
@Persist("flash")
private boolean secondPasswordSet;
/*
* where does I find the message for password validation ?
*/
@Component(parameters = { "value=prop:verifyPasswordValue",
"label=message:editor.verify.password",
"validate=prop:verifyPasswordValidator" })
private PasswordField verifyPassword;
 
@SuppressWarnings("rawtypes")
public FieldTranslator getPasswordTranslator() {
return context.getTranslator(password);
}
public String getPasswordValue() {
firstPasswordSet = false;
return (String)context.getPropertyValue();
}
 
public void setPasswordValue(String password) {
firstPasswordSet = true;
context.setPropertyValue(password);
}
 
public String getVerifyPasswordValue() {
if (verifyPasswordValue == null) {
verifyPasswordValue = (String)context.getPropertyValue();
secondPasswordSet = false;
}
return this.verifyPasswordValue;
}
 
public void setVerifyPasswordValue(String password2) {
this.verifyPasswordValue = password2;
secondPasswordSet = true;
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getPasswordValidator() {
return context.getValidator(password);
}
 
/**
* Verify that the value entered the second time match the first value. This
* validation is required.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public FieldValidator getVerifyPasswordValidator() {
List<FieldValidator> validators = new ArrayList<FieldValidator>();
if (firstPasswordSet && !secondPasswordSet) {
validators.add(fieldValidatorSource.createValidator(verifyPassword,
"required", null, null, context.getContainerMessages(),
locale));
}
validators.add(fieldValidatorSource.createValidator(verifyPassword,
"equals", Pattern.quote(context.getTranslator(verifyPassword)
.toClient(context.getPropertyValue())), null, context
.getContainerMessages(), locale));
return new CompositeFieldValidator(validators);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/AutocompleteDnEditBlock.java New file
0,0 → 1,207
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import javax.naming.InvalidNameException;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Mixins;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Value;
import org.apache.tapestry5.services.Environment;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.authorization.AuthorizationException;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.repository.LdapEntryRepository;
import org.linid.dm.wui.model.AttributeEditContext;
import org.springframework.ldap.SizeLimitExceededException;
 
/**
* Create a simple input type with auto completion to find people
*
* @author Sebastien Bahloul &lt;sebastien.bahloul@gmail.com&gt;
*/
public class AutocompleteDnEditBlock {
@Inject @Path("../../components/ldapentry/plus-16x16.png")
private Asset plusIcon;
 
@Inject
private LdapEntryRepository entryRepository;
@Inject @Value("${ldap.user.dn}")
private String base;
private String filter;
private String attributeToDisplay;
 
private static final int MAX_SIZE = 20;
private static final int MIN_LENGTH = 3;
 
@SuppressWarnings("unused")
private String dn;
 
@Persist
private PropertyEditContext saveContext;
@Inject
private Environment environment;
public AutocompleteDnEditBlock() {
filter = "(&(objectClass=inetOrgPerson)(cn=*{0}*))";
attributeToDisplay = "cn";
}
 
public AutocompleteDnEditBlock(String base, String filter, String attributeToDisplay) {
this.base = base;
this.filter = filter;
this.attributeToDisplay = attributeToDisplay;
}
 
public Asset getPlusIcon() {
return plusIcon;
}
public PropertyEditContext getContext() {
/* Clean persistence if needed */
PropertyEditContext context = environment.peek(PropertyEditContext.class);
if (context != null) {
this.saveContext = context;
}
return this.saveContext;
}
 
@Component(parameters = { "value=prop:namecompletion",
"label=prop:context.label",
"translate=prop:nametranslator",
"clientId=prop:context.propertyId"})
@Mixins({"Autocomplete"})
private TextField nameCompletion;
 
public FieldTranslator<?> getNameTranslator() {
return getContext().getTranslator(nameCompletion);
}
 
public String getNameCompletion() {
if(this.getContext().getPropertyValue() == null || this.getContext().getPropertyValue() == "") {
return "";
}
try {
IELdapEntry entry = entryRepository.get(new LdapName(getPrincipalDn()), new LdapName((String) this.getContext().getPropertyValue()));
if(entry.getAttribute(this.attributeToDisplay) != null) {
return entry.getAttribute(this.attributeToDisplay).getValue().toString() + " (" + entry.getRdn() + ")";
}
} catch (InvalidNameException e) {
return e.toString();
} catch (AuthorizationException e) {
return e.toString();
}
return "Dynamic error !";
}
 
public void setNameCompletion(String value) throws InvalidNameException {
if(value != null && value.indexOf(")") > value.indexOf("(")) {
String rdn = value.substring(value.lastIndexOf("(")+1,value.lastIndexOf(")"));
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.SUBTREE_SCOPE);
List<IELdapEntry> entries = null;
entries = entryRepository.search(new LdapName(getPrincipalDn()), new LdapName(base), "("+rdn+")", scs);
if (entries.size() == 1) {
this.getContext().setPropertyValue(entries.get(0).getDn().toString());
}
}
}
 
/**
* Prepend prefix on each table value
* @param prefix the prefix
* @param params the values table
* @return the prefixed values table
*/
public String[] prepend(String prefix, String[] params) {
if(params != null) {
int max = (params.length < MAX_SIZE ? params.length : MAX_SIZE);
String[] returns = new String[max];
for(int i = 0; i < max; i++) {
returns[i] = prefix + params[i];
}
return returns;
} else {
return new String[]{};
}
}
/**
* Provide the files / directories listing on the application server local filesystem
* @param partial the written path
* @return the list of values available to select on client side
* @throws InvalidNameException
*/
public String[] onProvideCompletions(String partial) throws InvalidNameException {
if (partial.length() < MIN_LENGTH) {
return null;
}
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.SUBTREE_SCOPE);
// scs.setCountLimit(MAX_SIZE);
List<IELdapEntry> entries = null;
try {
entries = entryRepository.search(new LdapName(getPrincipalDn()), new LdapName(base), replacePartialInFilter(partial), scs);
} catch (SizeLimitExceededException slee) {
// Forget it
}
List<String> values = new ArrayList<String>();
if(entries != null && entries.size() > 0 ) {
Iterator<IELdapEntry> entriesIterator = entries.iterator();
int i = 0;
while (entriesIterator.hasNext() && i++ < MAX_SIZE) {
IELdapEntry entry = entriesIterator.next();
values.add(entry.getAttribute(attributeToDisplay).getValue().toString() + " (" + entry.getRdn() + ")");
}
return values.toArray(new String[]{});
}
return null;
}
 
private String replacePartialInFilter(String partial) {
return new String(filter).replaceAll("\\{0\\}", partial);
}
public String getPrincipalDn() {
return ((AttributeEditContext) getContext()).getPrincipalDn();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/TextEditBlock.java New file
0,0 → 1,77
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.TextArea;
import org.apache.tapestry5.services.PropertyEditContext;
 
/**
* Create a simple dropdown select from a list of String
*
* @author Sebastien Bahloul
*/
public class TextEditBlock {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
/*
* Password validation field
*/
/*
* This editor verify that two password have the same input. It create two
* field that are backed by only one property
*/
@Component(parameters = { "value=context.propertyValue",
"label=prop:context.label",
"translate=prop:textareatranslator",
"validate=prop:textareaValidator",
"clientId=prop:context.propertyId" })
private TextArea textarea;
 
public String getDn() {
return (String) this.context.getPropertyValue();
}
 
public void setDn(String dn) {
this.context.setPropertyValue(dn);
}
 
public FieldTranslator<?> getTextareaTranslator() {
return context.getTranslator(textarea);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getTextareaValidator() {
return context.getValidator(textarea);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/AddressEditBlock.java New file
0,0 → 1,78
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.TextArea;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.wui.t5lib.components.AddressDisplayer;
 
public class AddressEditBlock {
public static String SEPARATOR = "\n";
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
@Component(parameters = { "value=convertedValue",
"label=prop:context.label",
"translate=prop:textareatranslator",
"validate=prop:textareaValidator",
"clientId=prop:context.propertyId" })
private TextArea textarea;
 
public String getDn() {
return (String) this.context.getPropertyValue();
}
 
public void setDn(String dn) {
this.context.setPropertyValue(dn);
}
 
public FieldTranslator<?> getTextareaTranslator() {
return context.getTranslator(textarea);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getTextareaValidator() {
return context.getValidator(textarea);
}
public String getConvertedValue() {
String value = (String)context.getPropertyValue();
return value.replaceAll(AddressDisplayer.SEPARATOR, SEPARATOR);
}
public void setConvertedValue(String convertedValue) {
String value = convertedValue.replaceAll(SEPARATOR, AddressDisplayer.SEPARATOR);
context.setPropertyValue(value);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/CodeValueEditBlock.java New file
0,0 → 1,151
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
 
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.Select;
import org.apache.tapestry5.services.PropertyEditContext;
import org.apache.tapestry5.util.AbstractSelectModel;
import org.linid.dm.wui.model.AttributeEditContext;
 
/**
* Create a dropdown select from a map of <code,values> String
*
* @author Sebastien Bahloul
*/
public class CodeValueEditBlock {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
/** Simple Code value selector */
@Component(parameters = { "value=attributeSelected",
"validate=prop:attributeCodeValueSelectValidator",
"label=prop:context.label", "model=attributeCodeValueSelectModel",
"clientId=prop:context.propertyId" })
private Select attributeCodeValueSelect;
 
public SelectModel getAttributeCodeValueSelectModel() {
Set<String> values = ((AttributeEditContext) this.context).getPossibleValues();
Map<String, String> options = new TreeMap<String, String>();
for ( String value : values ) {
if(value.indexOf("{") == 0 && value.indexOf("}") > 0 && value.indexOf("}") + 1 < value.length()) {
options.put(value.substring(1, value.indexOf("}")), value.substring(value.indexOf("}")+1));
} else {
options.put(value, value);
}
}
return new StringCodeValueSelectModel(options);
}
 
public String getAttributeSelected() {
return (String) this.context.getPropertyValue();
}
 
public void setAttributeSelected(String value) {
this.context.setPropertyValue(value);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getAttributeCodeValueSelectValidator() {
return context.getValidator(attributeCodeValueSelect);
}
 
/* simple value option model class */
private class ValueOptionModel implements OptionModel {
Map<String, String> attributes;
Object value;
String label;
boolean disabled;
 
public ValueOptionModel(Object value, String label, boolean disabled,
Map<String, String> attrs) {
this.value = value;
this.label = label;
this.disabled = disabled;
this.attributes = attrs;
}
 
public Map<String, String> getAttributes() {
return this.attributes;
}
 
public String getLabel() {
return this.label;
}
 
public Object getValue() {
return this.value;
}
 
public boolean isDisabled() {
return this.disabled;
}
}
 
/*
* ---------------------- simple select model class with value =
* label--------------------
*/
/* the select model to transform the list of value to a select element */
public class StringCodeValueSelectModel extends AbstractSelectModel {
 
private List<OptionModel> optionModels;
 
public StringCodeValueSelectModel(Map<String, String> options) {
optionModels = new ArrayList<OptionModel>();
for (String optionName : options.keySet()) {
optionModels.add(new ValueOptionModel(optionName, options.get(optionName), false, null));
}
}
 
/*
* No option group in this select model example
*
* @see org.apache.tapestry5.SelectModel#getOptionGroups()
*/
public List<OptionGroupModel> getOptionGroups() {
return null;
}
 
public List<OptionModel> getOptions() {
return this.optionModels;
}
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/MultilineTextEditBlock.java New file
0,0 → 1,57
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.TextArea;
import org.apache.tapestry5.services.PropertyEditContext;
 
public class MultilineTextEditBlock {
@Environmental
private PropertyEditContext context;
 
public PropertyEditContext getContext() {
return context;
}
 
@Component(parameters = { "value=context.propertyValue",
"label=prop:context.label",
"translate=prop:textareatranslator",
"validate=prop:textareaValidator",
"clientId=prop:context.propertyId" })
private TextArea textarea;
 
public FieldTranslator<?> getTextareaTranslator() {
return context.getTranslator(textarea);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getTextareaValidator() {
return context.getValidator(textarea);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/edit/DateEditBlock.java New file
0,0 → 1,107
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages.edit;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.corelib.components.DateField;
import org.apache.tapestry5.services.PropertyEditContext;
 
/**
* Create a simple dropdown select from a list of String
*
* @author LINAGORA
*/
public class DateEditBlock {
@Environmental
private PropertyEditContext context;
 
/**
* This is the standard LDAP date format : yyyyMMddHHmmss.S'Z'.
*/
public static final String LDAP_DATE_INTERNAL_STORAGE_FORMAT = "yyyyMMddHHmmss.S'Z'";
 
/**
* This is the simplified LDAP date format : yyyyMMddHHmmss'Z'.
*/
public static final String LDAP_DATE_SIMPLIFIED_STORAGE_FORMAT = "yyyyMMddHHmmss'Z'";
 
/**
* Internal transformation object. TODO fix this if there is a performance
* problem, I did a small cleanup and added synchronization as a DateFormat
* is not threadsafe
*/
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat(
LDAP_DATE_INTERNAL_STORAGE_FORMAT);
 
public PropertyEditContext getContext() {
return context;
}
 
@SuppressWarnings("unused")
private Date dateTime;
 
/**
* we need a new component here
* to manage date and time with T53
* CK component DateTimeField has to be changed
* */
@Component(parameters = { "value=prop:dateTime",
"label=prop:context.label",
"validate=prop:attributeDateTimeSelectValidator",
"clientId=prop:context.propertyId",
"datePattern=yyyyMMddHHmmss.S'Z'", "timePicker=true",
"timePickerAdjacent=true" })
private DateField attributeDateTime;
 
public Date getDateTime() {
try {
if(this.context.getPropertyValue() != null) {
return FORMATTER.parse((String) this.context.getPropertyValue());
} else {
return null;
}
} catch (ParseException e) {
return null;
}
}
 
public void setDateTime(Date value) {
this.context.setPropertyValue(value);
}
 
@SuppressWarnings("rawtypes")
public FieldValidator getAttributeDateTimeSelectValidator() {
return context.getValidator(attributeDateTime);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/MultilineTextDisplayBlock.java New file
0,0 → 1,41
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
 
public class MultilineTextDisplayBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
 
public String getValue() {
return (String)this.context.getPropertyValue();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/SimpleValueDisplayBlocks.java New file
0,0 → 1,39
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
 
public class SimpleValueDisplayBlocks {
@Environmental
private PropertyOutputContext context;
 
public String getAttributes() {
return (String)context.getPropertyValue();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/CheckBoxesDisplayBlock.java New file
0,0 → 1,162
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
 
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.entrymapping.pipeline.filters.AggregateCheckBoxesValues;
import org.linid.dm.wui.model.AttributeOutputContext;
 
/**
* Block for list of checkbox
*/
 
public class CheckBoxesDisplayBlock {
 
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
 
@Inject
private Messages messages;
@Property
private Item item;
public List<String> getSelected() {
String fromcontext = (String) this.context.getPropertyValue();
//the selected values come like this: AAAA#BBBB#CCCC
//see AggregateCheckBoxesValues
if (fromcontext != null) {
return Arrays.asList(fromcontext.split(AggregateCheckBoxesValues.CHARACTER_SEP));
} else {
return Collections.emptyList();
}
}
 
public List<Item> getItems() {
List<Item> returnList = new ArrayList<Item>();
List<String> selectedElements = getSelected(); // the selected values in the ldap attribute
AttributeOutputContext attrContext = (AttributeOutputContext) this.context;
Set<String> valuesFromEsSchema = attrContext.getPossibleValues();
String currentValue;
String currentLabel;
//for all possible values of the ldap schema
for (String oneValueFromEsSchema : valuesFromEsSchema) {
currentValue = oneValueFromEsSchema.substring(oneValueFromEsSchema.indexOf("{")+1, oneValueFromEsSchema.indexOf("}"));
//*** get the label
if(messages.contains(currentValue)){
//get the label from the application bundle.
currentLabel = messages.get(currentValue);
} else {
//get the label from the shema
currentLabel = oneValueFromEsSchema.substring(oneValueFromEsSchema.indexOf("}")+1);
}
//** get the status checked or not for the checkbox?
if(selectedElements.contains(currentValue)){
//checked
returnList.add(new Item(currentLabel, true, currentValue));
} else {
returnList.add(new Item(currentLabel, false, currentValue));
}
}
return returnList;
}
public ValueEncoder<Item> getEncoder() {
return new ValueEncoder<Item>() {
 
@Override
public String toClient(Item value) {
return value.getLabel();
}
 
@Override
public Item toValue(String clientValue) {
// TODO Auto-generated method stub
return null;
}
};
}
public class Item {
private String label;
private boolean checked;
private String value;
public String getLabel() {
return label;
}
public boolean isChecked() {
return checked;
}
public String getValue() {
return value;
}
public Item(String label, boolean checked, String value) {
super();
this.label = label;
this.checked = checked;
this.value = value;
}
}
}
 
 
 
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/SimplePropertyDisplayBlocks.java New file
0,0 → 1,71
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import java.util.Set;
 
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.ldap.objects.IELdapAttribute;
 
public class SimplePropertyDisplayBlocks {
@Environmental
private PropertyOutputContext context;
 
/* *********************************************
* LdapName Displayer *
********************************************* */
public String getConvertedDnValue() {
LdapName value = (LdapName) context.getPropertyValue();
 
if (value == null) return null;
return value.toString();
}
/* *********************************************
* Attributes Displayer *
********************************************* */
private IELdapAttribute attribute;
@SuppressWarnings("unchecked")
public Set<IELdapAttribute> getAttributes() {
return (Set<IELdapAttribute>)context.getPropertyValue();
}
 
public IELdapAttribute getAttribute() {
return this.attribute;
}
 
public void setAttribute(IELdapAttribute attribute) {
this.attribute = attribute;
}
public String displayAttribute() {
return attribute.toString();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/TextDisplayBlock.java New file
0,0 → 1,41
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
 
public class TextDisplayBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
 
public String getValue() {
return (String)this.context.getPropertyValue();
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/AddressDisplayBlock.java New file
0,0 → 1,54
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.t5lib.components.AddressDisplayer;
 
/**
* Display an address, splitting '$'
*
* @author Raph
*/
public class AddressDisplayBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
@Component(parameters = {
"value=prop:context.propertyValue"
// "label=prop:context.label",
// "clientId=prop:context.propertyId",
// "displayLink=prop:parameters.displayLink"
})
private AddressDisplayer addressDisplayer;
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/EmailDisplayBlock.java New file
0,0 → 1,54
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.t5lib.components.EmailDisplayer;
 
/**
* Display an email with mailto: link
*
* @author Raph
*/
public class EmailDisplayBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
@Component(parameters = {
"value=prop:context.propertyValue"
// "label=prop:context.label",
// "clientId=prop:context.propertyId",
// "displayLink=prop:parameters.displayLink"
})
private EmailDisplayer emailDisplayer;
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/DnDisplayerBlock.java New file
0,0 → 1,78
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.PropertyOutputContext;
import org.linid.dm.wui.model.AttributeOutputContext;
import org.linid.dm.wui.model.LdapSelectParameters;
import org.linid.dm.wui.t5lib.components.DnDisplayer;
import org.springframework.context.ApplicationContext;
 
/**
* Create a dropdown select from an LDAP request
*
* @author Raph
*/
public class DnDisplayerBlock {
@Environmental
private PropertyOutputContext context;
 
public PropertyOutputContext getContext() {
return context;
}
@InjectService("ApplicationContext")
private ApplicationContext applicationContext;
 
@Component(parameters = {
"principalDn=prop:principalDn",
"value=prop:context.propertyValue",
// "label=prop:context.label",
"displayParameters=prop:parameters.displayParameters",
// "clientId=prop:context.propertyId",
"displayLink=prop:parameters.displayLink",
"pageLink=prop:parameters.pageLink"
})
private DnDisplayer dnDisplayer;
public LdapSelectParameters getParameters() {
String bean = ((AttributeOutputContext) context).getTypeConfigurationBean();
if(bean == null) {
throw new RuntimeException("Enhanced schema type for attribute " +
((AttributeOutputContext) context).getPropertyName() + " does not reference " +
"any configuration bean type ! You must specify type a typeConfigurationBean attribute.");
}
return (LdapSelectParameters) applicationContext.getBean(bean);
}
public String getPrincipalDn() {
return ((AttributeOutputContext) context).getPrincipalDn();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/LdapSelectBlock.java New file
0,0 → 1,76
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.wui.model.AttributeEditContext;
import org.linid.dm.wui.model.LdapSelectParameters;
import org.linid.dm.wui.t5lib.components.LdapSelect;
import org.springframework.context.ApplicationContext;
 
/**
* Create a dropdown select from an LDAP request
*
* @author Raph
*/
public class LdapSelectBlock {
@Environmental
private PropertyEditContext context;
@InjectService("ApplicationContext")
private ApplicationContext applicationContext;
 
public PropertyEditContext getContext() {
return context;
}
 
@Component(parameters = {
"value=prop:context.propertyValue",
"label=prop:context.label",
"clientId=prop:context.propertyId",
"validate=required",
"principalDn=prop:principalDn",
"selectSearchBase=prop:parameters.searchBase",
"selectSearchScope=prop:parameters.searchScope",
"selectSearchFilter=prop:parameters.searchFilter",
"selectSearchKeyAttr=prop:parameters.searchKeyAttr",
"selectSearchValueAttr=prop:parameters.searchValueAttr"
})
private LdapSelect ldapSelect;
public LdapSelectParameters getParameters() {
String bean = ((AttributeEditContext) context).getTypeConfigurationBean();
return (LdapSelectParameters) applicationContext.getBean(bean);
}
public String getPrincipalDn() {
return ((AttributeEditContext) context).getPrincipalDn();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/pages/DnAutocompleteBlock.java New file
0,0 → 1,92
/* *********************************************************
* This file is a part of InterLDAP.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* InterLDAP is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Groupe Linagora - http://linagora.com
********************************************************* */
 
package org.linid.dm.wui.t5lib.pages;
 
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.PropertyEditContext;
import org.linid.dm.wui.model.AttributeEditContext;
import org.linid.dm.wui.model.LdapSelectParameters;
import org.linid.dm.wui.t5lib.components.DnAutocompleter;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.ldap.userdetails.LdapUserDetails;
 
/**
* Create an autocomplete textfield from an LDAP request
*
* @author Raph
*/
public class DnAutocompleteBlock {
@Environmental
private PropertyEditContext context;
@InjectService("ApplicationContext")
private ApplicationContext applicationContext;
 
public PropertyEditContext getContext() {
return context;
}
 
@Component(parameters = {
"value=prop:context.propertyValue",
"label=prop:context.label",
"clientId=prop:context.propertyId",
"principalDn=prop:principalDn",
"typeConfigurationBean=prop:typeConfigurationBean" })
private DnAutocompleter dnAutocompleter;
public LdapSelectParameters getParameters() {
String bean = ((AttributeEditContext) context).getTypeConfigurationBean();
return (LdapSelectParameters) applicationContext.getBean(bean);
}
// Can get it from environment because context is not available within Ajax requests
public LdapName getPrincipalDn() throws InvalidNameException {
LdapUserDetails tapestryPrincipal = null;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
 
if (authentication != null) {
Object acegiPrincipal = authentication.getPrincipal();
if (acegiPrincipal != null && acegiPrincipal instanceof LdapUserDetails) {
tapestryPrincipal = (LdapUserDetails) acegiPrincipal;
return new LdapName(tapestryPrincipal.getDn());
}
}
return null;
}
public String getTypeConfigurationBean() {
return ((AttributeEditContext) context).getTypeConfigurationBean();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/WuiCommonModule.java New file
0,0 → 1,344
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
 
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.Translator;
import org.apache.tapestry5.Validator;
import org.apache.tapestry5.beaneditor.DataTypeConstants;
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.SubModule;
import org.apache.tapestry5.ioc.annotations.Value;
import org.apache.tapestry5.ioc.services.SymbolProvider;
import org.apache.tapestry5.services.BeanBlockContribution;
import org.apache.tapestry5.services.DisplayBlockContribution;
import org.apache.tapestry5.services.EditBlockContribution;
import org.apache.tapestry5.services.LibraryMapping;
import org.apache.tapestry5.services.PersistentLocale;
import org.apache.tapestry5.services.Request;
import org.linid.dm.eschema.ESchemaLdapOperator;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.wui.entrymapping.EntryBeanModule;
import org.linid.dm.wui.model.SearchCriterion;
import org.linid.dm.wui.t5lib.data.DropDownList;
import org.linid.dm.wui.t5lib.pages.SimplePropertyEditBlocks;
import org.linid.dm.wui.t5lib.services.AttributeValidatorAssignement;
import org.linid.dm.wui.t5lib.services.JpegFileFormatChecker;
import org.linid.dm.wui.t5lib.services.LdapEditorAnalyzer;
import org.linid.dm.wui.t5lib.services.LdapTypeAnalyzer;
import org.linid.dm.wui.t5lib.services.LdapViewerAnalyzer;
import org.linid.dm.wui.t5lib.services.LocaleService;
import org.linid.dm.wui.t5lib.services.PasswordPolicyService;
import org.linid.dm.wui.t5lib.services.PhotoStorageService;
import org.linid.dm.wui.t5lib.services.impl.BooleanTranslator;
import org.linid.dm.wui.t5lib.services.impl.DefaultAttributeValidatorAssignement;
import org.linid.dm.wui.t5lib.services.impl.DefaultLdapEditorAnalyzer;
import org.linid.dm.wui.t5lib.services.impl.DefaultLdapTypeAnalyzer;
import org.linid.dm.wui.t5lib.services.impl.DefaultLdapViewerAnalyzer;
import org.linid.dm.wui.t5lib.services.impl.DefaultLocaleService;
import org.linid.dm.wui.t5lib.services.impl.ESchemaLdapOperatorTranslator;
import org.linid.dm.wui.t5lib.services.impl.IByteStringTranslator;
import org.linid.dm.wui.t5lib.services.impl.JpegFileFormatCheckerImpl;
import org.linid.dm.wui.t5lib.services.impl.PasswordPolicyServiceOpenLDAP;
import org.linid.dm.wui.t5lib.services.impl.PhotoFileService;
import org.linid.dm.wui.t5lib.services.impl.PropertiesSymbolProvider;
import org.linid.dm.wui.validator.EqualsValidator;
import org.linid.dm.wui.validator.RequiredAttributeValidator;
import org.linid.dm.wui.validator.ValidatorDefinition;
import org.springframework.web.context.WebApplicationContext;
 
/**
* This module is automatically included as part of the Tapestry IoC Registry,
* it's a good place to configure and extend Tapestry, or to place your own
* services.
*/
@SubModule( {EntryBeanModule.class })
public class WuiCommonModule {
 
/**
* Contribute the common lib to Tapestry managed classes
*/
public static void contributeComponentClassResolver(Configuration<LibraryMapping> config) {
config.add(new LibraryMapping("wui-commons", "org.linid.dm.wui.t5lib"));
}
/**
* This is a contribution to the type of editor that
* can be used in bean editor or similar components.
* Here, we declare that the page SimplePropertyEditBlocks
* contribute editor blocks.
* @see SimplePropertyEditBlocks
*/
public static void contributeDefaultDataTypeAnalyzer(MappedConfiguration<Class<?>, String> configuration) {
configuration.add(DropDownList.class, "dropdown");
configuration.add(LdapName.class, "ldapname");
//we do not wan't do have a default association between Set and attributes. It is done programmaticaly
/*
* Another contribution just for the SearchCriterion property type
* @see SimplePropertyEditBlocks
*/
configuration.add(SearchCriterion.class, "searchcriterion");
}
 
/**
* contribute input "editor" for component that use them, such as "BeanFormEdit" or "Ldapentry.editForm"
* @param configuration
*/
public static void contributeBeanBlockSource(Configuration<BeanBlockContribution> configuration) {
configuration.add(new EditBlockContribution("dropdown", "wui-commons/SimplePropertyEditBlocks", "dropdown"));
 
/* special block for Ldap attribute selectable from a list */
configuration.add(new EditBlockContribution("attributeInList", "wui-commons/SimplePropertyEditBlocks", "attributeInList"));
configuration.add(new DisplayBlockContribution("attributes", "wui-commons/SimplePropertyDisplayBlocks", "attributes"));
//default display block
// configuration.add(new DisplayBlockContribution("text", "wui-commons/SimpleValueDisplayBlocks", "attributes"));
configuration.add(new DisplayBlockContribution("nonEditableText", "wui-commons/SimplePropertyEditBlocks", "nonEditableText"));
configuration.add(new EditBlockContribution("hidden", "wui-commons/SimplePropertyEditBlocks", "hidden"));
 
configuration.add(new EditBlockContribution("passwordverify", "wui-commons/edit/PasswordEditBlock", "passwordverify"));
configuration.add(new DisplayBlockContribution("passwordverify", "wui-commons/PasswordDisplayBlock", "passwordverify"));
configuration.add(new EditBlockContribution("codeValue", "wui-commons/edit/CodeValueEditBlock", "codeValue"));
configuration.add(new EditBlockContribution("dnSelector", "wui-commons/edit/DnSelectorEditBlock", "dn"));
configuration.add(new EditBlockContribution("dateTime", "wui-commons/edit/DateEditBlock", "dateTime"));
configuration.add(new EditBlockContribution("fileCompletion", "wui-commons/edit/FileEditBlock", "fileCompletion"));
configuration.add(new EditBlockContribution("multiline", "wui-commons/edit/TextEditBlock", "multiline"));
configuration.add(new DisplayBlockContribution("multiline", "wui-commons/TextDisplayBlock", "multiline"));
configuration.add(new EditBlockContribution("multilinetext", "wui-commons/edit/MultilineTextEditBlock", "multilinetext"));
configuration.add(new DisplayBlockContribution("multilinetext", "wui-commons/MultilineTextDisplayBlock", "multilinetext"));
 
configuration.add(new EditBlockContribution("persondn", "wui-commons/edit/AutocompleteDnEditBlock", "dnCompletion"));
configuration.add(new EditBlockContribution("ldapselect", "wui-commons/LdapSelectBlock", "ldapSelect"));
configuration.add(new DisplayBlockContribution("dndisplayer", "wui-commons/DnDisplayerBlock", "dnDisplayer"));
configuration.add(new DisplayBlockContribution("ldapvalue", "wui-commons/LdapValueDisplayerBlock", "ldapValueDisplayer"));
configuration.add(new DisplayBlockContribution("email", "wui-commons/EmailDisplayBlock", "email"));
configuration.add(new EditBlockContribution("email", "PropertyEditBlocks", DataTypeConstants.TEXT));
configuration.add(new DisplayBlockContribution("address", "wui-commons/AddressDisplayBlock", "address"));
configuration.add(new EditBlockContribution("address", "wui-commons/edit/AddressEditBlock", "address"));
configuration.add(new DisplayBlockContribution("url", "wui-commons/URLDisplayBlock", "url"));
configuration.add(new EditBlockContribution("url", "PropertyEditBlocks", DataTypeConstants.TEXT));
configuration.add(new DisplayBlockContribution("checkBoxes", "wui-commons/CheckBoxesDisplayBlock", "checkBoxes"));
configuration.add(new EditBlockContribution("checkBoxes", "wui-commons/edit/CheckBoxesEditBlock", "checkBoxes"));
configuration.add(new EditBlockContribution("dnAutocomplete", "wui-commons/DnAutocompleteBlock", "dnAutocomplete"));
configuration.add(new DisplayBlockContribution("dnAutocomplete", "wui-commons/DnDisplayerBlock", "dnDisplayer"));
 
/*
* Another contribution just for the SearchCriterion property type
*/
configuration.add(new EditBlockContribution("searchCriterion", "wui-commons/SearchCriterionEditBlock", "searchCriterion"));
}
@SuppressWarnings("rawtypes")
public static AttributeValidatorAssignement buildAttributeValidatorAssignement(Map<String,List> contributions) {
return new DefaultAttributeValidatorAssignement(contributions);
}
@SuppressWarnings("rawtypes")
public static void contributeFieldValidatorSource(MappedConfiguration<String, Validator>configuration){
configuration.add(EqualsValidator.NAME, new EqualsValidator());
configuration.add(RequiredAttributeValidator.NAME, new RequiredAttributeValidator());
}
 
 
public static LdapEditorAnalyzer buildLdapEditorAnalyzer(Map<String,String> contributions) {
return new DefaultLdapEditorAnalyzer(contributions);
}
public static LdapViewerAnalyzer buildLdapViewerAnalyzer(Map<String,String> contributions) {
return new DefaultLdapViewerAnalyzer(contributions);
}
/**
* configure matching betwin LDAP type and input editor.
*
* <b>CONVENTION</b> : an LDAP type is the concatenation of attribute "Type"
* defined in enhanced schema and "_fromlist" if isChosenInList == true
* in enhanced attribute's schema
* @param configuration
*/
public static void contributeLdapEditorAnalyzer(MappedConfiguration<String, String> configuration) {
configuration.add("string_fromlist", "attributeInList");
configuration.add("file", "fileCompletion");
configuration.add("codevalue_fromlist", "codeValue");
configuration.add("dn", "dnSelector");
configuration.add("boolean", "checkbox");
configuration.add("dateTime", "dateTime");
configuration.add("multiline", "multiline");
configuration.add("multilinetext", "multilinetext");
configuration.add("passwordverify", "passwordverify");
configuration.add("email", "email");
configuration.add("address", "address");
configuration.add("url", "url");
configuration.add("hidden", "hidden");
/* exemple of using a the default text block for non configurated LDAP "date" type */
//configuration.add("date", "text");
configuration.add("persondn", "persondn");
configuration.add("ldapselect","ldapselect");
configuration.add("ldapvalueselect","ldapselect");
configuration.add("checkBoxes_fromlist","checkBoxes");
configuration.add("dnAutocomplete","dnAutocomplete");
}
public static void contributeLdapViewerAnalyzer(MappedConfiguration<String, String> configuration) {
configuration.add("ldapselect","dndisplayer");
configuration.add("ldapvalueselect","ldapvalue");
configuration.add("multiline", "multiline");
configuration.add("multilinetext", "multilinetext");
configuration.add("passwordverify", "passwordverify");
configuration.add("email", "email");
configuration.add("address", "address");
configuration.add("url", "url");
configuration.add("checkBoxes_fromlist","checkBoxes");
configuration.add("dnAutocomplete","dndisplayer");
}
 
@SuppressWarnings("rawtypes")
public static LdapTypeAnalyzer buildLdapTypeAnalyzer(Map<String,Class> contributions) {
return new DefaultLdapTypeAnalyzer(contributions);
}
/**
* configure matching betwin LDAP type and input editor.
*
* <b>CONVENTION</b> : an LDAP type is the concatenation of attribute "Type"
* defined in enhanced schema and "_fromlist" if isChosenInList == true
* in enhanced attribute's schema
* @param configuration
*/
public static void contributeLdapTypeAnalyzer(MappedConfiguration<String, Class<?>> configuration) {
configuration.add("hidden", String.class);
configuration.add("string", String.class);
configuration.add("boolean", Boolean.class);
configuration.add("passwordverify", String.class);
configuration.add("file", String.class);
configuration.add("codevalue", String.class);
configuration.add("datetime", String.class);
configuration.add("dn", String.class);
configuration.add("multiline", String.class);
configuration.add("multilinetext", String.class);
/* exemple of using a the default text block for non configurated LDAP "date" type */
// configuration.add("date", Date.class);
configuration.add("persondn", String.class);
configuration.add("ldapselect",String.class);
configuration.add("ldapvalueselect",String.class);
configuration.add("email",String.class);
configuration.add("address",String.class);
configuration.add("url",String.class);
configuration.add("checkBoxes", String.class);
configuration.add("dnAutocomplete", String.class);
}
 
/**
* Exemple of a validator for "date" attribute.
* We want that "date" match the regexp "YYYY-MM-DD"
*/
public static void contributeAttributeValidatorAssignement(MappedConfiguration<String,List<ValidatorDefinition>> configuration) {
List<ValidatorDefinition> dateValidators = new ArrayList<ValidatorDefinition>();
dateValidators.add(new ValidatorDefinition("regexp","\\d{4}-\\d{2}-\\d{2}"));
//well, say we want that date fields are not empty
// dateValidators.add(new ValidatorDefinition("minlength","10"));
// dateValidators.add(new ValidatorDefinition("maxlength","10"));
dateValidators.add(new ValidatorDefinition("required",null));
configuration.add("date", dateValidators);
}
// public static void contributeValidationMessagesSource(OrderedConfiguration<String> configuration) {
// configuration.add("wuicommon", "org/linid/dm/wui/t5lib/components/eschema/EditAttribute");
// }
public static void contributeComponentMessagesSource(OrderedConfiguration<Resource> configuration,
@Value("org/linid/dm/wui/t5lib/components/eschema/EditAttribute") Resource catalog) {
configuration.add("wuicommon", catalog);
}
/* ***********************
* Translate IByteString
*********************** */
// public static void contributeTranslatorSource (Configuration<Translator<?>> configuration) {
// configuration.add(new BooleanTranslator());
// configuration.add(new IByteStringTranslator());
// configuration.add(new ESchemaLdapOperatorTranslator());
// }
public static void contributeTranslatorSource(MappedConfiguration<Class<?>, Translator<?>> configuration)
{
configuration.add(Boolean.class, new BooleanTranslator());
configuration.add(IByteString.class, new IByteStringTranslator());
configuration.add(ESchemaLdapOperator.class, new ESchemaLdapOperatorTranslator());
}
// /* ****************************
// * Properties symbol provider *
// **************************** */
public static PropertiesSymbolProvider buildPropertiesSymbolProvider(
@InjectService("ApplicationContext") WebApplicationContext context,
Collection<String> configuration) {
return new PropertiesSymbolProvider(context, configuration);
}
public void contributePropertiesSymbolProvider(Configuration<String> configuration) {
configuration.add("classpath:configuration.properties");
}
public static void contributeSymbolSource(OrderedConfiguration<SymbolProvider> providers,
@InjectService("PropertiesSymbolProvider") PropertiesSymbolProvider propertiesSymbolProvider){
providers.add("properties", propertiesSymbolProvider);
}
public static LocaleService buildLocaleService(@InjectService("PersistentLocale") PersistentLocale persistentLocale,
@InjectService("Request") Request request) {
return new DefaultLocaleService(persistentLocale, request);
}
public static PhotoStorageService buildPhotoStorageService(@Value("${photo.user.dir}") String photoDirectory) {
return new PhotoFileService(photoDirectory);
}
public static void bind(ServiceBinder binder) {
binder.bind(JpegFileFormatChecker.class, JpegFileFormatCheckerImpl.class);
binder.bind(PasswordPolicyService.class, PasswordPolicyServiceOpenLDAP.class);
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/PhotoStorageService.java New file
0,0 → 1,38
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services;
 
import java.io.InputStream;
 
import org.apache.tapestry5.upload.services.UploadedFile;
 
public interface PhotoStorageService {
void store(String uid, UploadedFile file);
void delete(String uid);
void rename(String oldUid, String newUid);
InputStream get(String uid);
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/DropDownOptionProvider.java New file
0,0 → 1,35
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services;
 
/**
* This interface is a wrapper to List<String>
* so that a
* @author LINAGORA
*
*/
public interface DropDownOptionProvider {
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/LocaleService.java New file
0,0 → 1,37
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services;
 
import java.util.Locale;
 
/**
* This service is intended to easily get the locale used
* by the current user
*
*/
public interface LocaleService {
 
Locale getLocale();
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/LdapFriendlyUrlEncoder.java New file
0,0 → 1,154
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.BitSet;
 
import org.apache.tapestry5.services.URLEncoder;
 
/**
* This class is a copy/past of {@code URLEncoderImpl}
* that also consider '=' and ',' as safe characters.
* This way, it allows clean URL for most of the common
* LDAP dn.
* Note that spaces are not allowed in the URL,
* and DN have to be written without any of them.
*/
public class LdapFriendlyUrlEncoder implements URLEncoder {
 
static final String ENCODED_NULL = "$N";
static final String ENCODED_BLANK = "$B";
 
/**
* Bit set indicating which character are safe to pass through (when encoding or decoding) as-is. All other
* characters are encoded as a kind of unicode escape.
*/
private final BitSet safe = new BitSet(128);
 
public LdapFriendlyUrlEncoder()
{
markSafe("abcdefghijklmnopqrstuvwxyz");
markSafe("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
markSafe("01234567890-_.:");
/*
* The only modification from the original
* code
*/
markSafe("=,");
}
 
private void markSafe(String s)
{
for (char ch : s.toCharArray())
{
safe.set((int) ch);
}
}
 
 
public String encode(String input)
{
if (input == null) return ENCODED_NULL;
 
if (input.equals("")) return ENCODED_BLANK;
 
boolean dirty = false;
 
int length = input.length();
 
StringBuilder output = new StringBuilder(length * 2);
 
for (int i = 0; i < length; i++)
{
char ch = input.charAt(i);
 
if (ch == '$')
{
output.append("$$");
dirty = true;
continue;
}
 
int chAsInt = (int) ch;
 
if (safe.get(chAsInt))
{
output.append(ch);
continue;
}
 
output.append(String.format("$%04x", chAsInt));
dirty = true;
}
 
return dirty ? output.toString() : input;
}
 
public String decode(String input)
{
//Defense.notNull(input, "input");
assert input!= null;
if (input.equals(ENCODED_NULL)) return null;
 
if (input.equals(ENCODED_BLANK)) return "";
 
boolean dirty = false;
 
int length = input.length();
 
StringBuilder output = new StringBuilder(length * 2);
 
for (int i = 0; i < length; i++)
{
char ch = input.charAt(i);
 
if (ch == '$')
{
dirty = true;
 
if (i + 1 < length && input.charAt(i + 1) == '$')
{
output.append('$');
i++;
 
dirty = true;
continue;
}
 
if (i + 4 < length)
{
String hex = input.substring(i + 1, i + 5);
 
try
{
int unicode = Integer.parseInt(hex, 16);
 
output.append((char) unicode);
i += 4;
dirty = true;
continue;
}
catch (NumberFormatException ex)
{
// Ignore.
}
}
 
throw new IllegalArgumentException(String.format(
"Input string '%s' is not valid; the '$' character at position %d should be followed by another '$' or a four digit hex number (a unicode value).",
input, i + 1));
}
 
if (!safe.get((int) ch))
{
throw new IllegalArgumentException(
String.format("Input string '%s' is not valid; the character '%s' at position %d is not valid.",
input, ch, i + 1));
}
 
output.append(ch);
}
 
return dirty ? output.toString() : input;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/DefaultLdapEditorAnalyzer.java New file
0,0 → 1,68
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.Map;
 
import org.linid.dm.wui.t5lib.services.LdapEditorAnalyzer;
 
/**
* The default data type analyzer, which is based entirely on the type of the
* property (and not on annotations or naming conventions). This is based on a
* configuration of property type class to string provided as an IoC service
* configuration.
*/
public class DefaultLdapEditorAnalyzer implements LdapEditorAnalyzer {
private final Map<String,String> registry;
 
public DefaultLdapEditorAnalyzer(Map<String, String> configuration) {
registry =configuration;
}
 
public String identifyLdapEditor(String ldapType) {
String dataType = registry.get(ldapType);
// if (dataType.equals(""))
// return null;
return dataType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("DefaultLdapTypeAnalyzer:");
if(null == this.registry) {
sb.append("[null]");
} else {
if(this.registry.size() > 0) {
for(String s: this.registry.keySet()) {
sb.append("[" ).append(s).append(":").append(this.registry.get(s)).append("]\n");
}
} else {
sb.append("[no mapping]");
}
}
return sb.toString();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/JpegFileFormatCheckerImpl.java New file
0,0 → 1,60
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.jpeg.JpegParser;
import org.apache.tika.sax.BodyContentHandler;
import org.linid.dm.wui.t5lib.services.JpegFileFormatChecker;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
 
public class JpegFileFormatCheckerImpl implements JpegFileFormatChecker {
private JpegParser parser;
 
public JpegFileFormatCheckerImpl() {
parser = new JpegParser();
}
 
@Override
public boolean check(InputStream stream) throws IOException {
try {
Metadata metadata = new Metadata();
ContentHandler handler = new BodyContentHandler();
parser.parse(stream, handler, metadata, null);
} catch (SAXException e) {
return false;
} catch (TikaException e) {
return false;
}
return true;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/PhotoFileService.java New file
0,0 → 1,99
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.commons.io.IOUtils;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.linid.dm.wui.t5lib.services.PhotoStorageService;
 
public class PhotoFileService implements PhotoStorageService {
 
public final static String PHOTO_EXT = ".jpg";
private String photoDirectory;
 
public PhotoFileService(String photoDirectory) {
this.photoDirectory = photoDirectory;
}
 
@Override
public void store(String uid, UploadedFile file) {
File copied = new File(photoDirectory, uid + PHOTO_EXT);
file.write(copied);
}
 
@Override
public void delete(String uid) {
File image = new File(photoDirectory, uid + PHOTO_EXT);
if (image.exists()) {
image.delete();
}
}
 
@Override
public void rename(String oldUid, String newUid) {
File oldFile = new File(photoDirectory, oldUid + PHOTO_EXT);
if (!oldFile.exists()) {
return;
}
File newFile = new File(photoDirectory, newUid + PHOTO_EXT);
// If destination file already exists, overwrite it
oldFile.renameTo(newFile);
}
@Override
public InputStream get(String uid) {
File f = new File(photoDirectory, uid + PHOTO_EXT);
InputStream openStream;
byte[] imageBytes;
try {
openStream = new FileInputStream(f);
} catch (FileNotFoundException e) {
return null;
}
try {
imageBytes = IOUtils.toByteArray(openStream);
openStream.close();
} catch (IOException e) {
return null;
}
 
ByteArrayInputStream stream = new ByteArrayInputStream(imageBytes);
return stream;
}
 
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/DefaultAttributeValidatorAssignement.java New file
0,0 → 1,48
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.List;
import java.util.Map;
 
import org.linid.dm.wui.t5lib.services.AttributeValidatorAssignement;
import org.linid.dm.wui.validator.ValidatorDefinition;
 
public class DefaultAttributeValidatorAssignement implements AttributeValidatorAssignement {
 
@SuppressWarnings("rawtypes")
private Map<String, List> definitions;
@SuppressWarnings("rawtypes")
public DefaultAttributeValidatorAssignement(Map<String, List> definitions) {
this.definitions = definitions;
}
 
@SuppressWarnings("unchecked")
public List<ValidatorDefinition> getValidatorDefinitions(String attributeId) {
return definitions.get(attributeId);
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/DefaultLdapViewerAnalyzer.java New file
0,0 → 1,68
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.Map;
 
import org.linid.dm.wui.t5lib.services.LdapViewerAnalyzer;
 
/**
* The default data type analyzer, which is based entirely on the type of the
* property (and not on annotations or naming conventions). This is based on a
* configuration of property type class to string provided as an IoC service
* configuration.
*/
public class DefaultLdapViewerAnalyzer implements LdapViewerAnalyzer {
private final Map<String,String> registry;
 
public DefaultLdapViewerAnalyzer(Map<String, String> configuration) {
registry =configuration;
}
 
public String identifyLdapViewer(String ldapType) {
String dataType = registry.get(ldapType);
// if (dataType.equals(""))
// return null;
return dataType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("DefaultLdapTypeViewer:");
if(null == this.registry) {
sb.append("[null]");
} else {
if(this.registry.size() > 0) {
for(String s: this.registry.keySet()) {
sb.append("[" ).append(s).append(":").append(this.registry.get(s)).append("]\n");
}
} else {
sb.append("[no mapping]");
}
}
return sb.toString();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/IByteStringTranslator.java New file
0,0 → 1,61
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.internal.translator.AbstractTranslator;
import org.apache.tapestry5.services.FormSupport;
import org.linid.dm.ldap.objects.IByteString;
import org.linid.dm.ldap.objects.impl.ByteString;
 
public class IByteStringTranslator extends AbstractTranslator<IByteString> {
 
public IByteStringTranslator() {
super("ibytestring",IByteString.class,"iByteString-translator");
}
 
public String toClient(IByteString value) {
String s = null;
if(null == value || null == (s = value.stringValue())) {
return null;
} else {
return s;
}
}
 
public IByteString parseClient(Field field, String clientValue, String message) throws ValidationException {
if(null == clientValue) {
return null;
}
return new ByteString(clientValue);
}
 
public void render(Field field, String message, MarkupWriter writer, FormSupport formSupport) {
//TODO 5.0.18 ??
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/IELdapEntryValueEncoder.java New file
0,0 → 1,78
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.wui.t5lib.services.impl;
 
import javax.naming.InvalidNameException;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tapestry5.ValueEncoder;
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.objects.impl.ELdapEntry;
 
/**
* A value encode for LDAP entry objects
*
* We use the default toString method for toClient
* We create the reverse method for toValue
*
* Note: another idea for implementation would be to
* use only the DN and get entry from repository in toValue
* @author Clément OUDOT
*
*/
 
public class IELdapEntryValueEncoder implements ValueEncoder<IELdapEntry> {
private static final Log logger = LogFactory.getLog(IELdapEntryValueEncoder.class);
 
public String toClient(IELdapEntry value) {
 
// Call the toString() method of IELdapEntry
return value.toString();
}
 
public IELdapEntry toValue(String clientValue) {
 
IELdapEntry entry = null;
 
// Get the DN
String dn = clientValue.substring(clientValue.indexOf("dn: ")+4, clientValue.indexOf("\n", clientValue.indexOf("dn: ")));
 
// Create entry object
try {
entry = new ELdapEntry(dn);
} catch (InvalidNameException e) {
logger.error(e.getMessage(), e);
return entry;
}
 
// Get attributes
// TODO
 
return entry;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/DefaultLocaleService.java New file
0,0 → 1,54
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.Locale;
 
import org.apache.tapestry5.internal.util.LocaleUtils;
import org.apache.tapestry5.services.PersistentLocale;
import org.apache.tapestry5.services.Request;
import org.linid.dm.wui.t5lib.services.LocaleService;
 
public class DefaultLocaleService implements LocaleService {
 
private PersistentLocale persistentLocale;
private Request request;
public DefaultLocaleService(PersistentLocale persistentLocale, Request request) {
this.persistentLocale = persistentLocale;
this.request = request;
}
 
public Locale getLocale() {
Locale result = persistentLocale.get();
if (result == null) {
return LocaleUtils.toLocale(request.getLocale().getLanguage());
} else {
return result;
}
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/PasswordPolicyServiceOpenLDAP.java New file
0,0 → 1,78
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
 
package org.linid.dm.wui.t5lib.services.impl;
 
import javax.naming.InvalidNameException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapName;
 
import org.apache.tapestry5.annotations.Service;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.linid.dm.ldap.core.LdapFacade;
import org.linid.dm.wui.t5lib.services.PasswordPolicyService;
 
public class PasswordPolicyServiceOpenLDAP implements PasswordPolicyService {
 
public static final String LOCK_ATTRIBUTE_NAME = "pwdAccountLockedTime";
public static final String LOCK_VALUE = "00000101000000Z";
@Inject @Service("wuiLdapFacade")
private LdapFacade wuiLdapFacade;
public void lockAccount(String entryDn) {
LdapName entryDnName;
try {
entryDnName = new LdapName(entryDn);
} catch (InvalidNameException e) {
return;
}
Attributes attributes = new BasicAttributes(LOCK_ATTRIBUTE_NAME, LOCK_VALUE);
wuiLdapFacade.modifyAttributes(entryDnName, DirContext.REPLACE_ATTRIBUTE, attributes);
}
public void unlockAccount(String entryDn) {
LdapName entryDnName;
try {
entryDnName = new LdapName(entryDn);
} catch (InvalidNameException e) {
return;
}
Attributes attributes = new BasicAttributes(LOCK_ATTRIBUTE_NAME, null);
wuiLdapFacade.modifyAttributes(entryDnName, DirContext.REPLACE_ATTRIBUTE, attributes);
}
public String getLockAttributeName() {
return LOCK_ATTRIBUTE_NAME;
}
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/LdapTreeNodeService.java New file
0,0 → 1,65
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
**********************************************************/
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.List;
 
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
 
import org.linid.dm.ldap.objects.IELdapEntry;
import org.linid.dm.ldap.repository.LdapEntryRepository;
import org.linid.dm.wui.t5lib.beans.TreeNode;
import org.linid.dm.wui.t5lib.services.TreeNodeService;
 
/**
* This class is managing the directory Tree
* !!! But take care, that the whole tree is build in memory !!!
*/
public class LdapTreeNodeService implements TreeNodeService<IELdapEntry> {
 
private final LdapEntryRepository entryRepository;
public LdapTreeNodeService(LdapEntryRepository entryRepository) {
this.entryRepository = entryRepository;
}
public TreeNode<IELdapEntry> updateChildren(String actorId, TreeNode<IELdapEntry> node) {
try {
List<IELdapEntry> entries = entryRepository.getDirectChildren(new LdapName(actorId),
new LdapName(node.getUserObject().getId()));
for (IELdapEntry ldapEntry : entries) {
if(ldapEntry != null) {
node.add(updateChildren(actorId, new TreeNode<IELdapEntry>(ldapEntry)));
}
}
} catch (InvalidNameException e) {
//Does nothing
}
return node;
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/TreeExpansionServiceImpl.java New file
0,0 → 1,64
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.tapestry5.ioc.Messages;
import org.linid.dm.wui.model.tree.TreeExpansionView;
import org.linid.dm.wui.t5lib.services.TreeExpansionService;
 
public class TreeExpansionServiceImpl implements TreeExpansionService{
 
private Map<Integer,TreeExpansionView> allconfig = null;
/*
* key to search in the bundle (label for the select)
*/
private String messagekeylabel = null;
/**
* constructor spring
* @param allDnToExpand
* @param messagekeylabel
*/
public TreeExpansionServiceImpl(String[] allDnToExpand, String messagekeylabel) {
this.messagekeylabel = messagekeylabel;
init(allDnToExpand);
}
private void init(String[] treeExpand) {
if(allconfig==null){
allconfig = new HashMap<Integer,TreeExpansionView>();
 
int i = 1;
for (String config : treeExpand) {
allconfig.put(i,new TreeExpansionView(config.split(";"),messagekeylabel+"."+i,i));
i++;
}
}
}
@Override
public ArrayList<TreeExpansionView> getTreeExpansionValues() {
return new ArrayList<TreeExpansionView>(allconfig.values());
}
@Override
public ArrayList<TreeExpansionView> getTreeExpansionValues(Messages messages) {
ArrayList<TreeExpansionView> ar = new ArrayList<TreeExpansionView>(allconfig.values());
for (TreeExpansionView treeExpansionView : ar) {
treeExpansionView.setLabel(messages.get(treeExpansionView.getLabelKey()));
}
return ar;
}
@Override
public TreeExpansionView findById(int id) {
return allconfig.get(id);
}
 
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/BooleanTranslator.java New file
0,0 → 1,60
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.internal.translator.AbstractTranslator;
import org.apache.tapestry5.services.FormSupport;
 
public class BooleanTranslator extends AbstractTranslator<Boolean> {
 
public BooleanTranslator() {
super("boolean",Boolean.class,"boolean-translator");
}
public Boolean parseClient(Field field, String clientValue, String message) throws ValidationException {
if(null == clientValue) {
return null;
}
return Boolean.parseBoolean(clientValue);
}
 
public String toClient(Boolean value) {
if(null == value ) {
return null;
} else {
return value.toString();
}
}
 
public void render(Field field, String message, MarkupWriter writer,
FormSupport formSupport) {
// TODO 5.0.18 ???
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/ESchemaLdapOperatorTranslator.java New file
0,0 → 1,53
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.internal.translator.AbstractTranslator;
import org.apache.tapestry5.services.FormSupport;
import org.linid.dm.eschema.ESchemaLdapOperator;
 
public class ESchemaLdapOperatorTranslator extends AbstractTranslator<ESchemaLdapOperator> {
 
public ESchemaLdapOperatorTranslator() {
super("eschemaldapoperator", ESchemaLdapOperator.class, "eSchemaLdapOperator-translator");
}
public String toClient(ESchemaLdapOperator value) {
return value.name();
}
 
public ESchemaLdapOperator parseClient(Field field, String clientValue, String message) throws ValidationException {
return ESchemaLdapOperator.valueOf(clientValue);
}
 
public void render(Field field, String message, MarkupWriter writer,
FormSupport formSupport) {
//TODO 5.0.18
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/DefaultLdapTypeAnalyzer.java New file
0,0 → 1,72
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect
* the term of the license.
*
* NOTICE : THIS LICENSE IS FREE OF CHARGE AND THE SOFTWARE
* IS DISTRIBUTED WITHOUT ANY WARRANTIES OF ANY KIND
*
* ==LICENSE NOTICE==
*
* (c) 2008-2013 Linagora - http://linagora.com/
********************************************************* */
package org.linid.dm.wui.t5lib.services.impl;
 
import java.util.Map;
 
import org.linid.dm.wui.t5lib.services.LdapTypeAnalyzer;
 
/**
* The default data type analyzer, which is based entirely on the type of the
* property (and not on annotations or naming conventions). This is based on a
* configuration of property type class to string provided as an IoC service
* configuration.
*/
public class DefaultLdapTypeAnalyzer implements LdapTypeAnalyzer {
 
@SuppressWarnings("rawtypes")
private final Map<String,Class> registry;
 
@SuppressWarnings("rawtypes")
public DefaultLdapTypeAnalyzer(Map<String, Class> configuration) {
registry =configuration;
}
 
@SuppressWarnings("rawtypes")
public Class identifyLdapType(String ldapType) {
Class dataType = registry.get(ldapType);
// if (dataType.equals(""))
// return null;
return dataType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("DefaultLdapTypeAnalyzer:");
if(null == this.registry) {
sb.append("[null]");
} else {
if(this.registry.size() > 0) {
for(String s: this.registry.keySet()) {
sb.append("[" ).append(s).append(":").append(this.registry.get(s)).append("]\n");
}
} else {
sb.append("[no mapping]");
}
}
return sb.toString();
}
 
}
/branches/Tapestry-5.4-beta/src/main/java/org/linid/dm/wui/t5lib/services/impl/PropertiesSymbolProvider.java New file
0,0 → 1,65
/* *********************************************************
* This file is a part of LinID Directory Manager.
* This software is a computer program whose purpose is
* to manage electronic identity thanks to LDAP directories.
*
* ==LICENSE NOTICE==
* LinID Directory Manager is a free software subjected to the
* ** GNU Affero Public License ** as published by the
* Free Software Foundation, ** version 3 ** of the license.
*
* By application to section 7 in the GNU Affero GPLv3,
* dynamic and static links do not extend license to other
* softwares.
*
* You can redistribute and/or modify since you respect