repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServerType.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServerType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
public enum LdapServerType
{
ApacheDS,
OpenLdap,
Fedora389ds,
;
public TestLdapServer getLdapServer()
{
switch ( this )
{
case ApacheDS:
return ApacheDirectoryServer.getInstance();
case OpenLdap:
return OpenLdapServer.getInstance();
case Fedora389ds:
return Fedora389dsLdapServer.getInstance();
default:
throw new IllegalArgumentException( "Unknown LDAP server type " + this );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/SkipTestIfLdapServerIsNotAvailableInterceptor.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/SkipTestIfLdapServerIsNotAvailableInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
public class SkipTestIfLdapServerIsNotAvailableInterceptor implements InvocationInterceptor
{
@Override
public void interceptTestTemplateMethod( Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext ) throws Throwable
{
invocationContext.getArguments().stream()
.filter( TestLdapServer.class::isInstance )
.map( TestLdapServer.class::cast )
.forEach( server -> {
if ( !server.isAvailable() )
{
invocation.skip();
Assumptions.assumeTrue( false,
"Skip test because server " + server.getType() + " is not available" );
}
} );
invocation.proceed();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServersArgumentsProvider.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServersArgumentsProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
public class LdapServersArgumentsProvider implements ArgumentsProvider
{
@Override
public Stream<Arguments> provideArguments( ExtensionContext context ) throws Exception
{
// Determine possible server types by checking only/except annotation attributes
LdapServersSource annotation = context.getTestMethod().get().getAnnotation( LdapServersSource.class );
List<LdapServerType> types = new ArrayList<>();
types.addAll( Arrays.asList( annotation.only() ) );
if ( types.isEmpty() )
{
types.addAll( Arrays.asList( LdapServerType.values() ) );
}
types.removeAll( Arrays.asList( annotation.except() ) );
// Filter available server types
List<LdapServerType> available = types.stream().filter( type -> type.getLdapServer().isAvailable() )
.collect( Collectors.toList() );
if ( !available.isEmpty() )
{
// Pick a random one
if ( annotation.mode() == Mode.One )
{
available = Collections.singletonList( available.get( new Random().nextInt( available.size() ) ) );
}
// Prepare the available servers
for ( LdapServerType type : available )
{
try
{
type.getLdapServer().prepare();
}
catch ( Exception e )
{
throw new RuntimeException( "Prepare failed for LDAP server type " + type, e );
}
}
// Return the available/picked servers
return available.stream().map( LdapServerType::getLdapServer ).map( Arguments::of );
}
else
{
// Return all types even if not available, will be skipped in SkipTestIfLdapServerIsNotAvailableInterceptor
return types.stream().map( LdapServerType::getLdapServer ).map( Arguments::of );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/TestFixture.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/TestFixture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.api.ldap.model.message.AliasDerefMode;
import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.model.message.DeleteRequest;
import org.apache.directory.api.ldap.model.message.DeleteRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.api.ldap.model.schema.comparators.DnComparator;
import org.apache.directory.ldap.client.api.EntryCursorImpl;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.studio.connection.core.Controls;
import org.junit.jupiter.api.Assumptions;
/**
* A unified test fixture that defines the DIT structure for all tests and for all test LDAP servers.
*/
public class TestFixture
{
public static Dn dn( String dn )
{
try
{
return new Dn( dn );
}
catch ( LdapInvalidDnException e )
{
throw new RuntimeException( e );
}
}
public static Dn dn( Rdn rdn, Dn dn )
{
try
{
return dn.add( rdn );
}
catch ( LdapInvalidDnException e )
{
throw new RuntimeException( e );
}
}
public static Dn dn( String rdn, Dn dn )
{
try
{
return dn.add( rdn );
}
catch ( LdapInvalidDnException e )
{
throw new RuntimeException( e );
}
}
public static final String KRB5_REALM = "EXAMPLE>COM";
public static final String KDC_HOST = "kerby.example.com";
public static final int KDC_PORT = 60088;
public static void skipIfKdcServerIsNotAvailable()
{
boolean available = false;
try(Socket s = new Socket(KDC_HOST, KDC_PORT))
{
available = true;
}
catch ( Exception e )
{
available = false;
}
if ( !available )
{
Assumptions.assumeTrue( false,
"Skip test because KDC server " + KDC_HOST + " is not available" );
}
}
public static final String OBJECT_CLASS_ALL_FILTER = "(objectClass=*)";
public static final String TEST_FIXTURE_LDIF = "TestFixture.ldif";
public static final Dn CONTEXT_DN = dn( "dc=example,dc=org" );
public static final Dn MISC_DN = dn( "ou=misc", CONTEXT_DN );
public static final Dn MISC1_DN = dn( "ou=misc.1", MISC_DN );
public static final Dn MISC11_DN = dn( "ou=misc.1.1", MISC1_DN );
public static final Dn MISC111_DN = dn( "ou=misc.1.1.1", MISC11_DN );
public static final Dn BJENSEN_DN = dn( "cn=Barbara Jensen", MISC_DN );
public static final Dn HNELSON_DN = dn( "uid=hnelson", MISC_DN );
public static final Dn GERMAN_UMLAUT_DN = dn( "cn=Wolfgang K\u00f6lbel", MISC_DN );
public static final Dn MULTI_VALUED_RDN_DN = dn( "cn=Barbara Jensen+uid=bjensen", MISC_DN );
public static final Dn DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED = dn( "cn=\\#123456", MISC_DN );
public static final Dn DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED = dn( "cn=\\23123456", MISC_DN );
public static final Dn DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED = dn( "cn=\\\"\\+\\,\\;\\<\\>\\\\", MISC_DN );
public static final Dn DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED = dn( "cn=\\22\\2B\\2C\\3B\\3C\\3E\\5C",
MISC_DN );
public static final Dn DN_WITH_TRAILING_EQUALS_CHARACTER = dn( "cn=trailing=", MISC_DN );
public static final Dn DN_WITH_TRAILING_EQUALS_CHARACTER_HEX_PAIR_ESCAPED = dn( "cn=trailing\\3D", MISC_DN );
public static final Dn DN_WITH_IP_HOST_NUMBER = dn( "cn=loopback+ipHostNumber=127.0.0.1", MISC_DN );
public static final Dn ALIAS_DN = dn( "cn=alias", MISC_DN );
public static final Dn SUBENTRY_DN = dn( "cn=subentry", MISC_DN );
public static final Dn USERS_DN = dn( "ou=users", CONTEXT_DN );
public static final Dn USER1_DN = dn( "uid=user.1", USERS_DN );
public static final Dn USER2_DN = dn( "uid=user.2", USERS_DN );
public static final Dn USER3_DN = dn( "uid=user.3", USERS_DN );
public static final Dn USER4_DN = dn( "uid=user.4", USERS_DN );
public static final Dn USER5_DN = dn( "uid=user.5", USERS_DN );
public static final Dn USER8_DN = dn( "uid=user.8", USERS_DN );
public static final Dn GROUPS_DN = dn( "ou=groups", CONTEXT_DN );
public static final Dn GROUP1_DN = dn( "cn=group.1", GROUPS_DN );
public static final Dn TARGET_DN = dn( "ou=target", CONTEXT_DN );
public static final Dn REFERRALS_DN = dn( "ou=referrals", CONTEXT_DN );
public static final Dn REFERRAL_TO_USERS_DN = dn( "cn=referral-to-users", REFERRALS_DN );
public static final Dn REFERRAL_TO_USER1_DN = dn( "cn=referral-to-user.1", REFERRALS_DN );
public static final Dn REFERRAL_TO_REFERRAL_TO_USERS_DN = dn( "cn=referral-to-referral-to-users", REFERRALS_DN );
public static final Dn REFERRAL_TO_REFERRALS_DN = dn( "cn=referral-to-referrals", REFERRALS_DN );
public static final Dn REFERRAL_LOOP_1_DN = dn( "cn=referral-loop-1", REFERRALS_DN );
public static final Dn REFERRAL_LOOP_2_DN = dn( "cn=referral-loop-2", REFERRALS_DN );
public static final Dn REFERRAL_TO_MISC_DN = dn( "cn=referral-to-misc", REFERRALS_DN );
/**
* Creates the context entry "dc=example,dc=org" if it doesn't exist yet.
*/
public static void createContextEntry( TestLdapServer ldapServer )
{
ldapServer.withAdminConnection( connection -> {
if ( !connection.exists( CONTEXT_DN ) )
{
connection.add(
new DefaultEntry( CONTEXT_DN, "objectClass", "top", "objectClass", "domain", "dc", "example" ) );
}
} );
}
public static void importData( TestLdapServer ldapServer )
{
ldapServer.withAdminConnection( connection -> {
try ( LdifReader ldifReader = new LdifReader( TestFixture.class.getResourceAsStream( TEST_FIXTURE_LDIF ) ) )
{
ldifReader.setSchemaManager( connection.getSchemaManager() );
for ( LdifEntry entry : ldifReader )
{
replaceRefLdapUrl( ldapServer, entry );
connection.add( entry.getEntry() );
}
}
} );
}
private static void replaceRefLdapUrl( TestLdapServer ldapServer, LdifEntry entry )
throws LdapInvalidAttributeValueException
{
Attribute ref = entry.get( "ref" );
if ( ref != null )
{
String oldRefLdapUrl = ref.getString();
String newRefLdapUrl = oldRefLdapUrl.replace( "replace-with-host-port",
ldapServer.getHost() + ":" + ldapServer.getPort() );
ref.remove( oldRefLdapUrl );
ref.add( newRefLdapUrl );
}
}
/**
* Cleans all test data.
*/
public static void cleanup( TestLdapServer ldapServer )
{
ldapServer.withAdminConnection( connection -> {
// skip cleanup if context entry doesn't exist yet
if ( !connection.exists( CONTEXT_DN ) )
{
return;
}
// delete ou=referrals
deleteTree( connection, REFERRALS_DN, Optional.empty() );
// delete ou=groups
deleteTree( connection, GROUPS_DN, Optional.empty() );
// delete ou=users
deleteTree( connection, USERS_DN, Optional.empty() );
// delete ou=misc
deleteTree( connection, MISC_DN, Optional.of( Controls.SUBENTRIES_CONTROL ) );
deleteTree( connection, MISC_DN, Optional.empty() );
// delete ou=target
deleteTree( connection, TARGET_DN, Optional.of( Controls.SUBENTRIES_CONTROL ) );
deleteTree( connection, TARGET_DN, Optional.empty() );
} );
}
private static void deleteTree( LdapConnection connection, Dn baseDn, Optional<Control> control )
throws Exception
{
SearchRequest searchRequest = new SearchRequestImpl();
searchRequest.setBase( baseDn );
searchRequest.setFilter( OBJECT_CLASS_ALL_FILTER );
searchRequest.setScope( SearchScope.SUBTREE );
searchRequest.setDerefAliases( AliasDerefMode.NEVER_DEREF_ALIASES );
searchRequest.addControl( Controls.MANAGEDSAIT_CONTROL );
control.ifPresent( c -> searchRequest.addControl( c ) );
try ( SearchCursor searchCursor = connection.search( searchRequest );
EntryCursor entryCursor = new EntryCursorImpl( searchCursor ) )
{
List<Dn> dns = new ArrayList<>();
for ( Entry entry : entryCursor )
{
dns.add( entry.getDn() );
}
dns.sort( new DnComparator( "1.1" ) );
for ( Dn dn : dns )
{
DeleteRequest deleteRequest = new DeleteRequestImpl();
deleteRequest.setName( dn );
deleteRequest.addControl( Controls.MANAGEDSAIT_CONTROL );
control.ifPresent( c -> deleteRequest.addControl( c ) );
connection.delete( deleteRequest );
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/OpenLdapServer.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/OpenLdapServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapNoSuchAttributeException;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.ldap.client.api.LdapConnection;
/**
* An OpenLDAP implementation of a test LDAP server.
*
* This implementation expects that an existing OpenLDAP server is running
* and connection parameters are provided via environment variables.
*/
public class OpenLdapServer extends TestLdapServer
{
private static final String OPENLDAP_HOST = getEnvOrDefault( "OPENLDAP_HOST", "openldap.example.com" );
private static final int OPENLDAP_PORT = Integer.parseInt( getEnvOrDefault( "OPENLDAP_PORT", "20389" ) );
private static final int OPENLDAP_PORT_SSL = Integer.parseInt( getEnvOrDefault( "OPENLDAP_PORT_SSL", "20636" ) );
private static final String OPENLDAP_ADMIN_DN = getEnvOrDefault( "OPENLDAP_ADMIN_DN",
"cn=admin,dc=example,dc=org" );
private static final String OPENLDAP_ADMIN_PASSWORD = getEnvOrDefault( "OPENLDAP_ADMIN_PASSWORD", "admin" );
private static final String OPENLDAP_CONFIG_DN = getEnvOrDefault( "OPENLDAP_CONFIG_DN", "cn=admin,cn=config" );
private static final String OPENLDAP_CONFIG_PASSWORD = getEnvOrDefault( "OPENLDAP_CONFIG_PASSWORD", "config" );
public static OpenLdapServer getInstance()
{
return new OpenLdapServer();
}
private OpenLdapServer()
{
super( LdapServerType.OpenLdap, OPENLDAP_HOST, OPENLDAP_PORT, OPENLDAP_PORT_SSL, OPENLDAP_ADMIN_DN,
OPENLDAP_ADMIN_PASSWORD );
}
public void prepare()
{
super.prepare();
try ( LdapConnection connection = openConnection();
LdifReader ldifReader = new LdifReader( TestFixture.class.getResourceAsStream( "OpenLdapConfig.ldif" ) ) )
{
connection.bind( OPENLDAP_CONFIG_DN, OPENLDAP_CONFIG_PASSWORD );
for ( LdifEntry entry : ldifReader )
{
for ( Modification modification : entry.getModifications() )
{
connection.modify( entry.getDn(), modification );
}
}
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
}
@Override
public void setConfidentialityRequired( boolean confidentialityRequired )
{
if ( confidentialityRequired )
{
setSecurityProps( 128, 128 );
}
else
{
setSecurityProps( 0, 0 );
}
}
public void setSecurityProps( int ssf, int tls )
{
try ( LdapConnection connection = openConnection() )
{
connection.bind( OPENLDAP_CONFIG_DN, OPENLDAP_CONFIG_PASSWORD );
Modification modification1 = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE,
"olcSecurity", "ssf=" + ssf + " tls=" + tls );
Modification modification2 = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE,
"olcSaslSecProps", "noplain,noanonymous,minssf=" + ssf );
connection.modify( "cn=config", modification1, modification2 );
}
catch ( LdapNoSuchAttributeException e )
{
// ignore
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/CertificateUtil.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/CertificateUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.Enumeration;
import javax.net.ssl.KeyManagerFactory;
import javax.security.auth.x500.X500Principal;
import org.apache.directory.api.util.Strings;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
/**
* Helper class used to generate self-signed certificates, and load a KeyStore
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class CertificateUtil
{
private static final boolean SELF_SIGNED = true;
private static final boolean CA_SIGNED = false;
private static final boolean CRITICAL = true;
private CertificateUtil()
{
// Nothing to do
}
public static X509Certificate generateX509Certificate( X500Principal subjectDn, X500Principal issuerDn, KeyPair keyPair,
long daysValidity, String sigAlgorithm, boolean isCa )
throws CertificateException
{
Instant from = Instant.now();
Instant to = from.plus( Duration.ofDays( daysValidity ) );
BigInteger serialNumber = new BigInteger( 64, new SecureRandom() );
try
{
ContentSigner signer = new JcaContentSignerBuilder( sigAlgorithm ).build( keyPair.getPrivate() );
InetAddress localHost = InetAddress.getLocalHost();
GeneralName[] sanLocalHost = new GeneralName[] {
new GeneralName( GeneralName.dNSName,
localHost.getHostName() ),
new GeneralName( GeneralName.iPAddress, localHost.getHostAddress() )
};
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( issuerDn,
serialNumber,
Date.from( from ),
Date.from( to ),
subjectDn,
keyPair.getPublic() )
.addExtension( Extension.basicConstraints, CRITICAL, new BasicConstraints( isCa ) )
.addExtension( Extension.subjectAlternativeName, false, new GeneralNames( sanLocalHost ) );
return new JcaX509CertificateConverter().setProvider( new BouncyCastleProvider() )
.getCertificate( certificateBuilder.build( signer ) );
}
catch ( OperatorCreationException | CertIOException | UnknownHostException e )
{
throw new CertificateException( "BouncyCastle failed to generate the X509 certificate.", e );
}
}
/**
* Create a self signed certificate
*
* @param issuer The Issuer (which is the same as the subject
* @param keyPair The asymmetric keyPair
* @param days Validity number of days
* @param algoStr Algorithm
* @return A self signed CA certificate
* @throws CertificateException If the info store din the certificate is invalid
* @throws IOException If we can't store some info in the certificate
* @throws NoSuchAlgorithmException If the algorithm does not exist
* @throws SignatureException If the certificate cannot be signed
* @throws NoSuchProviderException If we don't have a security provider
* @throws InvalidKeyException If the KeyPair is invalid
*/
public static X509Certificate generateSelfSignedCertificate( X500Principal issuer, KeyPair keyPair, int days, String algoStr )
throws CertificateException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException
{
return generateX509Certificate( issuer, issuer, keyPair, days, algoStr, SELF_SIGNED );
}
/**
* Generate a Certificate signed by a CA certificate
*
* @param issuer The Issuer (which is the same as the subject
* @param keyPair The asymmetric keyPair
* @param days Validity number of days
* @param algoStr Algorithm
* @return A self signed CA certificate
* @throws CertificateException If the info store din the certificate is invalid
* @throws IOException If we can't store some info in the certificate
* @throws NoSuchAlgorithmException If the algorithm does not exist
* @throws SignatureException If the certificate cannot be signed
* @throws NoSuchProviderException If we don't have a security provider
* @throws InvalidKeyException If the KeyPair is invalid
*/
public static X509Certificate generateCertificate( X500Principal subject, X500Principal issuer, KeyPair keyPair, int days, String algoStr )
throws CertificateException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException
{
return generateX509Certificate( subject, issuer, keyPair, days, algoStr, CA_SIGNED );
}
/**
* Loads the digital certificate from a keystore file
*
* @param keyStoreFile The KeyStore file to load
* @param keyStorePasswordStr The KeyStore password
* @return The KeyManager factory it created
* @throws Exception If the KeyStore can't be loaded
*/
public static KeyManagerFactory loadKeyStore( String keyStoreFile, String keyStorePasswordStr ) throws Exception
{
char[] keyStorePassword = Strings.isEmpty( keyStorePasswordStr ) ? null : keyStorePasswordStr.toCharArray();
if ( !Strings.isEmpty( keyStoreFile ) )
{
// We have a provided KeyStore file: read it
KeyStore keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
try ( InputStream is = Files.newInputStream( Paths.get( keyStoreFile ) ) )
{
keyStore.load( is, keyStorePassword );
}
/*
* Verify key store:
* * Must only contain one entry which must be a key entry
* * Must contain a certificate chain
* * The private key must be recoverable by the key store password
*/
Enumeration<String> aliases = keyStore.aliases();
if ( !aliases.hasMoreElements() )
{
throw new KeyStoreException( "Key store is empty" );
}
String alias = aliases.nextElement();
if ( aliases.hasMoreElements() )
{
throw new KeyStoreException( "Key store contains more than one entry" );
}
if ( !keyStore.isKeyEntry( alias ) )
{
throw new KeyStoreException( "Key store must contain a key entry" );
}
if ( keyStore.getCertificateChain( alias ) == null )
{
throw new KeyStoreException( "Key store must contain a certificate chain" );
}
if ( keyStore.getKey( alias, keyStorePassword ) == null )
{
throw new KeyStoreException( "Private key must be recoverable by the key store password" );
}
// Set up key manager factory to use our key store
String algorithm = Security.getProperty( "ssl.KeyManagerFactory.algorithm" );
if ( algorithm == null )
{
algorithm = KeyManagerFactory.getDefaultAlgorithm();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( algorithm );
keyManagerFactory.init( keyStore, keyStorePassword );
return keyManagerFactory;
}
else
{
return null;
}
}
public static File createTempKeyStore( String keyStoreName, char[] keyStorePassword ) throws IOException, KeyStoreException,
NoSuchAlgorithmException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException
{
// Create a temporary keystore, be sure to remove it when exiting the test
File keyStoreFile = Files.createTempFile( keyStoreName, "ks" ).toFile();
keyStoreFile.deleteOnExit();
KeyStore keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
try ( InputStream keyStoreData = new FileInputStream( keyStoreFile ) )
{
keyStore.load( null, keyStorePassword );
}
// Generate the asymmetric keys, using EC algorithm
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( "EC" );
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Generate the subject's name
X500Principal owner = new X500Principal( "CN=apacheds,OU=directory,O=apache,C=US" );
// Create the self-signed certificate
X509Certificate certificate = CertificateUtil.generateSelfSignedCertificate( owner, keyPair, 365, "SHA256WithECDSA" );
keyStore.setKeyEntry( "apachedsKey", keyPair.getPrivate(), keyStorePassword, new X509Certificate[] { certificate } );
try ( FileOutputStream out = new FileOutputStream( keyStoreFile ) )
{
keyStore.store( out, keyStorePassword );
}
return keyStoreFile;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/Fedora389dsLdapServer.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/Fedora389dsLdapServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
/**
* An 389ds implementation of a test LDAP server.
*
* This implementation expects that an existing 389ds server is running
* and connection parameters are provided via environment variables.
*/
public class Fedora389dsLdapServer extends TestLdapServer
{
private static final String FEDORA_389DS_HOST = getEnvOrDefault( "FEDORA_389DS_HOST", "fedora389ds.example.com" );
private static final int FEDORA_389DS_PORT = Integer.parseInt( getEnvOrDefault( "FEDORA_389DS_PORT", "21389" ) );
private static final int FEDORA_389DS_PORT_SSL = Integer
.parseInt( getEnvOrDefault( "FEDORA_389DS_PORT_SSL", "21636" ) );
private static final String FEDORA_389DS_ADMIN_DN = getEnvOrDefault( "FEDORA_389DS_ADMIN_DN",
"cn=Directory Manager" );
private static final String FEDORA_389DS_ADMIN_PASSWORD = getEnvOrDefault( "FEDORA_389DS_ADMIN_PASSWORD", "admin" );
public static Fedora389dsLdapServer getInstance()
{
return new Fedora389dsLdapServer();
}
private Fedora389dsLdapServer()
{
super( LdapServerType.Fedora389ds, FEDORA_389DS_HOST, FEDORA_389DS_PORT, FEDORA_389DS_PORT_SSL,
FEDORA_389DS_ADMIN_DN, FEDORA_389DS_ADMIN_PASSWORD );
}
@Override
public void setConfidentialityRequired( boolean confidentialityRequired )
{
withAdminConnection( connection -> {
Modification modification = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE,
"nsslapd-require-secure-binds", confidentialityRequired ? "on" : "off" );
connection.modify( "cn=config", modification );
} );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServersSource.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/LdapServersSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.params.provider.ArgumentsSource;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ArgumentsSource(LdapServersArgumentsProvider.class)
public @interface LdapServersSource
{
Mode mode() default Mode.One;
LdapServerType[] only() default
{};
LdapServerType[] except() default
{};
String reason() default "";
enum Mode
{
One, All;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/TestLdapServer.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/TestLdapServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.NoVerificationTrustManager;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
/**
* An abstraction around an LDAP server that can be used for testing.
* Provides the LDAP server type and connection parameters.
*/
public abstract class TestLdapServer
{
public static String getEnvOrDefault( String key, String defaultValue )
{
return System.getenv().getOrDefault( key, defaultValue );
}
protected final LdapServerType type;
protected final String host;
protected final int port;
protected final int portSSL;
protected final String adminDn;
protected final String adminPassword;
protected TestLdapServer( LdapServerType type, String host, int port, int portSSL, String adminDn,
String adminPassword )
{
this.type = type;
this.host = host;
this.port = port;
this.portSSL = portSSL;
this.adminDn = adminDn;
this.adminPassword = adminPassword;
}
public boolean isAvailable()
{
try ( LdapConnection connection = openAdminConnection() )
{
}
catch ( InvalidConnectionException e )
{
return false;
}
catch ( LdapAuthenticationException e )
{
return false;
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
return true;
}
public LdapConnection openAdminConnection() throws LdapException
{
LdapConnection connection = openConnection();
connection.bind( adminDn, adminPassword );
return connection;
}
public LdapNetworkConnection openConnection() throws LdapException
{
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost( host );
config.setLdapPort( port );
config.setUseTls( true );
config.setTrustManagers( new NoVerificationTrustManager() );
LdapNetworkConnection connection = new LdapNetworkConnection( config );
connection.connect();
return connection;
}
public void withAdminConnection( LdapConnectionConsumer consumer )
{
try ( LdapConnection connection = openAdminConnection() )
{
consumer.accept( connection );
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
}
public static interface LdapConnectionConsumer
{
void accept( LdapConnection connection ) throws Exception;
}
public <T> T withAdminConnectionAndGet( LdapConnectionFunction<T> function )
{
try ( LdapConnection connection = openAdminConnection() )
{
return function.apply( connection );
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
}
public static interface LdapConnectionFunction<T>
{
T apply( LdapConnection connection ) throws Exception;
}
public void prepare()
{
TestFixture.createContextEntry( this );
TestFixture.cleanup( this );
TestFixture.importData( this );
setConfidentialityRequired( false );
String serverSpecificLdif = getType().name() + ".ldif";
if ( TestFixture.class.getResource( serverSpecificLdif ) != null )
{
withAdminConnection( connection -> {
try ( LdifReader ldifReader = new LdifReader(
TestFixture.class.getResourceAsStream( serverSpecificLdif ) ) )
{
for ( LdifEntry entry : ldifReader )
{
if ( entry.isChangeModify() )
{
connection.modify( entry.getDn(), entry.getModificationArray() );
}
if ( entry.isChangeAdd() )
{
connection.add( entry.getEntry() );
}
}
}
catch ( Exception e )
{
throw new RuntimeException( "Unexpected exception: " + e, e );
}
} );
}
}
public LdapServerType getType()
{
return type;
}
public String getHost()
{
return host;
}
public int getPort()
{
return port;
}
public int getPortSSL()
{
return portSSL;
}
public String getLdapUrl()
{
return "ldap://" + host + ":" + port;
}
public String getAdminDn()
{
return adminDn;
}
public String getAdminPassword()
{
return adminPassword;
}
public abstract void setConfidentialityRequired( boolean confidentialityRequired );
@Override
public String toString()
{
return type.name();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/Constants.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import org.apache.directory.api.util.Network;
public final class Constants
{
public static final String LOCALHOST = Network.LOOPBACK_HOSTNAME;
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/ApacheDirectoryServer.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/junit5/ApacheDirectoryServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.junit5;
import static org.apache.directory.studio.test.integration.junit5.Constants.LOCALHOST;
import java.io.File;
import java.util.Collections;
import java.util.stream.Collectors;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.api.partition.Partition;
import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.ldap.handlers.extended.PwdModifyHandler;
import org.apache.directory.server.ldap.handlers.extended.StartTlsHandler;
import org.apache.directory.server.ldap.handlers.extended.WhoAmIHandler;
import org.apache.directory.server.ldap.handlers.sasl.SimpleMechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.server.protocol.shared.transport.Transport;
import org.apache.mina.util.AvailablePortFinder;
/**
* An ApacheDS implementation of a test LDAP server.
*
* This implementation starts an embedded ApacheDS and adds a partition dc=example,dc=org.
*/
public class ApacheDirectoryServer extends TestLdapServer
{
private static ApacheDirectoryServer instance;
private DirectoryService service;
private LdapServer server;
private String defaultKeyStoreFile;
public static synchronized ApacheDirectoryServer getInstance()
{
if ( instance == null )
{
int port = AvailablePortFinder.getNextAvailable( 1024 );
int portSSL = AvailablePortFinder.getNextAvailable( port + 1 );
instance = new ApacheDirectoryServer( port, portSSL );
instance.startServer();
}
return instance;
}
private void startServer()
{
try
{
DefaultDirectoryServiceFactory factory = new DefaultDirectoryServiceFactory();
factory.init( "test" );
service = factory.getDirectoryService();
Partition partition = factory.getPartitionFactory().createPartition( service.getSchemaManager(),
service.getDnFactory(), "example.org", "dc=example,dc=org", 1024,
new File( service.getInstanceLayout().getPartitionsDirectory(), "example.org" ) );
partition.initialize();
service.addPartition( partition );
service.getSchemaManager().enable( "nis", "krb5kdc" );
service.getInterceptor( "passwordHashingInterceptor" );
service.setInterceptors( service.getInterceptors().stream()
.filter( i -> !i.getName().equals( "ConfigurableHashingInterceptor" ) )
.collect( Collectors.toList() ) );
service.setAllowAnonymousAccess( true );
server = new LdapServer();
server.setDirectoryService( service );
Transport ldap = new TcpTransport( port );
server.addTransports( ldap );
Transport ldaps = new TcpTransport( portSSL );
ldaps.setEnableSSL( true );
server.addTransports( ldaps );
server.addSaslMechanismHandler( "SIMPLE", new SimpleMechanismHandler() );
server.addSaslMechanismHandler( "CRAM-MD5", new CramMd5MechanismHandler() );
server.addSaslMechanismHandler( "DIGEST-MD5", new DigestMd5MechanismHandler() );
server.setSaslRealms( Collections.singletonList( "EXAMPLE.ORG" ) );
server.setSaslHost( getHost() );
server.setSearchBaseDn( TestFixture.CONTEXT_DN.getName() );
server.addExtendedOperationHandler( new StartTlsHandler() );
server.addExtendedOperationHandler( new PwdModifyHandler() );
server.addExtendedOperationHandler( new WhoAmIHandler() );
defaultKeyStoreFile = CertificateUtil.createTempKeyStore( "testStore", "changeit".toCharArray() )
.getAbsolutePath();
server.setKeystoreFile( defaultKeyStoreFile );
server.setCertificatePassword( "changeit" );
server.start();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
@Override
public void prepare()
{
super.prepare();
try
{
if ( !defaultKeyStoreFile.equals( server.getKeystoreFile() ) )
{
server.setKeystoreFile( defaultKeyStoreFile );
server.reloadSslContext();
}
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
public void setKeystore( String keystorePath ) throws Exception
{
server.setKeystoreFile( keystorePath );
server.reloadSslContext();
}
public DirectoryService getService()
{
return service;
}
@Override
public void setConfidentialityRequired( boolean confidentialityRequired )
{
server.setConfidentialityRequired( confidentialityRequired );
}
private ApacheDirectoryServer( int port, int portSSL )
{
super( LdapServerType.ApacheDS, LOCALHOST, port, portSSL, "uid=admin,ou=system", "secret" );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/DirectoryApiConnectionWrapperTest.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/DirectoryApiConnectionWrapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.core;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.CONTEXT_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC111_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRALS_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_LOOP_1_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_LOOP_2_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_REFERRALS_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_REFERRAL_TO_USERS_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_USERS_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER8_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.USERS_DN;
import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.ConnectException;
import java.nio.channels.UnresolvedAddressException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import javax.naming.directory.SearchControls;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.directory.api.ldap.codec.api.LdapApiService;
import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
//import org.apache.directory.api.ldap.extras.extended.endTransaction.EndTransactionRequest;
//import org.apache.directory.api.ldap.extras.extended.endTransaction.EndTransactionResponse;
import org.apache.directory.api.ldap.extras.extended.pwdModify.PasswordModifyRequest;
//import org.apache.directory.api.ldap.extras.extended.startTransaction.StartTransactionRequest;
//import org.apache.directory.api.ldap.extras.extended.startTransaction.StartTransactionResponse;
import org.apache.directory.api.ldap.extras.extended.whoAmI.WhoAmIRequest;
import org.apache.directory.api.ldap.extras.extended.whoAmI.WhoAmIResponse;
import org.apache.directory.api.ldap.model.constants.SaslQoP;
import org.apache.directory.api.ldap.model.constants.SaslSecurityStrength;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.entry.DefaultAttribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
import org.apache.directory.api.ldap.model.exception.LdapAuthenticationNotSupportedException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapLoopDetectedException;
import org.apache.directory.api.ldap.model.message.ExtendedResponse;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.util.Strings;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod;
import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.apache.directory.studio.connection.core.ConnectionParameter.AuthenticationMethod;
import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod;
import org.apache.directory.studio.connection.core.ConnectionParameter.Krb5CredentialConfiguration;
import org.apache.directory.studio.connection.core.ICertificateHandler.TrustLevel;
import org.apache.directory.studio.connection.core.IReferralHandler;
import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
import org.apache.directory.studio.connection.core.io.ConnectionWrapper;
import org.apache.directory.studio.connection.core.io.StudioLdapException;
import org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper;
import org.apache.directory.studio.connection.core.io.api.StudioSearchResult;
import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration;
import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeRootDSERunnable;
import org.apache.directory.studio.ldapbrowser.core.model.impl.BrowserConnection;
import org.apache.directory.studio.test.integration.junit5.LdapServerType;
import org.apache.directory.studio.test.integration.junit5.LdapServersSource;
import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode;
import org.apache.directory.studio.test.integration.junit5.SkipTestIfLdapServerIsNotAvailableInterceptor;
import org.apache.directory.studio.test.integration.junit5.TestData;
import org.apache.directory.studio.test.integration.junit5.TestFixture;
import org.apache.directory.studio.test.integration.junit5.TestLdapServer;
import org.apache.mina.util.AvailablePortFinder;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
/**
* Tests the {@link DirectoryApiConnectionWrapper}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
@ExtendWith(SkipTestIfLdapServerIsNotAvailableInterceptor.class)
public class DirectoryApiConnectionWrapperTest
{
protected ConnectionWrapper connectionWrapper;
@BeforeAll
public static void suspendEventFiringInCurrentThread()
{
ConnectionEventRegistry.suspendEventFiringInCurrentThread();
ConnectionCorePlugin.getDefault().setCertificateHandler( null );
}
@AfterAll
public static void resumeEventFiringInCurrentThread()
{
ConnectionEventRegistry.resumeEventFiringInCurrentThread();
}
@AfterEach
public void tearDown() throws Exception
{
if ( connectionWrapper != null )
{
connectionWrapper.disconnect();
}
}
/**
* Tests connecting to the server without encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testConnectPlain( TestLdapServer ldapServer )
{
StudioProgressMonitor monitor = getProgressMonitor();
getConnection( monitor, ldapServer, null, null );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
assertTrue( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNull( connectionWrapper.getSslSession() );
assertNull( monitor.getException() );
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Tests connecting to the server using ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testConnectLdaps( TestLdapServer ldapServer )
{
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, null, null );
connection.setPort( ldapServer.getPortSSL() );
connection.setEncryptionMethod( EncryptionMethod.LDAPS );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Tests connecting to the server using StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testConnectStartTls( TestLdapServer ldapServer )
{
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, null, null );
connection.setEncryptionMethod( EncryptionMethod.START_TLS );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test failed connections to the server.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testConnectFailures( TestLdapServer ldapServer )
{
StudioProgressMonitor monitor = null;
Connection connection = null;
// invalid port
monitor = getProgressMonitor();
connection = getConnection( monitor, ldapServer, null, null );
connection.setPort( AvailablePortFinder.getNextAvailable() );
connectionWrapper.connect( monitor );
assertFalse( connectionWrapper.isConnected() );
assertNotNull( monitor.getException() );
assertTrue( monitor.getException() instanceof StudioLdapException );
assertNotNull( monitor.getException().getCause() );
assertTrue( monitor.getException().getCause() instanceof InvalidConnectionException );
assertNotNull( monitor.getException().getCause().getCause() );
assertTrue( monitor.getException().getCause().getCause() instanceof ConnectException );
// unknown host
monitor = getProgressMonitor();
connection = getConnection( monitor, ldapServer, null, null );
connection.setHost( "555.555.555.555" );
connectionWrapper.connect( monitor );
assertFalse( connectionWrapper.isConnected() );
assertNotNull( monitor.getException() );
assertTrue( monitor.getException() instanceof StudioLdapException );
assertNotNull( monitor.getException().getCause() );
assertTrue( monitor.getException().getCause() instanceof InvalidConnectionException );
assertNotNull( monitor.getException().getCause().getCause() );
assertTrue( monitor.getException().getCause().getCause() instanceof UnresolvedAddressException );
}
private void assertSslSession( TestLdapServer ldapServer )
{
try
{
SSLSession sslSession = connectionWrapper.getSslSession();
assertNotNull( sslSession );
assertNotNull( sslSession.getProtocol() );
assertNotNull( sslSession.getCipherSuite() );
assertNotNull( sslSession.getPeerCertificates() );
if ( ldapServer.getType() == LdapServerType.ApacheDS )
{
assertEquals( "TLSv1.2", sslSession.getProtocol() );
}
else
{
assertEquals( "TLSv1.3", sslSession.getProtocol() );
}
}
catch ( SSLPeerUnverifiedException e )
{
throw new RuntimeException( e );
}
}
/**
* Test binding to the server using simple auth and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSimpleBindPlain( TestLdapServer ldapServer )
{
ldapServer.setConfidentialityRequired( false );
StudioProgressMonitor monitor = getProgressMonitor();
getConnection( monitor, ldapServer, ldapServer.getAdminDn(), ldapServer.getAdminPassword() );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using simple auth and no encryption should fail if the server requires confidentially.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSimpleBindPlainConfidentiallyRequired( TestLdapServer ldapServer )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
getConnection( monitor, ldapServer, ldapServer.getAdminDn(), ldapServer.getAdminPassword() );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertFalse( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNotNull( monitor.getException() );
assertTrue( monitor.getException() instanceof StudioLdapException );
assertTrue( monitor.getException().getMessage().contains( "[LDAP result code 13 - confidentialityRequired]" ) );
assertNotNull( monitor.getException().getCause() );
assertTrue( monitor.getException().getCause() instanceof LdapAuthenticationNotSupportedException );
}
/**
* Test binding to the server using simple auth and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSimpleBindLdaps( TestLdapServer ldapServer )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, ldapServer.getAdminDn(),
ldapServer.getAdminPassword() );
connection.setPort( ldapServer.getPortSSL() );
connection.setEncryptionMethod( EncryptionMethod.LDAPS );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using simple auth and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSimpleBindStartTls( TestLdapServer ldapServer )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, ldapServer.getAdminDn(),
ldapServer.getAdminPassword() );
connection.setEncryptionMethod( EncryptionMethod.START_TLS );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using SASL auth and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSaslDigestMd5BindAuthPlain( TestLdapServer ldapServer )
{
testSaslDigestMd5BindPlain( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using SASL auth-int and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthIntPlain( TestLdapServer ldapServer )
{
testSaslDigestMd5BindPlain( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using SASL auth-conf and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthConfPlain( TestLdapServer ldapServer )
{
testSaslDigestMd5BindPlain( ldapServer, SaslQoP.AUTH_CONF );
}
private void testSaslDigestMd5BindPlain( TestLdapServer ldapServer, SaslQoP saslQoP )
{
ldapServer.setConfidentialityRequired( false );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "user.1", "password" );
connection.setAuthMethod( AuthenticationMethod.SASL_DIGEST_MD5 );
connection.getConnectionParameter().setSaslQop( SaslQoP.AUTH_CONF );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using SASL and no encryption should fail if the server requires confidentially.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslBindPlainConfidentiallyRequired( TestLdapServer ldapServer )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "user.1", "password" );
connection.setAuthMethod( AuthenticationMethod.SASL_DIGEST_MD5 );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertFalse( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNotNull( monitor.getException() );
assertTrue( monitor.getException() instanceof StudioLdapException );
assertTrue( monitor.getException().getMessage().contains( "[LDAP result code 13 - confidentialityRequired]" ) );
assertNotNull( monitor.getException().getCause() );
assertTrue( monitor.getException().getCause() instanceof LdapAuthenticationNotSupportedException );
}
/**
* Test binding to the server using SASL auth and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthLdaps( TestLdapServer ldapServer )
{
testSaslDigestMd5BindLdaps( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using SASL auth-int and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthIntLdaps( TestLdapServer ldapServer )
{
testSaslDigestMd5BindLdaps( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using SASL auth-conf and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSaslDigestMd5BindAuthConfLdaps( TestLdapServer ldapServer )
{
testSaslDigestMd5BindLdaps( ldapServer, SaslQoP.AUTH_CONF );
}
private void testSaslDigestMd5BindLdaps( TestLdapServer ldapServer, SaslQoP saslQoP )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "user.1", "password" );
connection.setPort( ldapServer.getPortSSL() );
connection.setEncryptionMethod( EncryptionMethod.LDAPS );
connection.setAuthMethod( AuthenticationMethod.SASL_DIGEST_MD5 );
connection.getConnectionParameter().setSaslQop( saslQoP );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using SASL auth and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthStartTls( TestLdapServer ldapServer )
{
testSaslDigestMd5BindStartTls( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using SASL auth-int and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds)
public void testSaslDigestMd5BindAuthIntStartTls( TestLdapServer ldapServer )
{
testSaslDigestMd5BindStartTls( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using SASL auth-conf and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All)
public void testSaslDigestMd5BindAuthConfStartTls( TestLdapServer ldapServer )
{
testSaslDigestMd5BindStartTls( ldapServer, SaslQoP.AUTH_CONF );
}
private void testSaslDigestMd5BindStartTls( TestLdapServer ldapServer, SaslQoP saslQoP )
{
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "user.1", "password" );
connection.setEncryptionMethod( EncryptionMethod.START_TLS );
connection.setAuthMethod( AuthenticationMethod.SASL_DIGEST_MD5 );
connection.getConnectionParameter().setSaslQop( saslQoP );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using GSSAPI auth and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthPlain( TestLdapServer ldapServer )
{
testSaslGssapiBindPlain( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using GSSAPI auth-int and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthIntPlain( TestLdapServer ldapServer )
{
testSaslGssapiBindPlain( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using GSSAPI auth-conf and no encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthConfPlain( TestLdapServer ldapServer )
{
testSaslGssapiBindPlain( ldapServer, SaslQoP.AUTH_CONF );
}
private void testSaslGssapiBindPlain( TestLdapServer ldapServer, SaslQoP saslQoP )
{
TestFixture.skipIfKdcServerIsNotAvailable();
ldapServer.setConfidentialityRequired( false );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "hnelson", "secret" );
connection.setAuthMethod( AuthenticationMethod.SASL_GSSAPI );
connection.getConnectionParameter().setKrb5CredentialConfiguration( Krb5CredentialConfiguration.OBTAIN_TGT );
connection.getConnectionParameter().setSaslQop( saslQoP );
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertFalse( connectionWrapper.isSecured() );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using GSSAPI auth and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthLdaps( TestLdapServer ldapServer ) throws Exception
{
testSaslGssapiBindLdaps( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using GSSAPI auth-int and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthIntLdaps( TestLdapServer ldapServer ) throws Exception
{
testSaslGssapiBindLdaps( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using GSSAPI auth-conf and ldaps:// encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthConfLdaps( TestLdapServer ldapServer ) throws Exception
{
testSaslGssapiBindLdaps( ldapServer, SaslQoP.AUTH_CONF );
}
private void testSaslGssapiBindLdaps( TestLdapServer ldapServer, SaslQoP saslQoP ) throws Exception
{
TestFixture.skipIfKdcServerIsNotAvailable();
// obtain native TGT
String[] cmd =
{ "/bin/sh", "-c", "echo secret | /usr/bin/kinit hnelson" };
Process process = Runtime.getRuntime().exec( cmd );
int exitCode = process.waitFor();
assertEquals( 0, exitCode );
ldapServer.setConfidentialityRequired( true );
StudioProgressMonitor monitor = getProgressMonitor();
Connection connection = getConnection( monitor, ldapServer, "hnelson", "secret" );
connection.setPort( ldapServer.getPortSSL() );
connection.setEncryptionMethod( EncryptionMethod.LDAPS );
connection.setAuthMethod( AuthenticationMethod.SASL_GSSAPI );
connection.getConnectionParameter().setKrb5CredentialConfiguration( Krb5CredentialConfiguration.USE_NATIVE );
connection.getConnectionParameter().setSaslQop( saslQoP );
acceptAllCertificates();
assertFalse( connectionWrapper.isConnected() );
connectionWrapper.connect( monitor );
connectionWrapper.bind( monitor );
assertTrue( connectionWrapper.isConnected() );
assertTrue( connectionWrapper.isSecured() );
assertSslSession( ldapServer );
assertNull( monitor.getException() );
connectionWrapper.unbind();
connectionWrapper.disconnect();
assertFalse( connectionWrapper.isConnected() );
}
/**
* Test binding to the server using GSSAPI auth and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthStartTls( TestLdapServer ldapServer )
{
testSaslGssapiBindStartTls( ldapServer, SaslQoP.AUTH );
}
/**
* Test binding to the server using GSSAPI auth-int and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthIntStartTls( TestLdapServer ldapServer )
{
testSaslGssapiBindStartTls( ldapServer, SaslQoP.AUTH_INT );
}
/**
* Test binding to the server using GSSAPI auth-conf and StartTLS encryption.
*/
@ParameterizedTest
@LdapServersSource(mode = Mode.All, except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26")
public void testSaslGssapiBindAuthConfStartTls( TestLdapServer ldapServer )
{
testSaslGssapiBindStartTls( ldapServer, SaslQoP.AUTH_CONF );
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/ComputeDiffTest.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/ComputeDiffTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.core;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection.ModifyMode;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyConnection;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Value;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.utils.Utils;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.model.LdifFile;
import org.apache.directory.studio.ldifparser.model.container.LdifChangeModifyRecord;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ComputeDiffTest
{
private IBrowserConnection connection;
private IEntry oldEntry;
private IEntry newEntry;
static class TestConnection extends DummyConnection
{
private static final long serialVersionUID = 1L;
private ModifyMode modifyMode = ModifyMode.DEFAULT;
private ModifyMode modifyModeNoEMR = ModifyMode.DEFAULT;
public TestConnection()
{
super( Schema.DEFAULT_SCHEMA );
}
public ModifyMode getModifyMode()
{
return modifyMode;
}
public void setModifyMode( ModifyMode mode )
{
this.modifyMode = mode;
}
public ModifyMode getModifyModeNoEMR()
{
return modifyModeNoEMR;
}
public void setModifyModeNoEMR( ModifyMode mode )
{
this.modifyModeNoEMR = mode;
}
}
@BeforeEach
public void setup() throws Exception
{
ConnectionEventRegistry.suspendEventFiringInCurrentThread();
connection = new TestConnection();
oldEntry = new DummyEntry( new Dn( "cn=foo" ), connection );
newEntry = new DummyEntry( new Dn( "cn=foo" ), connection );
}
@Test
public void shouldReturnNullForEqualEntries()
{
// entries without attribute
assertThat( Utils.computeDiff( oldEntry, newEntry ), nullValue() );
assertThat( Utils.computeDiff( oldEntry, oldEntry ), nullValue() );
assertThat( Utils.computeDiff( newEntry, newEntry ), nullValue() );
// entries with attributes
addAttribute( oldEntry, "cn", "1" );
addAttribute( oldEntry, "member", "cn=1", "cn=2", "cn=3" );
addAttribute( newEntry, "cn", "1" );
addAttribute( newEntry, "member", "cn=1", "cn=2", "cn=3" );
assertThat( Utils.computeDiff( oldEntry, newEntry ), nullValue() );
assertThat( Utils.computeDiff( oldEntry, oldEntry ), nullValue() );
assertThat( Utils.computeDiff( newEntry, newEntry ), nullValue() );
}
@Test
public void shouldAddOneAttributeWithOneValue()
{
addAttribute( newEntry, "cn", "1" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "add:cn", "cn:1" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn", "cn:1" );
}
@Test
public void shouldAddMultipleAttributeWithMultipleValues()
{
addAttribute( newEntry, "cn", "1", "2" );
addAttribute( newEntry, "member", "cn=1", "cn=2", "cn=3" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"add:cn", "cn:1", "cn:2", "-", "add:member", "member:cn=1", "member:cn=2", "member:cn=3" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"replace:cn", "cn:1", "cn:2", "-", "replace:member", "member:cn=1", "member:cn=2", "member:cn=3" );
}
@Test
public void shouldAddOneValueToOneExistingAttribute()
{
addAttribute( oldEntry, "cn", "1" );
addAttribute( newEntry, "cn", "1", "2" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "add:cn", "cn:2" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn", "cn:1", "cn:2" );
}
@Test
public void shouldAddMultipleValuesToMultipleExistingAttributes()
{
addAttribute( oldEntry, "cn", "1" );
addAttribute( newEntry, "cn", "1", "2", "3" );
addAttribute( oldEntry, "member", "cn=1", "cn=2", "cn=3" );
addAttribute( newEntry, "member", "cn=1", "cn=2", "cn=3", "cn=4", "cn=5" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"add:cn", "cn:2", "cn:3", "-", "add:member", "member:cn=4", "member:cn=5" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"replace:cn", "cn:1", "cn:2", "cn:3", "-",
"replace:member", "member:cn=1", "member:cn=2", "member:cn=3", "member:cn=4", "member:cn=5" );
}
@Test
public void shouldDeleteAllOneValue()
{
addAttribute( oldEntry, "cn", "1" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "delete:cn", "cn:1" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn" );
}
@Test
public void shouldDeleteAllMultipleValues()
{
addAttribute( oldEntry, "cn", "1", "2" );
addAttribute( oldEntry, "member", "cn=1", "cn=2", "cn=3" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"delete:cn", "cn:1", "cn:2", "-",
"delete:member", "member:cn=1", "member:cn=2", "member:cn=3" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn", "-", "replace:member" );
}
@Test
public void shouldDeleteOneValue()
{
addAttribute( oldEntry, "cn", "1", "2", "3" );
addAttribute( newEntry, "cn", "1", "2" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "delete:cn", "cn:3" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn", "cn:1", "cn:2" );
}
@Test
public void shouldDeleteMultipleValues()
{
addAttribute( oldEntry, "cn", "1", "2", "3" );
addAttribute( newEntry, "cn", "1" );
addAttribute( oldEntry, "member", "cn=1", "cn=2", "cn=3", "cn=4", "cn=5" );
addAttribute( newEntry, "member", "cn=1" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"delete:cn", "cn:2", "cn:3", "-",
"delete:member", "member:cn=2", "member:cn=3", "member:cn=4", "member:cn=5" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"replace:cn", "cn:1", "-", "replace:member", "member:cn=1" );
}
@Test
public void shouldReplaceOneValue()
{
addAttribute( oldEntry, "cn", "1" );
addAttribute( newEntry, "cn", "2" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "delete:cn", "cn:1", "-", "add:cn", "cn:2" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ), "replace:cn", "cn:2" );
}
@Test
public void shouldReplaceMultipleValues()
{
addAttribute( oldEntry, "cn", "1", "2", "3" );
addAttribute( newEntry, "cn", "4" );
addAttribute( oldEntry, "member", "cn=1", "cn=2", "cn=3" );
addAttribute( newEntry, "member", "cn=1", "cn=4", "cn=5" );
connection.setModifyMode( ModifyMode.DEFAULT );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"delete:cn", "cn:1", "cn:2", "cn:3", "-", "add:cn", "cn:4", "-",
"delete:member", "member:cn=2", "member:cn=3", "-", "add:member", "member:cn=4", "member:cn=5" );
connection.setModifyMode( ModifyMode.REPLACE );
assertChangeModify( Utils.computeDiff( oldEntry, newEntry ),
"replace:cn", "cn:4", "-",
"replace:member", "member:cn=1", "member:cn=4", "member:cn=5" );
}
private static void addAttribute( IEntry entry, String attributeName, Object... rawValues )
{
Attribute attribute = new Attribute( entry, attributeName );
entry.addAttribute( attribute );
for ( Object rawValue : rawValues )
{
Value value = new Value( attribute, rawValue );
attribute.addValue( value );
}
}
private void assertChangeModify( LdifFile diff, String... lines )
{
assertThat( diff.isChangeType(), equalTo( true ) );
assertThat( diff.getContainers(), hasSize( 1 ) );
assertThat( diff.getLastContainer(), instanceOf( LdifChangeModifyRecord.class ) );
String s = "changetype:modify" + LdifParserConstants.LINE_SEPARATOR;
for ( String line : lines )
{
assertThat( diff.toRawString(), containsString( line ) );
s += line + LdifParserConstants.LINE_SEPARATOR;
}
s += "-" + LdifParserConstants.LINE_SEPARATOR;
assertThat( diff.toRawString(), containsString( s ) );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/SchemaTest.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/SchemaTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.core;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Collection;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.junit.jupiter.api.Test;
/**
* Tests the {@link Schema}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SchemaTest
{
/**
* Test that the default schema is properly loaded.
*/
@Test
public void testDefaultSchema()
{
Schema defaultSchema = Schema.DEFAULT_SCHEMA;
assertNotNull( defaultSchema );
Collection<ObjectClass> ocds = defaultSchema.getObjectClassDescriptions();
assertNotNull( ocds );
assertFalse( ocds.isEmpty() );
assertNotNull( defaultSchema.getObjectClassDescription( "top" ) );
assertNotNull( defaultSchema.getObjectClassDescription( "inetOrgPerson" ) );
assertNotNull( defaultSchema.getObjectClassDescription( "groupOfNames" ) );
Collection<AttributeType> atds = defaultSchema.getAttributeTypeDescriptions();
assertNotNull( atds );
assertFalse( atds.isEmpty() );
assertNotNull( defaultSchema.getAttributeTypeDescription( "objectClass" ) );
assertNotNull( defaultSchema.getAttributeTypeDescription( "cn" ) );
assertNotNull( defaultSchema.getAttributeTypeDescription( "member" ) );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/Activator.java | tests/test.integration.core/src/main/java/org/apache/directory/studio/test/integration/core/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.core;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends Plugin
{
/**
* @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext)
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
// Nasty hack to get the API bundles started. DO NOT REMOVE
Platform.getBundle( "org.apache.directory.api.ldap.codec.core" ).start();
Platform.getBundle( "org.apache.directory.api.ldap.extras.codec" ).start();
Platform.getBundle( "org.apache.directory.api.ldap.net.mina" ).start();
}
/**
* @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
*/
public void stop( BundleContext context ) throws Exception
{
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/EclipseLogLoggerFactory.java | plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/EclipseLogLoggerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.slf4j.impl;
import org.slf4j.ILoggerFactory;
/**
* Logger factory for the {@link EclipseLogLogger}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EclipseLogLoggerFactory implements ILoggerFactory
{
private final EclipseLogLogger logger = new EclipseLogLogger();
@Override
public EclipseLogLogger getLogger( String name )
{
return logger;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/EclipseLogLogger.java | plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/EclipseLogLogger.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.slf4j.impl;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.Bundle;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;
/**
* Adapts {@link org.slf4j.Logger} interface to Eclipse {@link org.eclipse.core.runtime.ILog}
* which writes logs to <code>.metadata/.log</code> and show them in the Eclipse 'Error Log' view.
* <p>
* Only log levels 'error' and 'warn' are implemented. Log level 'info' would write too much
* to the Eclipse log. There is no appropriate log level 'debug' and 'trace' in Eclipse log, thus
* those levels are also not supported.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EclipseLogLogger extends MarkerIgnoringBase
{
private static final long serialVersionUID = 1L;
private static final String SYMBOLIC_NAME = "org.apache.directory.studio.slf4j-eclipselog";
private void internalLog( int severity, String message, Throwable t )
{
Bundle bundle = Platform.getBundle( SYMBOLIC_NAME );
if ( bundle != null )
{
Status status = new Status( severity, SYMBOLIC_NAME, message, t );
Platform.getLog( bundle ).log( status );
}
}
// ERROR
public boolean isErrorEnabled()
{
return true;
}
public void error( String msg )
{
if ( isErrorEnabled() )
{
internalLog( Status.ERROR, msg, null );
}
}
public void error( String format, Object arg )
{
if ( isErrorEnabled() )
{
String msgStr = MessageFormatter.format( format, arg ).getMessage();
internalLog( Status.ERROR, msgStr, null );
}
}
public void error( String format, Object arg1, Object arg2 )
{
if ( isErrorEnabled() )
{
String msgStr = MessageFormatter.format( format, arg1, arg2 ).getMessage();
internalLog( Status.ERROR, msgStr, null );
}
}
public void error( String format, Object... argArray )
{
if ( isErrorEnabled() )
{
String msgStr = MessageFormatter.arrayFormat( format, argArray ).getMessage();
internalLog( Status.ERROR, msgStr, null );
}
}
public void error( String msg, Throwable t )
{
if ( isErrorEnabled() )
{
internalLog( Status.ERROR, msg, t );
}
}
// WARN
public boolean isWarnEnabled()
{
return true;
}
public void warn( String msg )
{
if ( isWarnEnabled() )
{
internalLog( Status.WARNING, msg, null );
}
}
public void warn( String format, Object arg )
{
if ( isWarnEnabled() )
{
String msgStr = MessageFormatter.format( format, arg ).getMessage();
internalLog( Status.WARNING, msgStr, null );
}
}
public void warn( String format, Object arg1, Object arg2 )
{
if ( isWarnEnabled() )
{
String msgStr = MessageFormatter.format( format, arg1, arg2 ).getMessage();
internalLog( Status.WARNING, msgStr, null );
}
}
public void warn( String format, Object... argArray )
{
if ( isWarnEnabled() )
{
String msgStr = MessageFormatter.arrayFormat( format, argArray ).getMessage();
internalLog( Status.WARNING, msgStr, null );
}
}
public void warn( String msg, Throwable t )
{
if ( isWarnEnabled() )
{
internalLog( Status.WARNING, msg, t );
}
}
// INFO disabled, it would write too much logs
public boolean isInfoEnabled()
{
return false;
}
public void info( String msg )
{
}
public void info( String format, Object arg )
{
}
public void info( String format, Object arg1, Object arg2 )
{
}
public void info( String format, Object... argArray )
{
}
public void info( String msg, Throwable t )
{
}
// DEBUG disabled, there is no appropriate log level in Eclipse log
public boolean isDebugEnabled()
{
return false;
}
public void debug( String msg )
{
}
public void debug( String format, Object arg )
{
}
public void debug( String format, Object arg1, Object arg2 )
{
}
public void debug( String format, Object... argArray )
{
}
public void debug( String msg, Throwable t )
{
}
// TRACE disabled, there is no appropriate log level in Eclipse log
public boolean isTraceEnabled()
{
return false;
}
public void trace( String msg )
{
}
public void trace( String format, Object arg )
{
}
public void trace( String format, Object arg1, Object arg2 )
{
}
public void trace( String format, Object... argArray )
{
}
public void trace( String msg, Throwable t )
{
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/StaticLoggerBinder.java | plugins/slf4j-eclipselog/src/main/java/org/slf4j/impl/StaticLoggerBinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.slf4j.impl;
import org.slf4j.spi.LoggerFactoryBinder;
/**
* The static logger binding for slf4j. Adopted from slf4j-log4j12 implementation.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StaticLoggerBinder implements LoggerFactoryBinder
{
/**
* The unique instance of this class.
*/
private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
/**
* Return the singleton of this class.
*
* @return the StaticLoggerBinder singleton
*/
public static final StaticLoggerBinder getSingleton()
{
return SINGLETON;
}
/**
* Declare the version of the SLF4J API this implementation is compiled
* against. The value of this field is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
public static String REQUESTED_API_VERSION = "1.7.0"; // !final
private EclipseLogLoggerFactory loggerFactory;
private StaticLoggerBinder()
{
loggerFactory = new EclipseLogLoggerFactory();
}
@Override
public EclipseLogLoggerFactory getLoggerFactory()
{
return loggerFactory;
}
@Override
public String getLoggerFactoryClassStr()
{
return EclipseLogLoggerFactory.class.getName();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/test/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIOTest.java | plugins/templateeditor/src/test/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIOTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.parser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.apache.directory.studio.templateeditor.model.FileTemplate;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIO;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIOException;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateCheckbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateComposite;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateFileChooser;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateForm;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateImage;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLabel;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLink;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateListbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplatePassword;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateRadioButtons;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSection;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSpinner;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTable;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTextField;
import org.apache.directory.studio.templateeditor.model.widgets.ValueItem;
/**
* This class is used test the {@link TemplateIO} class.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateIOTest
{
/**
* Tests the parser with a minimal template file.
*/
@Test
public void testReadTemplateMinimalTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource( "template_minimal.xml" ) //$NON-NLS-1$
.openStream() );
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking if a template has been created
assertNotNull( template );
// Checking the title
assertEquals( "id", template.getId() ); //$NON-NLS-1$
// Checking the title
assertEquals( "Template Title", template.getTitle() ); //$NON-NLS-1$
// Checking the objectClasses
assertNotNull( template.getStructuralObjectClass() );
assertNotNull( template.getAuxiliaryObjectClasses() );
assertEquals( 0, template.getAuxiliaryObjectClasses().size() );
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
}
/**
* Tests the parser with a minimal template file.
*/
@Test
public void testReadTemplateMinimalWithCompositeTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_minimal_with_composite.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking if a template has been created
assertNotNull( template );
// Checking the title
assertEquals( "id", template.getId() ); //$NON-NLS-1$
// Checking the title
assertEquals( "Template Title", template.getTitle() ); //$NON-NLS-1$
// Checking the objectClasses
assertNotNull( template.getStructuralObjectClass() );
assertNotNull( template.getAuxiliaryObjectClasses() );
assertEquals( 2, template.getAuxiliaryObjectClasses().size() );
assertEquals( "a", template.getAuxiliaryObjectClasses().get( 0 ) ); //$NON-NLS-1$
assertEquals( "b", template.getAuxiliaryObjectClasses().get( 1 ) ); //$NON-NLS-1$
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
}
/**
* Tests the parser with a template file containing a section with a
* 'columns' attribute.
*/
@Test
public void testReadTemplateSectionColumnsAttributeTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_section_with_columns_attribute.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertEquals( 2, section.getNumberOfColumns() );
}
/**
* Tests the parser with a template file containing a section with a
* 'columns' attribute.
*/
@Test
public void testReadTemplateSectionDescriptionAttributeTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_section_with_description_attribute.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertEquals( "Section description", section.getDescription() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a section with a
* 'columns' attribute.
*/
@Test
public void testReadTemplateSectionTitleAttributeTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_section_with_title_attribute.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertEquals( "Section title", section.getTitle() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a section with a wrong
* 'columns' attribute.
*/
@Test
public void testReadTemplateSectionWrongColumnsAttributeTest() throws Exception
{
testParsingFail( "template_section_with_wrong_columns_attribute.xml" ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a checkbox with a
* value for the 'attributeType' attribute.
*/
@Test
public void testReadTemplateCheckboxAttributetypeValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_checkbox_with_attributetype_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the checkbox
TemplateCheckbox checkbox = ( TemplateCheckbox ) section.getChildren().get( 0 );
assertNotNull( checkbox );
assertEquals( "1.2.3.4", checkbox.getAttributeType() ); //$NON-NLS-1$
assertEquals( "label", checkbox.getLabel() ); //$NON-NLS-1$
assertNull( checkbox.getCheckedValue() );
assertNull( checkbox.getUncheckedValue() );
}
/**
* Tests the parser with a template file containing a checkbox with a
* value for the 'checkedValue' attribute.
*/
@Test
public void testReadTemplateCheckboxCheckedValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_checkbox_with_checked_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the checkbox
TemplateCheckbox checkbox = ( TemplateCheckbox ) section.getChildren().get( 0 );
assertNotNull( checkbox );
assertEquals( "1.2.3.4", checkbox.getAttributeType() ); //$NON-NLS-1$
assertEquals( "label", checkbox.getLabel() ); //$NON-NLS-1$
assertEquals( "Checked value", checkbox.getCheckedValue() ); //$NON-NLS-1$
assertNull( checkbox.getUncheckedValue() );
}
/**
* Tests the parser with a template file containing a checkbox with a
* value for the 'uncheckedValue' attribute.
*/
@Test
public void testReadTemplateCheckboxUncheckedValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_checkbox_with_unchecked_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the checkbox
TemplateCheckbox checkbox = ( TemplateCheckbox ) section.getChildren().get( 0 );
assertNotNull( checkbox );
assertEquals( "1.2.3.4", checkbox.getAttributeType() ); //$NON-NLS-1$
assertEquals( "label", checkbox.getLabel() ); //$NON-NLS-1$
assertNull( checkbox.getCheckedValue() );
assertEquals( "Unchecked value", checkbox.getUncheckedValue() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a checkbox with a
* value for the 'uncheckedValue' attribute.
*/
@Test
public void testReadTemplateCheckboxCheckedAndUnheckedValuesTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_checkbox_with_checked_and_unchecked_values.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the checkbox
TemplateCheckbox checkbox = ( TemplateCheckbox ) section.getChildren().get( 0 );
assertNotNull( checkbox );
assertEquals( "1.2.3.4", checkbox.getAttributeType() ); //$NON-NLS-1$
assertEquals( "label", checkbox.getLabel() ); //$NON-NLS-1$
assertEquals( "Checked value", checkbox.getCheckedValue() ); //$NON-NLS-1$
assertEquals( "Unchecked value", checkbox.getUncheckedValue() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a file chooser with
* only value for the 'attributeType' attribute.
*/
@Test
public void testReadTemplateFileChooserAttributeTypeValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_filechooser_with_attributetype_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the filechooser
TemplateFileChooser filechooser = ( TemplateFileChooser ) section.getChildren().get( 0 );
assertNotNull( filechooser );
assertEquals( "1.2.3.4", filechooser.getAttributeType() ); //$NON-NLS-1$
assertTrue( filechooser.isShowBrowseButton() );
assertTrue( filechooser.isShowClearButton() );
assertTrue( filechooser.isShowSaveAsButton() );
assertEquals( 0, filechooser.getExtensions().size() );
assertNull( filechooser.getIcon() );
}
/**
* Tests the parser with a template file containing a file chooser with all
* values.
*/
@Test
public void testReadTemplateFileChooserAllValuesTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_filechooser_with_all_values.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the filechooser
TemplateFileChooser filechooser = ( TemplateFileChooser ) section.getChildren().get( 0 );
assertNotNull( filechooser );
assertEquals( "1.2.3.4", filechooser.getAttributeType() ); //$NON-NLS-1$
assertFalse( filechooser.isShowBrowseButton() );
assertFalse( filechooser.isShowClearButton() );
assertFalse( filechooser.isShowSaveAsButton() );
assertEquals( 2, filechooser.getExtensions().size() );
assertEquals( "data", filechooser.getIcon() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing an image with only the
* value for the 'attributeType' attribute.
*/
@Test
public void testReadTemplateImageAttributeTypeValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_image_with_attributetype_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the image
TemplateImage image = ( TemplateImage ) section.getChildren().get( 0 );
assertNotNull( image );
assertEquals( "1.2.3.4", image.getAttributeType() ); //$NON-NLS-1$
assertTrue( image.isShowBrowseButton() );
assertTrue( image.isShowClearButton() );
assertTrue( image.isShowSaveAsButton() );
assertNull( image.getImageData() );
assertEquals( -1, image.getImageWidth() );
assertEquals( -1, image.getImageHeight() );
}
/**
* Tests the parser with a template file containing an image with all
* values.
*/
@Test
public void testReadTemplateImageAllValuesTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass()
.getResource( "template_image_with_all_values.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the image
TemplateImage image = ( TemplateImage ) section.getChildren().get( 0 );
assertNotNull( image );
assertEquals( "1.2.3.4", image.getAttributeType() ); //$NON-NLS-1$
assertFalse( image.isShowBrowseButton() );
assertFalse( image.isShowClearButton() );
assertFalse( image.isShowSaveAsButton() );
assertEquals( "data", image.getImageData() ); //$NON-NLS-1$
assertEquals( 16, image.getImageWidth() );
assertEquals( 9, image.getImageHeight() );
}
/**
* Tests the parser with a template file containing a label with only the
* value for the 'attributeType' attribute.
*/
@Test
public void testReadTemplateLabelAttributeTypeValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_label_with_attributetype_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the label
TemplateLabel label = ( TemplateLabel ) section.getChildren().get( 0 );
assertNotNull( label );
assertEquals( "1.2.3.4", label.getAttributeType() ); //$NON-NLS-1$
assertNull( label.getValue() );
}
/**
* Tests the parser with a template file containing a label with a value
* for the 'value' attribute.
*/
@Test
public void testReadTemplateLabelValueValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_label_with_value_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the label
TemplateLabel label = ( TemplateLabel ) section.getChildren().get( 0 );
assertNotNull( label );
assertNull( label.getAttributeType() );
assertEquals( "A label", label.getValue() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a link with only the
* value for the 'attributeType' attribute.
*/
@Test
public void testReadTemplateLinkAttributeTypeValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_link_with_attributetype_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the link
TemplateLink link = ( TemplateLink ) section.getChildren().get( 0 );
assertNotNull( link );
assertEquals( "1.2.3.4", link.getAttributeType() ); //$NON-NLS-1$
assertNull( link.getValue() );
}
/**
* Tests the parser with a template file containing a link with a value
* for the 'value' attribute.
*/
@Test
public void testReadTemplateLinkValueValueTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass()
.getResource( "template_link_with_value_value.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the link
TemplateLink link = ( TemplateLink ) section.getChildren().get( 0 );
assertNotNull( link );
assertNull( link.getAttributeType() );
assertEquals( "http://www.apache.org", link.getValue() ); //$NON-NLS-1$
}
/**
* Tests the parser with a template file containing a listbox with the
* minimal set of elements and attributes.
*/
@Test
public void testReadTemplateListboxMinimalTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource( "template_listbox_minimal.xml" ) //$NON-NLS-1$
.openStream() );
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the listbox
TemplateListbox listbox = ( TemplateListbox ) section.getChildren().get( 0 );
assertNotNull( listbox );
assertEquals( "1.2.3.4", listbox.getAttributeType() ); //$NON-NLS-1$
assertTrue( listbox.isMultipleSelection() );
assertNotNull( listbox.getItems() );
assertEquals( 1, listbox.getItems().size() );
assertTrue( listbox.getItems().contains( new ValueItem( "label", "value" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Tests the parser with a template file containing a listbox with the
* minimal set of elements and attributes.
*/
@Test
public void testReadTemplateListboxSingleSelectionTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_listbox_single_selection.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the listbox
TemplateListbox listbox = ( TemplateListbox ) section.getChildren().get( 0 );
assertNotNull( listbox );
assertEquals( "1.2.3.4", listbox.getAttributeType() ); //$NON-NLS-1$
assertFalse( listbox.isMultipleSelection() );
assertNotNull( listbox.getItems() );
assertEquals( 1, listbox.getItems().size() );
assertTrue( listbox.getItems().contains( new ValueItem( "label", "value" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Tests the parser with a template file containing a listbox with
* multiple items.
*/
@Test
public void testReadTemplateListboxMultipleItemsTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource(
"template_listbox_multiple_items.xml" ).openStream() ); //$NON-NLS-1$
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the listbox
TemplateListbox listbox = ( TemplateListbox ) section.getChildren().get( 0 );
assertNotNull( listbox );
assertEquals( "1.2.3.4", listbox.getAttributeType() ); //$NON-NLS-1$
assertTrue( listbox.isMultipleSelection() );
assertNotNull( listbox.getItems() );
assertEquals( 3, listbox.getItems().size() );
assertTrue( listbox.getItems().contains( new ValueItem( "label 1", "value 1" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue( listbox.getItems().contains( new ValueItem( "label 2", "value 2" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue( listbox.getItems().contains( new ValueItem( "label 3", "value 3" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Tests the parser with a template file containing a password with the
* minimal set of elements and attributes.
*/
@Test
public void testReadTemplatePasswordMinimalTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource( "template_password_minimal.xml" ) //$NON-NLS-1$
.openStream() );
}
catch ( Exception e )
{
fail( e.getMessage() );
return;
}
// Checking the form
TemplateForm form = template.getForm();
assertNotNull( form );
assertNotNull( form.getChildren() );
assertEquals( 1, form.getChildren().size() );
// Checking the section
TemplateSection section = ( TemplateSection ) form.getChildren().get( 0 );
assertNotNull( section );
assertNotNull( section.getChildren() );
assertEquals( 1, section.getChildren().size() );
// Checking the password
TemplatePassword password = ( TemplatePassword ) section.getChildren().get( 0 );
assertNotNull( password );
assertEquals( "1.2.3.4", password.getAttributeType() ); //$NON-NLS-1$
assertTrue( password.isHidden() );
assertTrue( password.isShowEditButton() );
}
/**
* Tests the parser with a template file containing a password with the
* minimal set of elements and attributes.
*/
@Test
public void testReadTemplatePasswordNotHiddenTest()
{
FileTemplate template = null;
try
{
template = TemplateIO.readAsFileTemplate( this.getClass().getResource( "template_password_not_hidden.xml" ) //$NON-NLS-1$
.openStream() );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/TemplatesManager.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/TemplatesManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.apache.directory.studio.templateeditor.model.ExtensionPointTemplate;
import org.apache.directory.studio.templateeditor.model.FileTemplate;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIO;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIOException;
/**
* This class is used to manage the templates.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplatesManager
{
/** The preference delimiter used for default and disabled templates */
private static String PREFERENCE_DELIMITER = ";"; //$NON-NLS-1$
/** The preference sub delimiter used for default templates */
private static String PREFERENCE_SUB_DELIMITER = ":"; //$NON-NLS-1$
/** The plugin's preference store */
private IPreferenceStore preferenceStore;
/** The list containing all the templates */
private List<Template> templatesList = new ArrayList<Template>();
/** The maps containing all the templates by their id */
private Map<String, Template> templatesByIdMap = new HashMap<String, Template>();
/** The maps containing all the templates by ObjectClassDescription */
private MultiValuedMap<ObjectClass, Template> templatesByStructuralObjectClassMap = new ArrayListValuedHashMap<>();
/** The list containing *only* the IDs of the disabled templates */
private List<String> disabledTemplatesList = new ArrayList<String>();
/** The map containing the default templates */
private Map<ObjectClass, String> defaultTemplatesMap = new HashMap<ObjectClass, String>();
/** The list of listeners */
private List<TemplatesManagerListener> listeners = new ArrayList<TemplatesManagerListener>();
/**
* Creates a new instance of TemplatesManager.
*
* @param preferenceStore
* the plugin's preference store
*/
public TemplatesManager( IPreferenceStore preferenceStore )
{
this.preferenceStore = preferenceStore;
loadDefaultTemplates();
loadDisabledTemplates();
loadTemplates();
setDefaultTemplates();
}
/**
* Adds a listener.
*
* @param listener
* the listener
* @return
* <code>true</code> (as per the general contract of the
* <code>Collection.add</code> method).
*/
public boolean addListener( TemplatesManagerListener listener )
{
return listeners.add( listener );
}
/**
* Removes a listener.
*
* @param listener
* the listener
* @return
* <code>true</code> if this templates manager contained
* the specified listener.
*/
public boolean removeListener( TemplatesManagerListener listener )
{
return listeners.remove( listener );
}
/**
* Fires a "fireTemplateAdded" event to all the listeners.
*
* @param template
* the added template
*/
private void fireTemplateAdded( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateAdded( template );
}
}
/**
* Fires a "templateRemoved" event to all the listeners.
*
* @param template
* the removed template
*/
private void fireTemplateRemoved( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateRemoved( template );
}
}
/**
* Fires a "templateEnabled" event to all the listeners.
*
* @param template
* the enabled template
*/
private void fireTemplateEnabled( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateEnabled( template );
}
}
/**
* Fires a "templateDisabled" event to all the listeners.
*
* @param template
* the disabled template
*/
private void fireTemplateDisabled( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateDisabled( template );
}
}
/**
* Loads the templates
*/
private void loadTemplates()
{
// Loading the templates added using the extension point
loadExtensionPointTemplates();
// Loading the templates added via files on the disk (added by the user)
loadFileTemplates();
}
/**
* Loads the templates added using the extension point.
*/
private void loadExtensionPointTemplates()
{
// Getting the extension point
IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(
"org.apache.directory.studio.templateeditor.templates" ); //$NON-NLS-1$
// Getting all the extensions
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
if ( members != null )
{
// For each extension: load the template
for ( int m = 0; m < members.length; m++ )
{
IConfigurationElement member = members[m];
// Getting the URL of the file associated with the extension
String contributorName = member.getContributor().getName();
String filePathInPlugin = member.getAttribute( "file" ); //$NON-NLS-1$
URL fileUrl = Platform.getBundle( contributorName ).getResource( filePathInPlugin );
// Checking if the URL is null
if ( filePathInPlugin == null )
{
// Logging the error
EntryTemplatePluginUtils.logError( new NullPointerException(), Messages
.getString( "TemplatesManager.AnErrorOccurredWhenParsingTheTemplate3Params" ), contributorName, //$NON-NLS-1$
filePathInPlugin, Messages.getString( "TemplatesManager.URLCreatedForTheTemplateIsNull" ) ); //$NON-NLS-1$
}
// Parsing the template and adding it to the templates list
try
{
InputStream is = fileUrl.openStream();
ExtensionPointTemplate template = TemplateIO.readAsExtensionPointTemplate( is );
templatesList.add( template );
templatesByIdMap.put( template.getId(), template );
templatesByStructuralObjectClassMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ), template );
is.close();
}
catch ( TemplateIOException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.AnErrorOccurredWhenParsingTheTemplate3Params" ), //$NON-NLS-1$
contributorName, filePathInPlugin, e.getMessage() );
}
catch ( IOException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.AnErrorOccurredWhenParsingTheTemplate3Params" ), contributorName, //$NON-NLS-1$
filePathInPlugin, e.getMessage() );
}
}
}
}
/**
* Loads the templates added via files on the disk (added by the user).
*/
private void loadFileTemplates()
{
// Getting the templates folder
File templatesFolder = getTemplatesFolder().toFile();
// If the templates folder does not exist, we exit
if ( !templatesFolder.exists() )
{
return;
}
// Loading the templates contained in the templates folder
String[] templateNames = templatesFolder.list( new FilenameFilter()
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".xml" ); //$NON-NLS-1$
}
} );
// If there are no templates available, we exit
if ( ( templateNames == null ) || ( templateNames.length == 0 ) )
{
return;
}
// Loading each template
for ( String templateName : templateNames )
{
// Creating the template file
File templateFile = new File( templatesFolder, templateName );
// Parsing the template and adding it to the templates list
try
{
InputStream is = new FileInputStream( templateFile );
FileTemplate template = TemplateIO.readAsFileTemplate( is );
templatesList.add( template );
templatesByIdMap.put( template.getId(), template );
templatesByStructuralObjectClassMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ), template );
is.close();
}
catch ( TemplateIOException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.AnErrorOccurredWhenParsingTheTemplate2Params" ), //$NON-NLS-1$
templateFile.getAbsolutePath(), e.getMessage() );
}
catch ( IOException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.AnErrorOccurredWhenParsingTheTemplate2Params" ), //$NON-NLS-1$
templateFile.getAbsolutePath(), e.getMessage() );
}
}
}
/**
* Adds a template from a file on the disk.
*
* @param templateFile
* the template file
* @return
* <code>true</code> if the template file has been successfully added,
* <code>false</code> if the template file has not been added
*/
public boolean addTemplate( File templateFile )
{
// Getting the file template
FileTemplate fileTemplate = getFileTemplate( templateFile );
if ( fileTemplate == null )
{
// If the file is not valid, we simply return
return false;
}
// Verifying if a template with a similar ID does not already exist
if ( templatesByIdMap.containsKey( fileTemplate.getId() ) )
{
// Logging the error
EntryTemplatePluginUtils.logError( null, Messages
.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseATemplateWithSameIDAlreadyExist" ), //$NON-NLS-1$
templateFile.getAbsolutePath() );
return false;
}
// Verifying the folder containing the templates already exists
// If not we create it
File templatesFolder = getTemplatesFolder().toFile();
if ( !templatesFolder.exists() )
{
// The folder does not exist, we need to create it.
templatesFolder.mkdirs();
}
// Copying the template in the plugin's folder
try
{
// Creating the file object where the template will be saved
File destinationFile = getTemplatesFolder().append( fileTemplate.getId() + ".xml" ).toFile(); //$NON-NLS-1$
// Checking if the file does not already exist
if ( destinationFile.exists() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages
.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseATemplateWithSameIDAlreadyExist" ), //$NON-NLS-1$
templateFile.getAbsolutePath() );
return false;
}
// Copying the file
EntryTemplatePluginUtils.copyFile( templateFile, destinationFile );
}
catch ( IOException e )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateFileCouldNotBeCopiedToThePluginsFolder" ), templateFile.getAbsolutePath() ); //$NON-NLS-1$
return false;
}
// Adding the template
templatesList.add( fileTemplate );
templatesByIdMap.put( fileTemplate.getId(), fileTemplate );
templatesByStructuralObjectClassMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( fileTemplate.getStructuralObjectClass() ), fileTemplate );
// Firing the event
fireTemplateAdded( fileTemplate );
return true;
}
/**
* Get the file template associate with the template file.
*
* @param templateFile
* the template file
* @return
* the associated file template
*/
private FileTemplate getFileTemplate( File templateFile )
{
// Checking if the file exists
if ( !templateFile.exists() )
{
// Logging the error
EntryTemplatePluginUtils.logError( null, Messages
.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseItDoesNotExist" ), templateFile //$NON-NLS-1$
.getAbsolutePath() );
return null;
}
// Checking if the file is readable
if ( !templateFile.canRead() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseItCantBeRead" ), templateFile.getAbsolutePath() ); //$NON-NLS-1$
return null;
}
// Trying to parse the template file
FileTemplate fileTemplate = null;
try
{
FileInputStream fis = new FileInputStream( templateFile );
fileTemplate = TemplateIO.readAsFileTemplate( fis );
}
catch ( FileNotFoundException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseOfTheFollowingError" ), templateFile //$NON-NLS-1$
.getAbsolutePath(), e.getMessage() );
return null;
}
catch ( TemplateIOException e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, Messages
.getString( "TemplatesManager.TheTemplateFileCouldNotBeAddedBecauseOfTheFollowingError" ), templateFile //$NON-NLS-1$
.getAbsolutePath(), e.getMessage() );
return null;
}
// Everything went fine, the file is valid
return fileTemplate;
}
/**
* Removes a template.
*
* @param fileTemplate
* the file template to remove
* @return
* <code>true</code> if the file template has been successfully removed,
* <code>false</code> if the template file has not been removed
*/
public boolean removeTemplate( FileTemplate fileTemplate )
{
// Checking if the file template is null
if ( fileTemplate == null )
{
return false;
}
// Checking if the file template exists in the templates set
if ( !templatesList.contains( fileTemplate ) )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateCouldNotBeRemovedBecauseOfTheFollowingError" ) //$NON-NLS-1$
+ Messages.getString( "TemplatesManager.TheTemplateDoesNotExistInTheTemplateManager" ), fileTemplate.getTitle(), fileTemplate //$NON-NLS-1$
.getId() );
return false;
}
// Creating the file object associated with the template
File templateFile = getTemplatesFolder().append( fileTemplate.getId() + ".xml" ).toFile(); //$NON-NLS-1$
// Checking if the file exists
if ( !templateFile.exists() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateCouldNotBeRemovedBecauseOfTheFollowingError" ) //$NON-NLS-1$
+ Messages.getString( "TemplatesManager.TheFileAssociatedWithTheTemplateCouldNotBeFoundAt" ), fileTemplate.getTitle(), //$NON-NLS-1$
fileTemplate.getId(), templateFile.getAbsolutePath() );
return false;
}
// Checking if the file can be written, and thus deleted
if ( !templateFile.canWrite() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateCouldNotBeRemovedBecauseOfTheFollowingError" ) //$NON-NLS-1$
+ Messages.getString( "TemplatesManager.TheFileAssociatedWithTheTemplateCanNotBeModified" ), fileTemplate.getTitle(), //$NON-NLS-1$
fileTemplate.getId(), templateFile.getAbsolutePath() );
return false;
}
// Deleting the file
if ( !templateFile.delete() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages.getString( "TemplatesManager.TheTemplateCouldNotBeRemovedBecauseOfTheFollowingError" ) //$NON-NLS-1$
+ Messages
.getString( "TemplatesManager.AnErrorOccurredWhenRemovingTheFileAssociatedWithTheTemplate" ), fileTemplate //$NON-NLS-1$
.getTitle(), fileTemplate.getId(), templateFile.getAbsolutePath() );
return false;
}
// Removing the template from the disabled templates files
disabledTemplatesList.remove( fileTemplate );
// Removing the template for the templates list
templatesList.remove( fileTemplate );
templatesByIdMap.remove( fileTemplate.getId() );
templatesByStructuralObjectClassMap.remove( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( fileTemplate.getStructuralObjectClass() ) );
// Firing the event
fireTemplateRemoved( fileTemplate );
return true;
}
/**
* Gets the templates.
*
* @return
* the templates
*/
public Template[] getTemplates()
{
return templatesList.toArray( new Template[0] );
}
/**
* Gets the templates folder.
*
* @return
* the templates folder
*/
private static IPath getTemplatesFolder()
{
return EntryTemplatePlugin.getDefault().getStateLocation().append( "templates" ); //$NON-NLS-1$
}
/**
* Loads the {@link List} of disabled templates from the preference store.
*/
private void loadDisabledTemplates()
{
StringTokenizer tokenizer = new StringTokenizer( preferenceStore
.getString( EntryTemplatePluginConstants.PREF_DISABLED_TEMPLATES ), PREFERENCE_DELIMITER );
while ( tokenizer.hasMoreTokens() )
{
disabledTemplatesList.add( tokenizer.nextToken() );
}
}
/**
* Saves the {@link List} of disabled templates to the preference store.
*/
private void saveDisabledTemplates()
{
StringBuffer sb = new StringBuffer();
for ( String disabledTemplateId : disabledTemplatesList )
{
sb.append( disabledTemplateId );
sb.append( PREFERENCE_DELIMITER );
}
preferenceStore.setValue( EntryTemplatePluginConstants.PREF_DISABLED_TEMPLATES, sb.toString() );
}
/**
* Enables the given template.
*
* @param template
* the template
*/
public void enableTemplate( Template template )
{
if ( disabledTemplatesList.contains( template.getId() ) )
{
// Removing the id of the template to the list of disabled templates
disabledTemplatesList.remove( template.getId() );
// Saving the disabled templates list
saveDisabledTemplates();
// Firing the event
fireTemplateEnabled( template );
}
}
/**
* Disables the given template.
*
* @param template
* the template
*/
public void disableTemplate( Template template )
{
if ( !disabledTemplatesList.contains( template.getId() ) )
{
// Adding the id of the template to the list of disabled templates
disabledTemplatesList.add( template.getId() );
// Saving the disabled templates list
saveDisabledTemplates();
// Firing the event
fireTemplateDisabled( template );
}
}
/**
* Indicates if the given template is enabled or not.
*
* @param template
* the template
* @return
* <code>true</code> if the template is enabled,
* <code>false</code> if the template is disabled
*/
public boolean isEnabled( Template template )
{
return !disabledTemplatesList.contains( template.getId() );
}
/**
* Loads the {@link Map} of default templates from the preference store.
*/
private void loadDefaultTemplates()
{
// Getting each default set
StringTokenizer tokenizer = new StringTokenizer( preferenceStore
.getString( EntryTemplatePluginConstants.PREF_DEFAULT_TEMPLATES ), PREFERENCE_DELIMITER );
while ( tokenizer.hasMoreTokens() )
{
String token = tokenizer.nextToken();
// Splitting the default set
String[] splittedToken = token.split( ":" ); //$NON-NLS-1$
if ( splittedToken.length == 2 )
{
// Adding the default template value
defaultTemplatesMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( splittedToken[0] ), splittedToken[1] );
}
}
}
/**
* Saves the {@link Map} of default templates to the preference store.
*/
private void saveDefaultTemplates()
{
StringBuffer sb = new StringBuffer();
for ( ObjectClass objectClassDescription : defaultTemplatesMap.keySet() )
{
sb.append( objectClassDescription.getNames().get( 0 ) );
sb.append( PREFERENCE_SUB_DELIMITER );
sb.append( defaultTemplatesMap.get( objectClassDescription ) );
sb.append( PREFERENCE_DELIMITER );
}
preferenceStore.setValue( EntryTemplatePluginConstants.PREF_DEFAULT_TEMPLATES, sb.toString() );
}
/**
* Sets the default templates.
*/
private void setDefaultTemplates()
{
for ( Template template : templatesList )
{
if ( isEnabled( template ) )
{
String structuralObjectClass = template.getStructuralObjectClass();
// Checking if a default template is defined
if ( defaultTemplatesMap.get( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( structuralObjectClass ) ) == null )
{
// Assigning this template as the default one
defaultTemplatesMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( structuralObjectClass ), template.getId() );
}
}
}
// Saving default templates
saveDefaultTemplates();
}
/**
* Sets the given template as default for its structural object class.
*
* @param template
* the template
*/
public void setDefaultTemplate( Template template )
{
if ( isEnabled( template ) )
{
// Removing the old value
defaultTemplatesMap.remove( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ) );
// Setting the new value
defaultTemplatesMap.put( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ), template.getId() );
// Saving default templates
saveDefaultTemplates();
}
}
/**
* Unsets the given template as default for its structural object class.
*
* @param template
* the template
*/
public void unSetDefaultTemplate( Template template )
{
if ( isDefaultTemplate( template ) )
{
defaultTemplatesMap.remove( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ) );
// Saving default template
saveDefaultTemplates();
}
}
/**
* Indicates if the given template is the default one
* for its structural object class or not.
*
* @param template
* the template
* @return
* <code>true</code> if the given template is the default one
* for its structural object class,
* <code>false</code> if not
*/
public boolean isDefaultTemplate( Template template )
{
String defaultTemplateID = defaultTemplatesMap.get( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ) );
if ( defaultTemplateID != null )
{
return defaultTemplateID.equalsIgnoreCase( template.getId() );
}
return false;
}
/**
* Indicates whether the given name or OID for an object class has a default template.
*
* @param nameOrOid
* the name or OID
* @return
* <code>true</code> if the given name or OID for an object class has a default template
*/
public boolean hasDefaultTemplate( String nameOrOid )
{
return getDefaultTemplate( nameOrOid ) != null;
}
/**
* Gets the default template associated with given name or OID for an object class.
*
* @param nameOrOid
* @return
* the default template associated with given name or OID for an object class,
* or <code>null</code> if there's no default template
*/
public Template getDefaultTemplate( String nameOrOid )
{
return getTemplateById( defaultTemplatesMap.get( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( nameOrOid ) ) );
}
/**
* Gets the template identified by the given ID.
*
* @param id
* the ID
* @return
* the template identified by the given ID
*/
private Template getTemplateById( String id )
{
return templatesByIdMap.get( id );
}
/**
* Gets the list of templates associated with the given name or OID for an object class.
*
* @param nameOrOid
* the name or OID
* @return
* the list of templates associated with the given name or OID for an object class
* or <code>null</code> if there's no associated template
*/
@SuppressWarnings("unchecked")
public List<Template> getTemplatesByObjectClass( String nameOrOid )
{
return ( List<Template> ) templatesByStructuralObjectClassMap.get( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( nameOrOid ) );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePlugin.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePlugin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import java.io.IOException;
import java.net.URL;
import java.util.PropertyResourceBundle;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EntryTemplatePlugin extends AbstractUIPlugin
{
/** The shared instance */
private static EntryTemplatePlugin plugin;
/** The plugin properties */
private PropertyResourceBundle properties;
/** The templates manager */
private TemplatesManager templatesManager;
/**
* The constructor
*/
public EntryTemplatePlugin()
{
}
/**
* {@inheritDoc}
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
plugin = this;
// Creating the templates manager
templatesManager = new TemplatesManager( getPreferenceStore() );
}
/**
* {@inheritDoc}
*/
public void stop( BundleContext context ) throws Exception
{
plugin = null;
super.stop( context );
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static EntryTemplatePlugin getDefault()
{
return plugin;
}
/**
* Gets the templates manager.
*
* @return
* the templates manager
*/
public TemplatesManager getTemplatesManager()
{
return templatesManager;
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* PluginConstants for the key.
*
* @param key
* The key (relative path to the image in filesystem)
* @return The image descriptor or null
*/
public ImageDescriptor getImageDescriptor( String key )
{
if ( key != null )
{
URL url = FileLocator.find( getBundle(), new Path( key ), null );
if ( url != null )
{
return ImageDescriptor.createFromURL( url );
}
else
{
return null;
}
}
else
{
return null;
}
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* PluginConstants for the key. A ImageRegistry is used to manage the
* the key->Image mapping.
* <p>
* Note: Don't dispose the returned SWT Image. It is disposed
* automatically when the plugin is stopped.
*
* @param key The key (relative path to the image in filesystem)
* @return The SWT Image or null
*/
public Image getImage( String key )
{
Image image = getImageRegistry().get( key );
if ( image == null )
{
ImageDescriptor id = getImageDescriptor( key );
if ( id != null )
{
image = id.createImage();
getImageRegistry().put( key, image );
}
}
return image;
}
/**
* Gets the plugin properties.
*
* @return
* the plugin properties
*/
public PropertyResourceBundle getPluginProperties()
{
if ( properties == null )
{
try
{
properties = new PropertyResourceBundle( FileLocator.openStream( this.getBundle(), new Path(
"plugin.properties" ), false ) ); //$NON-NLS-1$
}
catch ( IOException e )
{
// We can't use the PLUGIN_ID constant since loading the plugin.properties file has failed,
// So we're using a default plugin id.
getLog().log( new Status( Status.ERROR, "org.apache.directory.studio.templateeditor", Status.OK, //$NON-NLS-1$
Messages.getString( "EntryTemplatePlugin.UnableToGetPluginProperties" ), e ) ); //$NON-NLS-1$
}
}
return properties;
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/TemplatesManagerListener.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/TemplatesManagerListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This interface defines a listener for the templates manager events.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface TemplatesManagerListener
{
/**
* This method is fired when a file template is added to the
* templates manager.
*
* @param template
* the added template
*/
void templateAdded( Template template );
/**
* This method is fired when a file template is removed from the
* templates manager.
*
* @param template
* the removed template
*/
void templateRemoved( Template template );
/**
* This method is fired when a template is enabled.
*
* @param template
* the enabled template
*/
void templateEnabled( Template template );
/**
* This method is fired when a template is disabled.
*
* @param template
* the disabled template
*/
void templateDisabled( Template template );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/PreferenceInitializer.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/PreferenceInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* This class initializes the preferences of the plugin.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer
{
/**
* {@inheritDoc}
*/
public void initializeDefaultPreferences()
{
IPreferenceStore store = EntryTemplatePlugin.getDefault().getPreferenceStore();
// Preferences
store.setDefault( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION,
EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS );
store.setDefault( EntryTemplatePluginConstants.PREF_DISABLED_TEMPLATES, "" ); //$NON-NLS-1$
store.setDefault( EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR,
EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR_ENTRIES_WITH_TEMPLATE );
// Dialogs
store.setDefault( EntryTemplatePluginConstants.DIALOG_IMPORT_TEMPLATES, System.getProperty( "user.home" ) ); //$NON-NLS-1$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePluginUtils.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePluginUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.api.ldap.model.schema.ObjectClassTypeEnum;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.eclipse.core.runtime.Status;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This class is a helper class for the Entry Template plugin.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EntryTemplatePluginUtils
{
/** The line separator */
public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); //$NON-NLS-1$
/** The default schema */
private static final Schema DEFAULT_SCHEMA = Schema.DEFAULT_SCHEMA;
/**
* Logs the given message and exception with the ERROR status level.
*
* @param exception
* the exception, can be <code>null</code>
* @param message
* the message
* @param args
* the arguments to use when formatting the message
*/
public static void logError( Throwable exception, String message, Object... args )
{
EntryTemplatePlugin.getDefault().getLog().log(
new Status( Status.ERROR, EntryTemplatePlugin.getDefault().getBundle().getSymbolicName(), Status.OK,
MessageFormat.format( message, args ), exception ) );
}
/**
* Logs the given message and exception with the WARNING status level.
*
* @param exception
* the exception, can be <code>null</code>
* @param message
* the message
* @param args
* the arguments to use when formatting the message
*/
public static void logWarning( Throwable exception, String message, Object... args )
{
EntryTemplatePlugin.getDefault().getLog().log(
new Status( Status.WARNING, EntryTemplatePlugin.getDefault().getBundle().getSymbolicName(), Status.OK,
MessageFormat.format( message, args ), exception ) );
}
/**
* Logs the given message and exception with the INFO status level.
*
* @param exception
* the exception, can be <code>null</code>
* @param message
* the message
* @param args
* the arguments to use when formatting the message
*/
public static void logInfo( Throwable exception, String message, Object... args )
{
EntryTemplatePlugin.getDefault().getLog().log(
new Status( Status.INFO, EntryTemplatePlugin.getDefault().getBundle().getSymbolicName(), Status.OK,
MessageFormat.format( message, args ), exception ) );
}
/**
* Logs the given message and exception with the OK status level.
*
* @param exception
* the exception, can be <code>null</code>
* @param message
* the message
* @param args
* the arguments to use when formatting the message
*/
public static void logOk( Throwable exception, String message, Object... args )
{
EntryTemplatePlugin.getDefault().getLog().log(
new Status( Status.OK, EntryTemplatePlugin.getDefault().getBundle().getSymbolicName(), Status.OK,
MessageFormat.format( message, args ), exception ) );
}
/**
* Copies a file from the given streams.
*
* @param source
* the source file
* @param destination
* the destination file
* @throws IOException
* if an error occurs when copying the file
*/
public static void copyFile( File source, File destination ) throws IOException
{
copyFile( new FileInputStream( source ), new FileOutputStream( destination ) );
}
/**
* Copies the input stream to the output stream.
*
* @param inputStream
* the input stream
* @param outputStream
* the output stream
* @throws IOException
* if an error occurs when copying the stream
*/
public static void copyFile( InputStream inputStream, OutputStream outputStream ) throws IOException
{
byte[] buf = new byte[1024];
int i = 0;
while ( ( i = inputStream.read( buf ) ) != -1 )
{
outputStream.write( buf, 0, i );
}
}
/**
* Gets a list of templates matching the given entry.
*
* @param entry
* the entry
* @return
* a list of templates matching the given entry
*/
public static List<Template> getMatchingTemplates( IEntry entry )
{
if ( entry != null )
{
// Looking for the highest (most specialized one) structural object class in the entry
ObjectClass highestStructuralObjectClass = getHighestStructuralObjectClassFromEntry( entry );
if ( highestStructuralObjectClass != null )
{
// We were able to determine the highest object class in the entry.
// Based on that information, we will use the entry's schema to retrieve the list of matching templates
return getTemplatesFromHighestObjectClass( highestStructuralObjectClass, entry.getBrowserConnection()
.getSchema() );
}
else
{
// We were not able to determine the highest object class in the entry.
// This means that either the schema information we received from the server is not sufficient,
// or the list of object classes in the entry is not complete.
// In that case we can't use the schema information to determine the list of templates.
// Instead we're going to gather all the templates associated with each object class description.
return getTemplatesFromObjectClassDescriptions( entry.getObjectClassDescriptions() );
}
}
return new ArrayList<Template>();
}
/**
* Gets the highest (most specialized one) object class description of the given entry
* if it can be found, or <code>null</code> if not.
*
* @param entry
* the entry
* @return
* the highest object class description of the given entry if it can be found,
* or <code>null</code> if not
*/
private static ObjectClass getHighestStructuralObjectClassFromEntry( IEntry entry )
{
if ( entry != null )
{
if ( ( entry.getBrowserConnection() != null ) && ( entry.getBrowserConnection().getSchema() != null ) )
{
// Getting the schema from the entry
Schema schema = entry.getBrowserConnection().getSchema();
// Getting object class descriptions
Collection<ObjectClass> objectClassDescriptions = entry.getObjectClassDescriptions();
if ( objectClassDescriptions != null )
{
// Creating the candidates list based on the initial list
List<ObjectClass> candidatesList = new ArrayList<ObjectClass>();
// Adding each structural object class description to the list
for ( ObjectClass objectClassDescription : objectClassDescriptions )
{
if ( objectClassDescription.getType() == ObjectClassTypeEnum.STRUCTURAL )
{
candidatesList.add( objectClassDescription );
}
}
// Looping on the given collection of ObjectClassDescription until the end of the list,
// or until the candidates list is reduced to one.
Iterator<ObjectClass> iterator = objectClassDescriptions.iterator();
while ( ( candidatesList.size() > 1 ) && ( iterator.hasNext() ) )
{
ObjectClass ocd = iterator.next();
removeSuperiors( ocd, candidatesList, schema );
}
// Looking if we've found the highest object class description
if ( candidatesList.size() == 1 )
{
return candidatesList.get( 0 );
}
}
}
}
return null;
}
/**
* Recursively removes superiors of the given object class description from the list.
*
* @param ocd
* the object class description
* @param ocdList
* the list of object class description
* @param schema
* the schema
*/
private static void removeSuperiors( ObjectClass ocd, List<ObjectClass> ocdList, Schema schema )
{
if ( ocd != null )
{
for ( String superior : ocd.getSuperiorOids() )
{
// Getting the ObjectClassDescription associated with the superior
ObjectClass superiorOcd = getObjectClass( superior, schema );
// Removing it from the list and recursively removing its superiors
ocdList.remove( superiorOcd );
removeSuperiors( superiorOcd, ocdList, schema );
}
}
}
/**
* Gets the list of matching templates for the given object class description.
* <p>
* To do this, we're using a "Breadth First Search" algorithm to go through all
* the superiors (and the superiors of these superiors, etc.).
*
* @param objectClassDescription
* the object class description
* @param schema
* the associated schema
* @return
* the list of matching templates for the given object class description
*/
private static List<Template> getTemplatesFromHighestObjectClass( ObjectClass objectClassDescription,
Schema schema )
{
// Creating a set to hold all the matching templates
List<Template> matchingTemplates = new ArrayList<Template>();
// Getting the templates manager
TemplatesManager manager = EntryTemplatePlugin.getDefault().getTemplatesManager();
// Getting the list of all the available templates
Template[] templates = manager.getTemplates();
// Creating a MultiValueMap that holds the templates ordered by ObjectClassDescription object
MultiValuedMap<ObjectClass, Template> templatesByOcd = new ArrayListValuedHashMap<>();
// Populating this map
for ( Template template : templates )
{
templatesByOcd.put( getObjectClass( template.getStructuralObjectClass(), schema ), template );
}
// Initializing the LIFO queue with the highest ObjectClassDescription object
LinkedList<ObjectClass> ocdQueue = new LinkedList<ObjectClass>();
ocdQueue.add( objectClassDescription );
// Looking if we need to test a new ObjectClassDescription object
while ( !ocdQueue.isEmpty() )
{
// Dequeuing the last object for testing
ObjectClass currentOcd = ocdQueue.removeLast();
// Adds the templates for the current object class description to the list of matching templates
addTemplatesForObjectClassDescription( currentOcd, matchingTemplates, manager );
// Adding each superior object to the queue
List<String> currentOcdSups = currentOcd.getSuperiorOids();
if ( currentOcdSups != null )
{
for ( String currentOcdSup : currentOcdSups )
{
ocdQueue.addFirst( getObjectClass( currentOcdSup, schema ) );
}
}
}
return matchingTemplates;
}
/**
* Gets the list of matching templates for the given object class descriptions.
*
* @param objectClasses
* the object classes
* @return
* the list of matching templates for the given object class description
*/
private static List<Template> getTemplatesFromObjectClassDescriptions(
Collection<ObjectClass> objectClasses )
{
if ( objectClasses != null )
{
// Creating a set to hold all the matching templates
List<Template> matchingTemplates = new ArrayList<Template>();
// Getting the templates manager
TemplatesManager manager = EntryTemplatePlugin.getDefault().getTemplatesManager();
for ( ObjectClass objectClassDescription : objectClasses )
{
// Adds the templates for the current object class description to the list of matching templates
addTemplatesForObjectClassDescription( objectClassDescription, matchingTemplates, manager );
}
return matchingTemplates;
}
return null;
}
/**
* Adds the templates found for the given object class description to the given templates set.
*
* @param ocd
* the object class description
* @param matchingTemplates
* the list of matching templates
* @param manager
* the manager
*/
private static void addTemplatesForObjectClassDescription( ObjectClass ocd,
List<Template> matchingTemplates, TemplatesManager manager )
{
// Creating a list of containing the names and OID of the current ObjectClassDescription object
List<String> namesAndOid = new ArrayList<String>();
for ( String name : ocd.getNames() )
{
namesAndOid.add( name );
}
String currentOcdOid = ocd.getOid();
if ( ( currentOcdOid != null ) && ( !"".equals( currentOcdOid ) ) ) //$NON-NLS-1$
{
namesAndOid.add( currentOcdOid );
}
// Looping on the names and OID to find all corresponding templates
for ( String nameOrOid : namesAndOid )
{
// Getting the default template and complete list of templates for the given name or OID
Template currentOcdDefaultTemplate = manager.getDefaultTemplate( nameOrOid );
List<Template> currentOcdTemplates = manager.getTemplatesByObjectClass( nameOrOid );
// Adding the default template
if ( currentOcdDefaultTemplate != null )
{
if ( !matchingTemplates.contains( currentOcdDefaultTemplate ) )
{
matchingTemplates.add( currentOcdDefaultTemplate );
}
}
// Adding the other templates
if ( currentOcdTemplates != null )
{
for ( Template template : currentOcdTemplates )
{
// Adding the template only if it is different from the default one (which is already added)
if ( ( !template.equals( currentOcdDefaultTemplate ) ) && ( manager.isEnabled( template ) )
&& ( !matchingTemplates.contains( template ) ) )
{
matchingTemplates.add( template );
}
}
}
}
}
/**
* Gets the object class description of the given name or OID found in the default schema.
* <p>
* If no object class description is found in the default schema, a new object class description
* is created with the given name or OID and returned.
*
* @param nameOrOid
* the name or OID
* @return
* the object class description of the given name or OID found in the default schema,
* or a new object class description created with the given name or OID if none can be found
*/
public static ObjectClass getObjectClassDescriptionFromDefaultSchema( String nameOrOid )
{
return getObjectClass( nameOrOid, DEFAULT_SCHEMA );
}
/**
* Gets the object class description of the given name or OID found in the given schema.
* <p>
* If no object class description is found in the given schema, a new object class description
* is created with the given name or OID and returned.
*
* @param nameOrOid
* the name or OID
* @param schema
* the schema
* @return
* the object class description of the given name or OID found in the given schema,
* or a new object class description created with the given name or OID if none can be found
*/
private static ObjectClass getObjectClass( String nameOrOid, Schema schema )
{
ObjectClass ocd = null;
// Looking for the object class description in the given schema
if ( schema != null )
{
ocd = schema.getObjectClassDescription( nameOrOid );
}
// Creating a new object class description if none could be found in the given schema
if ( ocd == null )
{
ocd = new ObjectClass( null );
ocd.setNames( Arrays.asList( new String[]
{ nameOrOid.toLowerCase() } ) );
}
return ocd;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePluginConstants.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/EntryTemplatePluginConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor;
/**
* This interface contains all the Constants used in the Plugin.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface EntryTemplatePluginConstants
{
/** The plug-in ID */
String PLUGIN_ID = EntryTemplatePluginConstants.class.getPackage().getName();
// Images
String IMG_EXPORT_TEMPLATES_WIZARD = "resources/icons/export_templates_wizard.gif"; //$NON-NLS-1$
String IMG_FILE = "resources/icons/file.gif"; //$NON-NLS-1$
String IMG_IMPORT_TEMPLATES_WIZARD = "resources/icons/import_templates_wizard.gif"; //$NON-NLS-1$
String IMG_NO_IMAGE = "resources/icons/no_image.gif"; //$NON-NLS-1$
String IMG_OBJECT_CLASS = "resources/icons/object_class.png"; //$NON-NLS-1$
String IMG_SWITCH_TEMPLATE = "resources/icons/switch_template.gif"; //$NON-NLS-1$
String IMG_TEMPLATE = "resources/icons/template.gif"; //$NON-NLS-1$
String IMG_TEMPLATE_DISABLED = "resources/icons/template_disabled.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_ADD_VALUE = "resources/icons/toolbar_add_value.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_BROWSE_FILE = "resources/icons/toolbar_browse_file.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_BROWSE_IMAGE = "resources/icons/toolbar_browse_image.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_CLEAR = "resources/icons/toolbar_clear.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_DELETE_VALUE = "resources/icons/toolbar_delete_value.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_EDIT_PASSWORD = "resources/icons/toolbar_edit_password.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_EDIT_DATE = "resources/icons/toolbar_edit_date.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_EDIT_VALUE = "resources/icons/toolbar_edit_value.gif"; //$NON-NLS-1$
String IMG_TOOLBAR_SAVE_AS = "resources/icons/toolbar_save_as.gif"; //$NON-NLS-1$
// Preferences
String PREF_TEMPLATE_ENTRY_EDITOR_PAGE_ID = "org.apache.directory.studio.templateeditor.view.preferences.TemplateEntryEditorPreferencePage"; //$NON-NLS-1$
String PREF_TEMPLATES_PRESENTATION = PLUGIN_ID + ".prefs.TemplatesPresentation"; //$NON-NLS-1$
int PREF_TEMPLATES_PRESENTATION_TEMPLATE = 1;
int PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS = 2;
String PREF_DISABLED_TEMPLATES = PLUGIN_ID + ".prefs.DisabledTemplates"; //$NON-NLS-1$
String PREF_USE_TEMPLATE_EDITOR_FOR = PLUGIN_ID + ".prefs.UseTemplateEditorFor"; //$NON-NLS-1$
int PREF_USE_TEMPLATE_EDITOR_FOR_ANY_ENTRY = 1;
int PREF_USE_TEMPLATE_EDITOR_FOR_ENTRIES_WITH_TEMPLATE = 2;
String PREF_DEFAULT_TEMPLATES = PLUGIN_ID + ".prefs.DefaultTemplates"; //$NON-NLS-1$
// Dialogs
String DIALOG_IMPORT_TEMPLATES = PLUGIN_ID + ".dialog.ImportTemplates"; //$NON-NLS-1$
String DIALOG_EXPORT_TEMPLATES = PLUGIN_ID + ".dialog.ExportTemplates"; //$NON-NLS-1$
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/FileTemplate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/FileTemplate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model;
import java.io.File;
/**
* This class implements a template based on a file (i.e. stored on the disk in the plugin's folder).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FileTemplate extends AbstractTemplate
{
/** The associated file */
private File file;
/**
* Gets the file.
*
* @return
* the file
*/
public File getFile()
{
return file;
}
/**
* Sets the file.
*
* @param file
* the file
*/
public void setFile( File file )
{
this.file = file;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/Template.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/Template.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model;
import java.util.List;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateForm;
/**
* This interface defines a template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface Template
{
/**
* Adds an auxiliary object class.
*
* @param objectClass
* the auxiliary object class
* @return
* <code>true</code> if the template did not already contain the
* specified element.
*/
boolean addAuxiliaryObjectClass( String objectClass );
/**
* Gets the auxiliary object classes.
*
* @return
* the auxiliary object classes
*/
List<String> getAuxiliaryObjectClasses();
/**
* Gets the form.
*
* @return
* the form
*/
TemplateForm getForm();
/**
* Gets the ID.
*
* @return
* the ID
*/
String getId();
/**
* Gets the structural object class.
*
* @return
* the structural object class
*/
String getStructuralObjectClass();
/**
* Gets the title.
*
* @return
* the title
*/
String getTitle();
/**
* Removes an auxiliary object class.
*
* @param objectClass
* the auxiliary object class
* @return
* <code>true</code> if the template contained the specified element.
*/
boolean removeAuxiliaryObjectClass( String objectClass );
/**
* Sets the auxiliary object classes.
*
* @param objectClasses
* the auxiliary object classes
*/
void setAuxiliaryObjectClasses( List<String> objectClasses );
/**
* Sets the form.
*
* @param form
* the form
*/
void setForm( TemplateForm form );
/**
* Sets the ID.
*
* @param id
* the ID
*/
void setId( String id );
/**
* Sets the structural object class.
*
* @param objectClass
* the structural object class
*/
void setStructuralObjectClass( String objectClass );
/**
* Sets the title.
*
* @param title
* the title
*/
void setTitle( String title );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.model.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/AbstractTemplate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/AbstractTemplate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateForm;
/**
* This abstract class defines the basic implementation for a template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractTemplate implements Template
{
/**
* Indicates if the ID is valid or not.
*
* @param id
* the id
* @return
* <code>true</code> if the ID is valid,
* <code>false</code> if not.
*/
public static boolean isValidId( String id )
{
return Pattern.matches( "[a-zA-Z][a-zA-Z0-9-.]*", id ); //$NON-NLS-1$
}
/** The ID */
private String id;
/** The title */
private String title;
/** The structural object class */
private String structuralObjectClass;
/** The list of auxiliary object classes */
private List<String> auxiliaryObjectClasses;
/** The form */
private TemplateForm form;
/**
* Creates a new instance of AbstractTemplate.
*/
public AbstractTemplate()
{
init();
}
/**
* Creates a new instance of AbstractTemplate.
*
* @param id
* the id of the template
*/
public AbstractTemplate( String id )
{
this.id = id;
init();
}
/**
* {@inheritDoc}
*/
public boolean addAuxiliaryObjectClass( String objectClass )
{
return auxiliaryObjectClasses.add( objectClass );
}
/**
* {@inheritDoc}
*/
public List<String> getAuxiliaryObjectClasses()
{
return auxiliaryObjectClasses;
}
/**
* {@inheritDoc}
*/
public TemplateForm getForm()
{
return form;
}
/**
* {@inheritDoc}
*/
public String getId()
{
return id;
}
/**
* Gets the structural object class.
*
* @return
* the structural object class
*/
public String getStructuralObjectClass()
{
return structuralObjectClass;
}
/**
* {@inheritDoc}
*/
public String getTitle()
{
return title;
}
/**
* Initializes the fields of the AbstractTemplate.
*/
private void init()
{
auxiliaryObjectClasses = new ArrayList<String>();
}
/**
* {@inheritDoc}
*/
public boolean removeAuxiliaryObjectClass( String objectClass )
{
return auxiliaryObjectClasses.remove( objectClass );
}
/**
* {@inheritDoc}
*/
public void setAuxiliaryObjectClasses( List<String> objectClasses )
{
this.auxiliaryObjectClasses = objectClasses;
}
/**
* {@inheritDoc}
*/
public void setForm( TemplateForm form )
{
this.form = form;
}
/**
* {@inheritDoc}
*/
public void setId( String id )
{
this.id = id;
}
/**
* Sets the structural object class.
*
* @param objectClass
* the structural object class
*/
public void setStructuralObjectClass( String objectClass )
{
structuralObjectClass = objectClass;
}
/**
* {@inheritDoc}
*/
public void setTitle( String title )
{
this.title = title;
}
/**
* {@inheritDoc}
*/
public String toString()
{
return ( title == null ) ? Messages.getString( "AbstractTemplate.UntitledTemplate" ) : title; //$NON-NLS-1$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/ExtensionPointTemplate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/ExtensionPointTemplate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model;
/**
* This class implements a template based on an extension point implementation
* (i.e. defined in the plugin.xml file of a plugin).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ExtensionPointTemplate extends AbstractTemplate
{
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateComposite.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateComposite.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template composite.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateComposite extends AbstractTemplateWidget
{
/** The default number of columns value */
public static int DEFAULT_NUMBER_OF_COLUMNS = 1;
/** The default equal columns value */
public static boolean DEFAULT_EQUAL_COLUMNS = false;
/** The number of columns of the layout */
private int numberOfColumns = DEFAULT_NUMBER_OF_COLUMNS;
/** The flag indicating if all columns are equal in width size */
private boolean equalColumns = DEFAULT_EQUAL_COLUMNS;
/**
* Creates a new instance of TemplateComposite.
*
* @param parent
* the parent element
*/
public TemplateComposite( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the number of columns.
*
* @return
* the number of columns
*/
public int getNumberOfColumns()
{
return numberOfColumns;
}
/**
* Indicates if the columns are equals in width.
*
* @return
* <code>true</code> if the columns are equals in width,
* <code>false</code> if not
*/
public boolean isEqualColumns()
{
return equalColumns;
}
/**
* Sets the flag that indicates if the columns are equals in width.
*
* @param equalColumns
* the flag that indicates if the columns are equals in width
*/
public void setEqualColumns( boolean equalColumns )
{
this.equalColumns = equalColumns;
}
/**
* Sets the number of columns.
*
* @param numberOfColumns
* the number of columns
*/
public void setNumberOfColumns( int numberOfColumns )
{
this.numberOfColumns = numberOfColumns;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateRadioButtons.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateRadioButtons.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements templates radio buttons.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateRadioButtons extends AbstractTemplateWidget
{
/** The default enabled value */
public static boolean DEFAULT_ENABLED = true;
/** The enable flag */
private boolean enabled = DEFAULT_ENABLED;
/** The list of buttons */
private List<ValueItem> buttons = new ArrayList<ValueItem>();
/**
* Creates a new instance of TemplateRadioButtons.
*
* @param parent
* the parent element
*/
public TemplateRadioButtons( TemplateWidget parent )
{
super( parent );
}
/**
* Adds a button.
*
* @param button
* the button
* @return
* <code>true</code> if the radio buttons did not already
* contain the specified element.
*/
public boolean addButton( ValueItem button )
{
return buttons.add( button );
}
/**
* Gets the buttons.
*
* @return
* the buttons
*/
public List<ValueItem> getButtons()
{
return buttons;
}
/**
* Indicates if the the checkbox is enabled.
*
* @return
* <code>true</code> if the checkbox is enabled,
* <code>false</code> if the checkbox is disabled
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Sets the buttons.
*
* @param buttons
* the buttons
*/
public void setButtons( List<ValueItem> buttons )
{
this.buttons = buttons;
}
/**
* Enables or disables the checkbox.
*
* @param enabled
* <code>true</code> if the checkbox is enabled,
* <code>false</code> if the checkbox is disabled
*/
public void setEnabled( boolean enabled )
{
this.enabled = enabled;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateSpinner.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateSpinner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template spinner.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateSpinner extends AbstractTemplateWidget
{
/** The default minimum value */
public static int DEFAULT_MINIMUM = Integer.MIN_VALUE;
/** The default maximum value */
public static int DEFAULT_MAXIMUM = Integer.MAX_VALUE;
/** The default increment value */
public static int DEFAULT_INCREMENT = 1;
/** The default page increment value */
public static int DEFAULT_PAGE_INCREMENT = 10;
/** The default digits value */
public static int DEFAULT_DIGITS = 0;
/** The minimum value */
private int minimum = DEFAULT_MINIMUM;
/** The maximum value */
private int maximum = DEFAULT_MAXIMUM;
/** The increment */
private int increment = DEFAULT_INCREMENT;
/** The page increment */
private int pageIncrement = DEFAULT_PAGE_INCREMENT;
/** The number of decimal places */
private int digits = DEFAULT_DIGITS;
/**
* Creates a new instance of TemplateSpinner.
*
* @param parent
* the parent element
*/
public TemplateSpinner( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the increment.
*
* @return
* the increment
*/
public int getIncrement()
{
return increment;
}
/**
* Gets the maximum.
*
* @return
* the maximum
*/
public int getMaximum()
{
return maximum;
}
/**
* Gets the minimum.
*
* @return
* the minimum
*/
public int getMinimum()
{
return minimum;
}
/**
* Gets the page increment.
*
* @return
* the page increment
*/
public int getPageIncrement()
{
return pageIncrement;
}
/**
* Sets the increment.
*
* @param increment
* the increment
*/
public void setIncrement( int increment )
{
this.increment = increment;
}
/**
* Sets the maximum.
*
* @param maximum
* the maximum
*/
public void setMaximum( int maximum )
{
this.maximum = maximum;
}
/**
* Sets the minimum.
*
* @param minimum
* the minimum
*/
public void setMinimum( int minimum )
{
this.minimum = minimum;
}
/**
* Sets the page increment.
*
* @param pageIncrement
* the page increment
*/
public void setPageIncrement( int pageIncrement )
{
this.pageIncrement = pageIncrement;
}
/**
* Sets the number of decimal places.
*
* @param digits
* the number of decimal places
*/
public void setDigits( int digits )
{
this.digits = digits;
}
/**
* Gets the number of decimal places.
*
* @return
* the number of decimal places
*/
public int getDigits()
{
return digits;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/ValueItem.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/ValueItem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a value item. A value item is composed of a value and
* eventually a label.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ValueItem
{
/** The label */
private String label;
/** The value */
private Object value;
/**
* Creates a new instance of ValueItem.
*/
public ValueItem()
{
}
/**
* Creates a new instance of ValueItem.
*
* @param label
* the label
*/
public ValueItem( String label )
{
this.label = label;
}
/**
* Creates a new instance of ValueItem.
*
* @param value
* the value
*/
public ValueItem( Object value )
{
this.value = value;
}
/**
* Creates a new instance of ValueItem.
*
* @param label
* the label
* @param value
* the value
*/
public ValueItem( String label, Object value )
{
this.label = label;
this.value = value;
}
/**
* Gets the label.
*
* @return
* the label
*/
public String getLabel()
{
return label;
}
/**
* Sets the label.
*
* @param label
* the label
*/
public void setLabel( String label )
{
this.label = label;
}
/**
* Gets the value.
*
* @return
* the value
*/
public Object getValue()
{
return value;
}
/**
* Sets the value.
*
* @param value
* the value
*/
public void setValue( Object value )
{
this.value = value;
}
/**
* {@inheritDoc}
*/
public boolean equals( Object obj )
{
if ( obj instanceof ValueItem )
{
ValueItem comparisonObject = ( ValueItem ) obj;
// Comparing the label
if ( ( getLabel() != null ) && ( comparisonObject.getLabel() != null ) )
{
if ( !getLabel().equals( comparisonObject.getLabel() ) )
{
return false;
}
}
// Comparing the value
if ( ( getValue() != null ) && ( comparisonObject.getValue() != null ) )
{
if ( !getValue().equals( comparisonObject.getValue() ) )
{
return false;
}
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public int hashCode()
{
int result = 17;
// The label
if ( getLabel() != null )
{
result = 37 * result + getLabel().hashCode();
}
// The value
if ( getValue() != null )
{
result = 37 * result + getValue().hashCode();
}
return result;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/WidgetAlignment.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/WidgetAlignment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This enum contains all the possible values for the alignment of a widget.
* <ul>
* <li>NONE, for no alignment (usually used as default value)</li>
* <li>BEGINNING, for alignment on the left when used horizontally and
* alignment on the top when used vertically</li>
* <li>CENTER, for centered alignment when used horizontally and vertically</li>
* <li>END, for alignment on the right when used horizontally and
* alignment on the bottom when used vertically</li>
* <li>FILL, for alignment taking the whole space when used horizontally and
* vertically</li>
* </ul>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public enum WidgetAlignment
{
NONE, BEGINNING, CENTER, END, FILL
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateLink.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateLink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template link.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateLink extends AbstractTemplateWidget
{
/** The default value value */
public static String DEFAULT_VALUE = null;
/** The label value */
private String value = DEFAULT_VALUE;
/**
* Creates a new instance of TemplateLink.
*
* @param parent
* the parent element
*/
public TemplateLink( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the value.
*
* @return
* the value
*/
public String getValue()
{
return value;
}
/**
* Sets the value.
*
* @param value
* the value
*/
public void setValue( String value )
{
this.value = value;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateForm.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateForm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template form.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateForm extends AbstractTemplateWidget
{
/**
* Creates a new instance of TemplateForm.
*/
public TemplateForm()
{
// A template form has no parent
super( null );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateTextField.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateTextField.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template text field.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateTextField extends AbstractTemplateWidget
{
/** The default number of rows value */
public static int DEFAULT_NUMBER_OF_ROWS = 1;
/** The default characters limit value */
public static int DEFAULT_CHARACTERS_LIMIT = -1;
/** The default dollar sign is new line value */
public static boolean DEFAULT_DOLLAR_SIGN_IS_NEW_LINE = false;
/** The number of rows */
private int numberOfRows = DEFAULT_NUMBER_OF_ROWS;
/** The characters limit */
private int charactersLimit = DEFAULT_CHARACTERS_LIMIT;
/** The flag which indicates if dollar sign ('$') is to be interpreted as a new line */
private boolean dollarSignIsNewLine = DEFAULT_DOLLAR_SIGN_IS_NEW_LINE;
/**
* Creates a new instance of TemplateTextField.
*
* @param parent
* the parent element
*/
public TemplateTextField( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the characters limit.
*
* @return
* the characters limit
*/
public int getCharactersLimit()
{
return charactersLimit;
}
/**
* Gets the number of rows.
*
* @return
* the number of rows
*/
public int getNumberOfRows()
{
return numberOfRows;
}
/**
* Indicates if dollar sign ('$') is to be interpreted as a new line.
*
* @return
* <code>true</code> if dollar sign ('$') is to be interpreted as a new line,
* <code>false</code> if not
*/
public boolean isDollarSignIsNewLine()
{
return dollarSignIsNewLine;
}
/**
* Sets the characters limit.
*
* @param charactersLimit
* the characters limit
*/
public void setCharactersLimit( int charactersLimit )
{
this.charactersLimit = charactersLimit;
}
/**
* Sets the flag which indicates if dollar sign ('$') is to be interpreted as a new line.
*
* @param dollarSignIsNewLine
* <code>true</code> if dollar sign ('$') is to be interpreted as a new line,
* <code>false</code> if not
*/
public void setDollarSignIsNewLine( boolean dollarSignIsNewLine )
{
this.dollarSignIsNewLine = dollarSignIsNewLine;
}
/**
* Sets the number of rows.
*
* @param numberOfRows
* the number of rows
*/
public void setNumberOfRows( int numberOfRows )
{
this.numberOfRows = numberOfRows;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateSection.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateSection.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template section.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateSection extends AbstractTemplateWidget
{
/** The default number of columns value */
public static int DEFAULT_NUMBER_OF_COLUMNS = 1;
/** The default equals columns value */
public static boolean DEFAULT_EQUAL_COLUMNS = false;
/** The default expandable value */
public static boolean DEFAULT_EXPANDABLE = false;
/** The default expanded value */
public static boolean DEFAULT_EXPANDED = true;
/** The default title value */
public static String DEFAULT_TITLE = null;
/** The default description value */
public static String DEFAULT_DESCRIPTION = null;
/** The number of columns of the layout */
private int numberOfColumns = DEFAULT_NUMBER_OF_COLUMNS;
/** The flag indicating if all columns are equal in width size */
private boolean equalColumns = DEFAULT_EQUAL_COLUMNS;
/** The flag indicating if the section is expandable */
private boolean expandable = DEFAULT_EXPANDABLE;
/** The flag indicating if the section is expanded */
private boolean expanded = DEFAULT_EXPANDED;
/** The title */
private String title = DEFAULT_TITLE;
/** The description */
private String description = DEFAULT_DESCRIPTION;
/**
* Creates a new instance of TemplateSection.
*
* @param parent
* the parent element
*/
public TemplateSection( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the description.
*
* @return
* the description
*/
public String getDescription()
{
return description;
}
/**
* Gets the number of columns.
*
* @return
* the number of columns
*/
public int getNumberOfColumns()
{
return numberOfColumns;
}
/**
* Gets the title.
*
* @return
* the title
*/
public String getTitle()
{
return title;
}
/**
* Indicates if the columns are equals in width.
*
* @return
* <code>true</code> if the columns are equals in width,
* <code>false</code> if not
*/
public boolean isEqualColumns()
{
return equalColumns;
}
/**
* Indicates if the section is expandable.
*
* @return
* <code>true</code> if the section is expandable,
* <code>false</code> if not
*/
public boolean isExpandable()
{
return expandable;
}
/**
* Indicates if the section is expanded.
*
* @return
* <code>true</code> if the section is expanded,
* <code>false</code> if not
*/
public boolean isExpanded()
{
return expanded;
}
/**
* Sets the description.
*
* @param description
* the description
*/
public void setDescription( String description )
{
this.description = description;
}
/**
* Sets the flag that indicates if the columns are equals in width.
*
* @param equalColumns
* the flag that indicates if the columns are equals in width
*/
public void setEqualColumns( boolean equalColumns )
{
this.equalColumns = equalColumns;
}
/**
* Sets the flag that indicates if the section is expandable.
*
* @param expandable
* the flag that indicates if the section is expandable
*/
public void setExpandable( boolean expandable )
{
this.expandable = expandable;
}
/**
* Sets the flag that indicates if the section is expanded.
*
* @param expanded
* the flag that indicates if the section is expanded
*/
public void setExpanded( boolean expanded )
{
this.expanded = expanded;
}
/**
* Sets the number of columns.
*
* @param numberOfColumns
* the number of columns
*/
public void setNumberOfColumns( int numberOfColumns )
{
this.numberOfColumns = numberOfColumns;
}
/**
* Sets the title.
*
* @param title
* the title
*/
public void setTitle( String title )
{
this.title = title;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateCheckbox.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateCheckbox.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateCheckbox extends AbstractTemplateWidget
{
/** The default enabled value */
public static boolean DEFAULT_ENABLED = true;
/** The default enabled value */
public static String DEFAULT_LABEL = ""; //$NON-NLS-1$
/** The default checked value value */
public static String DEFAULT_CHECKED_VALUE = null;
/** The default unchecked value value */
public static String DEFAULT_UNCHECKED_VALUE = null;
/** The label associated with the checkbox */
private String label = DEFAULT_LABEL;
/** The enabled flag */
private boolean enabled = DEFAULT_ENABLED;
/** The value when the checkbox is checked */
private String checkedValue = DEFAULT_CHECKED_VALUE;
/** The value when the checkbox is unchecked */
private String uncheckedValue = DEFAULT_UNCHECKED_VALUE;
/**
* Creates a new instance of TemplateCheckbox.
*
* @param parent
* the parent element
*/
public TemplateCheckbox( TemplateWidget parent )
{
super( parent );
}
/**
* Get the value when the checkbox is checked.
*
* @return
* the value when the checkbox is checked
*/
public String getCheckedValue()
{
return checkedValue;
}
/**
* Gets the label.
*
* @return
* the label
*/
public String getLabel()
{
return label;
}
/**
* Gets the value when the checkbox is not checked.
*
* @return
* the value when the checkbox is not checked
*/
public String getUncheckedValue()
{
return uncheckedValue;
}
/**
* Indicates if the the checkbox is enabled.
*
* @return
* <code>true</code> if the checkbox is enabled,
* <code>false</code> if the checkbox is disabled
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Sets the value when the checkbox is checked.
*
* @param checkedValue
* the value
*/
public void setCheckedValue( String checkedValue )
{
this.checkedValue = checkedValue;
}
/**
* Enables or disables the checkbox.
*
* @param enabled
* <code>true</code> if the checkbox is enabled,
* <code>false</code> if the checkbox is disabled
*/
public void setEnabled( boolean enabled )
{
this.enabled = enabled;
}
/**
* Sets the label.
*
* @param label
* the label
*/
public void setLabel( String label )
{
this.label = label;
}
/**
* Sets the value when the checkbox is not checked.
*
* @param uncheckedValue
* the value
*/
public void setUncheckedValue( String uncheckedValue )
{
this.uncheckedValue = uncheckedValue;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateTable.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateTable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateTable extends AbstractTemplateWidget
{
/** The default show add button value */
public static boolean DEFAULT_SHOW_ADD_BUTTON = true;
/** The default show edit button value */
public static boolean DEFAULT_SHOW_EDIT_BUTTON = true;
/** The default show delete button value */
public static boolean DEFAULT_SHOW_DELETE_BUTTON = true;
/** The flag which indicated if a "<em>Add...</em>" button should be shown */
private boolean showAddButton = DEFAULT_SHOW_ADD_BUTTON;
/** The flag which indicated if a "<em>Edit...</em>" button should be shown */
private boolean showEditButton = DEFAULT_SHOW_EDIT_BUTTON;
/** The flag which indicated if a "<em>Delete...</em>" button should be shown */
private boolean showDeleteButton = DEFAULT_SHOW_DELETE_BUTTON;
/**
* Creates a new instance of TemplateTable.
*
* @param parent
* the parent element
*/
public TemplateTable( TemplateWidget parent )
{
super( parent );
}
/**
* Indicates if a "<em>Add...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Add...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowAddButton()
{
return showAddButton;
}
/**
* Indicates if a "<em>Delete...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Delete...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowDeleteButton()
{
return showDeleteButton;
}
/**
* Indicates if a "<em>Edit...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowEditButton()
{
return showEditButton;
}
/**
* Sets the flag which indicates if a "<em>Add...</em>" button should
* be shown.
*
* @param showAddButton
* <code>true</code> if a "<em>Add...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowAddButton( boolean showAddButton )
{
this.showAddButton = showAddButton;
}
/**
* Sets the flag which indicates if a "<em>Delete...</em>" button should
* be shown.
*
* @param showDeleteButton
* <code>true</code> if a "<em>Delete...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowDeleteButton( boolean showDeleteButton )
{
this.showDeleteButton = showDeleteButton;
}
/**
* Sets the flag which indicates if a "<em>Edit...</em>" button should
* be shown.
*
* @param showEditButton
* <code>true</code> if a "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowEditButton( boolean showEditButton )
{
this.showEditButton = showEditButton;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateListbox.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateListbox.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements a template checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateListbox extends AbstractTemplateWidget
{
/** The default show browse button value */
public static boolean DEFAULT_MULTIPLE_SELECTION = true;
/** The default enabled value */
public static boolean DEFAULT_ENABLED = true;
/** The enabled flag */
private boolean enabled = DEFAULT_ENABLED;
/** The flag which indicates if the listbox allows multiple selection */
private boolean multipleSelection = DEFAULT_MULTIPLE_SELECTION;
/** The list of value items */
private List<ValueItem> items = new ArrayList<ValueItem>();
/**
* Creates a new instance of TemplateListbox.
*
* @param parent
* the parent element
*/
public TemplateListbox( TemplateWidget parent )
{
super( parent );
}
/**
* Adds a value.
*
* @param value
* the value
* @return
* <code>true</code> if the listbox did not already
* contain the specified element.
*/
public boolean addValue( ValueItem value )
{
return items.add( value );
}
/**
* Gets the items.
*
* @return
* the items
*/
public List<ValueItem> getItems()
{
return items;
}
/**
* Indicates if the the listbox is enabled.
*
* @return
* <code>true</code> if the listbox is enabled,
* <code>false</code> if the listbox is disabled
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Indicates if the listbox allows multiple selection.
*
* @return
* <code>true</code> if the listbox allows multiple selection,
* <code>false</code> if not.
*/
public boolean isMultipleSelection()
{
return multipleSelection;
}
/**
* Enables or disables the listbox.
*
* @param enabled
* <code>true</code> if the listbox is enabled,
* <code>false</code> if the listbox is disabled
*/
public void setEnabled( boolean enabled )
{
this.enabled = enabled;
}
/**
* Sets the items.
*
* @param items
* the items
*/
public void setItems( List<ValueItem> items )
{
this.items = items;
}
/**
* Sets the flag which indicates if the listbox allows multiple selection.
*
* @param multipleSelection
* <code>true</code> if the listbox allows multiple selection,
* <code>false</code> if not.
*/
public void setMultipleSelection( boolean multipleSelection )
{
this.multipleSelection = multipleSelection;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateLabel.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateLabel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateLabel extends AbstractTemplateWidget
{
/** The default value value */
public static String DEFAULT_VALUE = null;
/** The default show browse button value */
public static int DEFAULT_NUMBER_OF_ROWS = 1;
/** The default dollar sign is new line value */
public static boolean DEFAULT_DOLLAR_SIGN_IS_NEW_LINE = false;
/** The label value */
private String value = DEFAULT_VALUE;
/** The number of rows */
private int numberOfRows = DEFAULT_NUMBER_OF_ROWS;
/** The flag which indicates if dollar sign ('$') is to be interpreted as a new line */
private boolean dollarSignIsNewLine = DEFAULT_DOLLAR_SIGN_IS_NEW_LINE;
/**
* Creates a new instance of TemplateLabel.
*
* @param parent
* the parent element
*/
public TemplateLabel( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the number of rows.
*
* @return
* the number of rows
*/
public int getNumberOfRows()
{
return numberOfRows;
}
/**
* Gets the value.
*
* @return
* the value
*/
public String getValue()
{
return value;
}
/**
* Indicates if dollar sign ('$') is to be interpreted as a new line.
*
* @return
* <code>true</code> if dollar sign ('$') is to be interpreted as a new line,
* <code>false</code> if not
*/
public boolean isDollarSignIsNewLine()
{
return dollarSignIsNewLine;
}
/**
* Sets the flag which indicates if dollar sign ('$') is to be interpreted as a new line.
*
* @param dollarSignIsNewLine
* <code>true</code> if dollar sign ('$') is to be interpreted as a new line,
* <code>false</code> if not
*/
public void setDollarSignIsNewLine( boolean dollarSignIsNewLine )
{
this.dollarSignIsNewLine = dollarSignIsNewLine;
}
/**
* Sets the number of rows.
*
* @param numberOfRows
* the number of rows
*/
public void setNumberOfRows( int numberOfRows )
{
this.numberOfRows = numberOfRows;
}
/**
* Sets the value.
*
* @param value
* the value
*/
public void setValue( String value )
{
this.value = value;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateWidget.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateWidget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
import java.util.List;
/**
* This interface defines a widget that can be used in a template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface TemplateWidget
{
/** The default horizontal alignment value */
public static WidgetAlignment DEFAULT_HORIZONTAL_ALIGNMENT = WidgetAlignment.NONE;
/** The default vertical alignment value */
WidgetAlignment DEFAULT_VERTICAL_ALIGNMENT = WidgetAlignment.NONE;
/** The default grab excess horizontal space value */
boolean DEFAULT_GRAB_EXCESS_HORIZONTAL_SPACE = false;
/** The default grab excess vertical space value */
boolean DEFAULT_GRAB_EXCESS_VERTICAL_SPACE = false;
/** The default horizontal span value */
int DEFAULT_HORIZONTAL_SPAN = 1;
/** The default vertical span value */
int DEFAULT_VERTICAL_SPAN = 1;
/** The default integer value for sizes */
int DEFAULT_SIZE = -1;
/**
* Adds a child.
*
* @param widget
* the child
* @return
* <code>true</code> (as per the general contract of the Collection.add method).
*/
boolean addChild( TemplateWidget widget );
/**
* Gets the attribute type the widget is associated with.
*
* @return
* the attribute type the widget is associated with
*/
String getAttributeType();
/**
* Gets the children.
*
* @return
* the children
*/
List<TemplateWidget> getChildren();
/**
* Gets the preferred height.
*
* @return
* the preferred height
*/
int getImageHeight();
/**
* Gets how the widget is positioned horizontally.
*
* @return
* how the widget is positioned horizontally
*/
WidgetAlignment getHorizontalAlignment();
/**
* Gets the number of columns that the widget will take up.
*
* @return
* the number of columns that the widget will take up
*/
int getHorizontalSpan();
/**
* Gets the parent element.
*
* @return
* the parent element
*/
TemplateWidget getParent();
/**
* Gets how the widget is positioned vertically.
*
* @return
* how the widget is positioned vertically
*/
WidgetAlignment getVerticalAlignment();
/**
* Gets the number of rows that the widget will take up.
*
* @return
* the number of rows that the widget will take up
*/
int getVerticalSpan();
/**
* Gets the preferred width.
*
* @return
* the preferred width
*/
int getImageWidth();
/**
* Indicates if the widget has children.
*
* @return
* <code>true</code> if the widget has children,
* <code>false</code> if not.
*/
boolean hasChildren();
/**
* Indicates whether the widget will be made wide
* enough to fit the remaining horizontal space.
*
* @return
* <code>true</code> if the widget will be made wide
* enough to fit the remaining horizontal space,
* <code>false</code> if not
*/
boolean isGrabExcessHorizontalSpace();
/**
* Indicates whether the widget will be made wide
* enough to fit the remaining vertical space.
*
* @return
* <code>true</code> if the widget will be made wide
* enough to fit the remaining vertical space,
* <code>false</code> if not
*/
boolean isGrabExcessVerticalSpace();
/**
* Sets the attribute type the widget is associated with.
*
* @param attributeType
* the attribute type the widget is associated with
*/
void setAttributeType( String attributeType );
/**
* Sets whether the widget will be made wide
* enough to fit the remaining horizontal space.
*
* @param horizontalSpan
* whether the widget will be made wide
* enough to fit the remaining horizontal space
*/
void setGrabExcessHorizontalSpace( boolean grabExcessHorizontalSpace );
/**
* Sets whether the widget will be made wide
* enough to fit the remaining horizontal space.
*
* @param grabExcessVerticalSpace
* whether the widget will be made wide
* enough to fit the remaining vertical space
*/
void setGrabExcessVerticalSpace( boolean grabExcessVerticalSpace );
/**
* Sets the preferred height.
*
* @param height
* the preferred height
*/
void setImageHeight( int height );
/**
* Sets how the widget is positioned horizontally.
*
* @param horizontalAlignment
* how the widget is positioned horizontally
*/
void setHorizontalAlignment( WidgetAlignment horizontalAlignment );
/**
* Sets the number of columns that the widget will take up.
*
* @param grabExcessHorizontalSpace
* the number of columns that the widget will take up
*/
void setHorizontalSpan( int horizontalSpan );
/**
* Gets how the widget is positioned vertically.
*
* @param verticalAlignment
* how the widget is positioned vertically
*/
void setVerticalAlignment( WidgetAlignment verticalAlignment );
/**
* Sets the number of rows that the widget will take up.
*
* @param verticalSpan
* the number of rows that the widget will take up
*/
void setVerticalSpan( int verticalSpan );
/**
* Sets the preferred width.
*
* @param width
* the preferred width
*/
void setImageWidth( int width );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateDate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateDate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template link.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateDate extends AbstractTemplateWidget
{
/** The default format value */
public static String DEFAULT_FORMAT = null;
/** The default show edit button value */
public static boolean DEFAULT_SHOW_EDIT_BUTTON = true;
/** The format value */
private String format = DEFAULT_FORMAT;
/** The flag which indicates if an "<em>Edit...</em>" button should be shown */
private boolean showEditButton = DEFAULT_SHOW_EDIT_BUTTON;
/**
* Creates a new instance of TemplateLink.
*
* @param parent
* the parent element
*/
public TemplateDate( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the format.
*
* @return
* the format
*/
public String getFormat()
{
return format;
}
/**
* Indicates if an "<em>Edit...</em>" button should be shown.
*
* @return
* <code>true</code> if an "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowEditButton()
{
return showEditButton;
}
/**
* Sets the format.
*
* @param format
* the format
*/
public void setFormat( String format )
{
this.format = format;
}
/**
* Sets the flag which indicates if an "<em>Edit...</em>" button should
* be shown.
*
* @param showEditButton
* <code>true</code> if a "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowEditButton( boolean showEditButton )
{
this.showEditButton = showEditButton;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateFileChooser.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateFileChooser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
import java.util.HashSet;
import java.util.Set;
/**
* This class implements a template file chooser.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateFileChooser extends AbstractTemplateWidget
{
/** The default icon value */
public static String DEFAULT_ICON = null;
/** The default show save icon value */
public static boolean DEFAULT_SHOW_ICON = true;
/** The default show save as button value */
public static boolean DEFAULT_SHOW_SAVE_AS_BUTTON = true;
/** The default show clear button value */
public static boolean DEFAULT_SHOW_CLEAR_BUTTON = true;
/** The default show browse button value */
public static boolean DEFAULT_SHOW_BROWSE_BUTTON = true;
/** The icon */
private String icon = DEFAULT_ICON;
/** The set of extensions for the file */
private Set<String> extensions = new HashSet<String>();
/** The flag which indicates if an should be shown */
private boolean showIcon = DEFAULT_SHOW_ICON;
/** The flag which indicates if a "<em>Save As...</em>" button should be shown */
private boolean showSaveAsButton = DEFAULT_SHOW_SAVE_AS_BUTTON;
/** The flag which indicates if a "<em>Clear</em>" button should be shown */
private boolean showClearButton = DEFAULT_SHOW_CLEAR_BUTTON;
/** The flag which indicates if a "<em>Browse...</em>" button should be shown */
private boolean showBrowseButton = DEFAULT_SHOW_BROWSE_BUTTON;
/**
* Creates a new instance of TemplateFileChooser.
*
* @param parent
* the parent element
*/
public TemplateFileChooser( TemplateWidget parent )
{
super( parent );
}
/**
* Adds an extension.
*
* @param extension
* the extension
* @return
* <code>true</code> if the template file chooser did not already
* contain the specified element.
*/
public boolean addExtension( String extension )
{
return extensions.add( extension );
}
/**
* Gets the extensions.
*
* @return
* the extensions
*/
public Set<String> getExtensions()
{
return extensions;
}
/**
* Gets the icon.
*
* @return
* the icon
*/
public String getIcon()
{
return icon;
}
/**
* Indicates if a "<em>Browse...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Browse...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowBrowseButton()
{
return showBrowseButton;
}
/**
* Indicates if a "<em>Clear</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Clear</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowClearButton()
{
return showClearButton;
}
/**
* Indicates if an icon should be shown.
*
* @return
* <code>true</code> if an icon should be shown,
* <code>false</code> if not.
*/
public boolean isShowIcon()
{
return showIcon;
}
/**
* Indicates if a "<em>Save As...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Save As...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowSaveAsButton()
{
return showSaveAsButton;
}
/**
* Set the extensions.
*
* @param extensions
* the extensions
*/
public void setExtensions( Set<String> extensions )
{
this.extensions = extensions;
}
/**
* Sets the icon.
*
* @param icon
* the icon
*/
public void setIcon( String icon )
{
this.icon = icon;
}
/**
* Sets the flag which indicates if a "<em>Browse...</em>" button should
* be shown.
*
* @param showBrowseButton
* <code>true</code> if a "<em>Browse...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowBrowseButton( boolean showBrowseButton )
{
this.showBrowseButton = showBrowseButton;
}
/**
* Sets the flag which indicates if a "<em>Clear</em>" button should
* be shown.
*
* @param showClearButton
* <code>true</code> if a "<em>Clear</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowClearButton( boolean showClearButton )
{
this.showClearButton = showClearButton;
}
/**
* Sets the flag which indicates if an icon should be shown.
*
* @param showIcon
* <code>true</code> if an icon should be shown,
* <code>false</code> if not.
*/
public void setShowIcon( boolean showIcon )
{
this.showIcon = showIcon;
}
/**
* Sets the flag which indicates if a "<em>Save As...</em>" button should
* be shown.
*
* @param showSaveAsButton
* <code>true</code> if a "<em>Save As...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowSaveAsButton( boolean showSaveAsButton )
{
this.showSaveAsButton = showSaveAsButton;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplatePassword.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplatePassword.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplatePassword extends AbstractTemplateWidget
{
/** The default hidden value */
public static boolean DEFAULT_HIDDEN = true;
/** The default show edit button value */
public static boolean DEFAULT_SHOW_EDIT_BUTTON = true;
/** The default show password checkbox value */
public static boolean DEFAULT_SHOW_PASSWORD_CHECKBOX = true;
/** The flag which indicated if the password should be hidden */
private boolean hidden = DEFAULT_HIDDEN;
/** The flag which indicated if a "<em>Edit...</em>" button should be shown */
private boolean showEditButton = DEFAULT_SHOW_EDIT_BUTTON;
/** The flag which indicated if a "<em>Show Password</em>" checkbox should be shown */
private boolean showShowPasswordCheckbox = DEFAULT_SHOW_PASSWORD_CHECKBOX;
/**
* Creates a new instance of TemplatePassword.
*
* @param parent
* the parent element
*/
public TemplatePassword( TemplateWidget parent )
{
super( parent );
}
/**
* Indicates if the password should be displayed hidden
* ("••••") or not.
*
* @return
* <code>true</code> if should be displayed hidden
* ("••••"), <code>false</code> if not.
*/
public boolean isHidden()
{
return hidden;
}
/**
* Indicates if a "<em>Edit...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowEditButton()
{
return showEditButton;
}
/**
* Indicates if a "<em>Show Password</em>" checkbox should be shown.
*
* @return
* <code>true</code> if a "<em>Show Password</em>" checkbox should be
* shown, <code>false</code> if not.
*/
public boolean isShowShowPasswordCheckbox()
{
return showShowPasswordCheckbox;
}
/**
* Sets the flag which indicates if the password should be displayed hidden
* ("••••") or not.
*
* @param showBrowseButton
* <code>true</code> if a "<em>Change...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setHidden( boolean hidden )
{
this.hidden = hidden;
}
/**
* Sets the flag which indicates if a "<em>Edit...</em>" button should
* be shown.
*
* @param showEditButton
* <code>true</code> if a "<em>Edit...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowEditButton( boolean showEditButton )
{
this.showEditButton = showEditButton;
}
/**
* Sets the flag which indicated if a "<em>Show Password</em>" checkbox
* should be shown.
*
* @param showShowPasswordCheckbox
* <code>true</code> if a "<em>Show Password</em>" checkbox should
* be shown,
* <code>false</code> if not.
*/
public void setShowShowPasswordCheckbox( boolean showShowPasswordCheckbox )
{
this.showShowPasswordCheckbox = showShowPasswordCheckbox;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateImage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/TemplateImage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
/**
* This class implements a template image.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateImage extends AbstractTemplateWidget
{
/** The default show save as button value */
public static String DEFAULT_IMAGE_DATA = null;
/** The default show save as button value */
public static boolean DEFAULT_SHOW_SAVE_AS_BUTTON = true;
/** The default show clear button value */
public static boolean DEFAULT_SHOW_CLEAR_BUTTON = true;
/** The default show browse button value */
public static boolean DEFAULT_SHOW_BROWSE_BUTTON = true;
/** The image data */
private String imageData = DEFAULT_IMAGE_DATA;
/** The flag which indicates if a "<em>Save As...</em>" button should be shown */
private boolean showSaveAsButton = DEFAULT_SHOW_SAVE_AS_BUTTON;
/** The flag which indicates if a "<em>Clear</em>" button should be shown */
private boolean showClearButton = DEFAULT_SHOW_CLEAR_BUTTON;
/** The flag which indicates if a "<em>Browse...</em>" button should be shown */
private boolean showBrowseButton = DEFAULT_SHOW_BROWSE_BUTTON;
/** The width of the image */
private int imageWidth = TemplateWidget.DEFAULT_SIZE;
/** The height of the image */
private int imageHeight = TemplateWidget.DEFAULT_SIZE;
/**
* Creates a new instance of TemplateImage.
*
* @param parent
* the parent element
*/
public TemplateImage( TemplateWidget parent )
{
super( parent );
}
/**
* Gets the height of the image.
*
* @return
* the height of the image
*/
public int getImageHeight()
{
return imageHeight;
}
/**
* Gets the image data.
*
* @return
* the image data
*/
public String getImageData()
{
return imageData;
}
/**
* Gets the width of the image.
*
* @return
* the width of the image
*/
public int getImageWidth()
{
return imageWidth;
}
/**
* Indicates if a "<em>Browse...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Browse...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowBrowseButton()
{
return showBrowseButton;
}
/**
* Indicates if a "<em>Clear</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Clear</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowClearButton()
{
return showClearButton;
}
/**
* Indicates if a "<em>Save As...</em>" button should be shown.
*
* @return
* <code>true</code> if a "<em>Save As...</em>" button should be
* shown, <code>false</code> if not.
*/
public boolean isShowSaveAsButton()
{
return showSaveAsButton;
}
/**
* Sets the height of the image.
*
* @param imageHeight
* height of the image
*/
public void setImageHeight( int imageHeight )
{
this.imageHeight = imageHeight;
}
/**
* Sets the image data.
*
* @param imageData
* the image data
*/
public void setImageData( String imageData )
{
this.imageData = imageData;
}
/**
* Sets the flag which indicates if a "<em>Browse...</em>" button should
* be shown.
*
* @param showBrowseButton
* <code>true</code> if a "<em>Browse...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowBrowseButton( boolean showBrowseButton )
{
this.showBrowseButton = showBrowseButton;
}
/**
* Sets the flag which indicates if a "<em>Clear</em>" button should
* be shown.
*
* @param showClearButton
* <code>true</code> if a "<em>Clear</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowClearButton( boolean showClearButton )
{
this.showClearButton = showClearButton;
}
/**
* Sets the flag which indicates if a "<em>Save As...</em>" button should
* be shown.
*
* @param showSaveAsButton
* <code>true</code> if a "<em>Save As...</em>" button should be
* shown, <code>false</code> if not.
*/
public void setShowSaveAsButton( boolean showSaveAsButton )
{
this.showSaveAsButton = showSaveAsButton;
}
/**
* Sets the width of the image.
*
* @param imageWidth
* the width of the image
*/
public void setImageWidth( int imageWidth )
{
this.imageWidth = imageWidth;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/AbstractTemplateWidget.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/widgets/AbstractTemplateWidget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.widgets;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements an abstract widget for templates.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractTemplateWidget implements TemplateWidget
{
/** The parent element*/
private TemplateWidget parent;
/** The children list */
private List<TemplateWidget> children;
/** The attribute type the widget is associated with */
private String attributeType;
/** How the widget is positioned horizontally */
private WidgetAlignment horizontalAlignment = DEFAULT_HORIZONTAL_ALIGNMENT;
/** How the widget is positioned vertically */
private WidgetAlignment verticalAlignment = DEFAULT_VERTICAL_ALIGNMENT;
/**
* The flag to know whether the widget will be made wide
* enough to fit the remaining horizontal space.
*/
private boolean grabExcessHorizontalSpace = DEFAULT_GRAB_EXCESS_HORIZONTAL_SPACE;
/**
* The flag to know whether the widget will be made wide
* enough to fit the remaining vertical space.
*/
private boolean grabExcessVerticalSpace = DEFAULT_GRAB_EXCESS_VERTICAL_SPACE;
/** The number of columns that the widget will take up */
private int horizontalSpan = DEFAULT_HORIZONTAL_SPAN;
/** The number of rows that the widget will take up */
private int verticalSpan = DEFAULT_VERTICAL_SPAN;
/** The preferred width */
private int width = DEFAULT_SIZE;
/** The preferred height*/
private int height = DEFAULT_SIZE;
/**
* Creates a new instance of AbstractTemplateWidget.
*
* @param parent
* the parent element
*/
public AbstractTemplateWidget( TemplateWidget parent )
{
this.parent = parent;
children = new ArrayList<TemplateWidget>();
if ( parent != null )
{
parent.addChild( this );
}
}
/**
* {@inheritDoc}
*/
public boolean addChild( TemplateWidget widget )
{
return children.add( widget );
}
/**
* {@inheritDoc}
*/
public String getAttributeType()
{
return attributeType;
}
/**
* {@inheritDoc}
*/
public List<TemplateWidget> getChildren()
{
return children;
}
/**
* {@inheritDoc}
*/
public int getImageHeight()
{
return height;
}
/**
* {@inheritDoc}
*/
public WidgetAlignment getHorizontalAlignment()
{
return horizontalAlignment;
}
/**
* {@inheritDoc}
*/
public int getHorizontalSpan()
{
return horizontalSpan;
}
/**
* {@inheritDoc}
*/
public TemplateWidget getParent()
{
return parent;
}
/**
* {@inheritDoc}
*/
public WidgetAlignment getVerticalAlignment()
{
return verticalAlignment;
}
/**
* {@inheritDoc}
*/
public int getVerticalSpan()
{
return verticalSpan;
}
/**
* {@inheritDoc}
*/
public int getImageWidth()
{
return width;
}
/**
* {@inheritDoc}
*/
public boolean hasChildren()
{
return children.size() > 0;
}
/**
* {@inheritDoc}
*/
public boolean isGrabExcessHorizontalSpace()
{
return grabExcessHorizontalSpace;
}
/**
* {@inheritDoc}
*/
public boolean isGrabExcessVerticalSpace()
{
return grabExcessVerticalSpace;
}
/**
* {@inheritDoc}
*/
public void setAttributeType( String attributeType )
{
this.attributeType = attributeType;
}
/**
* {@inheritDoc}
*/
public void setGrabExcessHorizontalSpace( boolean grabExcessHorizontalSpace )
{
this.grabExcessHorizontalSpace = grabExcessHorizontalSpace;
}
/**
* {@inheritDoc}
*/
public void setGrabExcessVerticalSpace( boolean grabExcessVerticalSpace )
{
this.grabExcessVerticalSpace = grabExcessVerticalSpace;
}
/**
* {@inheritDoc}
*/
public void setImageHeight( int height )
{
this.height = height;
}
/**
* {@inheritDoc}
*/
public void setHorizontalAlignment( WidgetAlignment horizontalAlignment )
{
this.horizontalAlignment = horizontalAlignment;
}
/**
* {@inheritDoc}
*/
public void setHorizontalSpan( int horizontalSpan )
{
this.horizontalSpan = horizontalSpan;
}
/**
* {@inheritDoc}
*/
public void setVerticalAlignment( WidgetAlignment verticalAlignment )
{
this.verticalAlignment = verticalAlignment;
}
/**
* {@inheritDoc}
*/
public void setVerticalSpan( int verticalSpan )
{
this.verticalSpan = verticalSpan;
}
/**
* {@inheritDoc}
*/
public void setImageWidth( int width )
{
this.width = width;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIO.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIO.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.parser;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.eclipse.osgi.util.NLS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.directory.studio.templateeditor.model.AbstractTemplate;
import org.apache.directory.studio.templateeditor.model.ExtensionPointTemplate;
import org.apache.directory.studio.templateeditor.model.FileTemplate;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateCheckbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateComposite;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateDate;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateFileChooser;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateForm;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateImage;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLabel;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLink;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateListbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplatePassword;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateRadioButtons;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSection;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSpinner;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTable;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTextField;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateWidget;
import org.apache.directory.studio.templateeditor.model.widgets.ValueItem;
import org.apache.directory.studio.templateeditor.model.widgets.WidgetAlignment;
import org.apache.directory.studio.templateeditor.view.preferences.PreferencesFileTemplate;
/**
* This class is used to read/write the 'connections.xml' file.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateIO
{
/** The logger */
private static final Logger LOG = LoggerFactory.getLogger( TemplateIO.class );
private static final String THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE = Messages
.getString( "TemplateIO.FileIsNotAValidTemplateFile" ); //$NON-NLS-1$
// XML Elements
private static final String ATTRIBUTE_ATTRIBUTETYPE = "attributeType"; //$NON-NLS-1$
private static final String ATTRIBUTE_CHARACTERSLIMIT = "charactersLimit"; //$NON-NLS-1$
private static final String ATTRIBUTE_DESCRIPTION = "description"; //$NON-NLS-1$
private static final String ATTRIBUTE_DIGITS = "digits"; //$NON-NLS-1$
private static final String ATTRIBUTE_DOLLAR_SIGN_IS_NEW_LINE = "dollarSignIsNewLine"; //$NON-NLS-1$
private static final String ATTRIBUTE_EXTENSIONS = "extensions"; //$NON-NLS-1$
private static final String ATTRIBUTE_EQUALCOLUMNS = "equalColumns"; //$NON-NLS-1$
private static final String ATTRIBUTE_ENABLED = "enabled"; //$NON-NLS-1$
private static final String ATTRIBUTE_EXPANDABLE = "expandable"; //$NON-NLS-1$
private static final String ATTRIBUTE_EXPANDED = "expanded"; //$NON-NLS-1$
private static final String ATTRIBUTE_FORMAT = "format"; //$NON-NLS-1$
private static final String ATTRIBUTE_GRAB_EXCESS_HORIZONTAL_SPACE = "grabExcessHorizontalSpace"; //$NON-NLS-1$
private static final String ATTRIBUTE_GRAB_EXCESS_VERTICAL_SPACE = "grabExcessVerticalSpace"; //$NON-NLS-1$
private static final String ATTRIBUTE_HIDDEN = "hidden"; //$NON-NLS-1$
private static final String ATTRIBUTE_HEIGHT = "height"; //$NON-NLS-1$
private static final String ATTRIBUTE_HORIZONTAL_ALIGNMENT = "horizontalAlignment"; //$NON-NLS-1$
private static final String ATTRIBUTE_HORIZONTAL_SPAN = "horizontalSpan"; //$NON-NLS-1$
private static final String ATTRIBUTE_ID = "id"; //$NON-NLS-1$
private static final String ATTRIBUTE_IMAGE_HEIGHT = "imageHeight"; //$NON-NLS-1$
private static final String ATTRIBUTE_IMAGE_WIDTH = "imageWidth"; //$NON-NLS-1$
private static final String ATTRIBUTE_INCREMENT = "increment"; //$NON-NLS-1$
private static final String ATTRIBUTE_LABEL = "label"; //$NON-NLS-1$
private static final String ATTRIBUTE_MAXIMUM = "maximum"; //$NON-NLS-1$
private static final String ATTRIBUTE_MINIMUM = "minimum"; //$NON-NLS-1$
private static final String ATTRIBUTE_MULTIPLESELECTION = "multipleSelection"; //$NON-NLS-1$
private static final String ATTRIBUTE_NUMBEROFCOLUMNS = "numberOfColumns"; //$NON-NLS-1$
private static final String ATTRIBUTE_NUMBEROFROWS = "numberOfRows"; //$NON-NLS-1$
private static final String ATTRIBUTE_PAGEINCREMENT = "pageIncrement"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWADDBUTTON = "showAddButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWBROWSEBUTTON = "showBrowseButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWCLEARBUTTON = "showClearButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWDELETEBUTTON = "showDeleteButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWEDITBUTTON = "showEditButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWICON = "showIcon"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWSAVEASBUTTON = "showSaveAsButton"; //$NON-NLS-1$
private static final String ATTRIBUTE_SHOWSHOWPASSWORDCHECKBOX = "showShowPasswordCheckbox"; //$NON-NLS-1$
private static final String ATTRIBUTE_TITLE = "title"; //$NON-NLS-1$
private static final String ATTRIBUTE_VALUE = "value"; //$NON-NLS-1$
private static final String ATTRIBUTE_VERTICAL_ALIGNMENT = "verticalAlignment"; //$NON-NLS-1$
private static final String ATTRIBUTE_VERTICAL_SPAN = "verticalSpan"; //$NON-NLS-1$
private static final String ATTRIBUTE_WIDTH = "width"; //$NON-NLS-1$
private static final String ELEMENT_AUXILIARIES = "auxiliaries"; //$NON-NLS-1$
private static final String ELEMENT_AUXILIARY = "auxiliary"; //$NON-NLS-1$
private static final String ELEMENT_BUTTON = "button"; //$NON-NLS-1$
private static final String ELEMENT_BUTTONS = "buttons"; //$NON-NLS-1$
private static final String ELEMENT_CHECKBOX = "checkbox"; //$NON-NLS-1$
private static final String ELEMENT_CHECKEDVALUE = "checkedValue"; //$NON-NLS-1$
private static final String ELEMENT_COMPOSITE = "composite"; //$NON-NLS-1$
private static final String ELEMENT_DATA = "data"; //$NON-NLS-1$
private static final String ELEMENT_DATE = "date"; //$NON-NLS-1$
private static final String ELEMENT_FILECHOOSER = "fileChooser"; //$NON-NLS-1$
private static final String ELEMENT_FORM = "form"; //$NON-NLS-1$
private static final String ELEMENT_ICON = "icon"; //$NON-NLS-1$
private static final String ELEMENT_IMAGE = "image"; //$NON-NLS-1$
private static final String ELEMENT_ITEM = "item"; //$NON-NLS-1$
private static final String ELEMENT_ITEMS = "items"; //$NON-NLS-1$
private static final String ELEMENT_LABEL = "label"; //$NON-NLS-1$
private static final String ELEMENT_LINK = "link"; //$NON-NLS-1$
private static final String ELEMENT_LISTBOX = "listbox"; //$NON-NLS-1$
private static final String ELEMENT_OBJECTCLASSES = "objectClasses"; //$NON-NLS-1$
private static final String ELEMENT_PASSWORD = "password"; //$NON-NLS-1$
private static final String ELEMENT_RADIOBUTTONS = "radiobuttons"; //$NON-NLS-1$
private static final String ELEMENT_SECTION = "section"; //$NON-NLS-1$
private static final String ELEMENT_SPINNER = "spinner"; //$NON-NLS-1$
private static final String ELEMENT_STRUCTURAL = "structural"; //$NON-NLS-1$
private static final String ELEMENT_TABLE = "table"; //$NON-NLS-1$
private static final String ELEMENT_TEMPLATE = "template"; //$NON-NLS-1$
private static final String ELEMENT_TEXTFIELD = "textfield"; //$NON-NLS-1$
private static final String ELEMENT_VALUE = "value"; //$NON-NLS-1$
private static final String ELEMENT_UNCHECKEDVALUE = "uncheckedValue"; //$NON-NLS-1$
private static final String VALUE_BEGINNING = "beginning"; //$NON-NLS-1$
private static final String VALUE_CENTER = "center"; //$NON-NLS-1$
private static final String VALUE_END = "end"; //$NON-NLS-1$
private static final String VALUE_FALSE = "false"; //$NON-NLS-1$
private static final String VALUE_FILL = "fill"; //$NON-NLS-1$
private static final String VALUE_NONE = "none"; //$NON-NLS-1$
private static final String VALUE_TRUE = "true"; //$NON-NLS-1$
/**
* Reads the input stream as a file template
*
* @param is
* the input stream
* @return
* the template
* @throws TemplateIOException
* if an error occurs when converting the document
*/
public static FileTemplate readAsFileTemplate( InputStream is ) throws TemplateIOException
{
// Creating the FileTemplate
FileTemplate template = new FileTemplate();
// Reading the template
readTemplate( is, template );
// Returning the template
return template;
}
/**
* Reads the input stream as a preferences file template
*
* @param is
* the input stream
* @return
* the template
* @throws TemplateIOException
* if an error occurs when converting the document
*/
public static PreferencesFileTemplate readAsPreferencesFileTemplate( InputStream is ) throws TemplateIOException
{
// Creating the PreferencesFileTemplate
PreferencesFileTemplate template = new PreferencesFileTemplate();
// Reading the template
readTemplate( is, template );
// Returning the template
return template;
}
/**
* Reads the input stream as a file template
*
* @param is
* the input stream
* @return
* the template
* @throws TemplateIOException
* if an error occurs when converting the document
*/
public static ExtensionPointTemplate readAsExtensionPointTemplate( InputStream is ) throws TemplateIOException
{
// Creating the FileTemplate
ExtensionPointTemplate template = new ExtensionPointTemplate();
// Reading the template
readTemplate( is, template );
// Returning the template
return template;
}
/**
* Reads the input stream as a file template
*
* @param is
* the input stream
* @return
* the template
* @throws TemplateIOException
* if an error occurs when converting the document
*/
public static void readTemplate( InputStream is, Template template ) throws TemplateIOException
{
// Getting the document
Document document = getDocument( is );
// Reading the template.
readTemplate( document.getRootElement(), template );
}
/**
* Gets the document associated with the input stream.
*
* @param stream
* the input stream
* @return
* @throws TemplateIOException
*/
private static Document getDocument( InputStream is ) throws TemplateIOException
{
try
{
return ( new SAXReader() ).read( is );
}
catch ( DocumentException e )
{
throw new TemplateIOException( e.getMessage() );
}
}
/**
* Reads the template.
*
* @param rootElement
* the root element
* @param template
* the template
*/
private static void readTemplate( Element rootElement, Template template ) throws TemplateIOException
{
LOG.debug( "Reading the template" ); //$NON-NLS-1$
// Verifying the root 'template' element
if ( ( rootElement == null ) || ( !rootElement.getName().equalsIgnoreCase( ELEMENT_TEMPLATE ) ) )
{
LOG.error( "Unable to find element: '" + ELEMENT_TEMPLATE + "'." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindElement" ), ELEMENT_TEMPLATE ) ); //$NON-NLS-1$
}
// Reading the ID
Attribute idAttribute = rootElement.attribute( ATTRIBUTE_ID );
if ( ( idAttribute != null ) && ( idAttribute.getText() != null ) )
{
// Verifying if the ID is valid
if ( AbstractTemplate.isValidId( idAttribute.getText() ) )
{
LOG.debug( "ID='" + idAttribute.getText() + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
template.setId( idAttribute.getText() );
}
else
{
LOG.error( "Invalid ID attribute: '" + idAttribute.getText() + "'." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.InvalidIdAttribute" ), idAttribute.getText() ) ); //$NON-NLS-1$
}
}
else
{
LOG.error( "Unable to find attribute or attribute empty: '" + ATTRIBUTE_ID + "'." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.AttributeNotFoundOrEmpty" ), ATTRIBUTE_ID ) ); //$NON-NLS-1$
}
// Reading the title
Attribute titleAttribute = rootElement.attribute( ATTRIBUTE_TITLE );
if ( ( titleAttribute != null ) && ( titleAttribute.getText() != null ) )
{
LOG.debug( "Title='" + titleAttribute.getText() + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
template.setTitle( titleAttribute.getText() );
}
else
{
LOG.error( "Unable to find attribute or attribute empty: '" + ATTRIBUTE_TITLE + "'." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.AttributeNotFoundOrEmpty" ), ATTRIBUTE_TITLE ) ); //$NON-NLS-1$
}
// Reading the object classes
readObjectClasses( rootElement, template );
// Reading the form
readForm( rootElement, template );
}
/**
* Reads the object classes for the template.
*
* @param element
* the element
* @param template
* the template
* @throws TemplateIOException
*/
private static void readObjectClasses( Element element, Template template ) throws TemplateIOException
{
LOG.debug( "Reading the template's object classes" ); //$NON-NLS-1$
// Reading the 'objectClasses' element
Element objectClassesElement = element.element( ELEMENT_OBJECTCLASSES );
if ( objectClassesElement == null )
{
LOG.error( "Unable to find element: '" + ELEMENT_OBJECTCLASSES + "'." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindElement" ), ELEMENT_OBJECTCLASSES ) ); //$NON-NLS-1$
}
// Reading the 'structural' element
Element structuralElement = objectClassesElement.element( ELEMENT_STRUCTURAL );
if ( structuralElement != null )
{
String structuralObjectClassText = structuralElement.getText();
if ( ( structuralObjectClassText != null ) && ( !structuralObjectClassText.equals( "" ) ) ) //$NON-NLS-1$
{
template.setStructuralObjectClass( structuralObjectClassText );
}
}
else
{
LOG.error( "Unable to find any: '" + ELEMENT_STRUCTURAL + "' element." ); //$NON-NLS-1$ //$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindAnyElement" ), ELEMENT_STRUCTURAL ) ); //$NON-NLS-1$
}
// Reading the 'auxiliaries' element
Element auxliariesElement = objectClassesElement.element( ELEMENT_AUXILIARIES );
if ( auxliariesElement != null )
{
// Reading the auxiliaries object classes
for ( Iterator<?> i = auxliariesElement.elementIterator( ELEMENT_AUXILIARY ); i.hasNext(); )
{
Element auxliaryObjectClassElement = ( Element ) i.next();
String auxliaryObjectClassText = auxliaryObjectClassElement.getText();
if ( ( auxliaryObjectClassText != null ) && ( !auxliaryObjectClassText.equals( "" ) ) ) //$NON-NLS-1$
{
template.addAuxiliaryObjectClass( auxliaryObjectClassText );
}
}
}
}
/**
* Reads the form for the template.
*
* @param element
* the element
* @param template
* the template
* @throws TemplateIOException
*/
private static void readForm( Element element, Template template ) throws TemplateIOException
{
LOG.debug( "Reading the template's form" ); //$NON-NLS-1$
// Reading the 'form' element
Element formElement = element.element( ELEMENT_FORM );
if ( formElement == null )
{
LOG.error( "Unable to find element: '" + ELEMENT_FORM + "'." ); //$NON-NLS-1$//$NON-NLS-2$
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindElement" ), ELEMENT_FORM ) ); //$NON-NLS-1$
}
// Creating the form and setting it to the template
TemplateForm form = new TemplateForm();
template.setForm( form );
// Reading the child elements
for ( Iterator<?> i = formElement.elementIterator(); i.hasNext(); )
{
Element childElement = ( Element ) i.next();
// Getting the name of the element
String elementName = childElement.getName();
if ( elementName.equalsIgnoreCase( ELEMENT_COMPOSITE ) )
{
readComposite( childElement, form );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_SECTION ) )
{
readSection( childElement, form );
}
else
{
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.ElementNotAllowedAtThisLevel" ), //$NON-NLS-1$
new String[]
{ elementName, ELEMENT_SECTION, ELEMENT_COMPOSITE } ) );
}
}
// Verifying if we've found at least one section
if ( form.getChildren().size() == 0 )
{
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindAnyXOrYElement" ), new String[] //$NON-NLS-1$
{ ELEMENT_SECTION, ELEMENT_COMPOSITE } ) );
}
}
/**
* Reads a widget.
*
* @param element
* the element
* @param template
* the template
* @throws TemplateIOException
*/
private static void readWidget( Element element, TemplateWidget parent ) throws TemplateIOException
{
// Getting the name of the element
String elementName = element.getName();
// Switching on the various widgets we support
if ( elementName.equalsIgnoreCase( ELEMENT_CHECKBOX ) )
{
readCheckbox( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_COMPOSITE ) )
{
readComposite( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_DATE ) )
{
readDate( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_FILECHOOSER ) )
{
readFileChooser( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_IMAGE ) )
{
readImage( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_LABEL ) )
{
readLabel( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_LINK ) )
{
readLink( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_LISTBOX ) )
{
readListbox( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_PASSWORD ) )
{
readPassword( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_RADIOBUTTONS ) )
{
readRadioButtons( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_SECTION ) )
{
readSection( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_SPINNER ) )
{
readSpinner( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_TABLE ) )
{
readTable( element, parent );
}
else if ( elementName.equalsIgnoreCase( ELEMENT_TEXTFIELD ) )
{
readTextfield( element, parent );
}
// We could not find a widget associated with this name.
else
{
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnknownWidget" ), elementName ) ); //$NON-NLS-1$
}
}
/**
* Reads the widget common properties like 'attributeType' and all position related properties.
*
* @param element
* the element to read from
* @param widget
* the associated widget
* @param throwExceptionIfMissingAttributeType
* <code>true</code> if the method should throw an exception if the 'attributeType' value is missing,
* <code>false</code> if not
* @param widgetElementName
* the name of the XML element of the widget (for debug purposes)
* @throws TemplateIOException
* if the mandatory 'attributeType' value is missing
*/
private static void readWidgetCommonProperties( Element element, TemplateWidget widget,
boolean throwExceptionIfMissingAttributeType, String widgetElementName ) throws TemplateIOException
{
// Reading the 'attributeType' attribute
boolean foundAttributeTypeAttribute = readAttributeTypeAttribute( element, widget );
// If the 'attributeType' attribute does not exist, we throw an
// exception
if ( throwExceptionIfMissingAttributeType && !foundAttributeTypeAttribute )
{
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" //$NON-NLS-1$
+ NLS.bind( Messages.getString( "TemplateIO.UnableToFindMandatoryAttribute" ), new String[] //$NON-NLS-1$
{ ATTRIBUTE_ATTRIBUTETYPE, widgetElementName } ) );
}
// Reading the 'horizontalAlignment' attribute
Attribute horizontalAlignmentAttribute = element.attribute( ATTRIBUTE_HORIZONTAL_ALIGNMENT );
if ( ( horizontalAlignmentAttribute != null ) && ( horizontalAlignmentAttribute.getText() != null ) )
{
widget.setHorizontalAlignment( readWidgetAlignmentValue( horizontalAlignmentAttribute.getText() ) );
}
// Reading the 'verticalAlignment' attribute
Attribute verticalAlignmentAttribute = element.attribute( ATTRIBUTE_VERTICAL_ALIGNMENT );
if ( ( verticalAlignmentAttribute != null ) && ( verticalAlignmentAttribute.getText() != null ) )
{
widget.setVerticalAlignment( readWidgetAlignmentValue( verticalAlignmentAttribute.getText() ) );
}
// Reading the 'grabExcessHorizontalSpace' attribute
Attribute grabExcessHorizontalSpaceAttribute = element.attribute( ATTRIBUTE_GRAB_EXCESS_HORIZONTAL_SPACE );
if ( ( grabExcessHorizontalSpaceAttribute != null ) && ( grabExcessHorizontalSpaceAttribute.getText() != null ) )
{
widget.setGrabExcessHorizontalSpace( readBoolean( grabExcessHorizontalSpaceAttribute.getText() ) );
}
// Reading the 'grabExcessVerticalSpace' attribute
Attribute grabExcessVerticalSpaceAttribute = element.attribute( ATTRIBUTE_GRAB_EXCESS_VERTICAL_SPACE );
if ( ( grabExcessVerticalSpaceAttribute != null ) && ( grabExcessVerticalSpaceAttribute.getText() != null ) )
{
widget.setGrabExcessVerticalSpace( readBoolean( grabExcessVerticalSpaceAttribute.getText() ) );
}
// Reading the 'horizontalSpan' attribute
Attribute horizontalSpanAttribute = element.attribute( ATTRIBUTE_HORIZONTAL_SPAN );
if ( ( horizontalSpanAttribute != null ) && ( horizontalSpanAttribute.getText() != null ) )
{
widget.setHorizontalSpan( readInteger( horizontalSpanAttribute.getText() ) );
}
// Reading the 'verticalSpan' attribute
Attribute verticalSpanAttribute = element.attribute( ATTRIBUTE_VERTICAL_SPAN );
if ( ( verticalSpanAttribute != null ) && ( verticalSpanAttribute.getText() != null ) )
{
widget.setVerticalSpan( readInteger( verticalSpanAttribute.getText() ) );
}
// Reading the 'width' attribute
Attribute widthAttribute = element.attribute( ATTRIBUTE_WIDTH );
if ( ( widthAttribute != null ) && ( widthAttribute.getText() != null ) )
{
widget.setImageWidth( readInteger( widthAttribute.getText() ) );
}
// Reading the 'height' attribute
Attribute heightAttribute = element.attribute( ATTRIBUTE_HEIGHT );
if ( ( heightAttribute != null ) && ( heightAttribute.getText() != null ) )
{
widget.setImageHeight( readInteger( heightAttribute.getText() ) );
}
}
/**
* Reads a widget alignment value.
*
* @param text
* the widget alignment value
*/
private static WidgetAlignment readWidgetAlignmentValue( String text ) throws TemplateIOException
{
if ( text.equalsIgnoreCase( VALUE_NONE ) )
{
return WidgetAlignment.NONE;
}
else if ( text.equalsIgnoreCase( VALUE_BEGINNING ) )
{
return WidgetAlignment.BEGINNING;
}
else if ( text.equalsIgnoreCase( VALUE_CENTER ) )
{
return WidgetAlignment.CENTER;
}
else if ( text.equalsIgnoreCase( VALUE_END ) )
{
return WidgetAlignment.END;
}
else if ( text.equalsIgnoreCase( VALUE_FILL ) )
{
return WidgetAlignment.FILL;
}
else
{
String message = NLS.bind( Messages.getString( "TemplateIO.UnableToConvertStringToWidgetAlignmentValue" ), //$NON-NLS-1$
new String[]
{ VALUE_NONE, VALUE_BEGINNING, VALUE_CENTER, VALUE_END, VALUE_FILL, text } );
LOG.error( message );
throw new TemplateIOException( THE_FILE_DOES_NOT_SEEM_TO_BE_A_VALID_TEMPLATE_FILE + "\n" + message ); //$NON-NLS-1$
}
}
/**
* Reads the attribute type attribute.
*
* @param element
* the element to read from
* @param widget
* the associated widget
* @return
* <code>true</code> if the attribute type attribute has been found,
* <code>false</code> if not
*/
private static boolean readAttributeTypeAttribute( Element element, TemplateWidget widget )
{
// Reading the 'attributeType' attribute
Attribute attributeTypeAttribute = element.attribute( ATTRIBUTE_ATTRIBUTETYPE );
if ( ( attributeTypeAttribute != null ) && ( attributeTypeAttribute.getText() != null ) )
{
widget.setAttributeType( attributeTypeAttribute.getText() );
return true;
}
return false;
}
/**
* Reads a checkbox widget.
*
* @param element
* the element
* @param template
* the template
* @throws TemplateIOException
*/
private static void readCheckbox( Element element, TemplateWidget parent ) throws TemplateIOException
{
LOG.debug( "Reading a template checkbox" ); //$NON-NLS-1$
// Creating the checkbox
TemplateCheckbox templateCheckbox = new TemplateCheckbox( parent );
// Reading the widget's common properties
readWidgetCommonProperties( element, templateCheckbox, true, ELEMENT_CHECKBOX );
// Reading the 'label' attribute
Attribute labelAttribute = element.attribute( ATTRIBUTE_LABEL );
if ( ( labelAttribute != null ) && ( labelAttribute.getText() != null ) )
{
templateCheckbox.setLabel( labelAttribute.getText() );
}
// Reading the 'enabled' attribute
Attribute enabledAttribute = element.attribute( ATTRIBUTE_ENABLED );
if ( ( enabledAttribute != null ) && ( enabledAttribute.getText() != null ) )
{
templateCheckbox.setEnabled( readBoolean( enabledAttribute.getText() ) );
}
// Reading the 'checkedValue' element
Element checkedValueElement = element.element( ELEMENT_CHECKEDVALUE );
if ( checkedValueElement != null )
{
templateCheckbox.setCheckedValue( checkedValueElement.getText() );
}
// Reading the 'uncheckedValue' element
Element uncheckedValueElement = element.element( ELEMENT_UNCHECKEDVALUE );
if ( uncheckedValueElement != null )
{
templateCheckbox.setUncheckedValue( uncheckedValueElement.getText() );
}
}
/**
* Reads a composite widget.
*
* @param element
* the element
* @param template
* the template
* @throws TemplateIOException
*/
private static void readComposite( Element element, TemplateWidget parent ) throws TemplateIOException
{
LOG.debug( "Reading a template composite" ); //$NON-NLS-1$
// Creating the composite
TemplateComposite templateComposite = new TemplateComposite( parent );
// Reading the widget's common properties
readWidgetCommonProperties( element, templateComposite, false, ELEMENT_COMPOSITE );
// Reading the 'numberOfColumns' attribute
Attribute numberOfColumnsAttribute = element.attribute( ATTRIBUTE_NUMBEROFCOLUMNS );
if ( ( numberOfColumnsAttribute != null ) && ( numberOfColumnsAttribute.getText() != null ) )
{
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.parser;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.model.parser.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIOException.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/model/parser/TemplateIOException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.model.parser;
/**
* This exception can be raised when loading template file.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateIOException extends Exception
{
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of TemplateIOException.
*
* @param message
* the message
*/
public TemplateIOException( String message )
{
super( message );
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/MultiTabTemplateEntryEditor.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/MultiTabTemplateEntryEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
/**
* An entry editor the opens entries in a single editor for each entry.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class MultiTabTemplateEntryEditor extends TemplateEntryEditor
{
/**
* {@inheritDoc}
*/
public boolean isAutoSave()
{
return false;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEntryEditorNavigationLocation.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEntryEditorNavigationLocation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.entryeditors.EntryEditorExtension;
import org.apache.directory.studio.entryeditors.EntryEditorInput;
import org.apache.directory.studio.entryeditors.EntryEditorManager;
import org.apache.directory.studio.entryeditors.EntryEditorUtils;
import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin;
import org.apache.directory.studio.ldapbrowser.core.model.IBookmark;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.ISearch;
import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult;
import org.apache.directory.studio.ldapbrowser.ui.BrowserUIPlugin;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.INavigationLocation;
import org.eclipse.ui.NavigationLocation;
/**
* This class is used to mark the entry editor input to the navigation history.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateEntryEditorNavigationLocation extends NavigationLocation
{
private static final String BOOKMARK_TAG = "BOOKMARK"; //$NON-NLS-1$
private static final String CONNECTION_TAG = "CONNECTION"; //$NON-NLS-1$
private static final String DN_TAG = "DN"; //$NON-NLS-1$
private static final String EXTENSION_TAG = "EXTENSION"; //$NON-NLS-1$
private static final String SEARCH_TAG = "SEARCH"; //$NON-NLS-1$
private static final String TYPE_BOOKMARK_VALUE = "IBookmark"; //$NON-NLS-1$
private static final String TYPE_SEARCHRESULT_VALUE = "ISearchResult"; //$NON-NLS-1$
private static final String TYPE_TAG = "TYPE"; //$NON-NLS-1$
private static final String TYPE_ENTRY_VALUE = "IEntry"; //$NON-NLS-1$
/**
* Creates a new instance of EntryEditorNavigationLocation.
*
* @param editor the entry editor
*/
protected TemplateEntryEditorNavigationLocation( IEditorPart editor )
{
super( editor );
}
/**
* {@inheritDoc}
*/
public String getText()
{
String text = EntryEditorUtils.getHistoryNavigationText( getEntryEditorInput() );
return text != null ? text : super.getText();
}
/**
* {@inheritDoc}
*/
public void saveState( IMemento memento )
{
EntryEditorInput eei = getEntryEditorInput();
if ( eei != null )
{
memento.putString( EXTENSION_TAG, eei.getExtension().getId() );
if ( eei.getEntryInput() != null )
{
IEntry entry = eei.getEntryInput();
memento.putString( TYPE_TAG, TYPE_ENTRY_VALUE );
memento.putString( DN_TAG, entry.getDn().getName() );
memento.putString( CONNECTION_TAG, entry.getBrowserConnection().getConnection().getId() );
}
else if ( eei.getSearchResultInput() != null )
{
ISearchResult searchResult = eei.getSearchResultInput();
memento.putString( TYPE_TAG, TYPE_SEARCHRESULT_VALUE );
memento.putString( DN_TAG, searchResult.getDn().getName() );
memento.putString( SEARCH_TAG, searchResult.getSearch().getName() );
memento.putString( CONNECTION_TAG, searchResult.getSearch().getBrowserConnection().getConnection()
.getId() );
}
else if ( eei.getBookmarkInput() != null )
{
IBookmark bookmark = eei.getBookmarkInput();
memento.putString( TYPE_TAG, TYPE_BOOKMARK_VALUE );
memento.putString( BOOKMARK_TAG, bookmark.getName() );
memento.putString( CONNECTION_TAG, bookmark.getBrowserConnection().getConnection().getId() );
}
}
}
/**
* {@inheritDoc}
*/
public void restoreState( IMemento memento )
{
try
{
String type = memento.getString( TYPE_TAG );
String extensionId = memento.getString( EXTENSION_TAG );
EntryEditorManager entryEditorManager = BrowserUIPlugin.getDefault().getEntryEditorManager();
EntryEditorExtension entryEditorExtension = entryEditorManager.getEntryEditorExtension( extensionId );
if ( TYPE_ENTRY_VALUE.equals( type ) )
{
IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager()
.getBrowserConnectionById( memento.getString( CONNECTION_TAG ) );
Dn dn = new Dn( memento.getString( DN_TAG ) );
IEntry entry = connection.getEntryFromCache( dn );
super.setInput( new EntryEditorInput( entry, entryEditorExtension ) );
}
else if ( TYPE_SEARCHRESULT_VALUE.equals( type ) )
{
IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager()
.getBrowserConnectionById( memento.getString( CONNECTION_TAG ) );
ISearch search = connection.getSearchManager().getSearch( memento.getString( SEARCH_TAG ) );
ISearchResult[] searchResults = search.getSearchResults();
Dn dn = new Dn( memento.getString( DN_TAG ) );
for ( int i = 0; i < searchResults.length; i++ )
{
if ( dn.equals( searchResults[i].getDn() ) )
{
super.setInput( new EntryEditorInput( searchResults[i], entryEditorExtension ) );
break;
}
}
}
else if ( TYPE_BOOKMARK_VALUE.equals( type ) )
{
IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager()
.getBrowserConnectionById( memento.getString( CONNECTION_TAG ) );
IBookmark bookmark = connection.getBookmarkManager().getBookmark( memento.getString( BOOKMARK_TAG ) );
super.setInput( new EntryEditorInput( bookmark, entryEditorExtension ) );
}
}
catch ( LdapInvalidDnException e )
{
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
public void restoreLocation()
{
}
/**
* {@inheritDoc}
*/
public boolean mergeInto( INavigationLocation currentLocation )
{
if ( currentLocation == null )
{
return false;
}
if ( getClass() != currentLocation.getClass() )
{
return false;
}
TemplateEntryEditorNavigationLocation location = ( TemplateEntryEditorNavigationLocation ) currentLocation;
Object other = location.getEntryEditorInput().getInput();
Object entry = getEntryEditorInput().getInput();
if ( other == null && entry == null )
{
return true;
}
else if ( other == null || entry == null )
{
return false;
}
else
{
return entry.equals( other );
}
}
/**
* {@inheritDoc}
*/
public void update()
{
}
/**
* Gets the input.
*
* @return the input
*/
private EntryEditorInput getEntryEditorInput()
{
Object editorInput = getInput();
if ( editorInput instanceof EntryEditorInput )
{
EntryEditorInput entryEditorInput = ( EntryEditorInput ) editorInput;
return entryEditorInput;
}
return null;
}
/**
* {@inheritDoc}
*/
public String toString()
{
return "" + getEntryEditorInput().getInput(); //$NON-NLS-1$
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.editor.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/SingleTabTemplateEntryEditor.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/SingleTabTemplateEntryEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
/**
* An entry editor the opens all entries in one single editor tab.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SingleTabTemplateEntryEditor extends TemplateEntryEditor
{
/**
* {@inheritDoc}
*/
public boolean isAutoSave()
{
return false;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEditorWidget.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEditorWidget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.directory.studio.entryeditors.EntryEditorInput;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.actions.DisplayEntryInTemplateAction;
import org.apache.directory.studio.templateeditor.actions.DisplayEntryInTemplateMenuManager;
import org.apache.directory.studio.templateeditor.actions.EditorPagePropertiesAction;
import org.apache.directory.studio.templateeditor.actions.RefreshAction;
import org.apache.directory.studio.templateeditor.actions.SimpleActionProxy;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorCheckbox;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorComposite;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorDate;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorFileChooser;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorImage;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorLabel;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorLink;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorListbox;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorPassword;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorRadioButtons;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorSection;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorSpinner;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorTable;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorTextField;
import org.apache.directory.studio.templateeditor.editor.widgets.EditorWidget;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateCheckbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateComposite;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateDate;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateFileChooser;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateForm;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateImage;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLabel;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLink;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateListbox;
import org.apache.directory.studio.templateeditor.model.widgets.TemplatePassword;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateRadioButtons;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSection;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSpinner;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTable;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTextField;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateWidget;
/**
* This class implements a widget for the Template Editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateEditorWidget
{
/** The associated editor */
private IEntryEditor editor;
/** The flag to know whether or not the widget has been initialized */
private boolean initialized = false;
/** The parent {@link Composite} of the widget */
private Composite parent;
/** The associated {@link FormToolkit} */
private FormToolkit toolkit;
/** The associated {@link ScrolledForm} */
private ScrolledForm form;
/** The currently selected template */
private Template selectedTemplate;
/** The context menu */
private Menu contextMenu;
/** The list of editor widgets */
private Map<TemplateWidget, EditorWidget<? extends TemplateWidget>> editorWidgets = new HashMap<TemplateWidget, EditorWidget<? extends TemplateWidget>>();
/**
* Creates a new instance of TemplateEditorWidget.
*
* @param editor
* the editor
*/
public TemplateEditorWidget( IEntryEditor editor )
{
this.editor = editor;
}
/**
* {@inheritDoc}
*/
public void init( Composite parent )
{
initialized = true;
this.parent = parent;
// Creating the toolkit
toolkit = new FormToolkit( parent.getDisplay() );
// Creating the new form
form = toolkit.createScrolledForm( parent );
form.getBody().setLayout( new GridLayout() );
form.getToolBarManager().add( new RefreshAction( getEditor() ) );
form.getToolBarManager().add( new Separator() );
form.getToolBarManager().add( new DisplayEntryInTemplateAction( this ) );
form.getToolBarManager().update( true );
// Creating the new menu manager
MenuManager menuManager = new MenuManager();
contextMenu = menuManager.createContextMenu( form );
form.setMenu( contextMenu );
// Adding actions to the menu manager
menuManager.add( new DisplayEntryInTemplateMenuManager( this ) );
menuManager.add( new Separator() );
menuManager.add( new RefreshAction( getEditor() ) );
menuManager.add( new Separator() );
menuManager.add( new SimpleActionProxy( new EditorPagePropertiesAction( getEditor() ) ) );
createFormContent();
parent.layout();
}
/**
* Creates the from content
*/
private void createFormContent()
{
EntryEditorInput entryEditorInput = getEditor().getEntryEditorInput();
// Checking if the input is null
if ( entryEditorInput == null )
{
createFormContentUnableToDisplayTheEntry();
}
else
{
// Getting the entry and the template
IEntry entry = entryEditorInput.getSharedWorkingCopy( getEditor() );
// Special case in the case the entry is null
if ( entry == null )
{
// Hiding the context menu
form.setMenu( null );
// Creating the form content
createFormContentNoEntrySelected();
}
else
{
// Showing the context menu
form.setMenu( contextMenu );
// Checking if a template is selected
if ( selectedTemplate == null )
{
List<Template> matchingTemplates = EntryTemplatePluginUtils.getMatchingTemplates( entry );
if ( ( matchingTemplates != null ) && ( matchingTemplates.size() > 0 ) )
{
// Looking for the default template
for ( Template matchingTemplate : matchingTemplates )
{
if ( EntryTemplatePlugin.getDefault().getTemplatesManager().isDefaultTemplate(
matchingTemplate ) )
{
selectedTemplate = matchingTemplate;
break;
}
}
// If no default template has been found,
// select the first one
if ( selectedTemplate == null )
{
// Assigning the first template as the selected one
selectedTemplate = matchingTemplates.get( 0 );
}
// Creating the form content
createFormContentFromTemplate();
}
else
{
// Creating the form content
createFormContentNoTemplateMatching();
}
}
else
{
// Creating the form content
createFormContentFromTemplate();
}
}
}
form.layout( true, true );
}
/**
* Gets the associated editor.
*
* @return
*/
public IEntryEditor getEditor()
{
return editor;
}
/**
* Creates the form UI in case where the entry cannot be displayed.
*/
private void createFormContentUnableToDisplayTheEntry()
{
// Displaying an error message
form.setText( Messages.getString( "TemplateEditorWidget.UnableToDisplayTheEntry" ) ); //$NON-NLS-1$
form.setImage( PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) );
}
/**
* Creates the form UI from the template.
*
* @param managedForm
* the form
*/
private void createFormContentFromTemplate()
{
form.setText( selectedTemplate.getTitle() );
// Getting the template form
TemplateForm templateForm = selectedTemplate.getForm();
// Creating the children widgets
if ( templateForm.hasChildren() )
{
for ( TemplateWidget templateWidget : templateForm.getChildren() )
{
createFormTemplateWidget( form.getBody(), templateWidget );
}
}
}
/**
* Creates the editor widget associated with the {@link TemplateWidget} object .
*
* @param parent
* the parent composite
* @param templateWidget
* the template widget
*/
private void createFormTemplateWidget( Composite parent, TemplateWidget templateWidget )
{
// The widget composite
Composite widgetComposite = null;
// Creating the widget according to its type
if ( templateWidget instanceof TemplateCheckbox )
{
// Creating the editor checkbox
EditorCheckbox editorCheckbox = new EditorCheckbox( getEditor(), ( TemplateCheckbox ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorCheckbox );
// Creating the UI
widgetComposite = editorCheckbox.createWidget( parent );
}
else if ( templateWidget instanceof TemplateComposite )
{
// Creating the editor composite
EditorComposite editorComposite = new EditorComposite( getEditor(), ( TemplateComposite ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorComposite );
// Creating the UI
widgetComposite = editorComposite.createWidget( parent );
}
else if ( templateWidget instanceof TemplateDate )
{
// Creating the editor date
EditorDate editorDate = new EditorDate( getEditor(), ( TemplateDate ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorDate );
// Creating the UI
widgetComposite = editorDate.createWidget( parent );
}
else if ( templateWidget instanceof TemplateFileChooser )
{
// Creating the editor file chooser
EditorFileChooser editorFileChooser = new EditorFileChooser( getEditor(),
( TemplateFileChooser ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorFileChooser );
// Creating the UI
widgetComposite = editorFileChooser.createWidget( parent );
}
else if ( templateWidget instanceof TemplateImage )
{
// Creating the editor image
EditorImage editorImage = new EditorImage( getEditor(), ( TemplateImage ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorImage );
// Creating the UI
widgetComposite = editorImage.createWidget( parent );
}
else if ( templateWidget instanceof TemplateLabel )
{
// Creating the editor label
EditorLabel editorLabel = new EditorLabel( getEditor(), ( TemplateLabel ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorLabel );
// Creating the UI
widgetComposite = editorLabel.createWidget( parent );
}
else if ( templateWidget instanceof TemplateLink )
{
// Creating the editor link
EditorLink editorLink = new EditorLink( getEditor(), ( TemplateLink ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorLink );
// Creating the UI
widgetComposite = editorLink.createWidget( parent );
}
else if ( templateWidget instanceof TemplateListbox )
{
// Creating the editor link
EditorListbox editorListbox = new EditorListbox( getEditor(), ( TemplateListbox ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorListbox );
// Creating the UI
widgetComposite = editorListbox.createWidget( parent );
}
else if ( templateWidget instanceof TemplatePassword )
{
// Creating the editor password
EditorPassword editorPassword = new EditorPassword( getEditor(), ( TemplatePassword ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorPassword );
// Creating the UI
widgetComposite = editorPassword.createWidget( parent );
}
else if ( templateWidget instanceof TemplateRadioButtons )
{
// Creating the editor radio buttons
EditorRadioButtons editorRadioButtons = new EditorRadioButtons( getEditor(),
( TemplateRadioButtons ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorRadioButtons );
// Creating the UI
widgetComposite = editorRadioButtons.createWidget( parent );
}
else if ( templateWidget instanceof TemplateSection )
{
// Creating the editor section
EditorSection editorSection = new EditorSection( getEditor(), ( TemplateSection ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorSection );
// Creating the UI
widgetComposite = editorSection.createWidget( parent );
}
else if ( templateWidget instanceof TemplateSpinner )
{
// Creating the editor spinner
EditorSpinner editorSpinner = new EditorSpinner( getEditor(), ( TemplateSpinner ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorSpinner );
// Creating the UI
widgetComposite = editorSpinner.createWidget( parent );
}
else if ( templateWidget instanceof TemplateTable )
{
// Creating the editor table
EditorTable editorTable = new EditorTable( getEditor(), ( TemplateTable ) templateWidget, getToolkit() );
editorWidgets.put( templateWidget, editorTable );
// Creating the UI
widgetComposite = editorTable.createWidget( parent );
}
else if ( templateWidget instanceof TemplateTextField )
{
// Creating the editor text field
EditorTextField editorTextField = new EditorTextField( getEditor(), ( TemplateTextField ) templateWidget,
getToolkit() );
editorWidgets.put( templateWidget, editorTextField );
// Creating the UI
widgetComposite = editorTextField.createWidget( parent );
}
// Recursively looping on children
if ( templateWidget.hasChildren() )
{
for ( TemplateWidget templateWidgetChild : templateWidget.getChildren() )
{
createFormTemplateWidget( widgetComposite, templateWidgetChild );
}
}
}
/**
* Creates the form UI in case where no entry is selected.
*/
private void createFormContentNoEntrySelected()
{
// Displaying an error message
form.setText( Messages.getString( "TemplateEditorWidget.NoEntrySelected" ) ); //$NON-NLS-1$
}
/**
* Creates the form UI in case where no template is matching.
*/
private void createFormContentNoTemplateMatching()
{
// Displaying an error message
form.setText( Messages.getString( "TemplateEditorWidget.NoTemplateIsMatchingThisEntry" ) ); //$NON-NLS-1$
}
/**
* Gets the {@link FormToolkit} associated with the editor page.
*
* @return
* the {@link FormToolkit} associated with the editor page
*/
public FormToolkit getToolkit()
{
return toolkit;
}
/**
* {@inheritDoc}
*/
public void dispose()
{
//
// Disposing the toolkit, form and widgets
//
// Toolkit
if ( toolkit != null )
{
toolkit.dispose();
}
// Form
if ( ( form != null ) && ( !form.isDisposed() ) )
{
form.dispose();
}
// Widgets
for ( TemplateWidget key : editorWidgets.keySet() )
{
EditorWidget<?> widget = editorWidgets.get( key );
widget.dispose();
}
}
/**
* {@inheritDoc}
*/
public void update()
{
if ( isInitialized() )
{
// Updating widgets
for ( TemplateWidget key : editorWidgets.keySet() )
{
EditorWidget<?> widget = editorWidgets.get( key );
widget.update();
}
}
}
/**
* {@inheritDoc}
*/
public void setFocus()
{
if ( ( form != null ) && ( !form.isDisposed() ) )
{
form.setFocus();
}
}
/**
* {@inheritDoc}
*/
public void editorInputChanged()
{
if ( isInitialized() )
{
// Resetting the template
selectedTemplate = null;
// Updating the UI
disposeAndRecreateUI();
}
}
/**
* Gets the {@link List} of templates matching the current entry.
*
* @return
* the {@link List} of templates matching the current entry
*/
public List<Template> getMatchingTemplates()
{
return EntryTemplatePluginUtils.getMatchingTemplates( getEditor().getEntryEditorInput().getSharedWorkingCopy(
getEditor() ) );
}
/**
* Gets the selected template.
*
* @return
* the selected template
*/
public Template getSelectedTemplate()
{
return selectedTemplate;
}
/**
* Displays the entry with the given template.
*
* @param selectedTemplate
* the selected template
*/
public void switchTemplate( Template selectedTemplate )
{
// Assigning the selected template
this.selectedTemplate = selectedTemplate;
// Updating the UI
disposeAndRecreateUI();
}
/**
* Disposes and re-creates the UI (if the editor page has been initialized).
*/
private void disposeAndRecreateUI()
{
if ( isInitialized() )
{
// Disposing the previously created form
if ( ( form != null ) && ( !form.isDisposed() ) )
{
// Disposing the from (and all it's children elements
form.dispose();
// Disposing template widgets
for ( TemplateWidget key : editorWidgets.keySet() )
{
EditorWidget<?> widget = editorWidgets.get( key );
widget.dispose();
}
}
// Clearing all previously created editor widgets (which are now disposed)
editorWidgets.clear();
// Recreating the UI
init( parent );
}
}
/**
* Gets the associated {@link Form}.
*
* @return
* the associated {@link Form}
*/
public ScrolledForm getForm()
{
return form;
}
/**
* Indicated if the widget has been initialized.
*
* @return
* <code>true</code> if the widget has been initialized,
* <code>false</code> if not
*/
public boolean isInitialized()
{
return initialized;
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEntryEditor.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/TemplateEntryEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor;
import org.apache.directory.studio.entryeditors.EntryEditorInput;
import org.apache.directory.studio.entryeditors.EntryEditorUtils;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.ui.BrowserUIConstants;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.INavigationLocation;
import org.eclipse.ui.INavigationLocationProvider;
import org.eclipse.ui.IReusableEditor;
import org.eclipse.ui.IShowEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
/**
* This class implements the Template Entry Editor.
* <p>
* This editor is composed of a three tabs TabFolder object:
* <ul>
* <li>the Template Editor itself</li>
* <li>the Table Editor</li>
* <li>the LDIF Editor</li>
* </ul>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class TemplateEntryEditor extends EditorPart implements INavigationLocationProvider, IEntryEditor,
IReusableEditor, IShowEditorInput
{
/** The Template Editor page */
private TemplateEditorWidget templateEditorWidget;
/**
* {@inheritDoc}
*/
public void init( IEditorSite site, IEditorInput input ) throws PartInitException
{
setSite( site );
setInput( input );
}
/**
* {@inheritDoc}
*/
public void createPartControl( Composite parent )
{
templateEditorWidget = new TemplateEditorWidget( this );
templateEditorWidget.init( parent );
}
/**
* {@inheritDoc}
*/
public void workingCopyModified( Object source )
{
update();
if ( !isAutoSave() )
{
// mark as dirty
firePropertyChange( PROP_DIRTY );
}
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Template Editor Widget
if ( templateEditorWidget != null )
{
templateEditorWidget.dispose();
}
super.dispose();
}
/**
* {@inheritDoc}
*/
public boolean canHandle( IEntry entry )
{
int useTemplateEditorFor = EntryTemplatePlugin.getDefault().getPreferenceStore().getInt(
EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR );
if ( useTemplateEditorFor == EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR_ANY_ENTRY )
{
return true;
}
else if ( useTemplateEditorFor == EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR_ENTRIES_WITH_TEMPLATE )
{
if ( entry == null )
{
return true;
}
return canBeHandledWithATemplate( entry );
}
return false;
}
/**
* Indicates whether or not the entry can be handled with a (at least) template.
*
* @param entry
* the entry
* @return
* <code>true</code> if the entry can be handled with a template,
* <code>false</code> if not.
*/
private boolean canBeHandledWithATemplate( IEntry entry )
{
return ( EntryTemplatePluginUtils.getMatchingTemplates( entry ).size() > 0 );
}
/**
* {@inheritDoc}
*/
public void doSave( IProgressMonitor monitor )
{
if ( !isAutoSave() )
{
EntryEditorInput eei = getEntryEditorInput();
eei.saveSharedWorkingCopy( true, this );
}
}
/**
* {@inheritDoc}
*/
public boolean isDirty()
{
return getEntryEditorInput().isSharedWorkingCopyDirty( this );
}
/**
* {@inheritDoc}
*/
public boolean isSaveAsAllowed()
{
return false;
}
/**
* {@inheritDoc}
*/
public void doSaveAs()
{
// Nothing to do, will never occur as "Save As..." is not allowed
}
/**
* {@inheritDoc}
*/
public void setFocus()
{
if ( templateEditorWidget != null )
{
templateEditorWidget.setFocus();
}
}
/**
* {@inheritDoc}
*/
public EntryEditorInput getEntryEditorInput()
{
Object editorInput = getEditorInput();
if ( editorInput instanceof EntryEditorInput )
{
return ( EntryEditorInput ) editorInput;
}
return null;
}
/**
* Updates the selected AbstractTemplateEntryEditorPage.
*/
private void update()
{
if ( templateEditorWidget != null )
{
templateEditorWidget.update();
}
}
/**
* {@inheritDoc}
*/
public void setInput( IEditorInput input )
{
super.setInput( input );
setPartName( input.getName() );
}
/**
* {@inheritDoc}
*/
public INavigationLocation createEmptyNavigationLocation()
{
return null;
}
/**
* {@inheritDoc}
*/
public INavigationLocation createNavigationLocation()
{
return new TemplateEntryEditorNavigationLocation( this );
}
/**
* {@inheritDoc}
*/
public void showEditorInput( IEditorInput input )
{
if ( input instanceof EntryEditorInput )
{
/*
* Optimization: no need to set the input again if the same input is already set
*/
if ( getEntryEditorInput() != null
&& getEntryEditorInput().getResolvedEntry() == ( ( EntryEditorInput ) input ).getResolvedEntry() )
{
return;
}
// If the editor is dirty, let's ask for a save before changing the input
if ( isDirty() )
{
if ( !EntryEditorUtils.askSaveSharedWorkingCopyBeforeInputChange( this ) )
{
return;
}
}
// now set the real input and mark history location
setInput( input );
getSite().getPage().getNavigationHistory().markLocation( this );
firePropertyChange( BrowserUIConstants.INPUT_CHANGED );
// Updating the input on the template editor widget
templateEditorWidget.editorInputChanged();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorTable.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorTable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.util.Comparator;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.common.dialogs.TextDialog;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTable;
/**
* This class implements an editor table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorTable extends EditorWidget<TemplateTable>
{
/** The widget's composite */
private Composite composite;
/** The table viewer */
private TableViewer tableViewer;
/** The 'Add...' button */
private ToolItem addToolItem;
/** The 'Edit...' button */
private ToolItem editToolItem;
/** The 'Delete...' button */
private ToolItem deleteToolItem;
/**
* Creates a new instance of EditorTable.
*
* @param editor
* the associated editor
* @param templateTable
* the associated template table
* @param toolkit
* the associated toolkit
*/
public EditorTable( IEntryEditor editor, TemplateTable templateTable, FormToolkit toolkit )
{
super( templateTable, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the widget composite
composite = getToolkit().createComposite( parent );
composite.setLayoutData( getGridata() );
// Creating the layout
GridLayout gl = new GridLayout( ( needsToolbar() ? 2 : 1 ), false );
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Table Viewer
Table table = getToolkit().createTable( composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL );
table.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
tableViewer = new TableViewer( table );
tableViewer.setContentProvider( new ArrayContentProvider() );
tableViewer.setComparator( new ViewerComparator( new Comparator<String>()
{
public int compare( String s1, String s2 )
{
if ( s1 == null )
{
return 1;
}
else if ( s2 == null )
{
return -1;
}
else
{
return s1.compareToIgnoreCase( s2 );
}
}
} ) );
// Toolbar (if needed)
if ( needsToolbar() )
{
ToolBar toolbar = new ToolBar( composite, SWT.VERTICAL );
toolbar.setLayoutData( new GridData( SWT.NONE, SWT.FILL, false, true ) );
// Add Button
if ( getWidget().isShowAddButton() )
{
addToolItem = new ToolItem( toolbar, SWT.PUSH );
addToolItem.setToolTipText( Messages.getString( "EditorTable.Add" ) ); //$NON-NLS-1$
addToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_ADD_VALUE ) );
}
// Edit Button
if ( getWidget().isShowEditButton() )
{
editToolItem = new ToolItem( toolbar, SWT.PUSH );
editToolItem.setToolTipText( Messages.getString( "EditorTable.Edit" ) ); //$NON-NLS-1$
editToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_EDIT_VALUE ) );
editToolItem.setEnabled( false );
}
// Delete Button
if ( getWidget().isShowDeleteButton() )
{
deleteToolItem = new ToolItem( toolbar, SWT.PUSH );
deleteToolItem.setToolTipText( Messages.getString( "EditorTable.Delete" ) ); //$NON-NLS-1$
deleteToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_DELETE_VALUE ) );
deleteToolItem.setEnabled( false );
}
}
return composite;
}
/**
* Indicates if the widget needs a toolbar for actions.
*
* @return
* <code>true</code> if the widget needs a toolbar for actions,
* <code>false</code> if not
*/
private boolean needsToolbar()
{
return getWidget().isShowAddButton() || getWidget().isShowEditButton() || getWidget().isShowDeleteButton();
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
tableViewer.setInput( attribute.getStringValues() );
}
else
{
tableViewer.setInput( new String[0] );
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Add button
if ( ( addToolItem != null ) && ( !addToolItem.isDisposed() ) )
{
addToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addToolItemAction();
}
} );
}
// Edit button
if ( ( editToolItem != null ) && ( !editToolItem.isDisposed() ) )
{
editToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editToolItemAction();
}
} );
}
// Delete button
if ( ( deleteToolItem != null ) && ( !deleteToolItem.isDisposed() ) )
{
deleteToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
deleteToolItemAction();
}
} );
}
// Table Viewer
if ( ( tableViewer != null ) && ( !tableViewer.getTable().isDisposed() ) )
{
tableViewer.addSelectionChangedListener( new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
updateButtonsStates();
}
} );
tableViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
if ( ( editToolItem != null ) && ( !editToolItem.isDisposed() ) )
{
editToolItemAction();
}
}
} );
}
}
/**
* This method is called when the 'Add...' toolbar item is clicked.
*/
private void addToolItemAction()
{
TextDialog textDialog = new TextDialog( tableViewer.getTable().getShell(), "" ); //$NON-NLS-1$
if ( textDialog.open() == Dialog.OK )
{
String value = textDialog.getText();
addAttributeValue( value );
tableViewer.setSelection( new StructuredSelection( value ) );
}
}
/**
* This method is called when the 'Edit...' toolbar item is clicked.
*/
private void editToolItemAction()
{
StructuredSelection selection = ( StructuredSelection ) tableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedValue = ( String ) selection.getFirstElement();
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
IValue value = null;
for ( IValue attributeValue : attribute.getValues() )
{
if ( selectedValue.equals( attributeValue.getStringValue() ) )
{
value = attributeValue;
break;
}
}
if ( value != null )
{
TextDialog textDialog = new TextDialog( tableViewer.getTable().getShell(), selectedValue );
if ( textDialog.open() == Dialog.OK )
{
String newValue = textDialog.getText();
if ( !selectedValue.equals( newValue ) )
{
deleteAttributeValue( selectedValue );
addAttributeValue( newValue );
tableViewer.setSelection( new StructuredSelection( newValue ) );
}
}
}
}
}
}
/**
* This method is called when the 'Delete...' toolbar item is clicked.
*/
private void deleteToolItemAction()
{
StructuredSelection selection = ( StructuredSelection ) tableViewer.getSelection();
if ( !selection.isEmpty() )
{
// Launching a confirmation dialog
if ( MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages
.getString( "EditorTable.Confirmation" ), Messages.getString( "EditorTable.ConfirmationDeleteValue" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
deleteAttributeValue( ( String ) selection.getFirstElement() );
}
}
}
/**
* Updates the states of the buttons.
*/
private void updateButtonsStates()
{
StructuredSelection selection = ( StructuredSelection ) tableViewer.getSelection();
if ( ( editToolItem != null ) && ( !editToolItem.isDisposed() ) )
{
editToolItem.setEnabled( !selection.isEmpty() );
}
if ( ( deleteToolItem != null ) && ( !deleteToolItem.isDisposed() ) )
{
deleteToolItem.setEnabled( !selection.isEmpty() );
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorComposite.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorComposite.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateComposite;
/**
* This class implements an editor composite.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorComposite extends EditorWidget<TemplateComposite>
{
/**
* Creates a new instance of EditorComposite.
*
* @param editor
* the associated editor
* @param templateComposite
* the associated template composite
* @param toolkit
* the associated toolkit
*/
public EditorComposite( IEntryEditor editor, TemplateComposite templateComposite, FormToolkit toolkit )
{
super( templateComposite, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
Composite composite = getToolkit().createComposite( parent );
composite.setLayout( new GridLayout( getWidget().getNumberOfColumns(), getWidget().isEqualColumns() ) );
composite.setLayoutData( getGridata() );
return composite;
}
/**
* {@inheritDoc}
*/
public void update()
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorPassword.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorPassword.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.valueeditors.password.PasswordDialog;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.model.widgets.TemplatePassword;
/**
* This class implements an editor spinner.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorPassword extends EditorWidget<TemplatePassword>
{
/** The current password value */
private byte[] currentPassword;
/** The password text field */
private Text passwordTextField;
/** The "Edit..." button */
private ToolItem editToolItem;
/** The "Show Password" checkbox*/
private Button showPasswordCheckbox;
/**
* Creates a new instance of EditorPassword.
*
* @param editor
* the associated editor
* @param templatePassword
* the associated template password
* @param toolkit
* the associated toolkit
*/
public EditorPassword( IEntryEditor editor, TemplatePassword templatePassword, FormToolkit toolkit )
{
super( templatePassword, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the widget composite
Composite composite = getToolkit().createComposite( parent );
composite.setLayoutData( getGridata() );
// Calculating the number of columns needed
int numberOfColumns = 1;
if ( getWidget().isShowEditButton() )
{
numberOfColumns++;
}
// Creating the layout
GridLayout gl = new GridLayout( numberOfColumns, false );
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Creating the password text field
passwordTextField = getToolkit().createText( composite, null, SWT.BORDER );
passwordTextField.setEditable( false );
GridData gd = new GridData( SWT.FILL, SWT.CENTER, true, false );
gd.widthHint = 50;
passwordTextField.setLayoutData( gd );
// Setting the echo char for the password text field
if ( getWidget().isHidden() )
{
passwordTextField.setEchoChar( '\u2022' );
}
else
{
passwordTextField.setEchoChar( '\0' );
}
// Creating the edit password button
if ( getWidget().isShowEditButton() )
{
ToolBar toolbar = new ToolBar( composite, SWT.HORIZONTAL | SWT.FLAT );
editToolItem = new ToolItem( toolbar, SWT.PUSH );
editToolItem.setToolTipText( Messages.getString( "EditorPassword.EditPassword" ) ); //$NON-NLS-1$
editToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_EDIT_PASSWORD ) );
}
// Creating the show password checkbox
if ( getWidget().isShowShowPasswordCheckbox() )
{
showPasswordCheckbox = getToolkit().createButton( composite,
Messages.getString( "EditorPassword.ShowPassword" ), SWT.CHECK ); //$NON-NLS-1$
}
return composite;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Getting the current password value in the attribute
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.getValueSize() > 0 ) )
{
currentPassword = attribute.getValues()[0].getBinaryValue();
}
else
{
currentPassword = null;
}
// Updating the password text field
if ( currentPassword != null )
{
passwordTextField.setText( new String( currentPassword ) );
}
else
{
passwordTextField.setText( "" ); //$NON-NLS-1$
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Edit Password toolbar item
if ( ( editToolItem != null ) && ( !editToolItem.isDisposed() ) )
{
editToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editToolItemAction();
}
} );
}
// Show Password checkbox
if ( ( showPasswordCheckbox != null ) && ( !showPasswordCheckbox.isDisposed() ) )
{
showPasswordCheckbox.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
showPasswordAction();
}
} );
}
}
/**
* This method is called when the edit tool item is clicked.
*/
private void editToolItemAction()
{
// Creating and displaying a password dialog
PasswordDialog passwordDialog = new PasswordDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell(), currentPassword, getEntry() );
if ( passwordDialog.open() == Dialog.OK )
{
if ( passwordDialog.getNewPassword() != currentPassword )
{
currentPassword = passwordDialog.getNewPassword();
passwordTextField.setText( new String( currentPassword ) );
updateEntry();
}
}
}
/**
* This action is called when the 'Show Password' checkbox is clicked.
*/
private void showPasswordAction()
{
if ( showPasswordCheckbox.getSelection() )
{
passwordTextField.setEchoChar( '\0' );
}
else
{
passwordTextField.setEchoChar( '\u2022' );
}
}
/**
* This method is called when the entry has been updated in the UI.
*/
private void updateEntry()
{
// Getting the attribute
IAttribute attribute = getAttribute();
if ( attribute == null )
{
if ( ( currentPassword != null ) && ( currentPassword.length != 0 ) )
{
// Creating a new attribute with the value
addNewAttribute( currentPassword );
}
}
else
{
if ( ( currentPassword != null ) && ( currentPassword.length != 0 ) )
{
// Modifying the existing attribute
modifyAttributeValue( currentPassword );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorLink.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorLink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLink;
/**
* This class implements an editor link.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorLink extends EditorWidget<TemplateLink>
{
/** The Regex for matching an URL */
private static final String REGEX_URL = "([a-zA-Z][a-zA-Z0-9+-.]*:[^\\s]+)"; //$NON-NLS-1$
/** The Regex for matching an email address*/
private static final String REGEX_EMAIL_ADDRESS = "([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4})"; //$NON-NLS-1$
/** The link widget */
private Link link;
/**
* Creates a new instance of EditorLink.
*
* @param editor
* the associated editor
* @param templateLink
* the associated template link
* @param toolkit
* the associated toolkit
*/
public EditorLink( IEntryEditor editor, TemplateLink templateLink, FormToolkit toolkit )
{
super( templateLink, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the link widget
link = new Link( parent, SWT.NONE );
link.setLayoutData( getGridata() );
return parent;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Checking is we need to display a value taken from the entry
// or use the given value
String attributeType = getWidget().getAttributeType();
if ( attributeType != null )
{
link.setText( addLinksTags( EditorWidgetUtils.getConcatenatedValues( getEntry(), attributeType ) ) );
}
else
{
link.setText( addLinksTags( getWidget().getValue() ) );
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
link.addListener( SWT.Selection, new Listener()
{
public void handleEvent( Event event )
{
// Creating the URL
String url = null;
// Getting the text that was clicked
String text = event.text;
if ( isUrl( text ) )
{
url = text;
}
else if ( isEmailAddress( text ) )
{
url = "mailto:" + text; //$NON-NLS-1$
}
if ( url != null )
{
try
{
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL( new URL( url ) );
}
catch ( Exception e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, "An error occurred while opening the link.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorLink.ErrorMessageDialogTitle" ), Messages.getString( "EditorLink.ErrorMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
// Logging the error
EntryTemplatePluginUtils.logError( null, "An error occurred while opening the link. URL is null.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorLink.ErrorMessageDialogTitle" ), Messages.getString( "EditorLink.ErrorMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} );
}
/**
* Adds link tags (<a>link</a>) to the links (URLs and email
* addresses) found in the given string.
*
* @param s
* the string
* @return
* the string in which links have been added
*/
private static String addLinksTags( String s )
{
List<String> links = new ArrayList<String>();
// Getting the URLs
links.addAll( Arrays.asList( getUrls( s ) ) );
// Getting the email addresses
links.addAll( Arrays.asList( getEmailAddresses( s ) ) );
// Creating the final string
StringBuilder sb = new StringBuilder();
try
{
// Inserting link tags
int start = 0;
for ( String link : links )
{
int indexOfLink = s.indexOf( link );
sb.append( s.subSequence( start, indexOfLink ) );
sb.append( "<a>" ); //$NON-NLS-1$
sb.append( link );
sb.append( "</a>" ); //$NON-NLS-1$
start = indexOfLink + link.length();
}
sb.append( s.substring( start, s.length() ) );
}
catch ( StringIndexOutOfBoundsException e )
{
// In case we hit a wrong index, we fail gracefully by
// returning the original string
return s;
}
// Returning the final string
return sb.toString();
}
/**
* Get the urls contained in the email address.
*
* @param s
* the string
* @return
* an array containing the urls found in the given string
*/
private static String[] getUrls( String s )
{
return getMatchingStrings( s, Pattern.compile( REGEX_URL + ".*" ) ); //$NON-NLS-1$
}
/**
* Get the email addresses contained in the email address.
*
* @param s
* the string
* @return
* an array containing the email addresses found in the given string
*/
private static String[] getEmailAddresses( String s )
{
return getMatchingStrings( s, Pattern.compile( REGEX_EMAIL_ADDRESS + ".*" ) ); //$NON-NLS-1$
}
/**
* Get the matching strings contained in a string using a pattern.
*
* @param s
* the string
* @param p
* the pattern
* @return
* an array containing the matching strings found in the given string
*/
private static String[] getMatchingStrings( String s, Pattern p )
{
List<String> matchingStrings = new ArrayList<String>();
while ( s.length() > 0 )
{
Matcher m = p.matcher( s );
if ( m.matches() )
{
String link = m.group( 1 );
matchingStrings.add( link );
s = s.substring( link.length() );
}
else
{
s = s.substring( 1 );
}
}
return matchingStrings.toArray( new String[0] );
}
/**
* Indicates if the given string is a URL.
*
* @param s
* the string
* @return
* <code>true</code> if the given string is a URL,
* <code>false</code> if not.
*/
private boolean isUrl( String s )
{
return Pattern.matches( REGEX_URL, s );
}
/**
* Indicates if the given string is an email address.
*
* @param s
* the string
* @return
* <code>true</code> if the given string is an email address,
* <code>false</code> if not.
*/
private boolean isEmailAddress( String s )
{
return Pattern.matches( REGEX_EMAIL_ADDRESS, s );
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorImage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorImage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Base64;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateImage;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateWidget;
/**
* This class implements an editor image.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorImage extends EditorWidget<TemplateImage>
{
/** The widget's composite */
private Composite composite;
/** The image label, used to display the image */
private Label imageLabel;
/** The 'Save As...' button */
private ToolItem saveAsToolItem;
/** The 'Clear' button */
private ToolItem clearToolItem;
/** The 'Browse...' button */
private ToolItem browseToolItem;
/** The current image */
private Image image;
/** The image data as bytes array */
private byte[] imageBytes;
/** The default width */
private static int DEFAULT_WIDTH = 400;
/** The default height */
private static int DEFAULT_HEIGHT = 300;
/**
* Creates a new instance of EditorImage.
*
* @param editor
* the associated editor
* @param templateImage
* the associated template image
* @param toolkit
* the associated toolkit
*/
public EditorImage( IEntryEditor editor, TemplateImage templateImage, FormToolkit toolkit )
{
super( templateImage, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the widget composite
composite = getToolkit().createComposite( parent );
composite.setLayoutData( getGridata() );
// Creating the layout
GridLayout gl = new GridLayout( ( needsToolbar() ? 2 : 1 ), false );
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Image Label
imageLabel = getToolkit().createLabel( composite, null );
imageLabel.setLayoutData( new GridData( SWT.CENTER, SWT.CENTER, false, false ) );
// Toolbar (if needed)
if ( needsToolbar() )
{
ToolBar toolbar = new ToolBar( composite, SWT.VERTICAL );
toolbar.setLayoutData( new GridData( SWT.NONE, SWT.FILL, false, true ) );
// Save As Button
if ( getWidget().isShowSaveAsButton() )
{
saveAsToolItem = new ToolItem( toolbar, SWT.PUSH );
saveAsToolItem.setToolTipText( Messages.getString( "EditorImage.SaveAs" ) ); //$NON-NLS-1$
saveAsToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_SAVE_AS ) );
}
// Clear Button
if ( getWidget().isShowClearButton() )
{
clearToolItem = new ToolItem( toolbar, SWT.PUSH );
clearToolItem.setToolTipText( Messages.getString( "EditorImage.Clear" ) ); //$NON-NLS-1$
clearToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_CLEAR ) );
}
// Browse Button
if ( getWidget().isShowBrowseButton() )
{
browseToolItem = new ToolItem( toolbar, SWT.PUSH );
browseToolItem.setToolTipText( Messages.getString( "EditorImage.Browse" ) ); //$NON-NLS-1$
browseToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_BROWSE_IMAGE ) );
}
}
return composite;
}
/**
* Indicates if the widget needs a toolbar for actions.
*
* @return
* <code>true</code> if the widget needs a toolbar for actions,
* <code>false</code> if not
*/
private boolean needsToolbar()
{
return getWidget().isShowSaveAsButton() || getWidget().isShowClearButton() || getWidget().isShowBrowseButton();
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Initializing the image bytes from the given entry.
initImageBytesFromEntry();
// Constrains and displays it
constrainAndDisplayImage();
// Updating the states of the buttons
updateButtonsStates();
}
/**
* Initializes the image bytes from the given entry.
*/
private void initImageBytesFromEntry()
{
// Checking is we need to display a value taken from the entry
// or use the given value
String attributeType = getWidget().getAttributeType();
if ( attributeType != null )
{
// Getting the image bytes in the attribute
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isBinary() ) && ( attribute.getValueSize() > 0 ) )
{
imageBytes = attribute.getBinaryValues()[0];
}
else
{
imageBytes = null;
}
}
else
{
// Getting the image bytes given in the template
String imageDataString = getWidget().getImageData();
if ( ( imageDataString != null ) && ( !imageDataString.equals( "" ) ) ) //$NON-NLS-1$
{
imageBytes = Base64.getDecoder().decode( imageDataString );
}
}
}
/**
* Returns an {@link ImageData} constructed from an array of bytes.
*
* @param imageBytes
* the array of bytes
* @return
* the corresponding {@link ImageData}
* @throws SWTException
* if an error occurs when constructing the {@link ImageData}
*/
private ImageData getImageData( byte[] imageBytes ) throws SWTException
{
if ( imageBytes != null && imageBytes.length > 0 )
{
return new ImageData( new ByteArrayInputStream( imageBytes ) );
}
else
{
return null;
}
}
/**
* Returns the {@link ImageData} associated with the current image bytes.
*
* @return
* the {@link ImageData} associated with the current image bytes.
*/
private ImageData getImageData()
{
if ( imageBytes != null )
{
// Getting the image data associated with the bytes
try
{
return getImageData( imageBytes );
}
catch ( SWTException e )
{
// Nothing to do, we just need to return the default image.
}
}
// No image
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_NO_IMAGE ).getImageData();
}
/**
* Constrains and displays the image.
*/
private void constrainAndDisplayImage()
{
// Getting the image data
ImageData imageData = getImageData();
// Getting width and height from the template image
int templateImageWidth = getWidget().getImageWidth();
int templateImageHeight = getWidget().getImageHeight();
// No resizing is required
if ( ( templateImageWidth == TemplateWidget.DEFAULT_SIZE )
&& ( templateImageHeight == TemplateWidget.DEFAULT_SIZE ) )
{
// Checking if the dimensions of the image are greater than the default values
if ( ( imageData.width > DEFAULT_WIDTH ) || ( imageData.height > DEFAULT_HEIGHT ) )
{
// Calculating scale factors to determine whether width or height should be used
float widthScaleFactor = imageData.width / DEFAULT_WIDTH;
float heightScaleFactor = imageData.height / DEFAULT_HEIGHT;
// Resizing the image data
if ( widthScaleFactor >= heightScaleFactor )
{
imageData = getScaledImageData( imageData, DEFAULT_WIDTH, TemplateWidget.DEFAULT_SIZE );
}
else
{
imageData = getScaledImageData( imageData, TemplateWidget.DEFAULT_SIZE, DEFAULT_HEIGHT );
}
}
}
else
{
// Resizing the image data
imageData = getScaledImageData( imageData, templateImageWidth, templateImageHeight );
}
// Creating the image
image = new Image( PlatformUI.getWorkbench().getDisplay(), imageData );
// Setting the image
imageLabel.setImage( image );
}
/**
* Returns a scaled copy of the given data scaled to the given dimensions,
* or the original image data if scaling is not needed.
*
* @param imageData
* the image data
* @param width
* the preferred width
* @param height
* the preferred height
* @return
* a scaled copy of the given data scaled to the given dimensions,
* or the original image data if scaling is not needed.
*/
private ImageData getScaledImageData( ImageData imageData, int width, int height )
{
// Resizing the image with the given width value
if ( ( width != TemplateWidget.DEFAULT_SIZE ) && ( height == TemplateWidget.DEFAULT_SIZE ) )
{
// Computing the scale factor
float scaleFactor = ( float ) imageData.width / ( float ) width;
// Computing the final height
int finalHeight = ( int ) ( imageData.height / scaleFactor );
// Returning the scaled image data
return imageData.scaledTo( width, finalHeight );
}
// Resizing the image with the given height value
else if ( ( width == TemplateWidget.DEFAULT_SIZE ) && ( height != TemplateWidget.DEFAULT_SIZE ) )
{
// Computing the scale factor
float scaleFactor = ( float ) imageData.height / ( float ) height;
// Computing the final height
int finalWidth = ( int ) ( imageData.width / scaleFactor );
// Returning the scaled image data
return imageData.scaledTo( finalWidth, height );
}
// Resizing the image with the given width and height values
else if ( ( width != TemplateWidget.DEFAULT_SIZE ) && ( height != TemplateWidget.DEFAULT_SIZE ) )
{
// Returning the original image data
return imageData.scaledTo( width, height );
}
// No resizing needed
return imageData;
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Save As button
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
saveAsToolItemAction();
}
} );
}
// Clear button
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
clearToolItemAction();
}
} );
}
// Browse button
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
browseToolItemAction();
}
} );
}
}
/**
* This method is called when the 'Save As...' toolbar item is clicked.
*/
private void saveAsToolItemAction()
{
// Launching a FileDialog to select where to save the file
FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE );
String selected = fd.open();
if ( selected != null )
{
// Getting the selected file
File selectedFile = new File( selected );
if ( ( !selectedFile.exists() ) || ( selectedFile.canWrite() ) )
{
try
{
FileOutputStream fos = new FileOutputStream( selectedFile );
fos.write( imageBytes );
fos.close();
}
catch ( Exception e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, "An error occurred while saving the image to disk.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorImage.ErrorSavingMessageDialogTitle" ), Messages.getString( "EditorImage.ErrorSavingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
/**
* This method is called when the 'Clear...' toolbar item is clicked.
*/
private void clearToolItemAction()
{
// Launching a confirmation dialog
if ( MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages
.getString( "EditorImage.Confirmation" ), Messages.getString( "EditorImage.ConfirmationClearImage" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
// Removing the image bytes
imageBytes = null;
// Constrains and displays the image
constrainAndDisplayImage();
// Refreshing the states of the buttons
updateButtonsStates();
// Updating the entry
updateEntry();
// Updating the image
composite.getParent().update();
}
}
/**
* This method is called when the 'Browse...' toolbar item is clicked.
*/
private void browseToolItemAction()
{
// Launching a FileDialog to select the file to load
FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN );
String selected = fd.open();
if ( selected != null )
{
// Getting the selected file
File selectedFile = new File( selected );
if ( ( selectedFile.exists() ) && ( selectedFile.canRead() ) )
{
try
{
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try
{
fis = new FileInputStream( selectedFile );
baos = new ByteArrayOutputStream( ( int ) selectedFile.length() );
byte[] buf = new byte[4096];
int len;
while ( ( len = fis.read( buf ) ) > 0 )
{
baos.write( buf, 0, len );
}
imageBytes = baos.toByteArray();
}
finally
{
if ( fis != null )
{
fis.close();
}
if ( baos != null )
{
baos.close();
}
}
}
catch ( Exception e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, "An error occurred while reading the image from disk.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorImage.ErrorReadingMessageDialogTitle" ), Messages.getString( "EditorImage.ErrorReadingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
// Constrains and displays the image
constrainAndDisplayImage();
// Refreshing the states of the buttons
updateButtonsStates();
}
else
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
"An error occurred while reading the image from disk. Image file does not exist or is not readable.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorImage.ErrorReadingMessageDialogTitle" ), Messages.getString( "EditorImage.ErrorReadingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
// Updating the entry
updateEntry();
// Updating the image
composite.getParent().update();
}
}
/**
* Updates the states of the buttons.
*/
private void updateButtonsStates()
{
if ( ( imageBytes != null ) && ( imageBytes.length > 0 ) )
{
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.setEnabled( true );
}
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.setEnabled( true );
}
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.setEnabled( true );
}
}
else
{
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.setEnabled( false );
}
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.setEnabled( false );
}
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.setEnabled( true );
}
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
image.dispose();
}
/**
* This method is called when the entry has been updated in the UI.
*/
private void updateEntry()
{
// Getting the attribute
IAttribute attribute = getAttribute();
if ( attribute == null )
{
if ( ( imageBytes != null ) && ( imageBytes.length != 0 ) )
{
// Creating a new attribute with the value
addNewAttribute( imageBytes );
}
}
else
{
if ( ( imageBytes != null ) && ( imageBytes.length != 0 ) )
{
// Modifying the existing attribute
modifyAttributeValue( imageBytes );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorWidget.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorWidget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.EntryEditorInput;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Value;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateWidget;
import org.apache.directory.studio.templateeditor.model.widgets.WidgetAlignment;
/**
* This abstract class implements the base for an editor widget.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class EditorWidget<E extends TemplateWidget>
{
/** The widget*/
private E widget;
/** The associated editor */
private IEntryEditor entryEditor;
/** The toolkit */
private FormToolkit toolkit;
/**
* Creates a new instance of EditorWidget.
*
* @param widget
* the widget
* @param entryEditor
* the entryEditor
*/
public EditorWidget( E widget, IEntryEditor entryEditor, FormToolkit toolkit )
{
this.widget = widget;
this.entryEditor = entryEditor;
this.toolkit = toolkit;
}
/**
* Gets the widget.
*
* @return
* the widget
*/
public E getWidget()
{
return widget;
}
/**
* Creates the widget.
*
* @param parent
* the parent widget
* @return
* the associated composite
*/
public Composite createWidget( Composite parent )
{
return parent;
}
/**
* Gets the associated editor page.
*
* @return
* the associated editor page
*/
public IEntryEditor getEditor()
{
return entryEditor;
}
/**
* Gets the toolkit.
*
* @return
* the form toolkit
*/
public FormToolkit getToolkit()
{
return toolkit;
}
/**
* Gets the entry.
*
* @return
* the entry
*/
protected IEntry getEntry()
{
EntryEditorInput input = getEditor().getEntryEditorInput();
return input.getSharedWorkingCopy( getEditor() );
}
/**
* Updates the widget.
*/
public abstract void update();
/**
* Disposes the widget
*/
public abstract void dispose();
/**
* Gets the {@link GridData} object associated with the widget properties.
*
* @return
* the {@link GridData} object associated with the widget properties
*/
protected GridData getGridata()
{
// Creating the grid data with alignment and grab excess values
GridData gd = new GridData( convertWidgetAlignmentToSWTValue( widget.getHorizontalAlignment() ),
convertWidgetAlignmentToSWTValue( widget.getVerticalAlignment() ), widget.isGrabExcessHorizontalSpace(),
widget.isGrabExcessVerticalSpace(), widget.getHorizontalSpan(), widget.getVerticalSpan() );
// Setting width (if needed)
if ( widget.getImageWidth() != TemplateWidget.DEFAULT_SIZE )
{
gd.widthHint = widget.getImageWidth();
}
// Setting height (if needed)
if ( widget.getImageHeight() != TemplateWidget.DEFAULT_SIZE )
{
gd.heightHint = widget.getImageHeight();
}
return gd;
}
/**
* Converts the given widget alignment to the equivalent value in SWT.
*
* @param alignment
* the widget alignment
* @return
* the given widget alignment to the equivalent value in SWT
*/
private static int convertWidgetAlignmentToSWTValue( WidgetAlignment alignment )
{
switch ( alignment )
{
case NONE:
return SWT.NONE;
case BEGINNING:
return SWT.BEGINNING;
case CENTER:
return SWT.CENTER;
case END:
return SWT.END;
case FILL:
return SWT.FILL;
default:
return SWT.NONE;
}
}
/**
* Gets the attribute from the entry.
* <p>
* The attribute type description from the associated
* widget is used to get the attribute from the entry.
*
* @return
* the attribute from the entry
*/
protected IAttribute getAttribute()
{
if ( ( getEntry() != null ) && ( getWidget() != null ) )
{
return getEntry().getAttribute( getWidget().getAttributeType() );
}
return null;
}
/**
* Updates the attribute's value on the entry.
*
* @param value
* the value
*/
protected void updateAttributeValue( Object value )
{
IAttribute attribute = getAttribute();
if ( ( attribute == null ) )
{
if ( !"".equals( value ) ) //$NON-NLS-1$
{
// Creating a new attribute with the value
addNewAttribute( value );
}
}
else
{
if ( !"".equals( value ) ) //$NON-NLS-1$
{
// Modifying the existing attribute
modifyAttributeValue( value );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
}
/**
* Adds a new attribute (based on the attribute type value from the widget)
* with the given value.
*
* @param value
* the value
*/
protected void addNewAttribute( Object value )
{
if ( ( getEntry() != null ) && ( getWidget() != null ) )
{
Attribute newAttribute = new Attribute( getEntry(), getWidget().getAttributeType() );
newAttribute.addValue( new Value( newAttribute, value ) );
getEntry().addAttribute( newAttribute );
}
}
/**
* Modifies the attribute value with the given one.
*
* @param value
* the value
*/
protected void modifyAttributeValue( Object value )
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.getValueSize() > 0 ) )
{
attribute.deleteValue( attribute.getValues()[0] );
attribute.addValue( new Value( attribute, value ) );
}
}
/**
* Deletes the attribute.
*/
protected void deleteAttribute()
{
if ( ( getEntry() != null ) && ( getWidget() != null ) && ( getAttribute() != null ) )
{
getEntry().deleteAttribute( getAttribute() );
}
}
/**
* Adds a value to the attribute.
*
* @param value
* the value to add
*/
protected void addAttributeValue( String value )
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) )
{
attribute.addValue( new Value( attribute, value ) );
}
else
{
addNewAttribute( value );
}
}
/**
* Deletes a value from the attribute.
*
* @param value
* the value to delete
*/
protected void deleteAttributeValue( String value )
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
for ( IValue attributeValue : attribute.getValues() )
{
if ( attributeValue.getStringValue().equals( value ) )
{
attribute.deleteValue( attributeValue );
break;
}
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorFileChooser.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorFileChooser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Base64;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateFileChooser;
/**
* This class implements an Editor FileChooser.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorFileChooser extends EditorWidget<TemplateFileChooser>
{
/** The widget's composite */
private Composite composite;
/** The icon label */
private Label iconLabel;
/** The size label */
private Label sizeLabel;
/** The 'Save As...' toolbar item */
private ToolItem saveAsToolItem;
/** The 'Clear' toolbar item */
private ToolItem clearToolItem;
/** The 'Browse...' toolbar item */
private ToolItem browseToolItem;
/** The file data as bytes array */
private byte[] fileBytes;
/** The icon Image we might have to create */
private Image iconImage;
/**
* Creates a new instance of EditorFileChooser.
*
* @param editor the associated editor
* @param templateFileChooser the associated template file chooser
* @param toolkit the associated toolkit
*/
public EditorFileChooser( IEntryEditor editor, TemplateFileChooser templateFileChooser, FormToolkit toolkit )
{
super( templateFileChooser, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent the parent composite
* @return the associated composite
*/
private Composite initWidget( Composite parent )
{
composite = getToolkit().createComposite( parent );
composite.setLayoutData( getGridata() );
// Creating the layout
GridLayout gl = new GridLayout( getLayoutNumberOfColumns(), false );
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Icon Label
if ( getWidget().isShowIcon() )
{
// Creating the label for hosting the icon
iconLabel = getToolkit().createLabel( composite, null );
iconLabel.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) );
// Getting the icon (if available)
ImageData iconData = null;
String icon = getWidget().getIcon();
if ( ( icon != null ) && ( !icon.equals( "" ) ) ) //$NON-NLS-1$
{
try
{
iconData = new ImageData( new ByteArrayInputStream( Base64.getDecoder().decode( icon ) ) );
}
catch ( SWTException e )
{
// Nothing to do, we just need to return the default image.
}
}
// Assigning the icon
if ( iconData != null )
{
iconImage = new Image( PlatformUI.getWorkbench().getDisplay(), iconData );
iconLabel.setImage( iconImage );
}
else
{
iconLabel.setImage( EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_FILE ) );
}
}
// Size Label
sizeLabel = getToolkit().createLabel( composite, null );
sizeLabel.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, true, false ) );
// Toolbar (if needed)
if ( needsToolbar() )
{
ToolBar toolbar = new ToolBar( composite, SWT.HORIZONTAL | SWT.FLAT );
toolbar.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) );
// Save As Button
if ( getWidget().isShowSaveAsButton() )
{
saveAsToolItem = new ToolItem( toolbar, SWT.PUSH );
saveAsToolItem.setToolTipText( Messages.getString( "EditorFileChooser.SaveAs" ) ); //$NON-NLS-1$
saveAsToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_SAVE_AS ) );
}
// Clear Button
if ( getWidget().isShowClearButton() )
{
clearToolItem = new ToolItem( toolbar, SWT.PUSH );
clearToolItem.setToolTipText( Messages.getString( "EditorFileChooser.Clear" ) ); //$NON-NLS-1$
clearToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_CLEAR ) );
}
// Browse Button
if ( getWidget().isShowBrowseButton() )
{
browseToolItem = new ToolItem( toolbar, SWT.PUSH );
browseToolItem.setToolTipText( Messages.getString( "EditorFileChooser.Browse" ) ); //$NON-NLS-1$
browseToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_BROWSE_FILE ) );
}
}
return composite;
}
/**
* Gets the number of columns needed for the layout.
*
* @return the number of columns needed
*/
private int getLayoutNumberOfColumns()
{
int numberOfColumns = 1;
// Icon
if ( getWidget().isShowIcon() )
{
numberOfColumns++;
}
// Toolbar
if ( needsToolbar() )
{
numberOfColumns++;
}
return numberOfColumns;
}
/**
* Indicates if the widget needs a toolbar for actions.
*
* @return<code>true</code> if the widget needs a toolbar for actions,
* <code>false</code> if not
*/
private boolean needsToolbar()
{
return getWidget().isShowSaveAsButton() || getWidget().isShowClearButton() || getWidget().isShowBrowseButton();
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Initializing the image bytes from the given entry.
initImageBytesFromEntry();
// Updating the file label
updateSizeLabel();
// Updating the states of the buttons
updateButtonsStates();
}
/**
* Initializes the image bytes from the given entry.
*/
private void initImageBytesFromEntry()
{
// Getting the file bytes in the attribute
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isBinary() ) && ( attribute.getValueSize() > 0 ) )
{
fileBytes = attribute.getBinaryValues()[0];
return;
}
fileBytes = null;
}
/**
* Updates the "Size" label.
*/
private void updateSizeLabel()
{
sizeLabel.setText( getFileSizeString() );
sizeLabel.update();
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Save As toolbar item
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
saveAsToolItemAction();
}
} );
}
// Clear toolbar item
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
clearToolItemAction();
}
} );
}
// Browse toolbar item
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
browseToolItemAction();
}
} );
}
}
/**
* Gets the size string.
*
* @return the size string
*/
private String getFileSizeString()
{
if ( fileBytes != null )
{
int length = fileBytes.length;
if ( length > 1000000 )
{
return NLS.bind( Messages.getString( "EditorFileChooser.MB" ), new Object[] //$NON-NLS-1$
{ ( length / 1000000 ), length } );
}
else if ( length > 1000 )
{
return NLS.bind( Messages.getString( "EditorFileChooser.KB" ), new Object[] //$NON-NLS-1$
{ ( length / 1000 ), length } );
}
else
{
return NLS.bind( Messages.getString( "EditorFileChooser.Bytes" ), new Object[] //$NON-NLS-1$
{ length } );
}
}
else
{
return Messages.getString( "EditorFileChooser.NoValue" ); //$NON-NLS-1$
}
}
/**
* This method is called when the 'Save As...' toolbar item is clicked.
*/
private void saveAsToolItemAction()
{
// Launching a FileDialog to select where to save the file
FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE );
String selected = fd.open();
if ( selected != null )
{
// Getting the selected file
File selectedFile = new File( selected );
if ( ( !selectedFile.exists() ) || ( selectedFile.canWrite() ) )
{
try
{
FileOutputStream fos = new FileOutputStream( selectedFile );
fos.write( fileBytes );
fos.close();
}
catch ( Exception e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, "An error occurred while saving the file to disk.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorFileChooser.ErrorSavingMessageDialogTitle" ), Messages.getString( "EditorFileChooser.ErrorSavingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
/**
* This method is called when the 'Clear...' toolbar item is clicked.
*/
private void clearToolItemAction()
{
// Launching a confirmation dialog
if ( MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages
.getString( "EditorFileChooser.Confirmation" ), Messages //$NON-NLS-1$
.getString( "EditorFileChooser.ConfirmationClearFile" ) ) ) //$NON-NLS-1$
{
// Removing the file bytes
fileBytes = null;
// Refreshing the states of the buttons
updateButtonsStates();
// Updating the size label
updateSizeLabel();
// Updating the entry
updateEntry();
}
}
/**
* This method is called when the 'Browse...' toolbar item is clicked.
*/
private void browseToolItemAction()
{
// Launching a FileDialog to select the file to load
FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN );
String selected = fd.open();
if ( selected != null )
{
// Getting the selected file
File selectedFile = new File( selected );
if ( ( selectedFile.exists() ) && ( selectedFile.canRead() ) )
{
try
{
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try
{
fis = new FileInputStream( selectedFile );
baos = new ByteArrayOutputStream( ( int ) selectedFile.length() );
byte[] buf = new byte[4096];
int len;
while ( ( len = fis.read( buf ) ) > 0 )
{
baos.write( buf, 0, len );
}
fileBytes = baos.toByteArray();
}
finally
{
if ( fis != null )
{
fis.close();
}
if ( baos != null )
{
baos.close();
}
}
}
catch ( Exception e )
{
// Logging the error
EntryTemplatePluginUtils.logError( e, "An error occurred while reading the file from disk.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorFileChooser.ErrorReadingMessageDialogTitle" ), Messages.getString( "EditorFileChooser.ErrorReadingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
// Refreshing the states of the buttons
updateButtonsStates();
}
else
{
// Logging the error
EntryTemplatePluginUtils.logError( null,
"An error occurred while reading the file from disk. File does not exist or is not readable.", //$NON-NLS-1$
new Object[0] );
// Launching an error dialog
MessageDialog
.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
Messages.getString( "EditorFileChooser.ErrorReadingMessageDialogTitle" ), Messages.getString( "EditorFileChooser.ErrorReadingMessageDialogMessage" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
// Updating the size label
updateSizeLabel();
// Updating the entry
updateEntry();
}
}
/**
* This method is called when the entry has been updated in the UI.
*/
private void updateEntry()
{
// Getting the attribute
IAttribute attribute = getAttribute();
if ( attribute == null )
{
if ( ( fileBytes != null ) && ( fileBytes.length != 0 ) )
{
// Creating a new attribute with the value
addNewAttribute( fileBytes );
}
}
else
{
if ( ( fileBytes != null ) && ( fileBytes.length != 0 ) )
{
// Modifying the existing attribute
modifyAttributeValue( fileBytes );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
}
/**
* Updates the states of the buttons.
*/
private void updateButtonsStates()
{
if ( ( fileBytes != null ) && ( fileBytes.length > 0 ) )
{
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.setEnabled( true );
}
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.setEnabled( true );
}
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.setEnabled( true );
}
}
else
{
if ( ( saveAsToolItem != null ) && ( !saveAsToolItem.isDisposed() ) )
{
saveAsToolItem.setEnabled( false );
}
if ( ( clearToolItem != null ) && ( !clearToolItem.isDisposed() ) )
{
clearToolItem.setEnabled( false );
}
if ( ( browseToolItem != null ) && ( !browseToolItem.isDisposed() ) )
{
browseToolItem.setEnabled( true );
}
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
if ( iconImage != null )
{
iconImage.dispose();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorLabel.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorLabel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateLabel;
import org.apache.directory.studio.templateeditor.model.widgets.WidgetAlignment;
/**
* This class implements an editor label.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorLabel extends EditorWidget<TemplateLabel>
{
/** The label widget */
private Text label;
/**
* Creates a new instance of EditorLabel.
*
* @param editor
* the associated editor
* @param templateLabel
* the associated template label
* @param toolkit
* the associated toolkit
*/
public EditorLabel( IEntryEditor editor, TemplateLabel templateLabel, FormToolkit toolkit )
{
super( templateLabel, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the label
label = new Text( parent, getStyle() );
label.setEditable( false );
label.setBackground( parent.getBackground() );
// Setting the layout data
GridData gd = getGridata();
label.setLayoutData( gd );
// Calculating height for multiple rows
int numberOfRows = getWidget().getNumberOfRows();
if ( numberOfRows != 1 )
{
GC gc = new GC( parent );
try
{
gc.setFont( label.getFont() );
FontMetrics fontMetrics = gc.getFontMetrics();
gd.heightHint = fontMetrics.getHeight() * numberOfRows;
}
finally
{
gc.dispose();
}
}
return parent;
}
/**
* Gets the style of the widget.
*
* @return
* the style of the widget
*/
private int getStyle()
{
int style = SWT.WRAP;
// Multiple lines?
if ( getWidget().getNumberOfRows() == 1 )
{
style |= SWT.SINGLE;
}
else
{
style |= SWT.MULTI;
}
// Horizontal alignment set to end?
if ( getWidget().getHorizontalAlignment() == WidgetAlignment.END )
{
style |= SWT.RIGHT;
}
// Horizontal alignment set to center?
else if ( getWidget().getHorizontalAlignment() == WidgetAlignment.CENTER )
{
style |= SWT.CENTER;
}
return style;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Checking if we need to display a value taken from the entry
// or use the given value
String attributeType = getWidget().getAttributeType();
if ( ( attributeType != null ) || ( "".equals( attributeType ) ) ) //$NON-NLS-1$
{
IEntry entry = getEntry();
if ( entry != null )
{
// Getting the text to display
String text = EditorWidgetUtils.getConcatenatedValues( entry, attributeType );
// Replacing '$' by '/n' if needed
if ( getWidget().isDollarSignIsNewLine() )
{
text = text.replace( '$', '\n' );
}
// Assigning the text to the label
label.setText( text );
}
}
else
{
// Getting the text to display
String text = getWidget().getValue();
// Replacing '$' by '/n' if needed
if ( getWidget().isDollarSignIsNewLine() )
{
text = text.replace( '$', '\n' );
}
// Assigning the text to the label
label.setText( text );
}
// Forcing the re-layout of the label from its parent
label.getParent().layout();
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
label.dispose();
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorSection.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorSection.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSection;
/**
* This class implements an editor section.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorSection extends EditorWidget<TemplateSection>
{
/**
* Creates a new instance of EditorSection.
*
* @param editor
* the associated editor
* @param templateSection
* the associated template section
* @param toolkit
* the associated toolkit
*/
public EditorSection( IEntryEditor editor, TemplateSection templateSection, FormToolkit toolkit )
{
super( templateSection, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Calculating the style
int style = Section.TITLE_BAR;
if ( getWidget().getDescription() != null )
{
style |= Section.DESCRIPTION;
}
if ( getWidget().isExpandable() )
{
style |= Section.TWISTIE;
}
if ( getWidget().isExpanded() )
{
style |= Section.EXPANDED;
}
// Creating the section
Section section = getToolkit().createSection( parent, style );
section.setLayoutData( getGridata() );
// Creating the client composite
Composite clientComposite = getToolkit().createComposite( section );
section.setClient( clientComposite );
// Setting the layout for the client composite
clientComposite.setLayout( new GridLayout( getWidget().getNumberOfColumns(), getWidget().isEqualColumns() ) );
clientComposite.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Title
if ( ( getWidget().getTitle() != null ) && ( !"".equals( getWidget().getTitle() ) ) ) //$NON-NLS-1$
{
section.setText( getWidget().getTitle() );
}
// Description
if ( ( getWidget().getDescription() != null ) && ( !"".equals( getWidget().getDescription() ) ) ) //$NON-NLS-1$
{
section.setDescription( getWidget().getDescription() );
}
return clientComposite;
}
/**
* {@inheritDoc}
*/
public void update()
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.editor.widgets.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorCheckbox.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorCheckbox.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateCheckbox;
/**
* This class implements an editor checkbox.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorCheckbox extends EditorWidget<TemplateCheckbox>
{
/** The checkbox */
private Button checkbox;
/** The enum used to determine the state of a checkbox*/
private enum CheckboxState
{
UNCHECKED, CHECKED, GRAYED
}
/** Constant for the 'false' string value */
private static final String FALSE_STRING_VALUE = "FALSE"; //$NON-NLS-1$
/** Constant for the 'true' string value */
private static final String TRUE_STRING_VALUE = "TRUE"; //$NON-NLS-1$
/** The current state of the checkbox */
private CheckboxState currentState = CheckboxState.UNCHECKED;
/** The selection listener */
private SelectionListener selectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
// Changing the state of the checkbox
changeCheckboxState();
// Getting the value
boolean value = checkbox.getSelection();
IAttribute attribute = getAttribute();
String checkedValue = getWidget().getCheckedValue();
String uncheckedValue = getWidget().getUncheckedValue();
if ( attribute == null )
{
// The attribute does not exist
if ( ( checkedValue == null ) && ( uncheckedValue == null ) )
{
// Creating a new attribute with the value
addNewAttribute( ( value ? TRUE_STRING_VALUE : FALSE_STRING_VALUE ) );
}
else if ( ( checkedValue != null ) && ( uncheckedValue == null ) && value )
{
// Creating a new attribute with the value
addNewAttribute( checkedValue );
}
else if ( ( checkedValue == null ) && ( uncheckedValue != null ) && !value )
{
// Creating a new attribute with the value
addNewAttribute( uncheckedValue );
}
else if ( ( checkedValue != null ) && ( uncheckedValue != null ) )
{
// Creating a new attribute with the value
addNewAttribute( ( value ? checkedValue : uncheckedValue ) );
}
}
else
{
// The attribute exists
if ( ( checkedValue == null ) && ( uncheckedValue == null ) )
{
// Modifying the attribute
modifyAttributeValue( ( value ? TRUE_STRING_VALUE : FALSE_STRING_VALUE ) );
}
else if ( ( checkedValue != null ) && ( uncheckedValue == null ) )
{
if ( value )
{
// Modifying the attribute
modifyAttributeValue( checkedValue );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
else if ( ( checkedValue == null ) && ( uncheckedValue != null ) )
{
if ( value )
{
// Deleting the attribute
}
else
{
// Modifying the attribute
modifyAttributeValue( uncheckedValue );
}
}
else if ( ( checkedValue != null ) && ( uncheckedValue != null ) )
{
// Modifying the attribute
modifyAttributeValue( ( value ? checkedValue : uncheckedValue ) );
}
}
}
};
/**
* Creates a new instance of EditorCheckbox.
*
* @param editor
* the associated editor
* @param templateCheckbox
* the associated template checkbox
* @param toolkit
* the associated toolkit
*/
public EditorCheckbox( IEntryEditor editor, TemplateCheckbox templateCheckbox, FormToolkit toolkit )
{
super( templateCheckbox, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the checkbox
checkbox = getToolkit().createButton( parent, getWidget().getLabel(), SWT.CHECK );
checkbox.setLayoutData( getGridata() );
checkbox.setEnabled( getWidget().isEnabled() );
return parent;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
setCheckboxState( attribute.getStringValue() );
}
}
/**
* Sets the state of the checkbox.
*
* @param value
* the value
*/
private void setCheckboxState( String value )
{
String checkedValue = getWidget().getCheckedValue();
String uncheckedValue = getWidget().getUncheckedValue();
if ( ( checkedValue == null ) && ( uncheckedValue == null ) )
{
if ( TRUE_STRING_VALUE.equalsIgnoreCase( value ) )
{
setCheckboxCheckedState();
}
else if ( FALSE_STRING_VALUE.equalsIgnoreCase( value ) )
{
setCheckboxUncheckedState();
}
else
{
setCheckboxGrayedState();
}
}
else if ( ( checkedValue != null ) && ( uncheckedValue == null ) )
{
if ( checkedValue.equals( value ) )
{
setCheckboxCheckedState();
}
else
{
setCheckboxUncheckedState();
}
}
else if ( ( checkedValue == null ) && ( uncheckedValue != null ) )
{
if ( uncheckedValue.equals( value ) )
{
setCheckboxUncheckedState();
}
else
{
setCheckboxCheckedState();
}
}
else if ( ( checkedValue != null ) && ( uncheckedValue != null ) )
{
if ( checkedValue.equals( value ) )
{
setCheckboxCheckedState();
}
else if ( uncheckedValue.equals( value ) )
{
setCheckboxUncheckedState();
}
else
{
setCheckboxGrayedState();
}
}
}
/**
* Sets the checkbox in checked state.
*/
private void setCheckboxCheckedState()
{
checkbox.setGrayed( false );
checkbox.setSelection( true );
currentState = CheckboxState.CHECKED;
}
/**
* Sets the checkbox in unchecked state.
*
*/
private void setCheckboxUncheckedState()
{
checkbox.setGrayed( false );
checkbox.setSelection( false );
currentState = CheckboxState.UNCHECKED;
}
/**
* Sets the checkbox in grayed state.
*/
private void setCheckboxGrayedState()
{
checkbox.setGrayed( true );
checkbox.setSelection( true );
currentState = CheckboxState.GRAYED;
}
/**
* Adds the listeners.
*/
private void addListeners()
{
if ( ( checkbox != null ) && ( !checkbox.isDisposed() ) )
{
checkbox.addSelectionListener( selectionListener );
}
}
/**
* Changes the state of the checkbox.
*/
private void changeCheckboxState()
{
switch ( currentState )
{
case UNCHECKED:
setCheckboxCheckedState();
currentState = CheckboxState.CHECKED;
break;
case CHECKED:
setCheckboxUncheckedState();
currentState = CheckboxState.UNCHECKED;
break;
case GRAYED:
setCheckboxCheckedState();
currentState = CheckboxState.CHECKED;
break;
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorRadioButtons.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorRadioButtons.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.util.HashMap;
import java.util.Map;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateRadioButtons;
import org.apache.directory.studio.templateeditor.model.widgets.ValueItem;
/**
* This class implements an editor radio buttons.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorRadioButtons extends EditorWidget<TemplateRadioButtons>
{
/** The map of (ValueItem,Button) elements used in the UI */
private Map<ValueItem, Button> valueItemsToButtonsMap = new HashMap<ValueItem, Button>();
private Map<Button, ValueItem> buttonsToValueItemsMap = new HashMap<Button, ValueItem>();
/** The currently selected item */
private ValueItem selectedItem;
/** The selection listener */
private SelectionListener selectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
// Saving the selected item
selectedItem = buttonsToValueItemsMap.get( e.getSource() );
// Updating the entry
updateEntry();
}
};
/**
* Creates a new instance of EditorRadioButtons.
*
* @param editor
* the associated editor
* @param templateRadioButtons
* the associated template radio buttons
* @param toolkit
* the associated toolkit
*/
public EditorRadioButtons( IEntryEditor editor, TemplateRadioButtons templateRadioButtons,
FormToolkit toolkit )
{
super( templateRadioButtons, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the widget composite
Composite composite = getToolkit().createComposite( parent );
composite.setLayout( new GridLayout() );
composite.setLayoutData( getGridata() );
// Creating the layout
GridLayout gl = new GridLayout();
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Creating the Radio Buttons
for ( ValueItem valueItem : getWidget().getButtons() )
{
Button button = getToolkit().createButton( composite, valueItem.getLabel(), SWT.RADIO );
button.setEnabled( getWidget().isEnabled() );
valueItemsToButtonsMap.put( valueItem, button );
buttonsToValueItemsMap.put( button, valueItem );
}
return composite;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
// Getting the attribute value
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
String value = attribute.getStringValue();
for ( ValueItem valueItem : valueItemsToButtonsMap.keySet() )
{
Button button = valueItemsToButtonsMap.get( valueItem );
if ( button != null && !button.isDisposed() )
{
button.setSelection( value.equals( valueItem.getValue() ) );
}
}
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
for ( final ValueItem valueItem : valueItemsToButtonsMap.keySet() )
{
Button button = valueItemsToButtonsMap.get( valueItem );
if ( button != null )
{
button.addSelectionListener( selectionListener );
}
}
}
/**
* This method is called when the entry has been updated in the UI.
*/
private void updateEntry()
{
// Getting the attribute
IAttribute attribute = getAttribute();
if ( attribute == null )
{
if ( selectedItem != null )
{
// Creating a new attribute with the value
addNewAttribute( selectedItem.getValue() );
}
}
else
{
if ( ( selectedItem != null ) && ( !selectedItem.equals( "" ) ) ) //$NON-NLS-1$
{
// Modifying the existing attribute
modifyAttributeValue( selectedItem.getValue() );
}
else
{
// Deleting the attribute
deleteAttribute();
}
}
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorDate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorDate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.directory.api.util.GeneralizedTime;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.valueeditors.time.GeneralizedTimeValueDialog;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateDate;
/**
* This class implements an editor date.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorDate extends EditorWidget<TemplateDate>
{
/** The main composite */
private Composite composite;
/** The date text widget */
private Text dateText;
/** The 'Browse...' toolbar item */
private ToolItem editToolItem;
/**
* Creates a new instance of EditorLabel.
*
* @param editor
* the associated editor
* @param templateDate
* the associated template label
* @param toolkit
* the associated toolkit
*/
public EditorDate( IEntryEditor editor, TemplateDate templateDate, FormToolkit toolkit )
{
super( templateDate, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the widget composite
composite = getToolkit().createComposite( parent );
composite.setLayoutData( getGridata() );
// Calculating the number of columns needed
int numberOfColumns = 1;
if ( getWidget().isShowEditButton() )
{
numberOfColumns++;
}
// Creating the layout
GridLayout gl = new GridLayout( numberOfColumns, false );
gl.marginHeight = gl.marginWidth = 0;
gl.horizontalSpacing = gl.verticalSpacing = 0;
composite.setLayout( gl );
// Creating the label
dateText = new Text( composite, SWT.NONE );
dateText.setEditable( false );
dateText.setBackground( composite.getBackground() );
dateText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, false, false ) );
// Creating the edit password button
if ( getWidget().isShowEditButton() )
{
ToolBar toolbar = new ToolBar( composite, SWT.HORIZONTAL | SWT.FLAT );
editToolItem = new ToolItem( toolbar, SWT.PUSH );
editToolItem.setToolTipText( Messages.getString( "EditorDate.EditDate" ) ); //$NON-NLS-1$
editToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TOOLBAR_EDIT_DATE ) );
}
return parent;
}
/**
* Converts the given GeneralizedTime string representation of the date into
* the desired string format.
*
* @param dateString
* the GeneralizedTime string representation of the date
* @return
* the given date in the desired string format
*/
private String convertDate( String dateString )
{
try
{
// Creating a date
Date date = ( new GeneralizedTime( dateString ) ).getCalendar().getTime();
// Setting a default formatter
SimpleDateFormat formatter = new SimpleDateFormat();
// Getting the format defined in the template
String format = getWidget().getFormat();
if ( ( format != null ) && ( !format.equalsIgnoreCase( "" ) ) ) //$NON-NLS-1$
{
// Setting a custom formatter
formatter = new SimpleDateFormat( format );
}
// Returning the formatted date
return formatter.format( date );
}
catch ( ParseException pe )
{
// Returning the original value in that case
return dateString;
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Edit toolbar item
if ( ( editToolItem != null ) && ( !editToolItem.isDisposed() ) )
{
editToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editToolItemAction();
}
} );
}
}
/**
* This method is called when the 'Edit...' toolbar item is clicked.
*/
private void editToolItemAction()
{
// Creating and opening a GeneralizedTimeValueDialog
GeneralizedTimeValueDialog dialog = new GeneralizedTimeValueDialog( PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell(), getGeneralizedTimeValueFromAttribute() );
if ( dialog.open() == Dialog.OK )
{
// Updating the attribute with the new value
updateAttributeValue( dialog.getGeneralizedTime().toGeneralizedTime() );
}
}
/**
* Get the Generalized Time associated from the attribute.
*
* @return
* the Generalized Time associated from the attribute or <code>null</code>.
*/
private GeneralizedTime getGeneralizedTimeValueFromAttribute()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
try
{
return new GeneralizedTime( attribute.getStringValue() );
}
catch ( ParseException e )
{
// Nothing to do, will return null
}
}
return null;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
// Setting the date value
dateText.setText( convertDate( attribute.getStringValue() ) );
}
else
{
// No value
dateText.setText( Messages.getString( "EditorDate.NoValue" ) ); //$NON-NLS-1$
}
// Updating the layout of the composite
composite.layout();
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorTextField.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorTextField.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateTextField;
import org.apache.directory.studio.templateeditor.model.widgets.WidgetAlignment;
/**
* This class implements an editor text field.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorTextField extends EditorWidget<TemplateTextField>
{
/** The text field */
private Text textfield;
/** The modify listener */
private ModifyListener modifyListener = new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
// Getting the value
String value = textfield.getText();
// Replacing '$' by '/n' if needed
if ( getWidget().isDollarSignIsNewLine() )
{
value = value.replace( '\n', '$' );
}
// Updating the attribute's value
updateAttributeValue( value );
}
};
/**
* Creates a new instance of EditorTextField.
*
* @param editor
* the associated editor
* @param templateTextField
* the associated template text field
* @param toolkit
* the associated toolkit
*/
public EditorTextField( IEntryEditor editor, TemplateTextField templateTextField, FormToolkit toolkit )
{
super( templateTextField, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the text field
textfield = getToolkit().createText( parent, "", getStyle() ); //$NON-NLS-1$
GridData gd = getGridata();
textfield.setLayoutData( gd );
// Setting the characters limit
if ( getWidget().getCharactersLimit() != -1 )
{
textfield.setTextLimit( getWidget().getCharactersLimit() );
}
// Calculating height for multiple rows
int numberOfRows = getWidget().getNumberOfRows();
if ( numberOfRows != 1 )
{
GC gc = new GC( parent );
try
{
gc.setFont( textfield.getFont() );
FontMetrics fontMetrics = gc.getFontMetrics();
gd.heightHint = fontMetrics.getHeight() * numberOfRows;
}
finally
{
gc.dispose();
}
}
textfield.pack();
return parent;
}
/**
* Gets the style of the widget.
*
* @return
* the style of the widget
*/
private int getStyle()
{
int style = SWT.BORDER | SWT.WRAP;
// Multiple lines?
if ( getWidget().getNumberOfRows() == 1 )
{
style |= SWT.SINGLE;
}
else
{
style |= SWT.MULTI;
}
// Horizontal alignment set to end?
if ( getWidget().getHorizontalAlignment() == WidgetAlignment.END )
{
style |= SWT.RIGHT;
}
// Horizontal alignment set to center?
else if ( getWidget().getHorizontalAlignment() == WidgetAlignment.CENTER )
{
style |= SWT.CENTER;
}
return style;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
// Saving the current caret position by getting the current selection
Point selection = textfield.getSelection();
// Getting the text to display
String text = attribute.getStringValue();
// Replacing '$' by '/n' (if needed)
if ( getWidget().isDollarSignIsNewLine() )
{
text = text.replace( '$', '\n' );
}
// Assigning the text to the label
textfield.setText( text );
// Restoring the current caret position
textfield.setSelection( selection );
}
else
{
// There's no value to display
textfield.setText( "" ); //$NON-NLS-1$
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
if ( ( textfield != null ) && ( !textfield.isDisposed() ) )
{
textfield.addModifyListener( modifyListener );
}
}
/**
* Removes the listeners.
*/
private void removeListeners()
{
if ( ( textfield != null ) && ( !textfield.isDisposed() ) )
{
textfield.removeModifyListener( modifyListener );
}
}
/**
* {@inheritDoc}
*/
public void update()
{
removeListeners();
updateWidget();
addListeners();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
removeListeners();
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorListbox.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorListbox.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateListbox;
import org.apache.directory.studio.templateeditor.model.widgets.ValueItem;
/**
* This class implements an editor list box.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorListbox extends EditorWidget<TemplateListbox>
{
/** The list viewer */
private ListViewer listViewer;
/** The selection listener */
private ISelectionChangedListener selectionListener = new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
StructuredSelection selection = ( StructuredSelection ) listViewer.getSelection();
if ( !selection.isEmpty() )
{
// Deleting the old attribute
deleteAttribute();
// Re-creating the attribute with the selected values
Iterator<?> iterator = selection.iterator();
while ( iterator.hasNext() )
{
ValueItem item = ( ValueItem ) iterator.next();
addAttributeValue( ( String ) item.getValue() );
}
}
}
};
/**
* Creates a new instance of EditorListbox.
*
* @param editor
* the associated editor
* @param templateListbox
* the associated template list box
* @param toolkit
* the associated toolkit
*/
public EditorListbox( IEntryEditor editor, TemplateListbox templateListbox, FormToolkit toolkit )
{
super( templateListbox, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return the associated composite
*/
private Composite initWidget( Composite parent )
{
// Getting the style of the listbox
int style = SWT.BORDER /*| SWT.V_SCROLL | SWT.H_SCROLL*/;
if ( getWidget().isMultipleSelection() )
{
style |= SWT.MULTI;
}
else
{
style |= SWT.SINGLE;
}
// Creating the list
List list = new List( parent, style );
list.setLayoutData( getGridata() );
// Creating the associated viewer
listViewer = new ListViewer( list );
listViewer.getList().setEnabled( getWidget().isEnabled() );
listViewer.setContentProvider( new ArrayContentProvider() );
listViewer.setLabelProvider( new LabelProvider()
{
public String getText( Object element )
{
return ( ( ValueItem ) element ).getLabel();
}
} );
listViewer.setInput( getWidget().getItems() );
return parent;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.getValueSize() > 0 ) )
{
// Registering the values of the items in a map for easy
// access
Map<Object, ValueItem> itemsMap = new HashMap<Object, ValueItem>();
for ( ValueItem valueItem : getWidget().getItems() )
{
itemsMap.put( valueItem.getValue(), valueItem );
}
// Creating a list of the selected objects
java.util.List<ValueItem> selectedList = new ArrayList<ValueItem>();
// Checking each value
for ( IValue value : attribute.getValues() )
{
ValueItem valueItem = itemsMap.get( value.getRawValue() );
if ( valueItem != null )
{
selectedList.add( valueItem );
}
}
// Setting the selection to the viewer
if ( selectedList.size() > 0 )
{
listViewer.setSelection( new StructuredSelection( selectedList.toArray() ) );
}
}
else
{
listViewer.setSelection( null );
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
listViewer.addSelectionChangedListener( selectionListener );
}
/**
* Adds the listeners.
*/
private void removeListeners()
{
listViewer.removeSelectionChangedListener( selectionListener );
}
/**
* {@inheritDoc}
*/
public void update()
{
removeListeners();
updateWidget();
addListeners();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorSpinner.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorSpinner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.apache.directory.studio.templateeditor.model.widgets.TemplateSpinner;
/**
* This class implements an editor spinner.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorSpinner extends EditorWidget<TemplateSpinner>
{
/** The spinner */
private Spinner spinner;
/** The selection listener */
private SelectionListener selectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
// Getting the value
String value = spinner.getText();
// Updating the attribute's value
updateAttributeValue( value );
}
};
/**
* Creates a new instance of EditorSpinner.
*
* @param editor
* the associated editor
* @param templateSpinner
* the associated template spinner
* @param toolkit
* the associated toolkit
*/
public EditorSpinner( IEntryEditor editor, TemplateSpinner templateSpinner, FormToolkit toolkit )
{
super( templateSpinner, editor, toolkit );
}
/**
* {@inheritDoc}
*/
public Composite createWidget( Composite parent )
{
// Creating and initializing the widget UI
Composite composite = initWidget( parent );
// Updating the widget's content
updateWidget();
// Adding the listeners
addListeners();
return composite;
}
/**
* Creates and initializes the widget UI.
*
* @param parent
* the parent composite
* @return
* the associated composite
*/
private Composite initWidget( Composite parent )
{
// Creating the spinner
spinner = new Spinner( parent, SWT.BORDER );
spinner.setLayoutData( getGridata() );
// Setting the spinner values
spinner.setDigits( getWidget().getDigits() );
spinner.setIncrement( getWidget().getIncrement() );
spinner.setMaximum( getWidget().getMaximum() );
spinner.setMinimum( getWidget().getMinimum() );
spinner.setPageIncrement( getWidget().getPageIncrement() );
return parent;
}
/**
* Updates the widget's content.
*/
private void updateWidget()
{
IAttribute attribute = getAttribute();
if ( ( attribute != null ) && ( attribute.isString() ) && ( attribute.getValueSize() > 0 ) )
{
try
{
spinner.setSelection( Integer.parseInt( attribute.getStringValue() ) );
}
catch ( NumberFormatException e )
{
// Nothing to do, we fail gracefully
}
}
}
/**
* Adds the listeners.
*/
private void addListeners()
{
// Adding the listener
spinner.addSelectionListener( selectionListener );
}
/**
* {@inheritDoc}
*/
public void update()
{
updateWidget();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// Nothing to do
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorWidgetUtils.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/editor/widgets/EditorWidgetUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.editor.widgets;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorWidgetUtils
{
/**
* Gets the values of the attribute as a string.
*
* @param entry
* the entry
* @param attributeType
* the attribute type
* @return
* the values of the attribute as a string
*/
public static String getConcatenatedValues( IEntry entry, String attributeType )
{
if ( ( entry != null ) && ( attributeType != null ) )
{
// Getting the requested attribute
IAttribute attribute = entry.getAttribute( attributeType );
if ( attribute != null )
{
if ( attribute.getValues().length != 0 )
{
// Checking the type of the value(s)
if ( attribute.isBinary() )
{
// Binary value(s)
if ( attribute.getBinaryValues().length == 1 )
{
return Messages.getString( "EditorWidgetUtils.BinaryValue" ); //$NON-NLS-1$
}
else
{
return Messages.getString( "EditorWidgetUtils.BinaryValues" ); //$NON-NLS-1$
}
}
else if ( attribute.isString() )
{
// String value(s)
return EditorWidgetUtils.concatenateValues( attribute.getStringValues() );
}
}
}
}
return ""; //$NON-NLS-1$
}
/**
* Concatenates the given values.
* <p>
* Giving an array containing the following <code>["a", "b", "c"]</code>
* produces this string <em>a, b, c</em>.
*
* @param values
* the values
* @return
* a string with the concatenated values
*/
private static String concatenateValues( String[] values )
{
StringBuilder sb = new StringBuilder();
if ( values != null )
{
for ( String value : values )
{
sb.append( value );
sb.append( ", " ); //$NON-NLS-1$
}
sb.delete( sb.length() - 2, sb.length() );
}
return sb.toString();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SwitchTemplateAction.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SwitchTemplateAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.eclipse.jface.action.Action;
import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This Action switches the template editor widget to the given template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SwitchTemplateAction extends Action
{
/** The template editor widget */
private TemplateEditorWidget templateEditorWidget;
/** The template */
private Template template;
/**
* Creates a new instance of SwitchTemplateAction.
*
* @param templateEditorWidget
* the template editor widget
* @param template
* the template
*/
public SwitchTemplateAction( TemplateEditorWidget templateEditorWidget, Template template )
{
super( template.getTitle(), Action.AS_CHECK_BOX );
this.templateEditorWidget = templateEditorWidget;
this.template = template;
}
/**
* {@inheritDoc}
*/
public void run()
{
if ( ( templateEditorWidget != null ) && ( template != null ) )
{
// Switching the template
templateEditorWidget.switchTemplate( template );
// Getting the associated editor
IEntryEditor editor = templateEditorWidget.getEditor();
if ( editor instanceof SwitchTemplateListener )
{
// Calling the listener
( ( SwitchTemplateListener ) editor ).templateSwitched( templateEditorWidget, template );
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SwitchTemplateListener.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SwitchTemplateListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This interface defines a listener on 'Switch Template' events.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface SwitchTemplateListener
{
/**
* This method is called when a template has been switched.
*
* @param templateEditorWidget
* the template editor widget
* @param template
* the template
*/
void templateSwitched( TemplateEditorWidget templateEditorWidget, Template template );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/EntryTemplatePreferencePageAction.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/EntryTemplatePreferencePageAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
/**
* The OpenEntryEditorsPreferencePageAction is used to open the
* preference dialog with the entry editors preference page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EntryTemplatePreferencePageAction extends Action
{
/**
* Creates a new instance of OpenBrowserPreferencePageAction.
*/
public EntryTemplatePreferencePageAction()
{
super.setText( Messages.getString( "EntryTemplatePreferencePageAction.Preferences" ) ); //$NON-NLS-1$
setToolTipText( Messages.getString( "EntryTemplatePreferencePageAction.Preferences" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void run()
{
Shell shell = Display.getCurrent().getActiveShell();
String pageId = EntryTemplatePluginConstants.PREF_TEMPLATE_ENTRY_EDITOR_PAGE_ID;
PreferencesUtil.createPreferenceDialogOn( shell, pageId, new String[]
{ pageId }, null ).open();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/RefreshAction.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/RefreshAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.apache.directory.studio.connection.core.jobs.StudioConnectionJob;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeAttributesRunnable;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
/**
* This action refreshes the entry in the given editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RefreshAction extends Action
{
/** The associated editor */
private IEntryEditor editor;
/**
* Creates a new instance of RefreshAction.
*
* @param editor
* the associated editor
*/
public RefreshAction( IEntryEditor editor )
{
this.editor = editor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return BrowserCommonActivator.getDefault().getImageDescriptor( BrowserCommonConstants.IMG_REFRESH );
}
/**
* {@inheritDoc}
*/
public String getText()
{
return org.apache.directory.studio.ldapbrowser.common.actions.Messages
.getString( "RefreshAction.RelaodAttributes" ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
if ( editor != null )
{
return ( editor.getEntryEditorInput().getResolvedEntry() != null );
}
return false;
}
/**
* {@inheritDoc}
*/
public String getActionDefinitionId()
{
return "org.eclipse.ui.file.refresh"; //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void run()
{
if ( editor != null )
{
IEntry entry = editor.getEntryEditorInput().getResolvedEntry();
new StudioConnectionJob( new InitializeAttributesRunnable( entry ) ).execute();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.actions.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/EditorPagePropertiesAction.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/EditorPagePropertiesAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.apache.directory.studio.entryeditors.EntryEditorInput;
import org.apache.directory.studio.entryeditors.IEntryEditor;
import org.apache.directory.studio.ldapbrowser.common.actions.PropertiesAction;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
/**
* This Action opens the Property Dialog for a given object.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorPagePropertiesAction extends PropertiesAction
{
/** The associated editor */
private IEntryEditor editor;
/**
* Creates a new instance of EntryEditorPropertiesAction.
*
* @param editor
* the associated Entry Editor
*/
public EditorPagePropertiesAction( IEntryEditor editor )
{
super();
this.editor = editor;
}
/**
* {@inheritDoc}
*/
public IEntry[] getSelectedEntries()
{
// We're only returning the entry when no value is selected
if ( getSelectedValues().length == 0 )
{
if ( editor != null )
{
EntryEditorInput input = editor.getEntryEditorInput();
IEntry entry = ( ( EntryEditorInput ) input ).getResolvedEntry();
if ( entry != null )
{
return new IEntry[]
{ entry };
}
}
}
return new IEntry[0];
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/DisplayEntryInTemplateMenuManager.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/DisplayEntryInTemplateMenuManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This class implements the menu manager which is used in the Template Editor to
* allow to switch templates and open preferences.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DisplayEntryInTemplateMenuManager extends MenuManager implements IMenuListener
{
/** The associated {@link TemplateEditorWidget} */
private TemplateEditorWidget templateEditorPage;
/**
* Creates a new instance of DisplayEntryInTemplateMenuManager.
*
* @param templateEditorPage
* the associated editor page
*/
public DisplayEntryInTemplateMenuManager( TemplateEditorWidget templateEditorPage )
{
super(
Messages.getString( "DisplayEntryInTemplateMenuManager.DiplayEntryIn" ), EntryTemplatePlugin.getDefault().getImageDescriptor( //$NON-NLS-1$
EntryTemplatePluginConstants.IMG_SWITCH_TEMPLATE ), null );
addMenuListener( this );
this.templateEditorPage = templateEditorPage;
}
/**
* {@inheritDoc}
*/
public void menuAboutToShow( IMenuManager manager )
{
fillInMenuManager( manager, templateEditorPage );
}
/**
* {@inheritDoc}
*/
public boolean isVisible()
{
return true;
}
/**
* {@inheritDoc}
*/
public boolean isDynamic()
{
return true;
}
/**
* Fill the menu manager in with one menu item for each available template.
*
* @param menuManager
* the menu manager
* @param templateEditorWidget
* the associated editor widget
*/
protected static void fillInMenuManager( IMenuManager menuManager, TemplateEditorWidget templateEditorWidget )
{
// Getting the matching templates and currently selected one from the editor page
List<Template> matchingTemplates = new ArrayList<Template>( templateEditorWidget.getMatchingTemplates() );
Template selectedTemplate = templateEditorWidget.getSelectedTemplate();
// Sorting the list of matching templates by their title
Collections.sort( matchingTemplates, new Comparator<Template>()
{
public int compare( Template o1, Template o2 )
{
if ( ( o1 == null ) && ( o2 == null ) )
{
return 0;
}
else if ( ( o1 != null ) && ( o2 == null ) )
{
return 1;
}
else if ( ( o1 == null ) && ( o2 != null ) )
{
return -1;
}
else if ( ( o1 != null ) && ( o2 != null ) )
{
String title1 = o1.getTitle();
String title2 = o2.getTitle();
if ( ( title1 == null ) && ( title2 == null ) )
{
return 0;
}
else if ( ( title1 != null ) && ( title2 == null ) )
{
return 1;
}
else if ( ( title1 == null ) && ( title2 != null ) )
{
return -1;
}
else if ( ( title1 != null ) && ( title2 != null ) )
{
return title1.compareTo( title2 );
}
}
return 0;
};
} );
// As the Menu Manager is dynamic, we need to
// remove all the previously added actions
menuManager.removeAll();
if ( ( matchingTemplates != null ) && ( matchingTemplates.size() > 0 ) )
{
// Looping on the matching templates and creating an action for each one
for ( Template matchingTemplate : matchingTemplates )
{
// Creating the action associated with the entry editor
menuManager.add( createAction( templateEditorWidget, matchingTemplate, ( matchingTemplate
.equals( selectedTemplate ) ) ) );
}
}
else
{
// Creating a action that will be disabled when no template is available
Action noTemplateAction = new Action(
Messages.getString( "DisplayEntryInTemplateMenuManager.NoTemplate" ), Action.AS_CHECK_BOX ) //$NON-NLS-1$
{
};
noTemplateAction.setEnabled( false );
menuManager.add( noTemplateAction );
}
// Separator
menuManager.add( new Separator() );
// Preferences Action
menuManager.add( new EntryTemplatePreferencePageAction() );
}
/**
* Created the action.
*
* @param templateEditorWidget
* the template editor widget
* @param template
* the template
* @param isChecked
* <code>true</code> if the action is checked,
* <code>false</code> if not
* @return
* the associated action
*/
private static IAction createAction( TemplateEditorWidget templateEditorWidget, Template template, boolean isChecked )
{
Action action = new SwitchTemplateAction( templateEditorWidget, template );
action.setChecked( isChecked );
return action;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/DisplayEntryInTemplateAction.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/DisplayEntryInTemplateAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget;
/**
* This action is used to display a drop-down menu with the available
* templates for the entry in the editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DisplayEntryInTemplateAction extends Action
{
/** The associated {@link TemplateEditorWidget} */
private TemplateEditorWidget templateEditorPage;
/**
* Creates a new instance of DisplayEntryInTemplateAction.
*
* @param templateEditorPage
* the associated editor page
*/
public DisplayEntryInTemplateAction( TemplateEditorWidget templateEditorPage )
{
super( Messages.getString( "DisplayEntryInTemplateAction.DisplayEntryIn" ), Action.AS_DROP_DOWN_MENU ); //$NON-NLS-1$
setImageDescriptor( EntryTemplatePlugin.getDefault().getImageDescriptor(
EntryTemplatePluginConstants.IMG_SWITCH_TEMPLATE ) );
this.templateEditorPage = templateEditorPage;
}
/**
* {@inheritDoc}
*/
public void run()
{
MenuManager menuManager = new MenuManager();
DisplayEntryInTemplateMenuManager.fillInMenuManager( menuManager, templateEditorPage );
menuManager.createContextMenu( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell() );
menuManager.getMenu().setVisible( true );
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return true;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SimpleActionProxy.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/actions/SimpleActionProxy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.actions;
import org.apache.directory.studio.ldapbrowser.common.actions.BrowserAction;
import org.eclipse.jface.action.Action;
/**
* This class wraps a {@link BrowserAction} as a standard JFace {@link Action}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SimpleActionProxy extends Action
{
/** The {@link BrowserAction}*/
protected BrowserAction action;
/**
* Creates a new instance of SimpleActionProxy.
*
* @param action
* the {@link BrowserAction}
* @param style
* the style for the {@link Action}
*/
public SimpleActionProxy( BrowserAction action, int style )
{
super( action.getText(), style );
this.action = action;
super.setImageDescriptor( action.getImageDescriptor() );
super.setActionDefinitionId( action.getCommandId() );
}
/**
* Creates a new instance of SimpleActionProxy.
*
* @param action
* the {@link BrowserAction}
*/
public SimpleActionProxy( BrowserAction action )
{
this( action, action.getStyle() );
}
/**
* {@inheritDoc}
*/
public void run()
{
if ( action != null )
{
action.run();
}
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
if ( action != null )
{
return action.isEnabled();
}
else
{
return false;
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/ColumnsTableViewerComparator.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/ColumnsTableViewerComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
/**
* This class implements the comparator for a table viewer with columns.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ColumnsTableViewerComparator extends ViewerComparator
{
public static final int ASCENDING = 1;
/** The associated table label provider */
protected ITableLabelProvider labelProvider;
/** The comparison order */
int order = ASCENDING;
/** The column used to compare objects */
int column = 0;
/**
* Creates a new instance of ColumnsTableViewerComparator.
*
* @param labelProvider
* the label provider
*/
public ColumnsTableViewerComparator( ITableLabelProvider labelProvider )
{
this.labelProvider = labelProvider;
}
/**
* {@inheritDoc}
*/
public int compare( Viewer viewer, Object e1, Object e2 )
{
String s1 = labelProvider.getColumnText( e1, column );
String s2 = labelProvider.getColumnText( e2, column );
return s1.compareToIgnoreCase( s2 ) * order;
}
/**
* Gets the column.
*
* @return the column
*/
public int getColumn()
{
return column;
}
/**
* Gets the order.
*
* @return the order
*/
public int getOrder()
{
return order;
}
/**
* Reverses the order.
*/
public void reverseOrder()
{
order = order * -1;
}
/**
* Sets the column.
*
* @param column the column
*/
public void setColumn( int column )
{
this.column = column;
}
/**
* Sets the order.
*
* @param order the order
*/
public void setOrder( int order )
{
this.order = order;
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/ColumnsLabelProvider.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/ColumnsLabelProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
/**
* This class implements a label provider for viewers with columns.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ColumnsLabelProvider extends LabelProvider implements ITableLabelProvider
{
/**
* The <code>LabelProvider</code> implementation of this
* <code>ITableLabelProvider</code> method returns <code>null</code>.
* Subclasses may override.
*/
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
/**
* The <code>LabelProvider</code> implementation of this
* <code>ITableLabelProvider</code> method returns the element's
* <code>toString</code> string. Subclasses may override.
*/
public String getColumnText( Object element, int columnIndex )
{
return element == null ? "" : element.toString(); //$NON-NLS-1$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/ColumnViewerSortColumnUtils.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/ColumnViewerSortColumnUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.view.ColumnsTableViewerComparator;
/**
* This helper class can be used to add sort columns to {@link TableViewer}
* and {@link TreeViewer} objects.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ColumnViewerSortColumnUtils
{
/**
* Adds a sort column to the table viewer.
*
* @param tableViewer
* the table viewer
* @param tableColumn
* the table column
*/
public static void addSortColumn( TableViewer tableViewer, TableColumn tableColumn )
{
if ( tableColumn == null )
{
return;
}
Table table = tableViewer.getTable();
if ( table == null )
{
return;
}
// Looking for the column index of the table column
for ( int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++ )
{
if ( tableColumn.equals( table.getColumn( columnIndex ) ) )
{
tableColumn.addSelectionListener( getHeaderListener( tableViewer, columnIndex ) );
}
}
}
/**
* Gets a header listener for the given column.
*
* @param tableViewer
* the table viewer
* @param columnIndex
* the column index
* @return
* a header listener for the given column
*/
private static SelectionListener getHeaderListener( final TableViewer tableViewer, final int columnIndex )
{
return new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
if ( tableViewer == null )
{
return;
}
TableColumn column = ( TableColumn ) e.widget;
resortTable( tableViewer, column, columnIndex );
}
};
}
/**
* Resorts the table based on column.
*
* @param tableViewer
* the table viewer
* @param tableColumn
* the table column being resorted
* @param columnIndex
* the column index
*/
protected static void resortTable( final TableViewer tableViewer, final TableColumn tableColumn, int columnIndex )
{
// Getting the sorter
ColumnsTableViewerComparator sorter = ( ColumnsTableViewerComparator ) tableViewer.getComparator();
// Checking if sorting needs to be reversed or set to another columns
if ( columnIndex == sorter.getColumn() )
{
sorter.reverseOrder();
}
else
{
sorter.setColumn( columnIndex );
}
// Refreshing the table and updating the direction indicator asynchronously
PlatformUI.getWorkbench().getDisplay().asyncExec( new Runnable()
{
public void run()
{
tableViewer.refresh();
updateDirectionIndicator( tableViewer, tableColumn );
}
} );
}
/**
* Updates the direction indicator as column is now the primary column.
*
* @param tableViewer
* the table viewer
* @param tableColumn
* the table column
*/
protected static void updateDirectionIndicator( TableViewer tableViewer, TableColumn tableColumn )
{
tableViewer.getTable().setSortColumn( tableColumn );
if ( ( ( ColumnsTableViewerComparator ) tableViewer.getComparator() ).getOrder() == ColumnsTableViewerComparator.ASCENDING )
{
tableViewer.getTable().setSortDirection( SWT.UP );
}
else
{
tableViewer.getTable().setSortDirection( SWT.DOWN );
}
}
/**
* Adds a sort column to the tree viewer.
*
* @param treeViewer
* the tree viewer
* @param treeColumn
* the tree column
*/
public static void addSortColumn( TreeViewer treeViewer, TreeColumn treeColumn )
{
if ( treeColumn == null )
{
return;
}
Tree tree = treeViewer.getTree();
if ( tree == null )
{
return;
}
// Looking for the column index of the ttreeable column
for ( int columnIndex = 0; columnIndex < tree.getColumnCount(); columnIndex++ )
{
if ( treeColumn.equals( tree.getColumn( columnIndex ) ) )
{
treeColumn.addSelectionListener( getHeaderListener( treeViewer, columnIndex ) );
}
}
}
/**
* Gets a header listener for the given column.
*
* @param treeViewer
* the tree viewer
* @param columnIndex
* the column index
* @return
* a header listener for the given column
*/
private static SelectionListener getHeaderListener( final TreeViewer treeViewer, final int columnIndex )
{
return new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
if ( treeViewer == null )
{
return;
}
TreeColumn column = ( TreeColumn ) e.widget;
resortTree( treeViewer, column, columnIndex );
}
};
}
/**
* Resorts the tree based on column.
*
* @param treeViewer
* the tree viewer
* @param treeColumn
* the tree column being resorted
* @param columnIndex
* the column index
*/
protected static void resortTree( final TreeViewer treeViewer, final TreeColumn treeColumn, int columnIndex )
{
// Getting the sorter
ColumnsTableViewerComparator sorter = ( ColumnsTableViewerComparator ) treeViewer.getComparator();
// Checking if sorting needs to be reversed or set to another columns
if ( columnIndex == sorter.getColumn() )
{
sorter.reverseOrder();
}
else
{
sorter.setColumn( columnIndex );
}
// Refreshing the tree and updating the direction indicator asynchronously
PlatformUI.getWorkbench().getDisplay().asyncExec( new Runnable()
{
public void run()
{
treeViewer.refresh();
updateDirectionIndicator( treeViewer, treeColumn );
}
} );
}
/**
* Updates the direction indicator as column is now the primary column.
*
* @param treeViewer
* the tree viewer
* @param treeColumn
* the tree column
*/
protected static void updateDirectionIndicator( TreeViewer treeViewer, TreeColumn treeColumn )
{
treeViewer.getTree().setSortColumn( treeColumn );
if ( ( ( ColumnsTableViewerComparator ) treeViewer.getComparator() ).getColumn() == ColumnsTableViewerComparator.ASCENDING )
{
treeViewer.getTree().setSortDirection( SWT.UP );
}
else
{
treeViewer.getTree().setSortDirection( SWT.DOWN );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesLabelProvider.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesLabelProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import java.util.Iterator;
import java.util.List;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableFontProvider;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.view.ColumnsLabelProvider;
/**
* This class implements a label provider for the table viewer of
* the Template Entry Editor preference page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplatesLabelProvider extends ColumnsLabelProvider implements ITableFontProvider, ITableColorProvider
{
/** The templates manager */
private PreferencesTemplatesManager manager;
/** The preference store */
private IPreferenceStore store;
/**
* Creates a new instance of TemplatesLabelProvider.
*/
public TemplatesLabelProvider( PreferencesTemplatesManager manager )
{
this.manager = manager;
store = EntryTemplatePlugin.getDefault().getPreferenceStore();
}
/**
* {@inheritDoc}
*/
public Image getColumnImage( Object element, int columnIndex )
{
// Object class presentation
if ( isObjectClassPresentation() )
{
if ( columnIndex == 0 )
{
if ( element instanceof ObjectClass )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_OBJECT_CLASS );
}
else if ( element instanceof Template )
{
if ( manager.isEnabled( ( Template ) element ) )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_TEMPLATE );
}
else
{
return EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TEMPLATE_DISABLED );
}
}
}
}
// Template presentation
else if ( isTemplatePresentation() )
{
if ( columnIndex == 0 )
{
if ( element instanceof Template )
{
if ( manager.isEnabled( ( Template ) element ) )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_TEMPLATE );
}
else
{
return EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TEMPLATE_DISABLED );
}
}
}
else if ( columnIndex == 1 )
{
if ( element instanceof Template )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_OBJECT_CLASS );
}
}
}
return null;
}
/**
* {@inheritDoc}
*/
public String getColumnText( Object element, int columnIndex )
{
// Object class presentation
if ( isObjectClassPresentation() )
{
if ( columnIndex == 0 )
{
if ( element instanceof ObjectClass )
{
return concatenateObjectClassNames( ( ( ObjectClass ) element ).getNames() );
}
else if ( element instanceof Template )
{
Template template = ( Template ) element;
if ( manager.isDefaultTemplate( template ) )
{
return NLS.bind( Messages.getString( "TemplatesLabelProvider.Default" ), template.getTitle() ); //$NON-NLS-1$
}
else
{
return template.getTitle();
}
}
}
}
// Template presentation
else if ( isTemplatePresentation() )
{
if ( columnIndex == 0 )
{
if ( element instanceof Template )
{
return ( ( Template ) element ).getTitle();
}
}
else if ( columnIndex == 1 )
{
if ( element instanceof Template )
{
Template template = ( Template ) element;
return concatenateObjectClasses( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ), template
.getAuxiliaryObjectClasses() );
}
}
}
return ""; //$NON-NLS-1$
}
/**
* Indicates if the template presentation is selected.
*
* @return
* <code>true</code> if the template presentation is selected,
* <code>false</code> if not
*/
private boolean isTemplatePresentation()
{
return ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_TEMPLATE );
}
/**
* Indicates if the object class presentation is selected.
*
* @return
* <code>true</code> if the object class presentation is selected,
* <code>false</code> if not
*/
private boolean isObjectClassPresentation()
{
return ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS );
}
/**
* Concatenates the object classes in a single string.
*
* @param objectClass
* the object class
* @param auxiliaryObjectClasses
* the list of auxiliary object class names
* @return
* a string containing all the object classes separated
* by <code>", "</code> characters.
*/
private String concatenateObjectClasses( ObjectClass objectClass,
List<String> auxiliaryObjectClasses )
{
if ( ( objectClass != null ) && ( auxiliaryObjectClasses != null ) )
{
StringBuilder sb = new StringBuilder();
sb.append( concatenateObjectClassNames( objectClass.getNames() ) );
if ( auxiliaryObjectClasses.size() > 0 )
{
sb.append( " <" ); //$NON-NLS-1$
// Adding each auxiliary object class
Iterator<String> iterator = auxiliaryObjectClasses.iterator();
while ( iterator.hasNext() )
{
sb.append( ( String ) iterator.next() );
if ( iterator.hasNext() )
{
sb.append( ", " ); //$NON-NLS-1$
}
}
sb.append( ">" ); //$NON-NLS-1$
}
return sb.toString();
}
return ""; //$NON-NLS-1$
}
/**
* Concatenates the object class names in a single string.
*
* @param objectClasses
* the object classes
* @return
* a string containing all the object classes separated
* by <code>", "</code> characters.
*/
private String concatenateObjectClassNames( List<String> names )
{
if ( ( names != null ) && ( names.size() > 0 ) )
{
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = names.iterator();
while ( iterator.hasNext() )
{
sb.append( ( String ) iterator.next() );
if ( iterator.hasNext() )
{
sb.append( ", " ); //$NON-NLS-1$
}
}
return sb.toString();
}
return ""; //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public Font getFont( Object element, int columnIndex )
{
// Object class presentation
if ( isObjectClassPresentation() )
{
if ( element instanceof Template )
{
if ( manager.isDefaultTemplate( ( Template ) element ) )
{
// Get the default Bold Font
return JFaceResources.getFontRegistry().getBold( JFaceResources.DEFAULT_FONT );
}
}
}
return null;
}
/**
* {@inheritDoc}
*/
public Color getForeground( Object element, int columnIndex )
{
if ( element instanceof Template )
{
if ( !manager.isEnabled( ( Template ) element ) )
{
// TODO: get disabled color
return null;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public Color getBackground( Object element, int columnIndex )
{
return null;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/PreferencesFileTemplate.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/PreferencesFileTemplate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import org.apache.directory.studio.templateeditor.model.AbstractTemplate;
/**
* This class implements a template based on a file (i.e. stored on the disk in the plugin's folder).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PreferencesFileTemplate extends AbstractTemplate
{
/** The absolute path to the file */
private String filePath;
/**
* Gets the absolute file to the path.
*
* @return
* the asolute path to the file
*/
public String getFilePath()
{
return filePath;
}
/**
* Sets the absolute path to the file
*
* @param filePath
* the absolute path to the file
*/
public void setFilePath( String filePath )
{
this.filePath = filePath;
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.view.preferences.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesContentProvider.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesContentProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.TemplatesManagerListener;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This class implements a content provider for the table viewer of
* the Template Entry Editor preference page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplatesContentProvider implements ITreeContentProvider, TemplatesManagerListener
{
/** The associated page */
private TemplateEntryEditorPreferencePage page;
/** The templates manager */
private PreferencesTemplatesManager manager;
/** The preference store */
private IPreferenceStore store;
/** A flag indicating if the content provider has already been initialized */
private boolean initialized = false;
/** The list of templates */
private List<Template> templates;
/** The map where templates are organized by object classes */
private MultiValuedMap<ObjectClass, Template> objectClassesTemplatesMap;
/**
* Creates a new instance of TemplatesContentProvider.
*
* @param page
* the associated page
* @param manager
* the templates manager
*/
public TemplatesContentProvider( TemplateEntryEditorPreferencePage page, PreferencesTemplatesManager manager )
{
this.page = page;
this.manager = manager;
manager.addListener( this );
store = EntryTemplatePlugin.getDefault().getPreferenceStore();
templates = new ArrayList<Template>();
objectClassesTemplatesMap = new ArrayListValuedHashMap<>();
}
/**
* {@inheritDoc}
*/
public Object[] getChildren( Object parentElement )
{
// Object class presentation
if ( isObjectClassPresentation() )
{
if ( parentElement instanceof ObjectClass )
{
List<Template> templates = ( List<Template> ) objectClassesTemplatesMap
.get( ( ObjectClass ) parentElement );
if ( templates != null )
{
return templates.toArray();
}
}
}
// Template presentation
else if ( isTemplatePresentation() )
{
// Elements have no children
return new Object[0];
}
return new Object[0];
}
/**
* {@inheritDoc}
*/
public Object getParent( Object element )
{
// Elements have no parent, as they have no children
return null;
}
/**
* {@inheritDoc}
*/
public boolean hasChildren( Object element )
{
// Object class presentation
if ( isObjectClassPresentation() )
{
if ( element instanceof ObjectClass )
{
return objectClassesTemplatesMap.containsKey( ( ObjectClass ) element );
}
}
// Template presentation
else if ( isTemplatePresentation() )
{
// Elements have no children
return false;
}
return false;
}
/**
* {@inheritDoc}
*/
public Object[] getElements( Object inputElement )
{
if ( !initialized )
{
// Looping on the templates
for ( Template template : manager.getTemplates() )
{
// Adding the template
templates.add( template );
// Adding the structural object class
objectClassesTemplatesMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ), template );
}
// Setting the initialized flag to true
initialized = true;
}
// Object class presentation
if ( isObjectClassPresentation() )
{
// Returning the object classes
return objectClassesTemplatesMap.keySet().toArray();
}
// Template presentation
else if ( isTemplatePresentation() )
{
// Returning the templates
return templates.toArray();
}
return new Object[0];
}
/**
* {@inheritDoc}
*/
public void dispose()
{
EntryTemplatePlugin.getDefault().getTemplatesManager().removeListener( this );
}
/**
* {@inheritDoc}
*/
public void inputChanged( Viewer viewer, Object oldInput, Object newInput )
{
// Nothing to do.
}
/**
* Indicates if the template presentation is selected.
*
* @return
* <code>true</code> if the template presentation is selected,
* <code>false</code> if not
*/
public boolean isTemplatePresentation()
{
return ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_TEMPLATE );
}
/**
* Indicates if the object class presentation is selected.
*
* @return
* <code>true</code> if the object class presentation is selected,
* <code>false</code> if not
*/
public boolean isObjectClassPresentation()
{
return ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS );
}
/**
* {@inheritDoc}
*/
public void templateAdded( Template template )
{
// Adding the template
templates.add( template );
// Adding the structural object class
objectClassesTemplatesMap.put( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ), template );
// Refreshing the viewer
page.refreshViewer();
}
/**
* {@inheritDoc}
*/
public void templateRemoved( Template template )
{
// Removing the structural object class
objectClassesTemplatesMap.removeMapping( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ), template );
// Removing the template
templates.remove( template );
// Refreshing the viewer
page.refreshViewer();
}
/**
* {@inheritDoc}
*/
public void templateDisabled( Template template )
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
public void templateEnabled( Template template )
{
// Nothing to do
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesCheckStateListener.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplatesCheckStateListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This class is used to respond to a check state event.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplatesCheckStateListener implements ICheckStateListener
{
/** The associated content provider */
private TemplatesContentProvider contentProvider;
/** The templates manager */
private PreferencesTemplatesManager manager;
/**
* Creates a new instance of TemplatesCheckStateProviderListener.
*
* @param contentProvider
* the associated content provider
*/
public TemplatesCheckStateListener( TemplatesContentProvider contentProvider, PreferencesTemplatesManager manager )
{
this.contentProvider = contentProvider;
this.manager = manager;
}
/**
* {@inheritDoc}
*/
public void checkStateChanged( CheckStateChangedEvent event )
{
// Getting the element of the event
Object element = event.getElement();
// Object class presentation
if ( contentProvider.isObjectClassPresentation() )
{
if ( element instanceof Template )
{
setTemplateEnabled( ( Template ) element, event.getChecked() );
}
else if ( element instanceof ObjectClass )
{
// Getting the children of the node
Object[] children = contentProvider.getChildren( element );
if ( children != null )
{
for ( Object child : children )
{
setTemplateEnabled( ( Template ) child, event.getChecked() );
}
}
}
}
// Template presentation
else if ( contentProvider.isTemplatePresentation() )
{
setTemplateEnabled( ( Template ) element, event.getChecked() );
}
}
/**
* Enables or disables a template.
*
* @param template
* the template
* @param enabled
* <code>true</code> if the template needs to be enabled,
* <code>false</code> if the template needs to be disabled
*/
private void setTemplateEnabled( Template template, boolean enabled )
{
if ( enabled )
{
manager.enableTemplate( template );
}
else
{
manager.disableTemplate( template );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/PreferencesTemplatesManager.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/PreferencesTemplatesManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.TemplatesManager;
import org.apache.directory.studio.templateeditor.TemplatesManagerListener;
import org.apache.directory.studio.templateeditor.model.FileTemplate;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIO;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIOException;
/**
* This templates manager is to be used in the plugin's preference page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PreferencesTemplatesManager
{
/** The templates manager */
private TemplatesManager manager;
/** The list containing all the templates */
private List<Template> templatesList = new ArrayList<Template>();
/** The map containing the templates based on their IDs */
private Map<String, Template> templatesByIdMap = new HashMap<String, Template>();
/** The map containing the default templates */
private Map<ObjectClass, String> defaultTemplatesMap = new HashMap<ObjectClass, String>();
/** The set containing *only* the IDs of the disabled templates */
private List<String> disabledTemplatesList = new ArrayList<String>();
/** The list of listeners */
private List<TemplatesManagerListener> listeners = new ArrayList<TemplatesManagerListener>();
/**
* Creates a new instance of PreferencesTemplatesManager.
*/
public PreferencesTemplatesManager( TemplatesManager manager )
{
this.manager = manager;
init();
}
/**
* Adds a listener.
*
* @param listener
* the listener
* @return
* <code>true</code> (as per the general contract of the
* <code>Collection.add</code> method).
*/
public boolean addListener( TemplatesManagerListener listener )
{
return listeners.add( listener );
}
/**
* Removes a listener.
*
* @param listener
* the listener
* @return
* <code>true</code> if this templates manager contained
* the specified listener.
*/
public boolean removeListener( TemplatesManagerListener listener )
{
return listeners.remove( listener );
}
/**
* Fires a "fireTemplateAdded" event to all the listeners.
*
* @param template
* the added template
*/
private void fireTemplateAdded( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateAdded( template );
}
}
/**
* Fires a "templateRemoved" event to all the listeners.
*
* @param template
* the removed template
*/
private void fireTemplateRemoved( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateRemoved( template );
}
}
/**
* Fires a "templateEnabled" event to all the listeners.
*
* @param template
* the enabled template
*/
private void fireTemplateEnabled( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateEnabled( template );
}
}
/**
* Fires a "templateDisabled" event to all the listeners.
*
* @param template
* the disabled template
*/
private void fireTemplateDisabled( Template template )
{
for ( TemplatesManagerListener listener : listeners.toArray( new TemplatesManagerListener[0] ) )
{
listener.templateDisabled( template );
}
}
/**
* Initializes the Preferences manager from the plugin manager.
*/
private void init()
{
// Getting the templates from the plugin manager
Template[] pluginTemplates = manager.getTemplates();
for ( Template pluginTemplate : pluginTemplates )
{
templatesList.add( pluginTemplate );
templatesByIdMap.put( pluginTemplate.getId(), pluginTemplate );
// Is the template enabled?
if ( !manager.isEnabled( pluginTemplate ) )
{
disabledTemplatesList.add( pluginTemplate.getId() );
}
// Is it the default template?
if ( manager.isDefaultTemplate( pluginTemplate ) )
{
defaultTemplatesMap.put( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( pluginTemplate.getStructuralObjectClass() ),
pluginTemplate.getId() );
}
}
}
/**
* Saves the modifications back to the initial manager.
*/
public boolean saveModifications()
{
// Getting original templates
Template[] originalTemplates = manager.getTemplates();
// Creating a list of original templates
List<Template> originalTemplatesList = new ArrayList<Template>();
// Looping on original templates
for ( Template originalTemplate : originalTemplates )
{
// Checking if the enablement state has been changed
boolean isEnabled = isEnabled( originalTemplate );
if ( manager.isEnabled( originalTemplate ) != isEnabled )
{
if ( isEnabled )
{
manager.enableTemplate( originalTemplate );
}
else
{
manager.disableTemplate( originalTemplate );
}
}
// Checking if the default state has been changed
boolean isDefaultTemplate = isDefaultTemplate( originalTemplate );
if ( manager.isDefaultTemplate( originalTemplate ) != isDefaultTemplate )
{
if ( isDefaultTemplate )
{
manager.setDefaultTemplate( originalTemplate );
}
else
{
manager.unSetDefaultTemplate( originalTemplate );
}
}
// Checking if the original template has been removed
if ( !templatesList.contains( originalTemplate ) )
{
if ( !manager.removeTemplate( ( FileTemplate ) originalTemplate ) )
{
// Creating and opening the error dialog
String dialogTitle = Messages.getString( "PreferencesTemplatesManager.UnableToRemoveTheTemplate" ); //$NON-NLS-1$
String dialogMessage = MessageFormat
.format(
Messages.getString( "PreferencesTemplatesManager.TheTemplateCouldNotBeRemoved" ) //$NON-NLS-1$
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ Messages.getString( "PreferencesTemplatesManager.SeeTheLogsFileForMoreInformation" ), originalTemplate.getTitle() ); //$NON-NLS-1$
MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell(), dialogTitle, null, dialogMessage, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
return false;
}
}
// Adding the template to the list
originalTemplatesList.add( originalTemplate );
}
// Looping on the new templates list
for ( Template template : templatesList )
{
// Checking if the template has been added
if ( !originalTemplatesList.contains( template ) )
{
// Adding the new template
if ( !manager.addTemplate( new File( ( ( PreferencesFileTemplate ) template ).getFilePath() ) ) )
{
// Creating and opening the error dialog
String dialogTitle = Messages.getString( "PreferencesTemplatesManager.UnableToAddTheTemplate" ); //$NON-NLS-1$
String dialogMessage = MessageFormat
.format(
Messages.getString( "PreferencesTemplatesManager.TheTemplateCouldNotBeAdded" ) //$NON-NLS-1$
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ Messages.getString( "PreferencesTemplatesManager.SeeTheLogsFileForMoreInformation" ), template.getTitle() ); //$NON-NLS-1$
MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell(), dialogTitle, null, dialogMessage, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
return false;
}
// Setting the enablement state to the new template
boolean isEnabled = isEnabled( template );
if ( isEnabled )
{
manager.enableTemplate( template );
}
else
{
manager.disableTemplate( template );
}
// Setting the default state has been changed
boolean isDefaultTemplate = isDefaultTemplate( template );
if ( isDefaultTemplate )
{
manager.setDefaultTemplate( template );
}
else
{
manager.unSetDefaultTemplate( template );
}
}
}
return true;
}
/**
* Gets the templates.
*
* @return
* the templates
*/
public Template[] getTemplates()
{
return templatesList.toArray( new Template[0] );
}
/**
* Indicates if the given template is enabled or not.
*
* @param template
* the template
* @return
* <code>true</code> if the template is enabled,
* <code>false</code> if the template is disabled
*/
public boolean isEnabled( Template template )
{
return !disabledTemplatesList.contains( template.getId() );
}
/**
* Adds a template from a file on the disk.
*
* @param templateFile
* the template file
* @return
* <code>true</code> if the template file has been successfully added,
* <code>false</code> if the template file has not been added
*/
public boolean addTemplate( File templateFile )
{
// Getting the template
PreferencesFileTemplate template = getTemplateFromFile( templateFile );
if ( template == null )
{
// If the file is not valid, we simply return
return false;
}
if ( templatesByIdMap.containsKey( template.getId() ) )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeAddedBecauseATemplateWithSameIDAlreadyExist" ), //$NON-NLS-1$
templateFile.getAbsolutePath() );
return false;
}
// Adding the template
templatesList.add( template );
templatesByIdMap.put( template.getId(), template );
// If there's no default template, then set this one as default one
if ( !defaultTemplatesMap.containsKey( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ) ) )
{
setDefaultTemplate( template );
}
// Firing the event
fireTemplateAdded( template );
return true;
}
/**
* Get the file template associate with the template file.
*
* @param templateFile
* the template file
* @return
* the associated file template
*/
private PreferencesFileTemplate getTemplateFromFile( File templateFile )
{
// Checking if the file exists
if ( !templateFile.exists() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeAddedBecauseItDoesNotExist" ), templateFile //$NON-NLS-1$
.getAbsolutePath() );
return null;
}
// Checking if the file is readable
if ( !templateFile.canRead() )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeAddedBecauseItCantBeRead" ), templateFile.getAbsolutePath() ); //$NON-NLS-1$
return null;
}
// Trying to parse the template file
PreferencesFileTemplate fileTemplate = null;
try
{
InputStream is = new FileInputStream( templateFile );
fileTemplate = TemplateIO.readAsPreferencesFileTemplate( is );
fileTemplate.setFilePath( templateFile.getAbsolutePath() );
is.close();
}
catch ( IOException e )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
e,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeAddedBecauseOfTheFollowingError" ), templateFile //$NON-NLS-1$
.getAbsolutePath(), e.getMessage() );
return null;
}
catch ( TemplateIOException e )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
e,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeAddedBecauseOfTheFollowingError" ), templateFile //$NON-NLS-1$
.getAbsolutePath(), e.getMessage() );
return null;
}
// Everything went fine, the file is valid
return fileTemplate;
}
/**
* Removes a template.
*
* @param template
* the template to remove
* @return
* <code>true</code> if the template has been successfully removed,
* <code>false</code> if the template file has not been removed
*/
public boolean removeTemplate( Template template )
{
// Checking if the file template exists in the templates set
if ( !templatesList.contains( template ) )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
null,
Messages
.getString( "PreferencesTemplatesManager.TheTemplateFileCouldNotBeRemovedBecauseOfTheFollowingError" ) //$NON-NLS-1$
+ Messages
.getString( "PreferencesTemplatesManager.TheTemplateDoesNotExistInTheTemplateManager" ), template.getTitle(), template.getId() ); //$NON-NLS-1$
return false;
}
// Removing the template from the disabled templates list
if ( disabledTemplatesList.contains( template.getId() ) )
{
disabledTemplatesList.remove( template.getId() );
}
// Removing the template for the templates list
templatesList.remove( template );
templatesByIdMap.remove( template.getId() );
// Checking if the template is the default one
if ( isDefaultTemplate( template ) )
{
// Unsetting the template as default
unSetDefaultTemplate( template );
// Assign another default template.
setNewAutoDefaultTemplate( template.getStructuralObjectClass() );
}
// Firing the event
fireTemplateRemoved( template );
return true;
}
/**
* Enables the given template.
*
* @param template
* the template
*/
public void enableTemplate( Template template )
{
// Removing the id of the template to the list of disabled templates
disabledTemplatesList.remove( template.getId() );
// If there's no default template, then set this one as default one
if ( !defaultTemplatesMap.containsKey( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ) ) )
{
setDefaultTemplate( template );
}
// Firing the event
fireTemplateEnabled( template );
}
/**
* Disables the given template.
*
* @param template
* the template
*/
public void disableTemplate( Template template )
{
if ( !disabledTemplatesList.contains( template.getId() ) )
{
// Adding the id of the template to the list of disabled templates
disabledTemplatesList.add( template.getId() );
// Checking if the template is the default one
if ( isDefaultTemplate( template ) )
{
// Unsetting the template as default
unSetDefaultTemplate( template );
// Assign another default template.
setNewAutoDefaultTemplate( template.getStructuralObjectClass() );
}
// Firing the event
fireTemplateDisabled( template );
}
}
/**
* Sets the given template as default for its structural object class.
*
* @param template
* the template
*/
public void setDefaultTemplate( Template template )
{
if ( isEnabled( template ) )
{
// Removing the old value
defaultTemplatesMap.remove( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ) );
// Setting the new value
defaultTemplatesMap.put( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ), template.getId() );
}
}
/**
* Unsets the given template as default for its structural object class.
*
* @param template
* the template
*/
public void unSetDefaultTemplate( Template template )
{
if ( isDefaultTemplate( template ) )
{
defaultTemplatesMap.remove( EntryTemplatePluginUtils.getObjectClassDescriptionFromDefaultSchema( template
.getStructuralObjectClass() ) );
}
}
/**
* Automatically sets a new default template (if one is found) for the given structural object class.
*
* @param structuralObjectClass
* the structural object class
*/
public void setNewAutoDefaultTemplate( String structuralObjectClass )
{
ObjectClass structuralOcd = EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( structuralObjectClass );
for ( Template templateCandidate : templatesList )
{
ObjectClass templateCandidateOcd = EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( templateCandidate.getStructuralObjectClass() );
if ( structuralOcd.equals( templateCandidateOcd ) )
{
if ( isEnabled( templateCandidate ) )
{
// Setting the new value
defaultTemplatesMap.put( templateCandidateOcd, templateCandidate.getId() );
return;
}
}
}
}
/**
* Indicates if the given template is the default one
* for its structural object class or not.
*
* @param template
* the template
* @return
* <code>true</code> if the given template is the default one
* for its structural object class,
* <code>false</code> if not
*/
public boolean isDefaultTemplate( Template template )
{
String defaultTemplateID = defaultTemplatesMap.get( EntryTemplatePluginUtils
.getObjectClassDescriptionFromDefaultSchema( template.getStructuralObjectClass() ) );
if ( defaultTemplateID != null )
{
return defaultTemplateID.equalsIgnoreCase( template.getId() );
}
return false;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplateEntryEditorPreferencePage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/preferences/TemplateEntryEditorPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.preferences;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.FileTemplate;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.view.ColumnsTableViewerComparator;
import org.apache.directory.studio.templateeditor.view.wizards.ExportTemplatesWizard;
import org.apache.directory.studio.templateeditor.view.wizards.ImportTemplatesWizard;
/**
* This class implements the Template Entry Editor preference page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TemplateEntryEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
/** The root object for the templates viewer */
private static final Object TEMPLATES_VIEWER_ROOT = new Object();
/** The preferences store */
private IPreferenceStore store;
/** The preferences templates manager */
private PreferencesTemplatesManager manager;
// UI Fields
private ToolItem objectClassPresentationToolItem;
private ToolItem templatePresentationToolItem;
private Composite templatesViewerComposite;
private CheckboxTreeViewer templatesViewer;
private Button importTemplatesButton;
private Button exportTemplatesButton;
private Button removeTemplateButton;
private Button setDefaultTemplateButton;
private Button useForAnyEntryButton;
private Button useForOnlyEntriesWithTemplateButton;
/** The selection listener for the templates viewer */
private Listener templatesViewerSelectionListener = new Listener()
{
public void handleEvent( Event event )
{
if ( event.detail == SWT.CHECK )
{
templatesViewer.refresh();
TreeItem item = ( TreeItem ) event.item;
boolean checked = item.getChecked();
checkItems( item, checked );
checkPath( item.getParentItem(), checked, false );
updateButtonsStates();
}
}
/**
* Checks the path of the item in the tree viewer.
*
* @param item
* the item
* @param checked
* whether the item is checked or not
* @param grayed
* whether the item is grayed or not
*/
private void checkPath( TreeItem item, boolean checked, boolean grayed )
{
if ( item == null )
return;
if ( grayed )
{
checked = true;
}
else
{
int index = 0;
TreeItem[] items = item.getItems();
while ( index < items.length )
{
TreeItem child = items[index];
if ( child.getGrayed() || checked != child.getChecked() )
{
checked = grayed = true;
break;
}
index++;
}
}
item.setChecked( checked );
item.setGrayed( grayed );
checkPath( item.getParentItem(), checked, grayed );
}
/**
* Checks the item and the children items.
*
* @param item
* the item
* @param checked
* whether the item is checked or not
*/
private void checkItems( TreeItem item, boolean checked )
{
item.setGrayed( false );
item.setChecked( checked );
TreeItem[] items = item.getItems();
for ( int i = 0; i < items.length; i++ )
{
checkItems( items[i], checked );
}
}
};
/** The selection change listener for the templates viewer */
private ISelectionChangedListener templatesViewerSelectionChangedListener = new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
updateButtonsStates();
}
};
/**
* Creates a new instance of TemplateEntryEditorPreferencePage.
*/
public TemplateEntryEditorPreferencePage()
{
super();
super.setPreferenceStore( EntryTemplatePlugin.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "TemplateEntryEditorPreferencePage.PrefPageDescription" ) ); //$NON-NLS-1$
store = EntryTemplatePlugin.getDefault().getPreferenceStore();
manager = new PreferencesTemplatesManager( EntryTemplatePlugin.getDefault().getTemplatesManager() );
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
composite.setLayout( new GridLayout() );
composite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
createUI( composite );
initListeners();
initUI();
return composite;
}
/**
* Creates the user interface.
*
* @param parent
* the parent composite
*/
private void createUI( Composite parent )
{
// Main Composite
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// Templates Group
createTemplatesGroup( composite );
// Use Template Editor group
createUseTemplateEditorGroup( composite );
}
/**
* Creates the templates group.
*
* @param composite
* the parent composite
*/
private void createTemplatesGroup( Composite parent )
{
// Templates Group
Group templatesGroup = BaseWidgetUtils.createGroup( parent, Messages
.getString( "TemplateEntryEditorPreferencePage.Templates" ), 1 ); //$NON-NLS-1$
templatesGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
templatesGroup.setLayout( new GridLayout( 2, false ) );
// ToolBar
createToolbar( templatesGroup );
// ToolBar Filler (to fill the right part of the row)
new Label( templatesGroup, SWT.NONE );
// Templates Viewer Composite
createTemplatesViewerComposite( templatesGroup );
// Buttons
createTemplatesTableButtons( templatesGroup );
}
/**
* Creates the templates viewer's composite.
*
* @param composite
* the parent composite
*/
private void createTemplatesViewerComposite( Composite parent )
{
templatesViewerComposite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout();
gl.horizontalSpacing = 0;
gl.verticalSpacing = 0;
gl.marginHeight = 0;
gl.marginWidth = 0;
templatesViewerComposite.setLayout( gl );
templatesViewerComposite.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 5 ) );
templatesViewerComposite.addControlListener( new ControlAdapter()
{
public void controlResized( ControlEvent e )
{
// Resizing columns when the preference window (hence the composite) is resized
resizeColumsToFit();
}
} );
}
/**
* Creates the toolbar.
*
* @param composite
* the parent composite
*/
private void createToolbar( Composite composite )
{
Composite toolbarComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
toolbarComposite.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
Label toolbarLabel = BaseWidgetUtils.createLabel( toolbarComposite, Messages
.getString( "TemplateEntryEditorPreferencePage.Presentation" ), 1 ); //$NON-NLS-1$
toolbarLabel.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, true, false ) );
// ToolBar
ToolBar toolbar = new ToolBar( toolbarComposite, SWT.HORIZONTAL | SWT.FLAT );
toolbar.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false, false ) );
// Hierarchical object class oriented presentation toolitem
objectClassPresentationToolItem = new ToolItem( toolbar, SWT.RADIO );
objectClassPresentationToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_OBJECT_CLASS ) );
objectClassPresentationToolItem.setToolTipText( Messages
.getString( "TemplateEntryEditorPreferencePage.HierarchicalObjectClassOrientedPresentation" ) ); //$NON-NLS-1$
objectClassPresentationToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
if ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) != EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS )
{
objectClassPresentationToolItemSelected();
}
}
} );
// Flat template oriented presentation toolitem
templatePresentationToolItem = new ToolItem( toolbar, SWT.RADIO );
templatePresentationToolItem.setImage( EntryTemplatePlugin.getDefault().getImage(
EntryTemplatePluginConstants.IMG_TEMPLATE ) );
templatePresentationToolItem.setToolTipText( Messages
.getString( "TemplateEntryEditorPreferencePage.FlatTemplateOrientedPresentation" ) ); //$NON-NLS-1$
templatePresentationToolItem.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
if ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) != EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_TEMPLATE )
{
templatePresentationToolItemSelected();
}
}
} );
}
/**
* This method is called when the flat template oriented presentation
* toolitem is selected.
*/
private void templatePresentationToolItemSelected()
{
// Saving the setting in the preferences
store.setValue( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION,
EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_TEMPLATE );
// Removing listeners
removeTemplatesViewerListeners();
// Disposing the old templates viewer
if ( ( templatesViewer != null ) && ( !templatesViewer.getTree().isDisposed() ) )
{
templatesViewer.getTree().dispose();
templatesViewer = null;
}
// Creating a new one
createTemplatesViewer();
Tree templatesTree = templatesViewer.getTree();
// Title column
TreeColumn titleColumn = new TreeColumn( templatesTree, SWT.SINGLE );
titleColumn.setText( Messages.getString( "TemplateEntryEditorPreferencePage.Title" ) ); //$NON-NLS-1$
// Object classes column
TreeColumn objectClassesColumn = new TreeColumn( templatesTree, SWT.SINGLE );
objectClassesColumn.setText( Messages.getString( "TemplateEntryEditorPreferencePage.ObjectClasses" ) ); //$NON-NLS-1$
// Setting the default sort column
templatesTree.setSortColumn( titleColumn );
templatesTree.setSortDirection( SWT.UP );
// Setting the columns so they can be sorted
ColumnViewerSortColumnUtils.addSortColumn( templatesViewer, titleColumn );
ColumnViewerSortColumnUtils.addSortColumn( templatesViewer, objectClassesColumn );
// Showing the columns header
templatesTree.setHeaderVisible( true );
// Settings the templates to the templates viewer
templatesViewer.setInput( TEMPLATES_VIEWER_ROOT );
// Adding listeners
addTemplatesViewerListeners();
// Updating the parent composite
templatesViewerComposite.layout();
// Setting the state for checked and grayed elements
setStateForCheckedAndGrayedElements();
// Resizing columns
resizeColumsToFit();
// Hiding the 'Set Default' button
setDefaultTemplateButton.setVisible( false );
}
/**
* This method is called when the hierarchical object class oriented
* presentation toolitem is selected.
*/
private void objectClassPresentationToolItemSelected()
{
// Saving the setting in the preferences
store.setValue( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION,
EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS );
// Removing listeners
removeTemplatesViewerListeners();
// Disposing the old templates viewer
if ( ( templatesViewer != null ) && ( !templatesViewer.getTree().isDisposed() ) )
{
templatesViewer.getTree().dispose();
templatesViewer = null;
}
// Creating a new one
createTemplatesViewer();
Tree templatesTree = templatesViewer.getTree();
// Title column
TreeColumn titleColumn = new TreeColumn( templatesTree, SWT.SINGLE );
// Setting the columns so they can be sorted
ColumnViewerSortColumnUtils.addSortColumn( templatesViewer, titleColumn );
// Hiding the columns header
templatesTree.setHeaderVisible( false );
// Settings the templates to the templates viewer
templatesViewer.setInput( TEMPLATES_VIEWER_ROOT );
// Adding listeners
addTemplatesViewerListeners();
// Updating the parent composite
templatesViewerComposite.layout();
// Setting the state for checked and grayed elements
setStateForCheckedAndGrayedElements();
// Resizing columns
resizeColumsToFit();
// Showing the 'Set Default' button
setDefaultTemplateButton.setVisible( true );
setDefaultTemplateButton.setEnabled( false );
}
/**
* Creates the templates viewer.
*/
private void createTemplatesViewer()
{
// Templates tree
Tree templatesTree = new Tree( templatesViewerComposite, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION
| SWT.CHECK );
templatesTree.setLinesVisible( false );
// Templates table viewer
templatesViewer = new CheckboxTreeViewer( templatesTree );
GridData gridData2 = new GridData( SWT.FILL, SWT.NONE, true, false );
gridData2.heightHint = 160;
templatesViewer.getTree().setLayoutData( gridData2 );
// Templates content and label providers, and comparator
TemplatesContentProvider contentProvider = new TemplatesContentProvider( this, manager );
templatesViewer.setContentProvider( contentProvider );
TemplatesCheckStateListener checkStateProviderListener = new TemplatesCheckStateListener( contentProvider,
manager );
templatesViewer.addCheckStateListener( checkStateProviderListener );
TemplatesLabelProvider labelProvider = new TemplatesLabelProvider( manager );
templatesViewer.setLabelProvider( labelProvider );
templatesViewer.setComparator( new ColumnsTableViewerComparator( labelProvider ) );
templatesViewer.addDoubleClickListener( new IDoubleClickListener()
{
@SuppressWarnings("unchecked")
public void doubleClick( DoubleClickEvent event )
{
StructuredSelection selection = ( StructuredSelection ) templatesViewer.getSelection();
if ( !selection.isEmpty() )
{
Iterator<Object> selectionIterator = selection.iterator();
while ( selectionIterator.hasNext() )
{
Object selectedElement = ( Object ) selectionIterator.next();
if ( templatesViewer.getExpandedState( selectedElement ) )
{
templatesViewer.collapseToLevel( selectedElement, 1 );
}
else
{
templatesViewer.expandToLevel( selectedElement, 1 );
}
}
}
}
} );
}
/**
* Creates the buttons associated with the templates table.
*
* @param composite
* the parent composite
*/
private void createTemplatesTableButtons( Group composite )
{
importTemplatesButton = BaseWidgetUtils.createButton( composite, Messages
.getString( "TemplateEntryEditorPreferencePage.Import" ), 1 ); //$NON-NLS-1$
exportTemplatesButton = BaseWidgetUtils.createButton( composite, Messages
.getString( "TemplateEntryEditorPreferencePage.Export" ), 1 ); //$NON-NLS-1$
removeTemplateButton = BaseWidgetUtils.createButton( composite, Messages
.getString( "TemplateEntryEditorPreferencePage.Remove" ), 1 ); //$NON-NLS-1$
setDefaultTemplateButton = BaseWidgetUtils.createButton( composite, Messages
.getString( "TemplateEntryEditorPreferencePage.SetDefault" ), 1 ); //$NON-NLS-1$
}
/**
* Creates the Use Template Editor group.
*
* @param composite
* the parent composite
*/
private void createUseTemplateEditorGroup( Composite composite )
{
// Use Template Editor Group
Group editorActivationGroup = BaseWidgetUtils.createGroup( composite, Messages
.getString( "TemplateEntryEditorPreferencePage.UseTheTemplateEntryEditor" ), 1 ); //$NON-NLS-1$
editorActivationGroup.setLayout( new GridLayout() );
editorActivationGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// With For Entry Button
useForAnyEntryButton = BaseWidgetUtils.createRadiobutton( editorActivationGroup, Messages
.getString( "TemplateEntryEditorPreferencePage.ForAnyEntry" ), 1 ); //$NON-NLS-1$
useForAnyEntryButton.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// For Only Entries With Template Button
useForOnlyEntriesWithTemplateButton = BaseWidgetUtils.createRadiobutton( editorActivationGroup, Messages
.getString( "TemplateEntryEditorPreferencePage.OnlyForEntriesMatchingAtLeastOneEnabledTemplate" ), 1 ); //$NON-NLS-1$
useForOnlyEntriesWithTemplateButton.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* Initializes the listeners
*/
private void initListeners()
{
importTemplatesButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
importTemplatesAction();
}
} );
exportTemplatesButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
exportTemplatesAction();
}
} );
removeTemplateButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
removeTemplateAction();
}
} );
setDefaultTemplateButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
setDefaultTemplateAction();
}
} );
useForAnyEntryButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
useForAnyEntryAction();
}
} );
useForOnlyEntriesWithTemplateButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
useForOnlyEntriesWithTemplateAction();
}
} );
}
/**
* Adds the listeners to the templates viewer.
*/
private void addTemplatesViewerListeners()
{
if ( ( templatesViewer != null ) && ( !templatesViewer.getTree().isDisposed() ) )
{
templatesViewer.getTree().addListener( SWT.Selection, templatesViewerSelectionListener );
templatesViewer.addSelectionChangedListener( templatesViewerSelectionChangedListener );
}
}
/**
* Removes the listeners to the templates viewer.
*/
private void removeTemplatesViewerListeners()
{
if ( ( templatesViewer != null ) && ( !templatesViewer.getTree().isDisposed() ) )
{
templatesViewer.getTree().removeListener( SWT.Selection, templatesViewerSelectionListener );
templatesViewer.removeSelectionChangedListener( templatesViewerSelectionChangedListener );
}
}
/**
* Updates the states of the buttons.
*/
@SuppressWarnings("unchecked")
private void updateButtonsStates()
{
StructuredSelection selection = ( StructuredSelection ) templatesViewer.getSelection();
if ( !selection.isEmpty() )
{
if ( selection.size() == 1 )
{
// Only one row is selected
Object selectedObject = selection.getFirstElement();
removeTemplateButton.setEnabled( ( selectedObject instanceof FileTemplate )
|| ( selectedObject instanceof PreferencesFileTemplate ) );
// If we're in the object class presentation, we need to update the 'Set Default' button
if ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS )
{
if ( selectedObject instanceof Template )
{
Template selectedTemplate = ( Template ) selectedObject;
setDefaultTemplateButton.setEnabled( ( manager.isEnabled( selectedTemplate ) && ( !manager
.isDefaultTemplate( selectedTemplate ) ) ) );
}
else
{
setDefaultTemplateButton.setEnabled( false );
}
}
}
else
{
// More than one row is selected
removeTemplateButton.setEnabled( true );
Iterator<Object> selectionIterator = ( ( StructuredSelection ) templatesViewer.getSelection() )
.iterator();
while ( selectionIterator.hasNext() )
{
Object selectedObject = selectionIterator.next();
if ( !( ( selectedObject instanceof FileTemplate ) || ( selectedObject instanceof PreferencesFileTemplate ) ) )
{
removeTemplateButton.setEnabled( false );
break;
}
}
// If we're in the object class presentation, we need to update the 'Set Default' button
if ( store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION ) == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS )
{
setDefaultTemplateButton.setEnabled( false );
}
}
}
else
{
removeTemplateButton.setEnabled( false );
setDefaultTemplateButton.setEnabled( false );
}
}
/**
* Implements the import templates action.
*/
private void importTemplatesAction()
{
WizardDialog dialog = new WizardDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
new ImportTemplatesWizard( manager ) );
dialog.create();
dialog.open();
}
/**
* Implements the export templates action.
*/
@SuppressWarnings("unchecked")
private void exportTemplatesAction()
{
// Creating the Export Templates wizard
ExportTemplatesWizard wizard = new ExportTemplatesWizard();
// Collecting the selected objects
List<Object> selectedObjects = new ArrayList<Object>();
Iterator<Object> selectionIterator = ( ( StructuredSelection ) templatesViewer.getSelection() ).iterator();
while ( selectionIterator.hasNext() )
{
selectedObjects.add( selectionIterator.next() );
}
// Assigning these objects to the wizard
wizard.setPreCheckedObjects( selectedObjects.toArray() );
// Opening the wizard
WizardDialog dialog = new WizardDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), wizard );
dialog.create();
dialog.open();
}
/**
* Implements the remove template action.
*/
@SuppressWarnings("unchecked")
private void removeTemplateAction()
{
StructuredSelection selection = ( StructuredSelection ) templatesViewer.getSelection();
if ( !selection.isEmpty() )
{
Iterator<Object> selectionIterator = ( ( StructuredSelection ) templatesViewer.getSelection() ).iterator();
while ( selectionIterator.hasNext() )
{
Object selectedObject = selectionIterator.next();
if ( selectedObject instanceof Template )
{
Template template = ( Template ) selectedObject;
if ( !manager.removeTemplate( template ) )
{
// Creating and opening the dialog
String dialogTitle = Messages
.getString( "TemplateEntryEditorPreferencePage.UnableToRemoveTheTemplate" ); //$NON-NLS-1$
String dialogMessage = MessageFormat
.format(
Messages.getString( "TemplateEntryEditorPreferencePage.TheTemplateCouldNotBeRemoved" ) //$NON-NLS-1$
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ EntryTemplatePluginUtils.LINE_SEPARATOR
+ Messages
.getString( "TemplateEntryEditorPreferencePage.SeeTheLogsFileForMoreInformation" ), template.getTitle() ); //$NON-NLS-1$
MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell(), dialogTitle, null, dialogMessage, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
}
}
}
}
}
/**
* Implements the set default template action.
*/
private void setDefaultTemplateAction()
{
StructuredSelection selection = ( StructuredSelection ) templatesViewer.getSelection();
if ( !selection.isEmpty() )
{
Object selectedObject = selection.getFirstElement();
if ( selectedObject instanceof Template )
{
manager.setDefaultTemplate( ( Template ) selectedObject );
templatesViewer.refresh();
updateButtonsStates();
}
}
}
/**
* Implements the use for any entry action.
*/
private void useForAnyEntryAction()
{
useForAnyEntryButton.setSelection( true );
useForOnlyEntriesWithTemplateButton.setSelection( false );
}
/**
* Implements the use for only entries with template action.
*/
private void useForOnlyEntriesWithTemplateAction()
{
useForAnyEntryButton.setSelection( false );
useForOnlyEntriesWithTemplateButton.setSelection( true );
}
/**
* Initializes the User Interface.
*/
private void initUI()
{
// Setting the presentation of the templates viewer.
int templatesPresentation = store.getInt( EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION );
if ( templatesPresentation == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_TEMPLATE )
{
templatePresentationToolItem.setSelection( true );
templatePresentationToolItemSelected();
}
else if ( templatesPresentation == EntryTemplatePluginConstants.PREF_TEMPLATES_PRESENTATION_OBJECT_CLASS )
{
objectClassPresentationToolItem.setSelection( true );
objectClassPresentationToolItemSelected();
}
// Disabling the 'Remove Template' button
removeTemplateButton.setEnabled( false );
// Selecting the 'Use Template Editor' mode
int useTemplateEditorFor = store.getInt( EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR );
if ( useTemplateEditorFor == EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR_ANY_ENTRY )
{
useForAnyEntryButton.setSelection( true );
useForOnlyEntriesWithTemplateButton.setSelection( false );
}
else if ( useTemplateEditorFor == EntryTemplatePluginConstants.PREF_USE_TEMPLATE_EDITOR_FOR_ENTRIES_WITH_TEMPLATE )
{
useForAnyEntryButton.setSelection( false );
useForOnlyEntriesWithTemplateButton.setSelection( true );
}
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
// Nothing to do
}
/**
* Refreshes the templates viewer.
*/
public void refreshViewer()
{
// Refreshing the viewer
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ExportTemplatesWizardPage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ExportTemplatesWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.wizards;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
import org.apache.directory.studio.templateeditor.model.Template;
/**
* This class implements the wizard page for the wizard for exporting
* templates to the disk.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ExportTemplatesWizardPage extends AbstractWizardPage
{
/** The pre-checked objects */
private Object[] preCheckedObjects;
// UI Fields
private CheckboxTableViewer templatesTableViewer;
private Button templatesTableSelectAllButton;
private Button templatesTableDeselectAllButton;
private Label exportDirectoryLabel;
private Text exportDirectoryText;
private Button exportDirectoryButton;
/**
* Creates a new instance of ExportTemplatesWizardPage.
*
* @param preCheckedObjects
* an array containing the pre-checked elements
*/
public ExportTemplatesWizardPage( Object[] preCheckedObjects )
{
super( "ExportTemplatesWizardPage" ); //$NON-NLS-1$
setTitle( Messages.getString( "ExportTemplatesWizardPage.WizardPageTitle" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "ExportTemplatesWizardPage.WizardPageDescription" ) ); //$NON-NLS-1$
setImageDescriptor( EntryTemplatePlugin.getDefault().getImageDescriptor(
EntryTemplatePluginConstants.IMG_EXPORT_TEMPLATES_WIZARD ) );
this.preCheckedObjects = preCheckedObjects;
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// Templates Group
Group templatesGroup = new Group( composite, SWT.NONE );
templatesGroup.setText( Messages.getString( "ExportTemplatesWizardPage.Templates" ) ); //$NON-NLS-1$
templatesGroup.setLayout( new GridLayout( 2, false ) );
templatesGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Templates TableViewer
Label templatesLabel = new Label( templatesGroup, SWT.NONE );
templatesLabel.setText( Messages.getString( "ExportTemplatesWizardPage.SelectTheTemplatesToExport" ) ); //$NON-NLS-1$
templatesLabel.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
templatesTableViewer = new CheckboxTableViewer( new Table( templatesGroup, SWT.BORDER | SWT.CHECK
| SWT.FULL_SELECTION ) );
GridData templatesTableViewerGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 1, 2 );
templatesTableViewerGridData.heightHint = 125;
templatesTableViewer.getTable().setLayoutData( templatesTableViewerGridData );
templatesTableViewer.setContentProvider( new ArrayContentProvider() );
templatesTableViewer.setLabelProvider( new LabelProvider()
{
public String getText( Object element )
{
return ( ( Template ) element ).getTitle();
}
public Image getImage( Object element )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_TEMPLATE );
}
} );
templatesTableViewer.addCheckStateListener( new ICheckStateListener()
{
/**
* Notifies of a change to the checked state of an element.
*
* @param event
* event object describing the change
*/
public void checkStateChanged( CheckStateChangedEvent event )
{
dialogChanged();
}
} );
templatesTableSelectAllButton = new Button( templatesGroup, SWT.PUSH );
templatesTableSelectAllButton.setText( Messages.getString( "ExportTemplatesWizardPage.SelectAll" ) ); //$NON-NLS-1$
templatesTableSelectAllButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
templatesTableSelectAllButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
templatesTableViewer.setAllChecked( true );
dialogChanged();
}
} );
templatesTableDeselectAllButton = new Button( templatesGroup, SWT.PUSH );
templatesTableDeselectAllButton.setText( Messages.getString( "ExportTemplatesWizardPage.DeselectAll" ) ); //$NON-NLS-1$
templatesTableDeselectAllButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
templatesTableDeselectAllButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
templatesTableViewer.setAllChecked( false );
dialogChanged();
}
} );
// Export Destination Group
Group exportDestinationGroup = new Group( composite, SWT.NULL );
exportDestinationGroup.setText( Messages.getString( "ExportTemplatesWizardPage.ExportDestination" ) ); //$NON-NLS-1$
exportDestinationGroup.setLayout( new GridLayout( 3, false ) );
exportDestinationGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
exportDirectoryLabel = new Label( exportDestinationGroup, SWT.NONE );
exportDirectoryLabel.setText( Messages.getString( "ExportTemplatesWizardPage.Directory" ) ); //$NON-NLS-1$
exportDirectoryText = new Text( exportDestinationGroup, SWT.BORDER );
exportDirectoryText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
exportDirectoryText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
dialogChanged();
}
} );
exportDirectoryButton = new Button( exportDestinationGroup, SWT.PUSH );
exportDirectoryButton.setText( Messages.getString( "ExportTemplatesWizardPage.Browse" ) ); //$NON-NLS-1$
exportDirectoryButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
chooseExportDirectory();
dialogChanged();
}
} );
initFields();
setControl( composite );
}
/**
* Initializes the UI Fields.
*/
private void initFields()
{
// Filling the templates table
List<Template> templates = new ArrayList<Template>();
templates.addAll( Arrays.asList( EntryTemplatePlugin.getDefault().getTemplatesManager().getTemplates() ) );
Collections.sort( templates, new Comparator<Template>()
{
public int compare( Template o1, Template o2 )
{
return o1.getTitle().compareToIgnoreCase( o2.getTitle() );
}
} );
templatesTableViewer.setInput( templates );
templatesTableViewer.setCheckedElements( preCheckedObjects );
displayErrorMessage( null );
setPageComplete( false );
}
/**
* This method is called when the exportMultipleFiles 'browse' button is selected.
*/
private void chooseExportDirectory()
{
DirectoryDialog dialog = new DirectoryDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell() );
dialog.setText( Messages.getString( "ExportTemplatesWizardPage.ChooseFolder" ) ); //$NON-NLS-1$
dialog.setMessage( Messages.getString( "ExportTemplatesWizardPage.SelectTheFolderInWhichExportTheFiles" ) ); //$NON-NLS-1$
if ( "".equals( exportDirectoryText.getText() ) ) //$NON-NLS-1$
{
dialog.setFilterPath( EntryTemplatePlugin.getDefault().getPreferenceStore().getString(
EntryTemplatePluginConstants.DIALOG_EXPORT_TEMPLATES ) );
}
else
{
dialog.setFilterPath( exportDirectoryText.getText() );
}
String selectedDirectory = dialog.open();
if ( selectedDirectory != null )
{
exportDirectoryText.setText( selectedDirectory );
}
}
/**
* This method is called when the user modifies something in the UI.
*/
private void dialogChanged()
{
// Templates table
if ( templatesTableViewer.getCheckedElements().length == 0 )
{
displayErrorMessage( Messages.getString( "ExportTemplatesWizardPage.OneOrSeveralTemplatesMustBeSelected" ) ); //$NON-NLS-1$
return;
}
// Export Directory
String directory = exportDirectoryText.getText();
if ( ( directory == null ) || ( directory.equals( "" ) ) ) //$NON-NLS-1$
{
displayErrorMessage( Messages.getString( "ExportTemplatesWizardPage.ADirectoryMustBeSelected" ) ); //$NON-NLS-1$
return;
}
else
{
File directoryFile = new File( directory );
if ( !directoryFile.exists() )
{
displayErrorMessage( Messages.getString( "ExportTemplatesWizardPage.TheSelectedDirectoryDoesNotExist" ) ); //$NON-NLS-1$
return;
}
else if ( !directoryFile.isDirectory() )
{
displayErrorMessage( Messages
.getString( "ExportTemplatesWizardPage.TheSelectedDirectoryIsNotADirectory" ) ); //$NON-NLS-1$
return;
}
}
displayErrorMessage( null );
}
/**
* Gets the selected templates.
*
* @return
* the selected templates
*/
public Template[] getSelectedTemplates()
{
Object[] selectedTemplates = templatesTableViewer.getCheckedElements();
List<Template> templates = new ArrayList<Template>();
for ( Object selectedTemplate : selectedTemplates )
{
templates.add( ( Template ) selectedTemplate );
}
return templates.toArray( new Template[0] );
}
/**
* Gets the export directory.
*
* @return
* the export directory
*/
public String getExportDirectory()
{
return exportDirectoryText.getText();
}
/**
* Saves the dialog settings.
*/
public void saveDialogSettings()
{
EntryTemplatePlugin.getDefault().getPreferenceStore().putValue(
EntryTemplatePluginConstants.DIALOG_EXPORT_TEMPLATES, exportDirectoryText.getText() );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ImportTemplatesWizardPage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ImportTemplatesWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.wizards;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePlugin;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants;
/**
* This class implements the wizard page for the wizard for importing new
* templates from the disk.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ImportTemplatesWizardPage extends AbstractWizardPage
{
// UI Fields
private Text fromDirectoryText;
private Button fromDirectoryButton;
private CheckboxTableViewer templateFilesTableViewer;
private Button templateFilesTableSelectAllButton;
private Button templateFilesTableDeselectAllButton;
/**
* Creates a new instance of ImportTemplatesWizardPage.
*/
public ImportTemplatesWizardPage()
{
super( "ImportTemplatesWizardPage" ); //$NON-NLS-1$
setTitle( Messages.getString( "ImportTemplatesWizardPage.WizardPageTitle" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "ImportTemplatesWizardPage.WizardPageDescription" ) ); //$NON-NLS-1$
setImageDescriptor( EntryTemplatePlugin.getDefault().getImageDescriptor(
EntryTemplatePluginConstants.IMG_IMPORT_TEMPLATES_WIZARD ) );
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// From Directory Group
Group fromDirectoryGroup = new Group( composite, SWT.NONE );
fromDirectoryGroup.setText( Messages.getString( "ImportTemplatesWizardPage.FromDirectory" ) ); //$NON-NLS-1$
fromDirectoryGroup.setLayout( new GridLayout( 3, false ) );
fromDirectoryGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// From Directory
Label fromDirectoryLabel = new Label( fromDirectoryGroup, SWT.NONE );
fromDirectoryLabel.setText( Messages.getString( "ImportTemplatesWizardPage.FromDirectoryColon" ) ); //$NON-NLS-1$
fromDirectoryText = new Text( fromDirectoryGroup, SWT.BORDER );
fromDirectoryText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
fromDirectoryText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
dialogChanged();
}
} );
fromDirectoryButton = new Button( fromDirectoryGroup, SWT.PUSH );
fromDirectoryButton.setText( Messages.getString( "ImportTemplatesWizardPage.Browse" ) ); //$NON-NLS-1$
fromDirectoryButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
chooseFromDirectory();
}
} );
// Template files Group
Group templatesFilesGroup = new Group( composite, SWT.NONE );
templatesFilesGroup.setText( Messages.getString( "ImportTemplatesWizardPage.TemplateFiles" ) ); //$NON-NLS-1$
templatesFilesGroup.setLayout( new GridLayout( 2, false ) );
templatesFilesGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Template Files Viewer
templateFilesTableViewer = new CheckboxTableViewer( new Table( templatesFilesGroup, SWT.BORDER | SWT.CHECK
| SWT.FULL_SELECTION ) );
GridData templateFilesTableViewerGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 1, 2 );
templateFilesTableViewerGridData.heightHint = 125;
templateFilesTableViewer.getTable().setLayoutData( templateFilesTableViewerGridData );
templateFilesTableViewer.setContentProvider( new ArrayContentProvider() );
templateFilesTableViewer.setLabelProvider( new LabelProvider()
{
public String getText( Object element )
{
if ( element instanceof File )
{
return ( ( File ) element ).getName();
}
// Default
return super.getText( element );
}
public Image getImage( Object element )
{
if ( element instanceof File )
{
return EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_TEMPLATE );
}
// Default
return super.getImage( element );
}
} );
templateFilesTableViewer.addCheckStateListener( new ICheckStateListener()
{
public void checkStateChanged( CheckStateChangedEvent event )
{
dialogChanged();
}
} );
templateFilesTableSelectAllButton = new Button( templatesFilesGroup, SWT.PUSH );
templateFilesTableSelectAllButton.setText( Messages.getString( "ImportTemplatesWizardPage.SelectAll" ) ); //$NON-NLS-1$
templateFilesTableSelectAllButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
templateFilesTableSelectAllButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
templateFilesTableViewer.setAllChecked( true );
dialogChanged();
}
} );
templateFilesTableDeselectAllButton = new Button( templatesFilesGroup, SWT.PUSH );
templateFilesTableDeselectAllButton.setText( Messages.getString( "ImportTemplatesWizardPage.DeselectAll" ) ); //$NON-NLS-1$
templateFilesTableDeselectAllButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
templateFilesTableDeselectAllButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
templateFilesTableViewer.setAllChecked( false );
dialogChanged();
}
} );
initFields();
setControl( composite );
}
/**
* Initializes the UI Fields.
*/
private void initFields()
{
displayErrorMessage( null );
setPageComplete( false );
}
/**
* This method is called when the 'Browse...' button is selected.
*/
private void chooseFromDirectory()
{
DirectoryDialog dialog = new DirectoryDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell() );
dialog.setText( Messages.getString( "ImportTemplatesWizardPage.ChooseFolder" ) ); //$NON-NLS-1$
dialog.setMessage( Messages.getString( "ImportTemplatesWizardPage.SelectTheFolderFromWhichImportTheFiles" ) ); //$NON-NLS-1$
if ( "".equals( fromDirectoryText.getText() ) ) //$NON-NLS-1$
{
dialog.setFilterPath( EntryTemplatePlugin.getDefault().getPreferenceStore().getString(
EntryTemplatePluginConstants.DIALOG_IMPORT_TEMPLATES ) );
}
else
{
dialog.setFilterPath( fromDirectoryText.getText() );
}
String selectedDirectory = dialog.open();
if ( selectedDirectory != null )
{
fromDirectoryText.setText( selectedDirectory );
fillInTemplatesTable( selectedDirectory );
}
}
/**
* Fills in the templates table with the files found in the given path.
*
* @param path
* the path to search schema files in
*/
private void fillInTemplatesTable( String path )
{
List<File> files = new ArrayList<File>();
File selectedDirectory = new File( path );
if ( selectedDirectory.exists() )
{
// Filter for xml files
FilenameFilter filter = new FilenameFilter()
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".xml" ); //$NON-NLS-1$
}
};
for ( File file : selectedDirectory.listFiles( filter ) )
{
files.add( file );
}
}
templateFilesTableViewer.setInput( files );
}
/**
* This method is called when the user modifies something in the UI.
*/
private void dialogChanged()
{
// Templates table
if ( templateFilesTableViewer.getCheckedElements().length == 0 )
{
displayErrorMessage( Messages
.getString( "ImportTemplatesWizardPage.OneOrSeveralTemplateFilesMustBeSelected" ) ); //$NON-NLS-1$
return;
}
displayErrorMessage( null );
}
/**
* Gets the selected template files.
*
* @return
* the selected templates files
*/
public File[] getSelectedTemplateFiles()
{
Object[] selectedTemplateFiles = templateFilesTableViewer.getCheckedElements();
List<File> templateFiles = new ArrayList<File>();
for ( Object selectedTemplateFile : selectedTemplateFiles )
{
templateFiles.add( ( File ) selectedTemplateFile );
}
return templateFiles.toArray( new File[0] );
}
/**
* Saves the dialog settings.
*/
public void saveDialogSettings()
{
EntryTemplatePlugin.getDefault().getPreferenceStore().putValue(
EntryTemplatePluginConstants.DIALOG_IMPORT_TEMPLATES, fromDirectoryText.getText() );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ExportTemplatesWizard.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ExportTemplatesWizard.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.wizards;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils;
import org.apache.directory.studio.templateeditor.model.Template;
import org.apache.directory.studio.templateeditor.model.parser.TemplateIO;
/**
* This class implements the wizard for exporting templates to the disk.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ExportTemplatesWizard extends Wizard implements IImportWizard
{
/** The wizard page */
private ExportTemplatesWizardPage page;
/** The pre-checked objects */
private Object[] preCheckedObjects;
/**
* {@inheritDoc}
*/
public void addPages()
{
page = new ExportTemplatesWizardPage( preCheckedObjects );
addPage( page );
}
/**
* {@inheritDoc}
*/
public boolean performFinish()
{
// Saving the dialog settings
page.saveDialogSettings();
// Getting the selected templates and export directory
final Template[] selectedTemplates = page.getSelectedTemplates();
final File exportDirectory = new File( page.getExportDirectory() );
// Creating a list where all the template files that could not be
// exported will be stored
final List<Template> failedTemplates = new ArrayList<Template>();
if ( selectedTemplates != null )
{
try
{
getContainer().run( false, false, new IRunnableWithProgress()
{
public void run( IProgressMonitor monitor )
{
for ( Template selectedTemplate : selectedTemplates )
{
try
{
// Creating the output stream
FileOutputStream fos = new FileOutputStream( new File( exportDirectory,
selectedTemplate.getId() + ".xml" ) ); //$NON-NLS-1$
// Exporting the template
TemplateIO.save( selectedTemplate, fos );
fos.close();
}
catch ( FileNotFoundException e )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
e,
Messages
.getString( "ExportTemplatesWizard.TheTemplateCouldNotBeExportedBecauseOfTheFollowingError" ), //$NON-NLS-1$
selectedTemplate.getTitle(), selectedTemplate.getId(), e.getMessage() );
// Adding the template to the failed templates list
failedTemplates.add( selectedTemplate );
}
catch ( IOException e )
{
// Logging the error
EntryTemplatePluginUtils
.logError(
e,
Messages
.getString( "ExportTemplatesWizard.TheTemplateCouldNotBeExportedBecauseOfTheFollowingError" ), //$NON-NLS-1$
selectedTemplate.getTitle(), selectedTemplate.getId(), e.getMessage() );
// Adding the template to the failed templates list
failedTemplates.add( selectedTemplate );
}
}
}
} );
}
catch ( InvocationTargetException e )
{
// Nothing to do (it will never occur)
}
catch ( InterruptedException e )
{
// Nothing to do.
}
}
// Handling the templates that could not be exported
if ( failedTemplates.size() > 0 )
{
String title = null;
String message = null;
// Only one template could not be imported
if ( failedTemplates.size() == 1 )
{
// Getting the failed template
Template failedTemplate = failedTemplates.get( 0 );
// Creating the title and message
title = Messages.getString( "ExportTemplatesWizard.ATemplateCouldNotBeExported" ); //$NON-NLS-1$
message = MessageFormat.format( Messages
.getString( "ExportTemplatesWizard.TheTemplateCouldNotBeExported" ), failedTemplate //$NON-NLS-1$
.getTitle(), failedTemplate.getId() );
}
// Several templates could not be imported
else
{
title = Messages.getString( "ExportTemplatesWizard.SeveralTemplatesCouldNotBeExported" ); //$NON-NLS-1$
message = Messages.getString( "ExportTemplatesWizard.TheFollowingTemplatesCouldNotBeExported" ); //$NON-NLS-1$
for ( Template failedTemplate : failedTemplates )
{
message += EntryTemplatePluginUtils.LINE_SEPARATOR + " - " //$NON-NLS-1$
+ MessageFormat.format( "{0} ({1})", failedTemplate.getTitle(), failedTemplate.getId() ); //$NON-NLS-1$
}
}
// Common ending message
message += EntryTemplatePluginUtils.LINE_SEPARATOR + EntryTemplatePluginUtils.LINE_SEPARATOR
+ Messages.getString( "ExportTemplatesWizard.SeeTheLogsFileForMoreInformation" ); //$NON-NLS-1$
// Creating and opening the dialog
MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
title, null, message, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
}
return true;
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench, IStructuredSelection selection )
{
// Nothing to do.
}
/**
* Sets the objects that should be pre-checked.
*
* @param objects
* the pre-checked objects
*/
public void setPreCheckedObjects( Object[] objects )
{
this.preCheckedObjects = objects;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/Messages.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.wizards;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.templateeditor.view.wizards.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/AbstractWizardPage.java | plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/AbstractWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.templateeditor.view.wizards;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardPage;
/**
* This abstract class extends {@link WizardPage} and holds common methods
* for all our {@link WizardPage}s.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractWizardPage extends WizardPage
{
/**
* Creates a new wizard page with the given name, title, and image.
*
* @param pageName the name of the page
* @param title the title for this wizard page,
* or <code>null</code> if none
* @param titleImage the image descriptor for the title of this wizard page,
* or <code>null</code> if none
*/
protected AbstractWizardPage( String pageName, String title, ImageDescriptor titleImage )
{
super( pageName, title, titleImage );
}
/**
* Creates a new wizard page with the given name, and
* with no title or image.
*
* @param pageName the name of the page
*/
protected AbstractWizardPage( String pageName )
{
super( pageName );
}
/**
* Displays an error message and set the page status as incomplete
* if the message is not null.
*
* @param message
* the message to display
*/
protected void displayErrorMessage( String message )
{
setErrorMessage( message );
setPageComplete( message == null );
}
/**
* Displays a warning message and set the page status as complete.
*
* @param message
* the message to display
*/
protected void displayWarningMessage( String message )
{
setErrorMessage( null );
setMessage( message, DialogPage.WARNING );
setPageComplete( true );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.