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/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionServerType.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionServerType.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.connection.core; /** * This enum contains all detectable directory server types. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum ConnectionServerType { APACHEDS, IBM_DIRECTORY_SERVER, IBM_SECUREWAY_DIRECTORY, IBM_TIVOLI_DIRECTORY_SERVER, IBM_SECURITY_DIRECTORY_SERVER, MICROSOFT_ACTIVE_DIRECTORY_2000, MICROSOFT_ACTIVE_DIRECTORY_2003, NETSCAPE, NOVELL, OPENLDAP, OPENLDAP_2_0, OPENLDAP_2_1, OPENLDAP_2_2, OPENLDAP_2_3, OPENLDAP_2_4, SIEMENS_DIRX, SUN_DIRECTORY_SERVER, RED_HAT_389, FORGEROCK_OPEN_DJ, UNKNOWN; }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionManager.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionManager.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.connection.core; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.directory.api.util.FileUtils; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; import org.apache.directory.studio.connection.core.event.ConnectionUpdateListener; import org.apache.directory.studio.connection.core.io.ConnectionIO; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; /** * This class is used to manage {@link Connection}s. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionManager implements ConnectionUpdateListener { private static final String LOGS_PATH = "logs"; //$NON-NLS-1$ private static final String SEARCH_LOGS_PREFIX = "search-"; //$NON-NLS-1$ private static final String MODIFICATIONS_LOG_PREFIX = "modifications-"; //$NON-NLS-1$ private static final String LDIFLOG_SUFFIX = "-%u-%g.ldiflog"; //$NON-NLS-1$ private static final String CONNECTIONS_XML = "connections.xml"; //$NON-NLS-1$ public static final String ENCODING_UTF8 = "UTF-8"; //$NON-NLS-1$ public static final String TEMP_SUFFIX = "-temp"; //$NON-NLS-1$ /** The list of connections. */ private Set<Connection> connectionList; /** * Creates a new instance of ConnectionManager. */ public ConnectionManager() { this.connectionList = new HashSet<>(); loadInitializers(); loadConnections(); ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionCorePlugin.getDefault().getEventRunner() ); } /** * Loads the Connection Initializers. This happens only for the first time, * which is determined by whether or not the connectionStore file is present. */ private void loadInitializers() { File connectionStore = new File( getConnectionStoreFileName() ); if ( connectionStore.exists() ) { return; // connections are stored from a previous sessions - don't call initializers } IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint( "org.apache.directory.studio.connectionInitializer" ); //$NON-NLS-1$ IConfigurationElement[] configurationElements = extensionPoint.getConfigurationElements(); for ( IConfigurationElement configurationElement : configurationElements ) { if ( "connection".equals( configurationElement.getName() ) ) //$NON-NLS-1$ { addInitialConnection( configurationElement ); } } } /** * Creates the ConnectionParameter from the configElement and creates the connection. * * @param configurationElement The configuration element */ private void addInitialConnection( IConfigurationElement configurationElement ) { try { ConnectionParameter connectionParameter = ( ConnectionParameter ) configurationElement .createExecutableExtension( "class" ); //$NON-NLS-1$ Connection conn = new Connection( connectionParameter ); connectionList.add( conn ); } catch ( CoreException e ) { Status status = new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, Messages.error__execute_connection_initializer + e.getMessage(), e ); ConnectionCorePlugin.getDefault().getLog().log( status ); } } /** * Gets the Modification Log filename for the corresponding connection. * * @param connection * the connection * @return * the Modification Log filename */ public static final String getModificationLogFileName( Connection connection ) { IPath p = ConnectionCorePlugin.getDefault().getStateLocation().append( LOGS_PATH ); File file = p.toFile(); if ( !file.exists() ) { file.mkdir(); } return p.append( MODIFICATIONS_LOG_PREFIX + Utils.getFilenameString( connection.getId() ) + LDIFLOG_SUFFIX ) .toOSString(); } /** * Gets the Search Log filename for the corresponding connection. * * @param connection * the connection * @return * the Search Log filename */ public static final String getSearchLogFileName( Connection connection ) { IPath p = ConnectionCorePlugin.getDefault().getStateLocation().append( LOGS_PATH ); //$NON-NLS-1$ File file = p.toFile(); if ( !file.exists() ) { file.mkdir(); } return p.append( SEARCH_LOGS_PREFIX + Utils.getFilenameString( connection.getId() ) + LDIFLOG_SUFFIX ) .toOSString(); } /** * Gets the filename of the Connection Store. * * @return * the filename of the Connection Store */ public static final String getConnectionStoreFileName() { return ConnectionCorePlugin.getDefault().getStateLocation().append( CONNECTIONS_XML ).toOSString(); } /** * Adds the connection to the end of the connection list. If there is * already a connection with this name, the new connection is renamed. * * @param connection the connection to add */ public void addConnection( Connection connection ) { if ( getConnectionByName( connection.getConnectionParameter().getName() ) != null ) { String newConnectionName = Messages.bind( Messages.copy_n_of_s, "", connection.getConnectionParameter().getName() ); //$NON-NLS-1$ for ( int i = 2; getConnectionByName( newConnectionName ) != null; i++ ) { newConnectionName = Messages.bind( Messages.copy_n_of_s, i + " ", connection.getConnectionParameter().getName() ); //$NON-NLS-1$ } connection.getConnectionParameter().setName( newConnectionName ); } connectionList.add( connection ); ConnectionEventRegistry.fireConnectionAdded( connection, this ); } /** * Gets a connection from its id. * * @param id * the id of the Connection * @return * the corresponding Connection */ public Connection getConnectionById( String id ) { for ( Connection conn : connectionList ) { if ( conn.getConnectionParameter().getId().equals( id ) ) { return conn; } } return null; } /** * Gets a connection from its name. * * @param name * the name of the Connection * @return * the corresponding Connection */ public Connection getConnectionByName( String name ) { for ( Connection conn : connectionList ) { if ( conn.getConnectionParameter().getName().equals( name ) ) { return conn; } } return null; } /** * Removes the given Connection from the Connection list. * * @param connection * the connection to remove */ public void removeConnection( Connection connection ) { connectionList.remove( connection ); ConnectionEventRegistry.fireConnectionRemoved( connection, this ); } /** * Gets an array containing all the Connections. * * @return * an array containing all the Connections */ public Connection[] getConnections() { return connectionList.toArray( new Connection[0] ); } /** * Gets the number of Connections. * * @return * the number of Connections */ public int getConnectionCount() { return connectionList.size(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionAdded(org.apache.directory.studio.connection.core.Connection) */ public void connectionAdded( Connection connection ) { saveConnections(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionRemoved(org.apache.directory.studio.connection.core.Connection) */ public void connectionRemoved( Connection connection ) { saveConnections(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionUpdated(org.apache.directory.studio.connection.core.Connection) */ public void connectionUpdated( Connection connection ) { saveConnections(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionOpened(org.apache.directory.studio.connection.core.Connection) */ public void connectionOpened( Connection connection ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionClosed(org.apache.directory.studio.connection.core.Connection) */ public void connectionClosed( Connection connection ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderModified(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderModified( ConnectionFolder connectionFolder ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderAdded(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderAdded( ConnectionFolder connectionFolder ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderRemoved(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderRemoved( ConnectionFolder connectionFolder ) { } /** * Saves the Connections */ public synchronized void saveConnections() { Set<ConnectionParameter> connectionParameters = new HashSet<>(); for ( Connection connection : connectionList ) { connectionParameters.add( connection.getConnectionParameter() ); } File file = new File( getConnectionStoreFileName() ); File tempFile = new File( getConnectionStoreFileName() + TEMP_SUFFIX ); // To avoid a corrupt file, save object to a temp file first try ( FileOutputStream fileOutputStream = new FileOutputStream( tempFile ) ) { ConnectionIO.save( connectionParameters, fileOutputStream ); } catch ( IOException e ) { Status status = new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, Messages.error__saving_connections + e.getMessage(), e ); ConnectionCorePlugin.getDefault().getLog().log( status ); return; } // move temp file to good file if ( file.exists() ) { file.delete(); } try { String content = FileUtils.readFileToString( tempFile, ENCODING_UTF8 ); FileUtils.writeStringToFile( file, content, ENCODING_UTF8 ); } catch ( IOException e ) { Status status = new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, Messages.error__saving_connections + e.getMessage(), e ); ConnectionCorePlugin.getDefault().getLog().log( status ); return; } } /** * Loads the Connections */ private synchronized void loadConnections() { Set<ConnectionParameter> connectionParameters = null; File file = new File( getConnectionStoreFileName() ); if ( file.exists() ) { try ( FileInputStream fileInputStream = new FileInputStream( file ) ) { connectionParameters = ConnectionIO.load( fileInputStream ); } catch ( Exception e ) { Status status = new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, Messages.error__loading_connections + e.getMessage(), e ); ConnectionCorePlugin.getDefault().getLog().log( status ); } } if ( connectionParameters != null ) { for ( ConnectionParameter connectionParameter : connectionParameters ) { Connection conn = new Connection( connectionParameter ); connectionList.add( conn ); } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionCorePlugin.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionCorePlugin.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.connection.core; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.PropertyResourceBundle; import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeFailCause; import org.apache.directory.studio.connection.core.event.CoreEventRunner; import org.apache.directory.studio.connection.core.event.EventRunner; import org.apache.directory.studio.connection.core.io.api.LdifModificationLogger; import org.apache.directory.studio.connection.core.io.api.LdifSearchLogger; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Plugin; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.osgi.framework.BundleContext; import org.osgi.service.prefs.BackingStoreException; /** * The activator class controls the plug-in life cycle */ public class ConnectionCorePlugin extends Plugin { /** The file name of the permanent trust store */ private static final String PERMANENT_TRUST_STORE = "permanent.jks"; //$NON-NLS-1$ /** The password of the permanent trust store */ private static final String PERMANENT_TRUST_STORE_PASSWORD = "changeit"; //$NON-NLS-1$ /** The shared instance */ private static ConnectionCorePlugin plugin; /** The connection manager */ private ConnectionManager connectionManager; /** The connection folder manager */ private ConnectionFolderManager connectionFolderManager; /** The passwords keystore manager */ private PasswordsKeyStoreManager passwordsKeyStoreManager; /** The permanent trust store */ private StudioKeyStoreManager permanentTrustStoreManager; /** The session trust store */ private StudioKeyStoreManager sessionTrustStoreManager; /** The event runner. */ private EventRunner eventRunner; /** The authentication handler */ private IAuthHandler authHandler; /** The referral handler */ private IReferralHandler referralHandler; /** The certificate handler */ private ICertificateHandler certificateHandler; /** The LDAP loggers. */ private List<ILdapLogger> ldapLoggers; /** The connection listeners. */ private List<IConnectionListener> connectionListeners; /** The plugin properties */ private PropertyResourceBundle properties; /** * The constructor */ public ConnectionCorePlugin() { plugin = this; } /** * @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext) */ public void start( BundleContext context ) throws Exception { super.start( context ); if ( eventRunner == null ) { eventRunner = new CoreEventRunner(); } if ( connectionManager == null ) { connectionManager = new ConnectionManager(); } if ( connectionFolderManager == null ) { connectionFolderManager = new ConnectionFolderManager(); } if ( passwordsKeyStoreManager == null ) { passwordsKeyStoreManager = new PasswordsKeyStoreManager(); } if ( permanentTrustStoreManager == null ) { permanentTrustStoreManager = StudioKeyStoreManager.createFileKeyStoreManager( PERMANENT_TRUST_STORE, PERMANENT_TRUST_STORE_PASSWORD ); } if ( sessionTrustStoreManager == null ) { sessionTrustStoreManager = StudioKeyStoreManager.createMemoryKeyStoreManager(); } // 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 { plugin = null; super.stop( context ); if ( eventRunner != null ) { eventRunner = null; } if ( connectionManager != null ) { Connection[] connections = connectionManager.getConnections(); for ( int i = 0; i < connections.length; i++ ) { connections[i].getConnectionWrapper().disconnect(); } connectionManager = null; } if ( connectionFolderManager != null ) { connectionFolderManager = null; } if ( permanentTrustStoreManager != null ) { permanentTrustStoreManager = null; } if ( sessionTrustStoreManager != null ) { sessionTrustStoreManager = null; } } /** * Returns the shared instance * * @return the shared instance */ public static ConnectionCorePlugin getDefault() { return plugin; } /** * Gets the Connection Manager * * @return * the connection manager */ public ConnectionManager getConnectionManager() { return connectionManager; } /** * Gets the connection folder manager. * * @return the connection folder manager */ public ConnectionFolderManager getConnectionFolderManager() { return connectionFolderManager; } /** * Gets the event runner. * * @return the event runner */ public EventRunner getEventRunner() { return eventRunner; } /** * Gets the password keystore manager. * * @return the password keystore manager */ public PasswordsKeyStoreManager getPasswordsKeyStoreManager() { return passwordsKeyStoreManager; } /** * Gets the permanent trust store manager. * * @return the permanent trust store manager */ public StudioKeyStoreManager getPermanentTrustStoreManager() { return permanentTrustStoreManager; } /** * Gets the session trust store manager. * * @return the session trust store manager */ public StudioKeyStoreManager getSessionTrustStoreManager() { return sessionTrustStoreManager; } /** * Gets the authentication handler * * @return * the authentication handler */ public IAuthHandler getAuthHandler() { if ( authHandler == null ) { // if no authentication handler was set a default authentication handler is used // that only works if the bind password is stored within the connection parameters. authHandler = new IAuthHandler() { public ICredentials getCredentials( ConnectionParameter connectionParameter ) { if ( connectionParameter.getBindPrincipal() == null || "".equals( connectionParameter.getBindPrincipal() ) ) //$NON-NLS-1$ { return new Credentials( "", "", connectionParameter ); //$NON-NLS-1$ //$NON-NLS-2$ } else if ( connectionParameter.getBindPassword() != null && !"".equals( connectionParameter.getBindPassword() ) ) //$NON-NLS-1$ { return new Credentials( connectionParameter.getBindPrincipal(), connectionParameter .getBindPassword(), connectionParameter ); } else { // no credentials provided in connection parameters // returning null cancel the authentication return null; } } }; } return authHandler; } /** * Sets the authentication handler * * @param authHandler * the authentication handler to set */ public void setAuthHandler( IAuthHandler authHandler ) { this.authHandler = authHandler; } /** * Gets the referral handler * * @return * the referral handler */ public IReferralHandler getReferralHandler() { if ( referralHandler == null ) { // if no referral handler was set a default referral handler is used // that just cancels referral chasing referralHandler = new IReferralHandler() { public Connection getReferralConnection( List<String> referralUrls ) { // null cancels referral chasing return null; } }; } return referralHandler; } /** * Sets the referral handler * * @param referralHandler * the referral handler to set */ public void setReferralHandler( IReferralHandler referralHandler ) { this.referralHandler = referralHandler; } /** * Gets the certificate handler * * @return * the certificate handler */ public ICertificateHandler getCertificateHandler() { if ( certificateHandler == null ) { // if no certificate handler was set a default certificate handler is used // that just returns "No" certificateHandler = new ICertificateHandler() { public TrustLevel verifyTrustLevel( String host, X509Certificate[] certChain, Collection<LdapTlsHandshakeFailCause> failCauses ) { return TrustLevel.Not; } }; } return certificateHandler; } /** * Sets the certificate handler * * @param certificateHandler * the certificate handler to set */ public void setCertificateHandler( ICertificateHandler certificateHandler ) { this.certificateHandler = certificateHandler; } /** * Gets the LDIF modification logger. * * @return the LDIF modification logger, null if none found. */ public LdifModificationLogger getLdifModificationLogger() { List<ILdapLogger> ldapLoggers = getLdapLoggers(); for ( ILdapLogger ldapLogger : ldapLoggers ) { if ( ldapLogger instanceof LdifModificationLogger ) { return ( LdifModificationLogger ) ldapLogger; } } return null; } /** * Gets the LDIF search logger. * * @return the LDIF search logger, null if none found. */ public LdifSearchLogger getLdifSearchLogger() { List<ILdapLogger> ldapLoggers = getLdapLoggers(); for ( ILdapLogger ldapLogger : ldapLoggers ) { if ( ldapLogger instanceof LdifSearchLogger ) { return ( LdifSearchLogger ) ldapLogger; } } return null; } /** * Gets the LDAP loggers. * * @return the LDAP loggers */ public List<ILdapLogger> getLdapLoggers() { if ( ldapLoggers == null ) { ldapLoggers = new ArrayList<ILdapLogger>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = registry.getExtensionPoint( "org.apache.directory.studio.ldaplogger" ); //$NON-NLS-1$ IConfigurationElement[] members = extensionPoint.getConfigurationElements(); for ( IConfigurationElement member : members ) { try { ILdapLogger logger = ( ILdapLogger ) member.createExecutableExtension( "class" ); //$NON-NLS-1$ logger.setId( member.getAttribute( "id" ) ); //$NON-NLS-1$ logger.setName( member.getAttribute( "name" ) ); //$NON-NLS-1$ logger.setDescription( member.getAttribute( "description" ) ); //$NON-NLS-1$ ldapLoggers.add( logger ); } catch ( Exception e ) { getLog().log( new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, 1, Messages.error__unable_to_create_ldap_logger + member.getAttribute( "class" ), e ) ); //$NON-NLS-1$ } } } return ldapLoggers; } /** * Gets the connection listeners. * * @return the connection listeners */ public List<IConnectionListener> getConnectionListeners() { if ( connectionListeners == null ) { connectionListeners = new ArrayList<IConnectionListener>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = registry .getExtensionPoint( "org.apache.directory.studio.connectionlistener" ); //$NON-NLS-1$ IConfigurationElement[] members = extensionPoint.getConfigurationElements(); for ( IConfigurationElement member : members ) { try { IConnectionListener listener = ( IConnectionListener ) member.createExecutableExtension( "class" ); //$NON-NLS-1$ connectionListeners.add( listener ); } catch ( Exception e ) { getLog().log( new Status( IStatus.ERROR, ConnectionCoreConstants.PLUGIN_ID, 1, Messages.error__unable_to_create_connection_listener + member.getAttribute( "class" ), //$NON-NLS-1$ e ) ); } } } return connectionListeners; } /** * 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.connection.core", Status.OK, //$NON-NLS-1$ Messages.error__unable_to_get_plugin_properties, e ) ); } } return properties; } /** * Gets the default KRB5 login module. * * Right now the following context factories are supported: * <ul> * <li>com.sun.security.auth.module.Krb5LoginModule</li> * <li>org.apache.harmony.auth.module.Krb5LoginModule</li> * </ul> * * @return the default KRB5 login module */ public String getDefaultKrb5LoginModule() { String defaultKrb5LoginModule = ""; //$NON-NLS-1$ try { String sun = "com.sun.security.auth.module.Krb5LoginModule"; //$NON-NLS-1$ Class.forName( sun ); defaultKrb5LoginModule = sun; } catch ( ClassNotFoundException e ) { } try { String apache = "org.apache.harmony.auth.module.Krb5LoginModule"; //$NON-NLS-1$ Class.forName( apache ); defaultKrb5LoginModule = apache; } catch ( ClassNotFoundException e ) { } return defaultKrb5LoginModule; } public IEclipsePreferences getDefaultScopePreferences() { return DefaultScope.INSTANCE.getNode( ConnectionCoreConstants.PLUGIN_ID ); } public void flushDefaultScopePreferences() { try { getDefaultScopePreferences().flush(); } catch ( BackingStoreException e ) { throw new RuntimeException( e ); } } public IEclipsePreferences getInstanceScopePreferences() { return InstanceScope.INSTANCE.getNode( ConnectionCoreConstants.PLUGIN_ID ); } public void flushInstanceScopePreferences() { try { getInstanceScopePreferences().flush(); } catch ( BackingStoreException e ) { throw new RuntimeException( e ); } } public int getModificationLogsFileCount() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_COUNT, -1, null ); } public int getModificationLogsFileSize() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_SIZE, -1, null ); } public boolean isModificationLogsEnabled() { return Platform.getPreferencesService().getBoolean( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_ENABLE, true, null ); } public String getMModificationLogsMaskedAttributes() { return Platform.getPreferencesService().getString( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_MASKED_ATTRIBUTES, null, null ); } public int getSearchLogsFileCount() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_COUNT, -1, null ); } public int getSearchLogsFileSize() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_SIZE, -1, null ); } public boolean isSearchRequestLogsEnabled() { return Platform.getPreferencesService().getBoolean( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_SEARCHREQUESTLOGS_ENABLE, true, null ); } public boolean isSearchResultEntryLogsEnabled() { return Platform.getPreferencesService().getBoolean( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_SEARCHRESULTENTRYLOGS_ENABLE, false, 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/StudioControl.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/StudioControl.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.connection.core; import java.io.Serializable; import org.apache.directory.studio.ldifparser.model.lines.LdifControlLine; /** * The StudioControl class represents a LDAP control as defined in RFC 4511 * <pre> * Control ::= SEQUENCE { * controlType LDAPOID, * criticality BOOLEAN DEFAULT FALSE, * controlValue OCTET STRING OPTIONAL } * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioControl implements Serializable { /** The serialVersionUID. */ private static final long serialVersionUID = -1289018814649849178L; /** * The subentries control as defined in RFC 3672. */ public static final StudioControl SUBENTRIES_CONTROL = new StudioControl( "Subentries", "1.3.6.1.4.1.4203.1.10.1", //$NON-NLS-1$ //$NON-NLS-2$ false, new byte[] { 0x01, 0x01, ( byte ) 0xFF } ); /** * The Manage DSA IT control as defined in RFC 3296. */ public static final StudioControl MANAGEDSAIT_CONTROL = new StudioControl( "Manage DSA IT", //$NON-NLS-1$ "2.16.840.1.113730.3.4.2", false, null ); //$NON-NLS-1$ /** * The Tree Delete control as defined in draft-armijo-ldap-treedelete-02. */ public static final StudioControl TREEDELETE_CONTROL = new StudioControl( "Tree Delete", "1.2.840.113556.1.4.805", //$NON-NLS-1$ //$NON-NLS-2$ false, null ); /** The symbolic name. */ protected String name; /** The oid. */ protected String oid; /** The critical. */ protected boolean critical; /** The control value. */ protected byte[] controlValue; /** * Creates a new instance of Control. */ public StudioControl() { } /** * Creates a new instance of Control. * * @param name the symbolic name * @param oid the oid * @param critical the criticality * @param controlValue the control value */ public StudioControl( String name, String oid, boolean critical, byte[] controlValue ) { super(); this.name = name == null ? "" : name; //$NON-NLS-1$ this.oid = oid; this.critical = critical; this.controlValue = controlValue; } /** * Gets the control value. * * @return the control value */ public byte[] getControlValue() { return controlValue; } /** * Gets the oid. * * @return the oid */ public String getOid() { return oid; } /** * Checks if is critical. * * @return true, if is critical */ public boolean isCritical() { return critical; } /** * Gets the symbolic name. * * @return the name */ public String getName() { return name; } /** * {@inheritDoc} */ public String toString() { if ( oid == null ) { return ""; //$NON-NLS-1$ } LdifControlLine line = LdifControlLine.create( getOid(), isCritical(), getControlValue() ); String s = line.toRawString(); s = s.substring( line.getRawControlSpec().length(), s.length() ); s = s.substring( line.getRawControlType().length(), s.length() ); s = s.substring( 0, s.length() - line.getRawNewLine().length() ); return s; } /** * Sets the control value. * * @param controlValue the control value */ public void setControlValue( byte[] controlValue ) { this.controlValue = controlValue; } /** * Sets the critical. * * @param critical the critical */ public void setCritical( boolean critical ) { this.critical = critical; } /** * Sets the symbolic name. * * @param name the name */ public void setName( String name ) { this.name = name; } /** * Sets the oid. * * @param oid the oid */ public void setOid( String oid ) { this.oid = oid; } /** * {@inheritDoc} */ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + toString().hashCode(); return result; } /** * {@inheritDoc} */ public boolean equals( Object obj ) { if ( !( obj instanceof StudioControl ) ) { return false; } StudioControl other = ( StudioControl ) obj; return this.toString().equals( other.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/connection.core/src/main/java/org/apache/directory/studio/connection/core/StudioKeyStoreManager.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/StudioKeyStoreManager.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.connection.core; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; /** * A wrapper around {@link KeyStore}. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioKeyStoreManager { public enum Type { File, Memory } /** The type */ private Type type; /** The filename of the underlying key store, only relevant for type File */ private String filename; /** The password of the underlying key store, only relevant for type File */ private String password; /** The in-memory key store, only relevant for type Memory */ private KeyStore memoryKeyStore; /** * Creates a key store manager, backed by a key store on disk. * * @param filename the filename * @param password the password * * @return the key store manager */ public static StudioKeyStoreManager createFileKeyStoreManager( String filename, String password ) { StudioKeyStoreManager manager = new StudioKeyStoreManager( Type.File, filename, password ); manager.filename = filename; manager.password = password; return manager; } /** * Creates a key store manager, backed by an in-memory key store. * * @return the key store manager */ public static StudioKeyStoreManager createMemoryKeyStoreManager() { StudioKeyStoreManager manager = new StudioKeyStoreManager( Type.Memory, null, null ); return manager; } private StudioKeyStoreManager( Type type, String filename, String password ) { this.type = type; this.filename = filename; this.password = password; } /** * Gets the underlying key store. * * @return the key store */ public synchronized KeyStore getKeyStore() throws CertificateException { if ( type == Type.File ) { return getFileKeyStore(); } else { return getMemoryKeyStore(); } } /** * Gets the memory key store. * * @return the memory key store */ private KeyStore getMemoryKeyStore() throws CertificateException { if ( memoryKeyStore == null ) { try { memoryKeyStore = KeyStore.getInstance( KeyStore.getDefaultType() ); memoryKeyStore.load( null, null ); } catch ( Exception e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantReadTrustStore, e ); } } return memoryKeyStore; } /** * Loads the file key store. * * @return the file key store */ private KeyStore getFileKeyStore() throws CertificateException { try { KeyStore fileKeyStore = KeyStore.getInstance( KeyStore.getDefaultType() ); File file = ConnectionCorePlugin.getDefault().getStateLocation().append( filename ).toFile(); if ( file.exists() && file.isFile() && file.canRead() ) { try ( FileInputStream in = new FileInputStream( file ) ) { fileKeyStore.load( in, password.toCharArray() ); } } else { fileKeyStore.load( null, null ); } return fileKeyStore; } catch ( Exception e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantReadTrustStore, e ); } } /** * Adds the certificate to the key store. * * @param certificate the certificate */ public synchronized void addCertificate( X509Certificate certificate ) throws CertificateException { if ( type == Type.File ) { addToFileKeyStore( certificate ); } else { addToMemoryKeyStore( certificate ); } } /** * Adds the certificate to the memory key store. * * @param certificate the certificate */ private void addToMemoryKeyStore( X509Certificate certificate ) throws CertificateException { try { KeyStore memoryKeyStore = getMemoryKeyStore(); addToKeyStore( certificate, memoryKeyStore ); } catch ( Exception e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantAddCertificateToTrustStore, e ); } } /** * Adds the certificate to the file key store. * * @param certificate the certificate */ private void addToFileKeyStore( X509Certificate certificate ) throws CertificateException { try { KeyStore fileKeyStore = getFileKeyStore(); addToKeyStore( certificate, fileKeyStore ); File file = ConnectionCorePlugin.getDefault().getStateLocation().append( filename ).toFile(); try ( FileOutputStream out = new FileOutputStream( file ) ) { fileKeyStore.store( out, password.toCharArray() ); } } catch ( Exception e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantAddCertificateToTrustStore, e ); } } private void addToKeyStore( X509Certificate certificate, KeyStore keyStore ) throws Exception { // The alias is not relevant, it just needs to be an unique identifier. // The SHA-1 hash of the certificate should be unique. byte[] encoded = certificate.getEncoded(); String shaHex = DigestUtils.shaHex( encoded ); keyStore.setCertificateEntry( shaHex, certificate ); } /** * Gets the certificates contained in the key store. * * @return the certificates */ public X509Certificate[] getCertificates() throws CertificateException { try { List<X509Certificate> certificateList = new ArrayList<X509Certificate>(); KeyStore keyStore = getKeyStore(); Enumeration<String> aliases = keyStore.aliases(); while ( aliases.hasMoreElements() ) { String alias = aliases.nextElement(); Certificate certificate = keyStore.getCertificate( alias ); if ( certificate instanceof X509Certificate ) { certificateList.add( ( X509Certificate ) certificate ); } } return certificateList.toArray( new X509Certificate[0] ); } catch ( KeyStoreException e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantReadTrustStore, e ); } } /** * Removes the certificate from the key store. * * @param certificate the certificate */ public synchronized void removeCertificate( X509Certificate certificate ) throws CertificateException { if ( type == Type.File ) { removeFromFileKeyStore( certificate ); } else { removeFromMemoryKeyStore( certificate ); } } /** * Removes the certificate from the memory key store. * * @param certificate the certificate */ private void removeFromMemoryKeyStore( X509Certificate certificate ) throws CertificateException { try { KeyStore memoryKeyStore = getMemoryKeyStore(); removeFromKeyStore( certificate, memoryKeyStore ); } catch ( Exception e ) { throw new CertificateException( Messages.StudioKeyStoreManager_CantRemoveCertificateFromTrustStore, e ); } } /** * Removes the certificate from the file key store. * * @param certificate the certificate */ private void removeFromFileKeyStore( X509Certificate certificate ) throws CertificateException { try { KeyStore fileKeyStore = getFileKeyStore(); removeFromKeyStore( certificate, fileKeyStore ); File file = ConnectionCorePlugin.getDefault().getStateLocation().append( filename ).toFile(); try ( FileOutputStream out = new FileOutputStream( file ) ) { fileKeyStore.store( out, password.toCharArray() ); } } catch ( Exception e ) { e.printStackTrace(); throw new CertificateException( Messages.StudioKeyStoreManager_CantRemoveCertificateFromTrustStore, e ); } } private void removeFromKeyStore( X509Certificate certificate, KeyStore keyStore ) throws Exception { String alias = keyStore.getCertificateAlias( certificate ); if ( alias != null ) { keyStore.deleteEntry( alias ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ICertificateHandler.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ICertificateHandler.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.connection.core; import java.security.cert.X509Certificate; import java.util.Collection; import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeFailCause; /** * Callback interface to ask for the trust level of a certificate from a * higher-level layer (from the UI plugin). * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ICertificateHandler { /** * The trust level of a certificate. */ enum TrustLevel { /** Don't trust a certificate. */ Not, /** Trust a certificate within the current session. */ Session, /** Trust a certificate permanently. */ Permanent; } /** * Verifies the trust level of the given certificate chain. * * @param certChain the certificate chain * @param failCauses the causes of failed certificate validation * * @return the trust level */ TrustLevel verifyTrustLevel( String host, X509Certificate[] certChain, Collection<LdapTlsHandshakeFailCause> failCauses ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionCorePreferencesInitializer.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionCorePreferencesInitializer.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.connection.core; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.core.runtime.preferences.IEclipsePreferences; /** * This class is used to set default preference values. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionCorePreferencesInitializer extends AbstractPreferenceInitializer { /** * {@inheritDoc} */ public void initializeDefaultPreferences() { Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); IEclipsePreferences defaultPreferences = ConnectionCorePlugin.getDefault().getDefaultScopePreferences(); // LDAP connection settings preferences.setDefault( ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES, true ); String defaultKrb5LoginModule = ConnectionCorePlugin.getDefault().getDefaultKrb5LoginModule(); preferences.setDefault( ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE, defaultKrb5LoginModule ); preferences.setDefault( ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES, false ); // Modification Logs defaultPreferences.putBoolean( ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_ENABLE, true ); defaultPreferences.put( ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_MASKED_ATTRIBUTES, "" ); defaultPreferences.putInt( ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_COUNT, 10 ); defaultPreferences.putInt( ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_SIZE, 100 ); // Search Logs defaultPreferences.putBoolean( ConnectionCoreConstants.PREFERENCE_SEARCHREQUESTLOGS_ENABLE, true ); defaultPreferences.putBoolean( ConnectionCoreConstants.PREFERENCE_SEARCHRESULTENTRYLOGS_ENABLE, false ); defaultPreferences.putInt( ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_COUNT, 10 ); defaultPreferences.putInt( ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_SIZE, 100 ); // Connections Passwords Keystore preferences.setDefault( ConnectionCoreConstants.PREFERENCE_CONNECTIONS_PASSWORDS_KEYSTORE, ConnectionCoreConstants.PREFERENCE_CONNECTIONS_PASSWORDS_KEYSTORE_OFF ); ConnectionCorePlugin.getDefault().flushDefaultScopePreferences(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/IReferralHandler.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/IReferralHandler.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.connection.core; import java.util.List; /** * Callback interface to request the target connection * of a referral from a higher-level layer (from the UI plugin). * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IReferralHandler { /** * Gets the connection from this referral handler. * The connection is used to continue a LDAP request. * The referral handler may display a dialog to the user * to select a proper connection. * * @param referralURLs the referral URLs * @return the target connection, null to cancel referral chasing */ Connection getReferralConnection( List<String> referralUrls ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionFolder.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ConnectionFolder.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.connection.core; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; /** * A ConnectionFolder helps to organize connections in folders. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionFolder implements Cloneable { private String id; private String name; private List<String> subFolderIds; private List<String> connectionIds; /** * Creates a new instance of ConnectionFolder. */ public ConnectionFolder() { this.subFolderIds = new ArrayList<String>(); this.connectionIds = new ArrayList<String>(); } /** * Creates a new instance of ConnectionFolder. * * @param name the folder name */ public ConnectionFolder( String name ) { this(); this.id = createId(); this.name = name; } /** * @see java.lang.Object#clone() */ public Object clone() { ConnectionFolder folder = new ConnectionFolder( getName() ); // clone connections ConnectionManager connectionManager = ConnectionCorePlugin.getDefault().getConnectionManager(); for ( String id : connectionIds ) { Connection connection = connectionManager.getConnectionById( id ); if ( connection != null ) { Connection newConnection = ( Connection ) connection.clone(); connectionManager.addConnection( newConnection ); folder.addConnectionId( newConnection.getId() ); } } // clone subfolders ConnectionFolderManager connectionFolderManager = ConnectionCorePlugin.getDefault() .getConnectionFolderManager(); for ( String id : subFolderIds ) { ConnectionFolder subFolder = connectionFolderManager.getConnectionFolderById( id ); if ( subFolder != null ) { ConnectionFolder newFolder = ( ConnectionFolder ) subFolder.clone(); connectionFolderManager.addConnectionFolder( newFolder ); folder.addSubFolderId( newFolder.getId() ); } } return folder; } /** * Adds the connection id to the end of the connection list. * * @param connectionId the connection id */ public void addConnectionId( String connectionId ) { connectionIds.add( connectionId ); ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Removes the connection id from the connection list. * * @param connectionId the connection id */ public void removeConnectionId( String connectionId ) { connectionIds.remove( connectionId ); ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Adds the folder id to the end of the sub-folder list. * * @param folderId the folder id */ public void addSubFolderId( String folderId ) { subFolderIds.add( folderId ); ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Removes the connection folder from the sub-folder list. * * @param folderId the folder id */ public void removeSubFolderId( String folderId ) { subFolderIds.remove( folderId ); ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Gets the id. * * @return the id */ public String getId() { if ( id == null ) { id = createId(); } return id; } /** * Sets the id. * * @param id the new id */ public void setId( String id ) { this.id = id; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName( String name ) { this.name = name; ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Gets the sub-folder ids. * * @return the sub-folder ids */ public List<String> getSubFolderIds() { List<String> ids = new ArrayList<String>(); for ( String id : subFolderIds ) { if ( ConnectionCorePlugin.getDefault().getConnectionFolderManager().getConnectionFolderById( id ) != null ) { ids.add( id ); } } return ids; } /** * Sets the sub-folder ids. * * @param subFolderIds the new sub-folder ids */ public void setSubFolderIds( List<String> subFolderIds ) { this.subFolderIds = subFolderIds; ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Gets the connection ids. * * @return the connection ids */ public List<String> getConnectionIds() { List<String> ids = new ArrayList<String>(); for ( String id : connectionIds ) { if ( ConnectionCorePlugin.getDefault().getConnectionManager().getConnectionById( id ) != null ) { ids.add( id ); } } return ids; } /** * Sets the connection ids. * * @param connectionIds the new connection ids */ public void setConnectionIds( List<String> connectionIds ) { this.connectionIds = connectionIds; ConnectionEventRegistry.fireConnectonFolderModified( this, this ); } /** * Creates a unique id. * * @return the created id */ private String createId() { return UUID.randomUUID().toString(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return getId().hashCode(); } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals( Object obj ) { if ( obj instanceof ConnectionFolder ) { ConnectionFolder other = ( ConnectionFolder ) obj; return getId().equals( other.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/connection.core/src/main/java/org/apache/directory/studio/connection/core/Connection.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/Connection.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.connection.core; 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.url.LdapUrl; 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.Krb5Configuration; import org.apache.directory.studio.connection.core.ConnectionParameter.Krb5CredentialConfiguration; 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.api.DirectoryApiConnectionWrapper; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ui.IActionFilter; /** * The Connection class is the central . * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class Connection implements ConnectionPropertyPageProvider, IAdaptable { /** * Enum for alias dereferencing method. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum AliasDereferencingMethod { /** Never. */ NEVER(0), /** Always. */ ALWAYS(1), /** Finding. */ FINDING(2), /** Search. */ SEARCH(3); private final int ordinal; private AliasDereferencingMethod( int ordinal ) { this.ordinal = ordinal; } /** * Gets the ordinal. * * @return the ordinal */ public int getOrdinal() { return ordinal; } /** * Gets the AliasDereferencingMethod by ordinal. * * @param ordinal the ordinal * * @return the AliasDereferencingMethod */ public static AliasDereferencingMethod getByOrdinal( int ordinal ) { switch ( ordinal ) { case 0: return NEVER; case 1: return ALWAYS; case 2: return FINDING; case 3: return SEARCH; default: return null; } } } /** * Enum for referral handling method. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum ReferralHandlingMethod { /** Ignore. */ IGNORE(0), /** Follow automatically. */ FOLLOW(1), /** Manage. */ //MANAGE(2), /** Follow manually. */ FOLLOW_MANUALLY(3); private final int ordinal; private ReferralHandlingMethod( int ordinal ) { this.ordinal = ordinal; } /** * Gets the ordinal. * * @return the ordinal */ public int getOrdinal() { return ordinal; } /** * Gets the ReferralHandlingMethod by ordinal. * * @param ordinal the ordinal * * @return the ReferralHandlingMethod */ public static ReferralHandlingMethod getByOrdinal( int ordinal ) { switch ( ordinal ) { case 0: return IGNORE; case 1: return FOLLOW; case 2: return FOLLOW_MANUALLY; case 3: return FOLLOW_MANUALLY; default: return null; } } } /** The connection parameter */ private ConnectionParameter connectionParameter; /** The connection wrapper */ private ConnectionWrapper connectionWrapper; /** The detected connection properties */ private DetectedConnectionProperties detectedConnectionProperties; /** * Creates a new instance of Connection. * * @param connectionParameter */ public Connection( ConnectionParameter connectionParameter ) { this.connectionParameter = connectionParameter; detectedConnectionProperties = new DetectedConnectionProperties( this ); } /** * @see java.lang.Object#clone() */ public Object clone() { ConnectionParameter cp = new ConnectionParameter( getName(), getHost(), getPort(), getEncryptionMethod(), getAuthMethod(), getBindPrincipal(), getBindPassword(), getSaslRealm(), isReadOnly(), getConnectionParameter().getExtendedProperties() , getTimeoutMillis() ); return new Connection( cp ); } /** * Gets the connection wrapper. * * @return the connection wrapper */ public ConnectionWrapper getConnectionWrapper() { return getDirectoryApiConnectionWrapper(); } /** * Gets the Directory API connection wrapper. * * @return * the Directory API connection wrapper */ private ConnectionWrapper getDirectoryApiConnectionWrapper() { if ( !( connectionWrapper instanceof DirectoryApiConnectionWrapper ) ) { connectionWrapper = new DirectoryApiConnectionWrapper( this ); } return connectionWrapper; } /** * Gets the connection parameter. * * @return the connection parameter */ public ConnectionParameter getConnectionParameter() { return connectionParameter; } /** * Sets the connection parameter. * * @param connectionParameter the connection parameter */ public void setConnectionParameter( ConnectionParameter connectionParameter ) { this.connectionParameter = connectionParameter; ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Gets the detected connection properties. * * @return the detected connection properties */ public DetectedConnectionProperties getDetectedConnectionProperties() { return detectedConnectionProperties; } /** * Sets the detected connection properties. * * @param detectedConnectionProperties the detected connection properties */ public void setDetectedConnectionProperties( DetectedConnectionProperties detectedConnectionProperties ) { this.detectedConnectionProperties = detectedConnectionProperties; } /** * Gets the auth method. * * @return the auth method */ public AuthenticationMethod getAuthMethod() { return connectionParameter.getAuthMethod(); } /** * Gets the bind password. * * @return the bind password */ public String getBindPassword() { return connectionParameter.getBindPassword(); } /** * Gets the bind principal. * * @return the bind principal */ public String getBindPrincipal() { return connectionParameter.getBindPrincipal(); } /** * Gets the encryption method. * * @return the encryption method */ public EncryptionMethod getEncryptionMethod() { return connectionParameter.getEncryptionMethod(); } /** * Gets the id. * * @return the id */ public String getId() { return connectionParameter.getId(); } /** * Gets the host. * * @return the host */ public String getHost() { return connectionParameter.getHost(); } /** * Gets the name. * * @return the name */ public String getName() { return connectionParameter.getName(); } /** * Gets the port. * * @return the port */ public int getPort() { return connectionParameter.getPort(); } /** * Gets the SASL realm. * * @return the SASL realm */ public String getSaslRealm() { return connectionParameter.getSaslRealm(); } /** * Gets the SASL quality of protection. * * @return the SASL quality of protection */ public SaslQoP getSaslQop() { return connectionParameter.getSaslQop(); } /** * Gets the SASL security strength. * * @return the SASL security strength */ public SaslSecurityStrength getSaslSecurityStrength() { return connectionParameter.getSaslSecurityStrength(); } /** * Checks if is SASL mutual authentication. * * @return true, if is SASL mutual authentication */ public boolean isSaslMutualAuthentication() { return connectionParameter.isSaslMutualAuthentication(); } /** * Gets the Kerberos credential configuration. * * @return the Kerberos credential configuration */ public Krb5CredentialConfiguration getKrb5CredentialConfiguration() { return connectionParameter.getKrb5CredentialConfiguration(); } /** * Gets the Kerberos configuration. * * @return the Kerberos configuration */ public Krb5Configuration getKrb5Configuration() { return connectionParameter.getKrb5Configuration(); } /** * Gets the Kerberos configuration file. * * @return the Kerberos configuration file */ public String getKrb5ConfigurationFile() { return connectionParameter.getKrb5ConfigurationFile(); } /** * Gets the Kerberos realm. * * @return the Kerberos realm */ public String getKrb5Realm() { return connectionParameter.getKrb5Realm(); } /** * Gets the Kerberos KDC host. * * @return the Kerberos KDC host */ public String getKrb5KdcHost() { return connectionParameter.getKrb5KdcHost(); } /** * Gets the Kerberos KDC port. * * @return the Kerberos KDCport */ public int getKrb5KdcPort() { return connectionParameter.getKrb5KdcPort(); } /** * Checks if this connection is read only. * * @return true, if this connection is read only */ public boolean isReadOnly() { return connectionParameter.isReadOnly(); } /** * Gets the timeout in milliseconds. * * @return the timeout in milliseconds */ public long getTimeoutMillis() { return connectionParameter.getTimeoutMillis(); } /** * Sets the auth method. * * @param authMethod the auth method */ public void setAuthMethod( AuthenticationMethod authMethod ) { connectionParameter.setAuthMethod( authMethod ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the bind password. * * @param bindPassword the bind password */ public void setBindPassword( String bindPassword ) { connectionParameter.setBindPassword( bindPassword ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the bind principal. * * @param bindPrincipal the bind principal */ public void setBindPrincipal( String bindPrincipal ) { connectionParameter.setBindPrincipal( bindPrincipal ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the encryption method. * * @param encryptionMethod the encryption method */ public void setEncryptionMethod( EncryptionMethod encryptionMethod ) { connectionParameter.setEncryptionMethod( encryptionMethod ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the host. * * @param host the host */ public void setHost( String host ) { connectionParameter.setHost( host ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the name. * * @param name the name */ public void setName( String name ) { connectionParameter.setName( name ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the port. * * @param port the port */ public void setPort( int port ) { connectionParameter.setPort( port ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the SASL realm. * * @param realm the new SASL realm */ public void setSaslRealm( String realm ) { connectionParameter.setSaslRealm( realm ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the read only flag. * * @param isReadOnly the new read only flag */ public void setReadOnly( boolean isReadOnly ) { connectionParameter.setReadOnly( isReadOnly ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * Sets the timeout in milliseconds. * * @param timeoutMillis the timeout in milliseconds */ public void setTimeoutMillis( long timeoutMillis ) { connectionParameter.setTimeoutMillis( timeoutMillis ); ConnectionEventRegistry.fireConnectionUpdated( this, this ); } /** * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ @SuppressWarnings("unchecked") public Object getAdapter( Class adapter ) { if ( adapter == Connection.class ) { return this; } else if ( adapter.isAssignableFrom( IActionFilter.class ) ) { return ConnectionActionFilterAdapter.getInstance(); } return null; } /** * Gets the LDAP URL. * * @return the LDAP URL */ public LdapUrl getUrl() { LdapUrl url = new LdapUrl(); url.setHost( getHost() ); url.setPort( getPort() ); return url; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ILdapLogger.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/ILdapLogger.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.connection.core; import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.naming.directory.SearchControls; 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.message.Control; import org.apache.directory.api.ldap.model.message.Referral; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.io.api.StudioSearchResult; import org.eclipse.core.runtime.Platform; /** * Callback interface to log modifications. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ILdapLogger { /** * Logs a changetype:add. * * @param connection the connection * @param entry the entry * @param controls the controls * @param ex the LDAP exception if an error occurred, null otherwise */ default void logChangetypeAdd( Connection connection, final Entry entry, final Control[] controls, StudioLdapException ex ) { } /** * Logs a changetype:delete. * * @param connection the connection * @param dn the Dn * @param controls the controls * @param ex the LDAP exception if an error occurred, null otherwise * */ default void logChangetypeDelete( Connection connection, final Dn dn, final Control[] controls, StudioLdapException ex ) { } /** * Logs a changetype:modify. * * @param connection the connection * @param dn the Dn * @param modifications the modification items * @param ex the LDAP exception if an error occurred, null otherwise * @param controls the controls */ default void logChangetypeModify( Connection connection, final Dn dn, final Collection<Modification> modifications, final Control[] controls, StudioLdapException ex ) { } /** * Logs a changetype:moddn. * * @param connection the connection * @param oldDn the old Dn * @param newDn the new Dn * @param deleteOldRdn the delete old Rdn * @param controls the controls * @param ex the LDAP exception if an error occurred, null otherwise */ default void logChangetypeModDn( Connection connection, final Dn oldDn, final Dn newDn, final boolean deleteOldRdn, final Control[] controls, StudioLdapException ex ) { } /** * Sets the logger ID. * * @param id the new logger ID */ void setId( String id ); /** * Gets the logger ID. * * @return the logger ID */ String getId(); /** * Sets the logger name. * * @param name the new logger name */ void setName( String name ); /** * Gets the logger name. * * @return the logger name */ String getName(); /** * Sets the logger description. * * @param description the new logger description */ void setDescription( String description ); /** * Gets the logger description. * * @return the logger description */ String getDescription(); /** * Logs a search request. * * @param connection the connection * @param searchBase the search base * @param filter the filter * @param searchControls the search controls * @param aliasesDereferencingMethod the aliases dereferncing method * @param controls the LDAP controls * @param requestNum the request number * @param ex the LDAP exception if an error occurred, null otherwise */ default void logSearchRequest( Connection connection, String searchBase, String filter, SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls, long requestNum, StudioLdapException ex ) { } /** * Logs a search result entry. * * @param connection the connection * @param studioSearchResult the search result entry * @param requestNum the request number * @param ex the LDAP exception if an error occurred, null otherwise */ default void logSearchResultEntry( Connection connection, StudioSearchResult studioSearchResult, long requestNum, StudioLdapException ex ) { } /** * Logs a search result reference. * * @param connection the connection * @param referral the referral * @param referralsInfo the referrals info containing further URLs and DNs * @param requestNum the request number * @param ex the LDAP exception if an error occurred, null otherwise */ default void logSearchResultReference( Connection connection, Referral referral, ReferralsInfo referralsInfo, long requestNum, StudioLdapException ex ) { } /** * Logs a search result done. * * @param connection the connection * @param count the number of received entries * @param requestNum the request number * @param ex the LDAP exception if an error occurred, null otherwise */ default void logSearchResultDone( Connection connection, long count, long requestNum, StudioLdapException ex ) { } /** * Gets the masked attributes. * * @return the masked attributes */ default Set<String> getMaskedAttributes() { Set<String> maskedAttributes = new HashSet<String>(); String maskedAttributeString = Platform.getPreferencesService().getString( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_MASKED_ATTRIBUTES, "", null ); String[] splitted = maskedAttributeString.split( "," ); //$NON-NLS-1$ for ( String s : splitted ) { maskedAttributes.add( Strings.toLowerCaseAscii( s ) ); } return maskedAttributes; } /** * Deletes a file. Retries up to 5 times to work around Windows file delete issues. */ default void deleteFileWithRetry( File file ) { for ( int i = 0; i < 6; i++ ) { if ( file != null && file.exists() ) { if ( file.delete() ) { break; } try { Thread.sleep( 500L ); } catch ( InterruptedException e ) { } } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionRunnableWithProgress.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionRunnableWithProgress.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioRunnableWithProgress; import org.apache.directory.studio.connection.core.Connection; /** * A runnable with a progress monitor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface StudioConnectionRunnableWithProgress extends StudioRunnableWithProgress { /** * Gets the connections that must be opened before running this runnable. * * @return the connections, null if none */ Connection[] getConnections(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/OpenConnectionsRunnable.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/OpenConnectionsRunnable.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.IConnectionListener; import org.apache.directory.studio.connection.core.Messages; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; /** * Runnable to open a connection to a directory server. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class OpenConnectionsRunnable implements StudioConnectionBulkRunnableWithProgress { private Connection[] connections; /** * Creates a new instance of OpenConnectionsJob. * * @param connection the connection */ public OpenConnectionsRunnable( Connection connection ) { this( new Connection[] { connection } ); } /** * Creates a new instance of OpenConnectionsJob. * * @param connections the connections */ public OpenConnectionsRunnable( Connection[] connections ) { this.connections = connections; } /** * {@inheritDoc} */ public String getName() { return connections.length == 1 ? Messages.jobs__open_connections_name_1 : Messages.jobs__open_connections_name_n; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return connections; } /** * {@inheritDoc} */ public String getErrorMessage() { return connections.length == 1 ? Messages.jobs__open_connections_error_1 : Messages.jobs__open_connections_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", connections.length * 6 + 1 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( Connection connection : connections ) { if ( !connection.getConnectionWrapper().isConnected() ) { monitor.setTaskName( Messages.bind( Messages.jobs__open_connections_task, new String[] { connection.getName() } ) ); monitor.worked( 1 ); connection.getConnectionWrapper().connect( monitor ); if ( connection.getConnectionWrapper().isConnected() ) { connection.getConnectionWrapper().bind( monitor ); } } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( Connection connection : connections ) { if ( connection.getConnectionWrapper().isConnected() ) { for ( IConnectionListener listener : ConnectionCorePlugin.getDefault().getConnectionListeners() ) { listener.connectionOpened( connection, monitor ); } } } for ( Connection connection : connections ) { if ( connection.getConnectionWrapper().isConnected() ) { ConnectionEventRegistry.fireConnectionOpened( connection, this ); } } } /** * {@inheritDoc} */ public Connection[] getConnections() { 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CloseConnectionsRunnable.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CloseConnectionsRunnable.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.connection.core.jobs; import java.util.List; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.IConnectionListener; import org.apache.directory.studio.connection.core.Messages; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; /** * Runnable to close a connection to a directory server. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CloseConnectionsRunnable implements StudioConnectionBulkRunnableWithProgress { private Connection[] connections; /** * Creates a new instance of CloseConnectionsJob. * * @param connection the connection */ public CloseConnectionsRunnable( Connection connection ) { this( new Connection[] { connection } ); } /** * Creates a new instance of CloseConnectionsJob. * * @param connections the connections */ public CloseConnectionsRunnable( Connection[] connections ) { this.connections = connections; } /** * Creates a new instance of CloseConnectionsJob. * * @param connections the connections */ public CloseConnectionsRunnable( List<Connection> connections ) { this.connections = connections.toArray( new Connection[connections.size()] ); } /** * {@inheritDoc} */ public String getName() { return connections.length == 1 ? Messages.jobs__close_connections_name_1 : Messages.jobs__close_connections_name_n; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return connections; } /** * {@inheritDoc} */ public String getErrorMessage() { return connections.length == 1 ? Messages.jobs__close_connections_error_1 : Messages.jobs__close_connections_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", connections.length * 6 + 1 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( Connection connection : connections ) { if ( connection.getConnectionWrapper().isConnected() ) { monitor.setTaskName( Messages.bind( Messages.jobs__close_connections_task, new String[] { connection.getName() } ) ); monitor.worked( 1 ); connection.getConnectionWrapper().unbind(); connection.getConnectionWrapper().disconnect(); } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( Connection connection : connections ) { if ( !connection.getConnectionWrapper().isConnected() ) { for ( IConnectionListener listener : ConnectionCorePlugin.getDefault().getConnectionListeners() ) { listener.connectionClosed( connection, monitor ); } } } for ( Connection connection : connections ) { if ( !connection.getConnectionWrapper().isConnected() ) { ConnectionEventRegistry.fireConnectionClosed( connection, this ); } } } /** * {@inheritDoc} */ public Connection[] getConnections() { 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CheckBindRunnable.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CheckBindRunnable.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Messages; /** * Runnable to check binding (authentication) to a directory server * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CheckBindRunnable implements StudioConnectionRunnableWithProgress { private Connection connection; /** * Creates a new instance of CheckBindJob. * * @param connection the connection */ public CheckBindRunnable( Connection connection ) { this.connection = connection; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { connection }; } /** * {@inheritDoc} */ public String getName() { return Messages.jobs__check_bind_name; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( Messages.jobs__check_bind_task, 4 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); connection.getConnectionWrapper().connect( monitor ); connection.getConnectionWrapper().bind( monitor ); connection.getConnectionWrapper().disconnect(); } /** * {@inheritDoc} */ public String getErrorMessage() { return Messages.jobs__check_bind_error; } /** * {@inheritDoc} */ public Connection[] getConnections() { 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionJob.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionJob.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioJob; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.IConnectionListener; import org.apache.directory.studio.connection.core.Messages; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; /** * Job to run {@link StudioRunnableWithProgress} runnables. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioConnectionJob extends StudioJob<StudioConnectionRunnableWithProgress> { /** * Creates a new instance of StudioConnectionJob. * * @param runnables the runnables to run */ public StudioConnectionJob( StudioConnectionRunnableWithProgress... runnables ) { super( runnables ); } /** * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run( IProgressMonitor ipm ) { StudioProgressMonitor monitor = new StudioProgressMonitor( ipm ); // ensure that connections are opened for ( StudioConnectionRunnableWithProgress runnable : runnables ) { Connection[] connections = runnable.getConnections(); if ( connections != null ) { for ( Connection connection : connections ) { if ( connection != null && !connection.getConnectionWrapper().isConnected() ) { monitor.setTaskName( Messages.bind( Messages.jobs__open_connections_task, new String[] { connection.getName() } ) ); monitor.worked( 1 ); connection.getConnectionWrapper().connect( monitor ); if ( connection.getConnectionWrapper().isConnected() ) { connection.getConnectionWrapper().bind( monitor ); } if ( connection.getConnectionWrapper().isConnected() ) { for ( IConnectionListener listener : ConnectionCorePlugin.getDefault() .getConnectionListeners() ) { listener.connectionOpened( connection, monitor ); } ConnectionEventRegistry.fireConnectionOpened( connection, this ); } } } } } // execute job if ( !monitor.errorsReported() ) { try { for ( StudioConnectionRunnableWithProgress runnable : runnables ) { if ( runnable instanceof StudioConnectionBulkRunnableWithProgress ) { StudioConnectionBulkRunnableWithProgress bulkRunnable = ( StudioConnectionBulkRunnableWithProgress ) runnable; suspendEventFiringInCurrentThread(); try { bulkRunnable.run( monitor ); } finally { resumeEventFiringInCurrentThread(); } bulkRunnable.runNotification( monitor ); } else { runnable.run( monitor ); } } } catch ( Exception e ) { monitor.reportError( e ); } } // always set done, even if errors were reported monitor.done(); ipm.done(); // error handling if ( monitor.isCanceled() ) { return Status.CANCEL_STATUS; } else if ( monitor.errorsReported() ) { return monitor.getErrorStatus( runnables[0].getErrorMessage() ); } else { return Status.OK_STATUS; } } /** * Suspends event firing in current thread. */ protected void suspendEventFiringInCurrentThread() { ConnectionEventRegistry.suspendEventFiringInCurrentThread(); } /** * Resumes event firing in current thread. */ protected void resumeEventFiringInCurrentThread() { ConnectionEventRegistry.resumeEventFiringInCurrentThread(); } /** * {@inheritDoc} */ public boolean shouldSchedule() { // We don't schedule a job if the same type of runnable should run // that works on the same entry as the current runnable. for ( StudioConnectionRunnableWithProgress runnable : runnables ) { Object[] myLockedObjects = runnable.getLockedObjects(); String[] myLockedObjectsIdentifiers = getLockIdentifiers( myLockedObjects ); Job[] jobs = getJobManager().find( null ); for ( int i = 0; i < jobs.length; i++ ) { Job job = jobs[i]; if ( job instanceof StudioConnectionJob ) { StudioConnectionJob otherJob = ( StudioConnectionJob ) job; for ( StudioConnectionRunnableWithProgress otherRunnable : otherJob.runnables ) { if ( runnable.getClass() == otherRunnable.getClass() && runnable != otherRunnable ) { Object[] otherLockedObjects = otherRunnable.getLockedObjects(); String[] otherLockedObjectIdentifiers = getLockIdentifiers( otherLockedObjects ); for ( int j = 0; j < otherLockedObjectIdentifiers.length; j++ ) { String other = otherLockedObjectIdentifiers[j]; for ( int k = 0; k < myLockedObjectsIdentifiers.length; k++ ) { String my = myLockedObjectsIdentifiers[k]; if ( other.startsWith( my ) || my.startsWith( other ) ) { return false; } } } } } } } } return super.shouldSchedule(); } /** * {@inheritDoc} */ protected String[] getLockIdentifiers( Object[] objects ) { String[] identifiers = new String[objects.length]; for ( int i = 0; i < identifiers.length; i++ ) { Object o = objects[i]; if ( o instanceof Connection ) { identifiers[i] = getLockIdentifier( ( Connection ) o ); } else { identifiers[i] = getLockIdentifier( objects[i] ); } } return identifiers; } /** * Gets the string identifier for a {@link Connection} object. * * @param connection * the connection * @return * the lock identifier for the connection */ private String getLockIdentifier( Connection connection ) { return connection.getHost() + ':' + connection.getPort(); } /** * Gets the generic lock identifier for an object. * * @param object * the object * @return * the lock identifier for the object */ private String getLockIdentifier( Object object ) { String s = object != null ? object.toString() : "null"; //$NON-NLS-1$ s = '-' + s; return s; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CheckNetworkParameterRunnable.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/CheckNetworkParameterRunnable.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.connection.core.jobs; import javax.net.ssl.SSLSession; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Messages; /** * Runnable to check if a connection to a directory server could be established * using the given connection parmeter. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CheckNetworkParameterRunnable implements StudioConnectionRunnableWithProgress { private Connection connection; private SSLSession sslSession; /** * Creates a new instance of CheckNetworkParameterJob. * * @param connection the connection */ public CheckNetworkParameterRunnable( Connection connection ) { this.connection = connection; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { connection }; } /** * {@inheritDoc} */ public String getName() { return Messages.jobs__check_network_name; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( Messages.jobs__check_network_task, 3 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); connection.getConnectionWrapper().connect( monitor ); this.sslSession = connection.getConnectionWrapper().getSslSession(); connection.getConnectionWrapper().disconnect(); } /** * {@inheritDoc} */ public String getErrorMessage() { return Messages.jobs__check_network_error; } /** * {@inheritDoc} */ public Connection[] getConnections() { return null; } public SSLSession getSslSession() { return sslSession; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionBulkRunnableWithProgress.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionBulkRunnableWithProgress.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; /** * A runnable with a progess monitor. When invoked by the {@link StudioJob} * during the run() method all event notifications are blocked and the runNotification() * method is called afterwards to fire event notifications. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface StudioConnectionBulkRunnableWithProgress extends StudioConnectionRunnableWithProgress { /** * Runs notification, called by {@link StudioJob} after the run() method. * * @param monitor the monitor */ void runNotification( StudioProgressMonitor monitor ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionRunnableWithProgressAdapter.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/jobs/StudioConnectionRunnableWithProgressAdapter.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.connection.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioRunnableWithProgressAdapter; import org.apache.directory.studio.connection.core.Connection; /** * An adapter class for StudioConnectionRunnableWithProgress. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class StudioConnectionRunnableWithProgressAdapter extends StudioRunnableWithProgressAdapter implements StudioConnectionRunnableWithProgress { /** The connections*/ private static final Connection[] EMPTY_CONNECTION_ARRAY = new Connection[0]; /** * @return an empty array */ public Connection[] getConnections() { return EMPTY_CONNECTION_ARRAY; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/CoreEventRunner.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/CoreEventRunner.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.connection.core.event; /** * Default implementation of {@link EventRunner} that executes an {@link EventRunnable} * withing the current thread. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CoreEventRunner implements EventRunner { /** * {@inheritDoc} * * This implementation executes the given {@link EventRunnable} within * the current thread. */ public void execute( EventRunnable runnable ) { runnable.run(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunnable.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunnable.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.connection.core.event; /** * An <code>EventRunnable</code> is used to notify a listener * about an event. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface EventRunnable extends Runnable { }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunner.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunner.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.connection.core.event; /** * An EventRunner is used to execute an {@link EventRunnable}. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface EventRunner { /** * Executes the given {@link EventRunnable}. * * @param runnable the event runnable to run */ void execute( EventRunnable runnable ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionUpdateListener.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionUpdateListener.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.connection.core.event; import java.util.EventListener; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionFolder; /** * A listener for connection updates * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ConnectionUpdateListener extends EventListener { /** * Called when an {@link Connection} was opened. * * @param connection the opened connection */ void connectionOpened( Connection connection ); /** * Called when an {@link Connection} was closed. * * @param connection the closed connection */ void connectionClosed( Connection connection ); /** * Called when an {@link Connection} was added. * * @param connection the added connection */ void connectionAdded( Connection connection ); /** * Called when an {@link Connection} was removed. * * @param connection the removed connection */ void connectionRemoved( Connection connection ); /** * Called when {@link Connection} parameters were updated. * * @param connection the updated connection */ void connectionUpdated( Connection connection ); /** * Called when an {@link ConnectionFolder} was modified. * * @param connectionFolder the modified connection folder */ void connectionFolderModified( ConnectionFolder connectionFolder ); /** * Called when an {@link ConnectionFolder} was added. * * @param connectionFolder the added connection folder */ void connectionFolderAdded( ConnectionFolder connectionFolder ); /** * Called when an {@link ConnectionFolder} was removed. * * @param connectionFolder the removed connection folder */ void connectionFolderRemoved( ConnectionFolder connectionFolder ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunnableFactory.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/EventRunnableFactory.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.connection.core.event; /** * Factory to create {@link EventRunnable} objects. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface EventRunnableFactory<L> { /** * Creates a new {@link EventRunnable} object. * * @param listener the listener receiving the event notification * * @return the {@link EventRunnable} object */ EventRunnable createEventRunnable( L listener ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionUpdateAdapter.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionUpdateAdapter.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.connection.core.event; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionFolder; /** * This class implements a simple {@link ConnectionUpdateListener} which does nothing. * <p> * All methods are "empty". * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionUpdateAdapter implements ConnectionUpdateListener { /** * {@inheritDoc} */ public void connectionOpened( Connection connection ) { } /** * {@inheritDoc} */ public void connectionClosed( Connection connection ) { } /** * {@inheritDoc} */ public void connectionAdded( Connection connection ) { } /** * {@inheritDoc} */ public void connectionRemoved( Connection connection ) { } /** * {@inheritDoc} */ public void connectionUpdated( Connection connection ) { } /** * {@inheritDoc} */ public void connectionFolderModified( ConnectionFolder connectionFolder ) { } /** * {@inheritDoc} */ public void connectionFolderAdded( ConnectionFolder connectionFolder ) { } /** * {@inheritDoc} */ public void connectionFolderRemoved( ConnectionFolder connectionFolder ) { } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionEventRegistry.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/event/ConnectionEventRegistry.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.connection.core.event; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCoreConstants; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionFolder; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * The ConnectionEventRegistry is a central point to register for connection specific * events and to fire events to registered listeners. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionEventRegistry { /** The list of threads with suspended event firing. */ private static List<Long> suspendedEventFiringThreads = new ArrayList<Long>(); /** The lock used to synchronize event firings */ protected static Object lock = new Object(); /** The list with time stamps of recent event firings */ private static List<Long> fireTimeStamps = new ArrayList<Long>(); /** A counter for fired events */ private static long fireCount = 0L; /** * Checks if event firing is suspended in the current thread. * * @return true, if event firing is suspended in the current thread */ protected static boolean isEventFiringSuspendedInCurrentThread() { boolean suspended = suspendedEventFiringThreads.contains( Thread.currentThread().getId() ); // count the number of fired event in the last second // if more then five per second: print a warning if ( !suspended ) { fireCount++; synchronized ( fireTimeStamps ) { long now = System.currentTimeMillis(); // remove all time stamps older than one second for ( Iterator<Long> it = fireTimeStamps.iterator(); it.hasNext(); ) { Long ts = it.next(); if ( ts + 1000 < now ) { it.remove(); } else { break; } } fireTimeStamps.add( now ); if ( fireTimeStamps.size() > 10 ) { String message = "Warning: More then " + fireTimeStamps.size() + " events were fired per second!"; //$NON-NLS-1$ //$NON-NLS-2$ ConnectionCorePlugin.getDefault().getLog().log( new Status( IStatus.WARNING, ConnectionCoreConstants.PLUGIN_ID, message, new Exception( message ) ) ); } } } return suspended; } /** * Gets the number of fired events. * * @return the number of fired events */ public static long getFireCount() { return fireCount; } /** * Resumes event firing in the current thread. */ public static void resumeEventFiringInCurrentThread() { synchronized ( suspendedEventFiringThreads ) { suspendedEventFiringThreads.remove( Thread.currentThread().getId() ); } } /** * Suspends event firing in the current thread. */ public static void suspendEventFiringInCurrentThread() { synchronized ( suspendedEventFiringThreads ) { suspendedEventFiringThreads.add( Thread.currentThread().getId() ); } } private static final EventManager<ConnectionUpdateListener, EventRunner> connectionUpdateEventManager = new EventManager<ConnectionUpdateListener, EventRunner>(); /** * Adds the connection update listener. * * @param listener the listener * @param runner the runner */ public static void addConnectionUpdateListener( ConnectionUpdateListener listener, EventRunner runner ) { connectionUpdateEventManager.addListener( listener, runner ); } /** * Removes the connection update listener. * * @param listener the listener */ public static void removeConnectionUpdateListener( ConnectionUpdateListener listener ) { connectionUpdateEventManager.removeListener( listener ); } /** * Notifies each {@link ConnectionUpdateListener} about the opened connection. * Uses the {@link EventRunner}s. * * @param connection the opened connection * @param source the source */ public static void fireConnectionOpened( final Connection connection, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionOpened( connection ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the closed connection. * Uses the {@link EventRunner}s. * * @param connection the closed connection * @param source the source */ public static void fireConnectionClosed( final Connection connection, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionClosed( connection ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the updated connection. * Uses the {@link EventRunner}s. * * @param connection the updated connection * @param source the source */ public static void fireConnectionUpdated( final Connection connection, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionUpdated( connection ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the added connection. * Uses the {@link EventRunner}s. * * @param connection the added connection * @param source the source */ public static void fireConnectionAdded( final Connection connection, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionAdded( connection ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the removed connection. * Uses the {@link EventRunner}s. * * @param connection the removed connection * @param source the source */ public static void fireConnectionRemoved( final Connection connection, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionRemoved( connection ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the modified connection folder. * Uses the {@link EventRunner}s. * * @param connectionFolder the modified connection folder * @param source the source */ public static void fireConnectonFolderModified( final ConnectionFolder connectionFolder, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionFolderModified( connectionFolder ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the added connection folder. * Uses the {@link EventRunner}s. * * @param connectionFolder the added connection folder * @param source the source */ public static void fireConnectonFolderAdded( final ConnectionFolder connectionFolder, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionFolderAdded( connectionFolder ); } }; } }; connectionUpdateEventManager.fire( factory ); } /** * Notifies each {@link ConnectionUpdateListener} about the removed connection folder. * Uses the {@link EventRunner}s. * * @param connectionFolder the removed connection folder * @param source the source */ public static void fireConnectonFolderRemoved( final ConnectionFolder connectionFolder, final Object source ) { EventRunnableFactory<ConnectionUpdateListener> factory = new EventRunnableFactory<ConnectionUpdateListener>() { public EventRunnable createEventRunnable( final ConnectionUpdateListener listener ) { return new EventRunnable() { public void run() { listener.connectionFolderRemoved( connectionFolder ); } }; } }; connectionUpdateEventManager.fire( factory ); } public static class EventManager<L, R extends EventRunner> { private Map<L, EventRunner> listeners = new HashMap<L, EventRunner>(); /** * Adds the listener. * * @param listener the listener * @param runner the runner */ public void addListener( L listener, R runner ) { assert listener != null; assert runner != null; synchronized ( listeners ) { if ( !listeners.containsKey( listener ) ) { listeners.put( listener, runner ); } } } /** * Removes the listener. * * @param listener the listener */ public void removeListener( L listener ) { synchronized ( listeners ) { if ( listeners.containsKey( listener ) ) { listeners.remove( listener ); } } } /** * Notifies each {@link ConnectionUpdateListener} about the removed connection. * Uses the {@link EventRunner}s. * * @param connection the removed connection * @param source the source */ public void fire( EventRunnableFactory<L> factory ) { if ( isEventFiringSuspendedInCurrentThread() ) { return; } Map<L, EventRunner> clone = new HashMap<L, EventRunner>( listeners ); for ( final L listener : clone.keySet() ) { EventRunner runner = clone.get( listener ); synchronized ( lock ) { EventRunnable runnable = factory.createEventRunnable( listener ); runner.execute( runnable ); } } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/StudioTrustManager.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/StudioTrustManager.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.connection.core.io; import java.security.KeyStore; import java.security.cert.CertPathValidatorException.Reason; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeExceptionClassifier; import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeFailCause; import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeFailCause.LdapApiReason; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ICertificateHandler; import org.apache.directory.studio.connection.core.Messages; import org.apache.http.conn.ssl.DefaultHostnameVerifier; /** * A wrapper for a real {@link TrustManager}. If the certificate chain is not trusted * then ask the user. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioTrustManager implements X509TrustManager { private X509TrustManager jvmTrustManager; private String host; /** * Creates a new instance of StudioTrustManager. * * @param jvmTrustManager the JVM trust manager * * @throws Exception the exception */ public StudioTrustManager( X509TrustManager jvmTrustManager ) throws Exception { this.jvmTrustManager = jvmTrustManager; } /** * Sets the host, used to verify the hostname of the certificate. * * @param host the new host */ public void setHost( String host ) { this.host = host; } /** * {@inheritDoc} */ public void checkClientTrusted( X509Certificate[] chain, String authType ) throws CertificateException { jvmTrustManager.checkClientTrusted( chain, authType ); } /** * {@inheritDoc} */ public void checkServerTrusted( X509Certificate[] chain, String authType ) throws CertificateException { // check permanent trusted certificates, return on success try { X509TrustManager permanentTrustManager = getPermanentTrustManager(); if ( permanentTrustManager != null ) { permanentTrustManager.checkServerTrusted( chain, authType ); return; } } catch ( CertificateException ce ) { } // check temporary trusted certificates, return on success try { X509TrustManager sessionTrustManager = getSessionTrustManager(); if ( sessionTrustManager != null ) { sessionTrustManager.checkServerTrusted( chain, authType ); return; } } catch ( CertificateException ce ) { } // below here no manually trusted certificate (either permanent or temporary) matched Map<Reason, LdapTlsHandshakeFailCause> failCauses = new LinkedHashMap<>(); CertificateException certificateException = null; // perform trust check of JVM trust manager try { jvmTrustManager.checkServerTrusted( chain, authType ); } catch ( CertificateException ce ) { certificateException = ce; LdapTlsHandshakeFailCause failCause = LdapTlsHandshakeExceptionClassifier.classify( ce, chain[0] ); failCauses.put( failCause.getReason(), failCause ); } // perform a certificate validity check try { chain[0].checkValidity(); } catch ( CertificateException ce ) { certificateException = ce; LdapTlsHandshakeFailCause failCause = LdapTlsHandshakeExceptionClassifier.classify( ce, chain[0] ); failCauses.put( failCause.getReason(), failCause ); } // perform host name verification try { DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(); hostnameVerifier.verify( host, chain[0] ); } catch ( SSLException ssle ) { certificateException = new CertificateException( ssle ); LdapTlsHandshakeFailCause failCause = new LdapTlsHandshakeFailCause( ssle, ssle, LdapApiReason.HOST_NAME_VERIFICATION_FAILED, "Hostname verification failed" ); failCauses.put( failCause.getReason(), failCause ); } if ( !failCauses.isEmpty() ) { // either trust check or host name verification // ask for confirmation ICertificateHandler ch = ConnectionCorePlugin.getDefault().getCertificateHandler(); ICertificateHandler.TrustLevel trustLevel = ch.verifyTrustLevel( host, chain, failCauses.values() ); switch ( trustLevel ) { case Permanent: ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().addCertificate( chain[0] ); break; case Session: ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().addCertificate( chain[0] ); break; case Not: throw certificateException; } } } /** * {@inheritDoc} */ public X509Certificate[] getAcceptedIssuers() { return jvmTrustManager.getAcceptedIssuers(); } /** * Gets the permanent trust manager, based on the permanent trust store. * * @return the permanent trust manager, null if the trust store is empty * * @throws CertificateException the certificate exception */ private X509TrustManager getPermanentTrustManager() throws CertificateException { KeyStore permanentTrustStore = ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().getKeyStore(); X509TrustManager permanentTrustManager = getTrustManager( permanentTrustStore ); return permanentTrustManager; } /** * Gets the session trust manager, based on the session trust store. * * @return the session trust manager, null if the trust store is empty * * @throws CertificateException the certificate exception */ private X509TrustManager getSessionTrustManager() throws CertificateException { KeyStore sessionTrustStore = ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().getKeyStore(); X509TrustManager sessionTrustManager = getTrustManager( sessionTrustStore ); return sessionTrustManager; } private X509TrustManager getTrustManager( KeyStore trustStore ) throws CertificateException { try { Enumeration<String> aliases = trustStore.aliases(); if ( aliases.hasMoreElements() ) { TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory .getDefaultAlgorithm() ); factory.init( trustStore ); TrustManager[] permanentTrustManagers = factory.getTrustManagers(); TrustManager permanentTrustManager = permanentTrustManagers[0]; return ( X509TrustManager ) permanentTrustManager; } } catch ( Exception e ) { throw new CertificateException( Messages.StudioTrustManager_CantCreateTrustManager, e ); } 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.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.connection.core.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.directory.api.ldap.model.constants.SaslQoP; import org.apache.directory.api.ldap.model.constants.SaslSecurityStrength; import org.apache.directory.studio.connection.core.ConnectionFolder; 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.Krb5Configuration; import org.apache.directory.studio.connection.core.ConnectionParameter.Krb5CredentialConfiguration; 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; /** * 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 ConnectionIO { // XML tags private static final String CONNECTIONS_TAG = "connections"; //$NON-NLS-1$ private static final String CONNECTION_TAG = "connection"; //$NON-NLS-1$ private static final String ID_TAG = "id"; //$NON-NLS-1$ private static final String NAME_TAG = "name"; //$NON-NLS-1$ private static final String HOST_TAG = "host"; //$NON-NLS-1$ private static final String PORT_TAG = "port"; //$NON-NLS-1$ private static final String ENCRYPTION_METHOD_TAG = "encryptionMethod"; //$NON-NLS-1$ private static final String AUTH_METHOD_TAG = "authMethod"; //$NON-NLS-1$ private static final String BIND_PRINCIPAL_TAG = "bindPrincipal"; //$NON-NLS-1$ private static final String BIND_PASSWORD_TAG = "bindPassword"; //$NON-NLS-1$ private static final String SASL_REALM_TAG = "saslRealm"; //$NON-NLS-1$ private static final String SASL_QOP_TAG = "saslQop"; //$NON-NLS-1$ private static final String SASL_SEC_STRENGTH_TAG = "saslSecStrenght"; //$NON-NLS-1$ private static final String SASL_MUTUAL_AUTH_TAG = "saslMutualAuth"; //$NON-NLS-1$ private static final String KRB5_CREDENTIALS_CONF_TAG = "krb5CredentialsConf"; //$NON-NLS-1$ private static final String KRB5_CONFIG_TAG = "krb5Config"; //$NON-NLS-1$ private static final String KRB5_CONFIG_FILE_TAG = "krb5ConfigFile"; //$NON-NLS-1$ private static final String KRB5_REALM_TAG = "krb5Realm"; //$NON-NLS-1$ private static final String KRB5_KDC_HOST_TAG = "krb5KdcHost"; //$NON-NLS-1$ private static final String KRB5_KDC_PORT_TAG = "krb5KdcPort"; //$NON-NLS-1$ private static final String READ_ONLY_TAG = "readOnly"; //$NON-NLS-1$ private static final String TIMEOUT_TAG = "timeout"; //$NON-NLS-1$ private static final String EXTENDED_PROPERTIES_TAG = "extendedProperties"; //$NON-NLS-1$ private static final String EXTENDED_PROPERTY_TAG = "extendedProperty"; //$NON-NLS-1$ private static final String KEY_TAG = "key"; //$NON-NLS-1$ private static final String VALUE_TAG = "value"; //$NON-NLS-1$ private static final String CONNECTION_FOLDERS_TAG = "connectionFolders"; //$NON-NLS-1$ private static final String CONNECTION_FOLDER_TAG = "connectionFolder"; //$NON-NLS-1$ private static final String SUB_FOLDERS_TAG = "subFolders"; //$NON-NLS-1$ private static final String SUB_FOLDER_TAG = "subFolder"; //$NON-NLS-1$ /** * Loads the connections using the reader * * @param stream the FileInputStream * @return the connections * @throws ConnectionIOException if an error occurs when converting the document */ public static Set<ConnectionParameter> load( InputStream stream ) throws ConnectionIOException { Set<ConnectionParameter> connections = new HashSet<>(); SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read( stream ); } catch ( DocumentException e ) { throw new ConnectionIOException( e.getMessage() ); } Element rootElement = document.getRootElement(); if ( !rootElement.getName().equals( CONNECTIONS_TAG ) ) { throw new ConnectionIOException( "The file does not seem to be a valid Connections file." ); //$NON-NLS-1$ } for ( Iterator<?> i = rootElement.elementIterator( CONNECTION_TAG ); i.hasNext(); ) { Element connectionElement = ( Element ) i.next(); connections.add( readConnection( connectionElement ) ); } return connections; } /** * Reads a connection from the given Element. * * @param element the element * @return the corresponding connection * @throws ConnectionIOException if an error occurs when converting values */ private static ConnectionParameter readConnection( Element element ) throws ConnectionIOException { ConnectionParameter connection = new ConnectionParameter(); // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { connection.setId( idAttribute.getValue() ); } // Name Attribute nameAttribute = element.attribute( NAME_TAG ); if ( nameAttribute != null ) { connection.setName( nameAttribute.getValue() ); } // Host Attribute hostAttribute = element.attribute( HOST_TAG ); if ( hostAttribute != null ) { connection.setHost( hostAttribute.getValue() ); } // Port Attribute portAttribute = element.attribute( PORT_TAG ); if ( portAttribute != null ) { try { connection.setPort( Integer.parseInt( portAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'Port' of connection '" + connection.getName() //$NON-NLS-1$ + "' as int value. Port value :" + portAttribute.getValue() ); //$NON-NLS-1$ } } // Timeout Attribute timeoutAttribute = element.attribute( TIMEOUT_TAG ); if ( timeoutAttribute != null ) { try { connection.setTimeoutMillis( Long.parseLong( timeoutAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'Timeout' of connection '" + connection.getName() //$NON-NLS-1$ + "' as int value. Timeout value :" + timeoutAttribute.getValue() ); //$NON-NLS-1$ } } // Encryption Method Attribute encryptionMethodAttribute = element.attribute( ENCRYPTION_METHOD_TAG ); if ( encryptionMethodAttribute != null ) { try { connection.setEncryptionMethod( EncryptionMethod.valueOf( encryptionMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Encryption Method' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. Encryption Method value :" //$NON-NLS-1$ + encryptionMethodAttribute.getValue() ); } } // Auth Method Attribute authMethodAttribute = element.attribute( AUTH_METHOD_TAG ); if ( authMethodAttribute != null ) { try { connection.setAuthMethod( AuthenticationMethod.valueOf( authMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Authentication Method' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. Authentication Method value :" //$NON-NLS-1$ + authMethodAttribute.getValue() ); } } // Bind Principal Attribute bindPrincipalAttribute = element.attribute( BIND_PRINCIPAL_TAG ); if ( bindPrincipalAttribute != null ) { connection.setBindPrincipal( bindPrincipalAttribute.getValue() ); } // Bind Password Attribute bindPasswordAttribute = element.attribute( BIND_PASSWORD_TAG ); if ( bindPasswordAttribute != null ) { connection.setBindPassword( bindPasswordAttribute.getValue() ); } // SASL Realm Attribute saslRealmAttribute = element.attribute( SASL_REALM_TAG ); if ( saslRealmAttribute != null ) { connection.setSaslRealm( saslRealmAttribute.getValue() ); } // SASL Quality of Protection Attribute saslQopAttribute = element.attribute( SASL_QOP_TAG ); if ( saslQopAttribute != null ) { if ( "AUTH_INT_PRIV".equals( saslQopAttribute.getValue() ) ) //$NON-NLS-1$ { // Used for legacy setting (before we used SaslQop enum from Shared) connection.setSaslQop( SaslQoP.AUTH_CONF ); } else { try { connection.setSaslQop( SaslQoP.valueOf( saslQopAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'SASL Quality of Protection' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. SASL Quality of Protection value :" //$NON-NLS-1$ + saslQopAttribute.getValue() ); } } } // SASL Security Strength Attribute saslSecStrengthAttribute = element.attribute( SASL_SEC_STRENGTH_TAG ); if ( saslSecStrengthAttribute != null ) { try { connection .setSaslSecurityStrength( SaslSecurityStrength.valueOf( saslSecStrengthAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'SASL Security Strength' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. SASL Security Strength value :" //$NON-NLS-1$ + saslSecStrengthAttribute.getValue() ); } } // SASL Mutual Authentication Attribute saslMutualAuthAttribute = element.attribute( SASL_MUTUAL_AUTH_TAG ); if ( saslMutualAuthAttribute != null ) { connection.setSaslMutualAuthentication( Boolean.parseBoolean( saslMutualAuthAttribute.getValue() ) ); } // KRB5 Credentials Conf Attribute krb5CredentialsConf = element.attribute( KRB5_CREDENTIALS_CONF_TAG ); if ( krb5CredentialsConf != null ) { try { connection.setKrb5CredentialConfiguration( Krb5CredentialConfiguration.valueOf( krb5CredentialsConf .getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'KRB5 Credentials Conf' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. KRB5 Credentials Conf value :" //$NON-NLS-1$ + krb5CredentialsConf.getValue() ); } } // KRB5 Configuration Attribute krb5Config = element.attribute( KRB5_CONFIG_TAG ); if ( krb5Config != null ) { try { connection.setKrb5Configuration( Krb5Configuration.valueOf( krb5Config.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'KRB5 Configuration' of connection '" //$NON-NLS-1$ + connection.getName() + "' as int value. KRB5 Configuration value :" //$NON-NLS-1$ + krb5Config.getValue() ); } } // KRB5 Configuration File Attribute krb5ConfigFile = element.attribute( KRB5_CONFIG_FILE_TAG ); if ( krb5ConfigFile != null ) { connection.setKrb5ConfigurationFile( krb5ConfigFile.getValue() ); } // KRB5 REALM Attribute krb5Realm = element.attribute( KRB5_REALM_TAG ); if ( krb5Realm != null ) { connection.setKrb5Realm( krb5Realm.getValue() ); } // KRB5 KDC Host Attribute krb5KdcHost = element.attribute( KRB5_KDC_HOST_TAG ); if ( krb5KdcHost != null ) { connection.setKrb5KdcHost( krb5KdcHost.getValue() ); } // KRB5 KDC Port Attribute krb5KdcPort = element.attribute( KRB5_KDC_PORT_TAG ); if ( krb5KdcPort != null ) { try { connection.setKrb5KdcPort( Integer.valueOf( krb5KdcPort.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'KRB5 KDC Port' of connection '" + connection.getName() //$NON-NLS-1$ + "' as int value. KRB5 KDC Port value :" + krb5KdcPort.getValue() ); //$NON-NLS-1$ } } // Read Only Attribute readOnly = element.attribute( READ_ONLY_TAG ); if ( readOnly != null ) { connection.setReadOnly( Boolean.parseBoolean( readOnly.getValue() ) ); } // Extended Properties Element extendedPropertiesElement = element.element( EXTENDED_PROPERTIES_TAG ); if ( extendedPropertiesElement != null ) { for ( Object elementObject : extendedPropertiesElement.elements( EXTENDED_PROPERTY_TAG ) ) { Element extendedPropertyElement = ( Element ) elementObject; Attribute keyAttribute = extendedPropertyElement.attribute( KEY_TAG ); Attribute valueAttribute = extendedPropertyElement.attribute( VALUE_TAG ); if ( keyAttribute != null && valueAttribute != null ) { connection.setExtendedProperty( keyAttribute.getValue(), valueAttribute.getValue() ); } } } return connection; } /** * Saves the connections using the writer. * * @param connections the connections * @param stream the OutputStream * @throws IOException if an I/O error occurs */ public static void save( Set<ConnectionParameter> connections, OutputStream stream ) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement( CONNECTIONS_TAG ); if ( connections != null ) { for ( ConnectionParameter connection : connections ) { addConnection( root, connection ); } } // Writing the file to disk OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding( "UTF-8" ); //$NON-NLS-1$ XMLWriter writer = new XMLWriter( stream, outformat ); writer.write( document ); writer.flush(); } /** * Adds the given connection to the given parent Element. * * @param parent * the parent Element * @param connection * the connection */ private static void addConnection( Element parent, ConnectionParameter connection ) { Element connectionElement = parent.addElement( CONNECTION_TAG ); // ID connectionElement.addAttribute( ID_TAG, connection.getId() ); // Name connectionElement.addAttribute( NAME_TAG, connection.getName() ); // Host connectionElement.addAttribute( HOST_TAG, connection.getHost() ); // Port connectionElement.addAttribute( PORT_TAG, Integer.toString( connection.getPort() ) ); //$NON-NLS-1$ // Encryption Method connectionElement.addAttribute( ENCRYPTION_METHOD_TAG, connection.getEncryptionMethod().toString() ); // Auth Method connectionElement.addAttribute( AUTH_METHOD_TAG, connection.getAuthMethod().toString() ); // Bind Principal connectionElement.addAttribute( BIND_PRINCIPAL_TAG, connection.getBindPrincipal() ); // Bind Password connectionElement.addAttribute( BIND_PASSWORD_TAG, connection.getBindPassword() ); // SASL Realm connectionElement.addAttribute( SASL_REALM_TAG, connection.getSaslRealm() ); // SASL Quality of Protection connectionElement.addAttribute( SASL_QOP_TAG, connection.getSaslQop().toString() ); // SASL Security Strength connectionElement.addAttribute( SASL_SEC_STRENGTH_TAG, connection.getSaslSecurityStrength().toString() ); // SASL Mutual Authentication connectionElement.addAttribute( SASL_MUTUAL_AUTH_TAG, Boolean.toString( connection.isSaslMutualAuthentication() ) ); //$NON-NLS-1$ // KRB5 Credentials Conf connectionElement.addAttribute( KRB5_CREDENTIALS_CONF_TAG, connection.getKrb5CredentialConfiguration() .toString() ); // KRB5 Configuration connectionElement.addAttribute( KRB5_CONFIG_TAG, connection.getKrb5Configuration().toString() ); // KRB5 Configuration File connectionElement.addAttribute( KRB5_CONFIG_FILE_TAG, connection.getKrb5ConfigurationFile() ); // KRB5 REALM connectionElement.addAttribute( KRB5_REALM_TAG, connection.getKrb5Realm() ); // KRB5 KDC Host connectionElement.addAttribute( KRB5_KDC_HOST_TAG, connection.getKrb5KdcHost() ); // KRB5 KDC Port connectionElement.addAttribute( KRB5_KDC_PORT_TAG, Integer.toString( connection.getKrb5KdcPort() ) ); //$NON-NLS-1$ // Read Only connectionElement.addAttribute( READ_ONLY_TAG, Boolean.toString( connection.isReadOnly() ) ); //$NON-NLS-1$ // Connection timeout connectionElement.addAttribute( TIMEOUT_TAG, Long.toString( connection.getTimeoutMillis() ) ); //$NON-NLS-1$ // Extended Properties Element extendedPropertiesElement = connectionElement.addElement( EXTENDED_PROPERTIES_TAG ); Map<String, String> extendedProperties = connection.getExtendedProperties(); if ( extendedProperties != null ) { for ( Map.Entry<String, String> element : extendedProperties.entrySet() ) { Element extendedPropertyElement = extendedPropertiesElement.addElement( EXTENDED_PROPERTY_TAG ); extendedPropertyElement.addAttribute( KEY_TAG, element.getKey() ); extendedPropertyElement.addAttribute( VALUE_TAG, element.getValue() ); } } } /** * Loads the connection folders using the reader * * @param stream the FileInputStream * @return the connection folders * @throws ConnectionIOException if an error occurs when converting the document */ public static Set<ConnectionFolder> loadConnectionFolders( InputStream stream ) throws ConnectionIOException { Set<ConnectionFolder> connectionFolders = new HashSet<>(); SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read( stream ); } catch ( DocumentException e ) { throw new ConnectionIOException( e.getMessage() ); } Element rootElement = document.getRootElement(); if ( !rootElement.getName().equals( CONNECTION_FOLDERS_TAG ) ) { throw new ConnectionIOException( "The file does not seem to be a valid ConnectionFolders file." ); //$NON-NLS-1$ } for ( Iterator<?> i = rootElement.elementIterator( CONNECTION_FOLDER_TAG ); i.hasNext(); ) { Element connectionFolderElement = ( Element ) i.next(); connectionFolders.add( readConnectionFolder( connectionFolderElement ) ); } return connectionFolders; } /** * Reads a connection folder from the given Element. * * @param element the element * @return the corresponding connection folder */ private static ConnectionFolder readConnectionFolder( Element element ) { ConnectionFolder connectionFolder = new ConnectionFolder(); // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { connectionFolder.setId( idAttribute.getValue() ); } // Name Attribute nameAttribute = element.attribute( NAME_TAG ); if ( nameAttribute != null ) { connectionFolder.setName( nameAttribute.getValue() ); } // Connections Element connectionsElement = element.element( CONNECTIONS_TAG ); if ( connectionsElement != null ) { for ( Iterator<?> i = connectionsElement.elementIterator( CONNECTION_TAG ); i.hasNext(); ) { Element connectionElement = ( Element ) i.next(); Attribute connectionIdAttribute = connectionElement.attribute( ID_TAG ); if ( connectionIdAttribute != null ) { connectionFolder.addConnectionId( connectionIdAttribute.getValue() ); } } } // Sub-folders Element foldersElement = element.element( SUB_FOLDERS_TAG ); if ( foldersElement != null ) { for ( Iterator<?> i = foldersElement.elementIterator( SUB_FOLDER_TAG ); i.hasNext(); ) { Element folderElement = ( Element ) i.next(); Attribute folderIdAttribute = folderElement.attribute( ID_TAG ); if ( folderIdAttribute != null ) { connectionFolder.addSubFolderId( folderIdAttribute.getValue() ); } } } return connectionFolder; } /** * Saves the connection folders using the writer. * * @param connectionFolders the connection folders * @param stream the OutputStream * @throws IOException if an I/O error occurs */ public static void saveConnectionFolders( Set<ConnectionFolder> connectionFolders, OutputStream stream ) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement( CONNECTION_FOLDERS_TAG ); if ( connectionFolders != null ) { for ( ConnectionFolder connectionFolder : connectionFolders ) { addFolderConnection( root, connectionFolder ); } } // Writing the file to disk OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding( "UTF-8" ); //$NON-NLS-1$ XMLWriter writer = new XMLWriter( stream, outformat ); writer.write( document ); writer.flush(); } /** * Adds the given connection folder to the given parent Element. * * @param parent the parent Element * @param connectionFolder the connection folder */ private static void addFolderConnection( Element parent, ConnectionFolder connectionFolder ) { Element connectionFolderElement = parent.addElement( CONNECTION_FOLDER_TAG ); // ID connectionFolderElement.addAttribute( ID_TAG, connectionFolder.getId() ); // Name connectionFolderElement.addAttribute( NAME_TAG, connectionFolder.getName() ); // Connections Element connectionsElement = connectionFolderElement.addElement( CONNECTIONS_TAG ); for ( String connectionId : connectionFolder.getConnectionIds() ) { Element connectionElement = connectionsElement.addElement( CONNECTION_TAG ); connectionElement.addAttribute( ID_TAG, connectionId ); } // Sub-folders Element foldersElement = connectionFolderElement.addElement( SUB_FOLDERS_TAG ); for ( String folderId : connectionFolder.getSubFolderIds() ) { Element folderElement = foldersElement.addElement( SUB_FOLDER_TAG ); folderElement.addAttribute( ID_TAG, folderId ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/LdapRuntimeException.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/LdapRuntimeException.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.connection.core.io; import org.apache.directory.api.ldap.model.exception.LdapException; public class LdapRuntimeException extends RuntimeException { private static final long serialVersionUID = 3618077059423567243L; public LdapRuntimeException( LdapException exception ) { super( 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionWrapper.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionWrapper.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.connection.core.io; import java.util.Collection; import javax.naming.directory.SearchControls; import javax.net.ssl.SSLSession; 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.message.Control; import org.apache.directory.api.ldap.model.message.ExtendedRequest; import org.apache.directory.api.ldap.model.message.ExtendedResponse; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; 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.ReferralsInfo; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; /** * A ConnectionWrapper is a wrapper for a real directory connection implementation. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ConnectionWrapper { /** * Connects to the directory server. * * @param monitor the progres monitor */ void connect( StudioProgressMonitor monitor ); /** * Disconnects from the directory server. */ void disconnect(); /** * Binds to the directory server. * * @param monitor the progress monitor */ void bind( StudioProgressMonitor monitor ); /** * Unbinds from the directory server. */ void unbind(); /** * Checks if is connected. * * @return true, if is connected */ boolean isConnected(); /** * Checks if the connection is secured. * * @return true, if is secured */ boolean isSecured(); /** * Gets the {@link SSLSession} associated with the connection. * * @return the {@link SSLSession} associated with the connection or null if the connection is not secured */ SSLSession getSslSession(); /** * Sets the binary attributes. * * @param binaryAttributes the binary attributes */ void setBinaryAttributes( Collection<String> binaryAttributes ); /** * Search. * * @param searchBase the search base * @param filter the filter * @param searchControls the controls * @param aliasesDereferencingMethod the aliases dereferencing method * @param referralsHandlingMethod the referrals handling method * @param controls the LDAP controls * @param monitor the progress monitor * @param referralsInfo the referrals info * * @return the naming enumeration or null if an exception occurs. */ StudioSearchResultEnumeration search( final String searchBase, final String filter, final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod, final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ); /** * Modifies attributes of an entry. * * @param dn the Dn * @param modifications the modification items * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ void modifyEntry( final Dn dn, final Collection<Modification> modifications, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ); /** * Renames an entry. * * @param oldDn the old Dn * @param newDn the new Dn * @param deleteOldRdn true to delete the old Rdn * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ void renameEntry( final Dn oldDn, final Dn newDn, final boolean deleteOldRdn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ); /** * Creates an entry. * * @param entry the entry * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ void createEntry( final Entry entry, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ); /** * Deletes an entry. * * @param dn the Dn of the entry to delete * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ void deleteEntry( final Dn dn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ); ExtendedResponse extended( ExtendedRequest request, final StudioProgressMonitor monitor ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/StudioLdapException.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/StudioLdapException.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.connection.core.io; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.directory.api.ldap.model.exception.LdapContextNotEmptyException; import org.apache.directory.api.ldap.model.exception.LdapEntryAlreadyExistsException; import org.apache.directory.api.ldap.model.exception.LdapOperationException; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; public class StudioLdapException extends Exception { private static final long serialVersionUID = -1L; public StudioLdapException( Exception exception ) { super( exception ); } @Override public String getMessage() { String message = ""; Throwable cause = getCause(); if ( cause instanceof LdapOperationException ) { LdapOperationException loe = ( LdapOperationException ) cause; ResultCodeEnum rc = loe.getResultCode(); String template = " [LDAP result code %d - %s]"; //$NON-NLS-1$ message += String.format( Locale.ROOT, template, rc.getResultCode(), rc.getMessage() ); } if ( StringUtils.isNotBlank( cause.getMessage() ) ) { message += " " + cause.getMessage(); //$NON-NLS-1$ } return message; } public static boolean isEntryAlreadyExistsException( Exception exception ) { return ExceptionUtils.indexOfThrowable( exception, LdapEntryAlreadyExistsException.class ) > -1; } public static boolean isContextNotEmptyException( Exception exception ) { return ExceptionUtils.indexOfThrowable( exception, LdapContextNotEmptyException.class ) > -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/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionWrapperUtils.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionWrapperUtils.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.connection.core.io; import java.util.ArrayList; import org.apache.directory.api.ldap.model.message.Referral; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.IConnectionListener; import org.apache.directory.studio.connection.core.IReferralHandler; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; /** * Connection wrapper helper class. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionWrapperUtils { /** * Gets the referral connection from the given URL. * * @param url the URL * @param monitor the progress monitor * @param source the source * * @return the referral connection */ public static Connection getReferralConnection( Referral referral, StudioProgressMonitor monitor, Object source ) { Connection referralConnection = null; IReferralHandler referralHandler = ConnectionCorePlugin.getDefault().getReferralHandler(); if ( referralHandler != null ) { referralConnection = referralHandler .getReferralConnection( new ArrayList<String>( referral.getLdapUrls() ) ); // open connection if not yet open if ( referralConnection != null && !referralConnection.getConnectionWrapper().isConnected() ) { referralConnection.getConnectionWrapper().connect( monitor ); referralConnection.getConnectionWrapper().bind( monitor ); for ( IConnectionListener listener : ConnectionCorePlugin.getDefault().getConnectionListeners() ) { listener.connectionOpened( referralConnection, monitor ); } ConnectionEventRegistry.fireConnectionOpened( referralConnection, source ); } } return referralConnection; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIOException.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIOException.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.connection.core.io; /** * This exception can be raised when loading the Connections file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ConnectionIOException extends Exception { private static final long serialVersionUID = 1L; /** * Creates a new instance of ConnectionIOException. * * @param message * the message */ public ConnectionIOException( 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/StudioSearchResultEnumeration.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/StudioSearchResultEnumeration.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.connection.core.io.api; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import javax.naming.directory.SearchControls; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.SearchCursor; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.Referral; import org.apache.directory.api.ldap.model.message.Response; import org.apache.directory.api.ldap.model.message.SearchResultDone; import org.apache.directory.api.ldap.model.message.SearchResultEntry; import org.apache.directory.api.ldap.model.message.SearchResultEntryImpl; import org.apache.directory.api.ldap.model.message.SearchResultReference; import org.apache.directory.api.ldap.model.url.LdapUrl; 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.ILdapLogger; import org.apache.directory.studio.connection.core.ReferralsInfo; import org.apache.directory.studio.connection.core.io.ConnectionWrapperUtils; /** * A naming enumeration that handles referrals itself. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioSearchResultEnumeration { private Connection connection; private String searchBase; private String filter; private SearchControls searchControls; private AliasDereferencingMethod aliasesDereferencingMethod; private ReferralHandlingMethod referralsHandlingMethod; private Control[] controls; private long requestNum; private StudioProgressMonitor monitor; private ReferralsInfo referralsInfo; private long resultEntryCounter; private SearchCursor cursor; private SearchResultEntry currentSearchResultEntry; private List<String> currentReferralUrlsList; private StudioSearchResultEnumeration referralEnumeration; private SearchResultDone searchResultDone; /** * Creates a new instance of StudioSearchResultEnumeration. * * @param connection the connection * @param cursor the search cursor * @param searchBase the search base * @param filter the filter * @param searchControls the search controls * @param aliasesDereferencingMethod the aliases dereferencing method * @param referralsHandlingMethod the referrals handling method * @param controls the LDAP controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public StudioSearchResultEnumeration( Connection connection, SearchCursor cursor, String searchBase, String filter, SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, ReferralHandlingMethod referralsHandlingMethod, Control[] controls, long requestNum, StudioProgressMonitor monitor, ReferralsInfo referralsInfo ) { // super( connection, searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, // controls, requestNum, monitor, referralsInfo ); this.connection = connection; this.searchBase = searchBase; this.filter = filter; this.searchControls = searchControls; this.aliasesDereferencingMethod = aliasesDereferencingMethod; this.referralsHandlingMethod = referralsHandlingMethod; this.controls = controls; this.requestNum = requestNum; this.monitor = monitor; this.referralsInfo = referralsInfo; this.resultEntryCounter = 0; if ( referralsInfo == null ) { this.referralsInfo = new ReferralsInfo( false ); } this.cursor = cursor; } public void close() throws LdapException { try { cursor.close(); } catch ( Exception e ) { throw new LdapException( e.getMessage() ); } } public boolean hasMore() throws LdapException { try { // Nulling the current search result entry currentSearchResultEntry = null; // Do we have another response in the cursor? while ( cursor.next() ) { Response currentResponse = cursor.get(); // Is it a search result entry? if ( currentResponse instanceof SearchResultEntry ) { currentSearchResultEntry = ( SearchResultEntry ) currentResponse; // return true if the current response is a search result entry return true; } // Is it a search result reference (ie. a referral)? else if ( currentResponse instanceof SearchResultReference ) { // Are we ignoring referrals? if ( referralsHandlingMethod != ReferralHandlingMethod.IGNORE ) { // Storing the referral for later use referralsInfo.addReferral( ( ( SearchResultReference ) currentResponse ).getReferral() ); } } } // Storing the search result done (if needed) if ( searchResultDone == null ) { searchResultDone = ( ( SearchCursor ) cursor ).getSearchResultDone(); Referral referral = searchResultDone.getLdapResult().getReferral(); if ( referralsHandlingMethod != ReferralHandlingMethod.IGNORE && referral != null ) { // Storing the referral for later use referralsInfo.addReferral( referral ); } } // Are we following referrals manually? if ( referralsHandlingMethod == ReferralHandlingMethod.FOLLOW_MANUALLY ) { // Checking the current referral's URLs list if ( ( currentReferralUrlsList != null ) && ( currentReferralUrlsList.size() > 0 ) ) { // return true if there's at least one referral LDAP URL to handle return true; } // Checking the referrals list if ( referralsInfo.hasMoreReferrals() ) { // Getting the list of the next referral currentReferralUrlsList = new ArrayList<String>( referralsInfo.getNextReferral().getLdapUrls() ); // return true if there's at least one referral LDAP URL to handle return currentReferralUrlsList.size() > 0; } } // Are we following referrals automatically? else if ( referralsHandlingMethod == ReferralHandlingMethod.FOLLOW ) { if ( ( referralEnumeration != null ) && ( referralEnumeration.hasMore() ) ) { // return true if there's at least one more entry in the current cursor naming enumeration return true; } if ( referralsInfo.hasMoreReferrals() ) { Referral referral = referralsInfo.getNextReferral(); List<String> referralUrls = new ArrayList<String>( referral.getLdapUrls() ); LdapUrl url = new LdapUrl( referralUrls.get( 0 ) ); Connection referralConnection = ConnectionWrapperUtils.getReferralConnection( referral, monitor, this ); if ( referralConnection != null ) { String referralSearchBase = url.getDn() != null && !url.getDn().isEmpty() ? url.getDn().getName() : searchBase; String referralFilter = url.getFilter() != null && url.getFilter().length() == 0 ? url.getFilter() : filter; SearchControls referralSearchControls = new SearchControls(); referralSearchControls.setSearchScope( url.getScope().getScope() > -1 ? url.getScope().getScope() : searchControls.getSearchScope() ); referralSearchControls .setReturningAttributes( url.getAttributes() != null && url.getAttributes().size() > 0 ? url.getAttributes().toArray( new String[url.getAttributes().size()] ) : searchControls.getReturningAttributes() ); referralSearchControls.setCountLimit( searchControls.getCountLimit() ); referralSearchControls.setTimeLimit( searchControls.getTimeLimit() ); referralSearchControls.setDerefLinkFlag( searchControls.getDerefLinkFlag() ); referralSearchControls.setReturningObjFlag( searchControls.getReturningObjFlag() ); referralEnumeration = referralConnection.getConnectionWrapper().search( referralSearchBase, referralFilter, referralSearchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, monitor, referralsInfo ); return referralEnumeration.hasMore(); } } } for ( ILdapLogger logger : ConnectionCorePlugin.getDefault().getLdapLoggers() ) { logger.logSearchResultDone( connection, resultEntryCounter, requestNum, null ); } return false; } catch ( CursorException e ) { throw new LdapException( e.getMessage(), e ); } } public StudioSearchResult next() throws LdapException { try { if ( currentSearchResultEntry != null ) { resultEntryCounter++; StudioSearchResult ssr = new StudioSearchResult( currentSearchResultEntry, connection, false, null ); for ( ILdapLogger logger : ConnectionCorePlugin.getDefault().getLdapLoggers() ) { logger.logSearchResultEntry( connection, ssr, requestNum, null ); } return ssr; } // Are we following referrals manually? if ( referralsHandlingMethod == ReferralHandlingMethod.FOLLOW_MANUALLY ) { // Checking the current referral's URLs list if ( ( currentReferralUrlsList != null ) && ( currentReferralUrlsList.size() > 0 ) ) { resultEntryCounter++; // Building an LDAP URL from the the url LdapUrl url = new LdapUrl( currentReferralUrlsList.remove( 0 ) ); // Building the search result SearchResultEntry sre = new SearchResultEntryImpl(); sre.setEntry( new DefaultEntry() ); sre.setObjectName( url.getDn() ); return new StudioSearchResult( sre, null, false, url ); } } // Are we following referrals automatically? else if ( referralsHandlingMethod == ReferralHandlingMethod.FOLLOW ) { resultEntryCounter++; return new StudioSearchResult( referralEnumeration.next().getSearchResultEntry(), connection, true, null ); } return null; } catch ( Exception e ) { throw new LdapException( e.getMessage() ); } } /** * Gets the connection. * * @return the connection */ public Connection getConnection() { return connection; } /** * Gets the response controls. * * @return the response controls, may be null */ public Collection<Control> getResponseControls() { if ( searchResultDone != null ) { Map<String, Control> controlsMap = searchResultDone .getControls(); if ( ( controlsMap != null ) && ( controlsMap.size() > 0 ) ) { return controlsMap.values(); } } return Collections.emptyList(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/StudioSearchResult.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/StudioSearchResult.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.connection.core.io.api; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.message.SearchResultEntry; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.studio.connection.core.Connection; /** * Wrapper around {@link SearchResultEntry} that holds a reference to the * underlying connection. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioSearchResult { private final SearchResultEntry searchResultEntry; /** The connection. */ private Connection connection; /** The is continued search result flag */ private final boolean isContinuedSearchResult; /** The URL with information on how to continue the search. */ private final LdapUrl searchContinuationUrl; /** * Creates a new instance of StudioSearchResult. * * @param searchResultEntry the original search result * @param connection the connection * @param isContinuedSearchResult if the search result is a result from a continued search * @param searchContinuationUrl the URL with information on how to continue the search */ public StudioSearchResult( SearchResultEntry searchResultEntry, Connection connection, boolean isContinuedSearchResult, LdapUrl searchContinuationUrl ) { this.searchResultEntry = searchResultEntry; this.connection = connection; this.isContinuedSearchResult = isContinuedSearchResult; this.searchContinuationUrl = searchContinuationUrl; } SearchResultEntry getSearchResultEntry() { return searchResultEntry; } public Dn getDn() { return getEntry().getDn(); } public Entry getEntry() { return searchResultEntry.getEntry(); } /** * Gets the connection. * * @return the connection */ public Connection getConnection() { return connection; } /** * Sets the connection. * * @param connection the new connection */ public void setConnection( Connection connection ) { this.connection = connection; } /** * Checks if this search result is a result from a continued search. * * @return true, if this search result is a result from a continued search */ public boolean isContinuedSearchResult() { return isContinuedSearchResult; } /** * The URL with information on how to continue the search. * * @return the URL with information on how to continue the search */ public LdapUrl getSearchContinuationUrl() { return searchContinuationUrl; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.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.connection.core.io.api; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.naming.directory.SearchControls; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration; import org.apache.directory.api.ldap.codec.api.DefaultConfigurableBinaryAttributeDetector; import org.apache.directory.api.ldap.model.cursor.SearchCursor; 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.exception.LdapException; import org.apache.directory.api.ldap.model.filter.ExprNode; import org.apache.directory.api.ldap.model.filter.FilterParser; import org.apache.directory.api.ldap.model.message.AddRequest; import org.apache.directory.api.ldap.model.message.AddRequestImpl; import org.apache.directory.api.ldap.model.message.AddResponse; import org.apache.directory.api.ldap.model.message.AliasDerefMode; import org.apache.directory.api.ldap.model.message.BindRequest; import org.apache.directory.api.ldap.model.message.BindRequestImpl; import org.apache.directory.api.ldap.model.message.BindResponse; 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.DeleteResponse; import org.apache.directory.api.ldap.model.message.ExtendedRequest; import org.apache.directory.api.ldap.model.message.ExtendedResponse; import org.apache.directory.api.ldap.model.message.LdapResult; import org.apache.directory.api.ldap.model.message.ModifyDnRequest; import org.apache.directory.api.ldap.model.message.ModifyDnRequestImpl; import org.apache.directory.api.ldap.model.message.ModifyDnResponse; import org.apache.directory.api.ldap.model.message.ModifyRequest; import org.apache.directory.api.ldap.model.message.ModifyRequestImpl; import org.apache.directory.api.ldap.model.message.ModifyResponse; import org.apache.directory.api.ldap.model.message.Referral; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; import org.apache.directory.api.ldap.model.message.ResultResponse; 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.url.LdapUrl; import org.apache.directory.ldap.client.api.LdapConnectionConfig; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.directory.ldap.client.api.SaslCramMd5Request; import org.apache.directory.ldap.client.api.SaslDigestMd5Request; import org.apache.directory.ldap.client.api.SaslGssApiRequest; 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.ConnectionCoreConstants; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionParameter; import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod; import org.apache.directory.studio.connection.core.IAuthHandler; import org.apache.directory.studio.connection.core.ICredentials; import org.apache.directory.studio.connection.core.ILdapLogger; import org.apache.directory.studio.connection.core.Messages; import org.apache.directory.studio.connection.core.ReferralsInfo; import org.apache.directory.studio.connection.core.io.ConnectionWrapper; import org.apache.directory.studio.connection.core.io.ConnectionWrapperUtils; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.io.StudioTrustManager; import org.eclipse.core.runtime.Preferences; import org.eclipse.osgi.util.NLS; /** * A ConnectionWrapper is a wrapper for a real directory connection implementation. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class DirectoryApiConnectionWrapper implements ConnectionWrapper { /** The search request number */ private static int searchRequestNum = 0; /** The Studio connection */ private Connection connection; /** The LDAP connection */ private LdapNetworkConnection ldapConnection; /** The binary attribute detector */ private DefaultConfigurableBinaryAttributeDetector binaryAttributeDetector; /** The current job thread */ private Thread jobThread; /** * Creates a new instance of DirectoryApiConnectionWrapper. * * @param connection the connection */ public DirectoryApiConnectionWrapper( Connection connection ) { this.connection = connection; } /** * {@inheritDoc} */ public void connect( StudioProgressMonitor monitor ) { ldapConnection = null; jobThread = null; try { doConnect( monitor ); } catch ( Exception e ) { disconnect(); monitor.reportError( e ); } } private void doConnect( final StudioProgressMonitor monitor ) throws Exception { ldapConnection = null; LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig(); ldapConnectionConfig.setLdapHost( connection.getHost() ); ldapConnectionConfig.setLdapPort( connection.getPort() ); long timeoutMillis = connection.getTimeoutMillis(); if ( timeoutMillis < 0 ) { timeoutMillis = 30000L; } ldapConnectionConfig.setTimeout( timeoutMillis ); binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector(); ldapConnectionConfig.setBinaryAttributeDetector( binaryAttributeDetector ); AtomicReference<StudioTrustManager> studioTrustmanager = new AtomicReference<>(); if ( ( connection.getEncryptionMethod() == EncryptionMethod.LDAPS ) || ( connection.getEncryptionMethod() == EncryptionMethod.START_TLS ) ) { ldapConnectionConfig.setUseSsl( connection.getEncryptionMethod() == EncryptionMethod.LDAPS ); ldapConnectionConfig.setUseTls( connection.getEncryptionMethod() == EncryptionMethod.START_TLS ); try { // get default trust managers (using JVM "cacerts" key store) TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory .getDefaultAlgorithm() ); factory.init( ( KeyStore ) null ); TrustManager[] defaultTrustManagers = factory.getTrustManagers(); // create wrappers around the trust managers StudioTrustManager[] trustManagers = new StudioTrustManager[defaultTrustManagers.length]; for ( int i = 0; i < defaultTrustManagers.length; i++ ) { trustManagers[i] = new StudioTrustManager( ( X509TrustManager ) defaultTrustManagers[i] ); trustManagers[i].setHost( connection.getHost() ); } studioTrustmanager.set( trustManagers[0] ); ldapConnectionConfig.setTrustManagers( trustManagers ); } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException( e ); } } InnerRunnable runnable = new InnerRunnable() { public void run() { /* * Use local temp variable while the connection is being established and secured. * This process can take a while and the user might be asked to inspect the server * certificate. During that process the connection must not be used. */ LdapNetworkConnection ldapConnectionUnderConstruction = null; try { // Set lower timeout for connecting long oldTimeout = ldapConnectionConfig.getTimeout(); ldapConnectionConfig.setTimeout( Math.min( oldTimeout, 5000L ) ); // Connecting ldapConnectionUnderConstruction = new LdapNetworkConnection( ldapConnectionConfig ); ldapConnectionUnderConstruction.connect(); // DIRSTUDIO-1219: Establish TLS layer if TLS is enabled and SSL is not if ( ldapConnectionConfig.isUseTls() && !ldapConnectionConfig.isUseSsl() ) { ldapConnectionUnderConstruction.startTls(); } // Set original timeout again ldapConnectionConfig.setTimeout( oldTimeout ); ldapConnectionUnderConstruction.setTimeOut( oldTimeout ); // Now set the LDAP connection once the (optional) security layer is in place ldapConnection = ldapConnectionUnderConstruction; if ( !isConnected() ) { throw new Exception( Messages.DirectoryApiConnectionWrapper_UnableToConnect ); } // DIRSTUDIO-1219: Verify secure connection if ldaps:// or StartTLS is configured if ( ldapConnectionConfig.isUseTls() || ldapConnectionConfig.isUseSsl() ) { if ( !isSecured() ) { throw new Exception( Messages.DirectoryApiConnectionWrapper_UnsecuredConnection ); } } } catch ( Exception e ) { exception = toStudioLdapException( e ); try { if ( ldapConnectionUnderConstruction != null ) { ldapConnectionUnderConstruction.close(); } } catch ( Exception exception ) { // Nothing to do } finally { ldapConnection = null; binaryAttributeDetector = null; } } } }; runAndMonitor( runnable, monitor ); if ( runnable.getException() != null ) { throw runnable.getException(); } } /** * {@inheritDoc} */ public void disconnect() { if ( jobThread != null ) { Thread t = jobThread; jobThread = null; t.interrupt(); } if ( ldapConnection != null ) { try { ldapConnection.close(); } catch ( Exception e ) { // ignore } ldapConnection = null; binaryAttributeDetector = null; } } /** * {@inheritDoc} */ public void bind( StudioProgressMonitor monitor ) { try { doBind( monitor ); } catch ( Exception e ) { disconnect(); monitor.reportError( e ); } } private BindResponse bindSimple( String bindPrincipal, String bindPassword ) throws LdapException { BindRequest bindRequest = new BindRequestImpl(); bindRequest.setName( bindPrincipal ); bindRequest.setCredentials( bindPassword ); return ldapConnection.bind( bindRequest ); } private void doBind( final StudioProgressMonitor monitor ) throws Exception { if ( isConnected() ) { InnerRunnable runnable = new InnerRunnable() { public void run() { try { BindResponse bindResponse = null; // No Authentication if ( connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.NONE ) { BindRequest bindRequest = new BindRequestImpl(); bindResponse = ldapConnection.bind( bindRequest ); } else { // Setup credentials IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler(); if ( authHandler == null ) { Exception exception = new Exception( Messages.model__no_auth_handler ); monitor.setCanceled( true ); monitor.reportError( Messages.model__no_auth_handler, exception ); throw exception; } ICredentials credentials = authHandler .getCredentials( connection.getConnectionParameter() ); if ( credentials == null ) { Exception exception = new Exception(); monitor.setCanceled( true ); monitor.reportError( Messages.model__no_credentials, exception ); throw exception; } if ( credentials.getBindPrincipal() == null || credentials.getBindPassword() == null ) { Exception exception = new Exception( Messages.model__no_credentials ); monitor.reportError( Messages.model__no_credentials, exception ); throw exception; } String bindPrincipal = credentials.getBindPrincipal(); String bindPassword = credentials.getBindPassword(); switch ( connection.getConnectionParameter().getAuthMethod() ) { case SIMPLE: // Simple Authentication bindResponse = bindSimple( bindPrincipal, bindPassword ); break; case SASL_CRAM_MD5: // CRAM-MD5 Authentication SaslCramMd5Request cramMd5Request = new SaslCramMd5Request(); cramMd5Request.setUsername( bindPrincipal ); cramMd5Request.setCredentials( bindPassword ); cramMd5Request .setQualityOfProtection( connection.getConnectionParameter().getSaslQop() ); cramMd5Request.setSecurityStrength( connection.getConnectionParameter() .getSaslSecurityStrength() ); cramMd5Request.setMutualAuthentication( connection.getConnectionParameter() .isSaslMutualAuthentication() ); bindResponse = ldapConnection.bind( cramMd5Request ); break; case SASL_DIGEST_MD5: // DIGEST-MD5 Authentication SaslDigestMd5Request digestMd5Request = new SaslDigestMd5Request(); digestMd5Request.setUsername( bindPrincipal ); digestMd5Request.setCredentials( bindPassword ); digestMd5Request.setRealmName( connection.getConnectionParameter().getSaslRealm() ); digestMd5Request.setQualityOfProtection( connection.getConnectionParameter() .getSaslQop() ); digestMd5Request.setSecurityStrength( connection.getConnectionParameter() .getSaslSecurityStrength() ); digestMd5Request.setMutualAuthentication( connection.getConnectionParameter() .isSaslMutualAuthentication() ); bindResponse = ldapConnection.bind( digestMd5Request ); break; case SASL_GSSAPI: // GSSAPI Authentication SaslGssApiRequest gssApiRequest = new SaslGssApiRequest(); Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); boolean useKrb5SystemProperties = preferences .getBoolean( ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES ); String krb5LoginModule = preferences .getString( ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE ); if ( !useKrb5SystemProperties ) { gssApiRequest.setUsername( bindPrincipal ); gssApiRequest.setCredentials( bindPassword ); gssApiRequest.setQualityOfProtection( connection .getConnectionParameter().getSaslQop() ); gssApiRequest.setSecurityStrength( connection .getConnectionParameter() .getSaslSecurityStrength() ); gssApiRequest.setMutualAuthentication( connection .getConnectionParameter() .isSaslMutualAuthentication() ); gssApiRequest .setLoginModuleConfiguration( new InnerConfiguration( krb5LoginModule ) ); switch ( connection.getConnectionParameter().getKrb5Configuration() ) { case FILE: gssApiRequest.setKrb5ConfFilePath( connection.getConnectionParameter() .getKrb5ConfigurationFile() ); break; case MANUAL: gssApiRequest.setRealmName( connection.getConnectionParameter() .getKrb5Realm() ); gssApiRequest.setKdcHost( connection.getConnectionParameter() .getKrb5KdcHost() ); gssApiRequest.setKdcPort( connection.getConnectionParameter() .getKrb5KdcPort() ); break; default: break; } } bindResponse = ldapConnection.bind( gssApiRequest ); break; } } checkResponse( bindResponse ); } catch ( Exception e ) { exception = toStudioLdapException( e ); } } }; runAndMonitor( runnable, monitor ); if ( runnable.getException() != null ) { throw runnable.getException(); } } else { throw new Exception( Messages.DirectoryApiConnectionWrapper_NoConnection ); } } /*** * {@inheritDoc} */ public void unbind() { disconnect(); } /** * {@inheritDoc} */ public boolean isConnected() { return ( ldapConnection != null && ldapConnection.isConnected() ); } /** * {@inheritDoc} */ public boolean isSecured() { return isConnected() && ldapConnection.isSecured(); } @Override public SSLSession getSslSession() { return isConnected() ? ldapConnection.getSslSession() : null; } /** * {@inheritDoc} */ public void setBinaryAttributes( Collection<String> binaryAttributes ) { if ( binaryAttributeDetector != null ) { // Clear the initial list binaryAttributeDetector.setBinaryAttributes(); // Add each binary attribute for ( String binaryAttribute : binaryAttributes ) { binaryAttributeDetector.addBinaryAttribute( binaryAttribute ); } } } /** * {@inheritDoc} */ public StudioSearchResultEnumeration search( final String searchBase, final String filter, final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod, final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ) { final long requestNum = searchRequestNum++; InnerRunnable runnable = new InnerRunnable() { public void run() { try { // Preparing the search request SearchRequest request = new SearchRequestImpl(); request.setBase( new Dn( searchBase ) ); ExprNode node = FilterParser.parse( filter, true ); request.setFilter( node ); request.setScope( convertSearchScope( searchControls ) ); if ( searchControls.getReturningAttributes() != null ) { request.addAttributes( searchControls.getReturningAttributes() ); } if ( controls != null ) { request.addAllControls( controls ); } request.setSizeLimit( searchControls.getCountLimit() ); request.setTimeLimit( searchControls.getTimeLimit() ); request.setDerefAliases( convertAliasDerefMode( aliasesDereferencingMethod ) ); // Performing the search operation SearchCursor cursor = ldapConnection.search( request ); // Returning the result of the search searchResultEnumeration = new StudioSearchResultEnumeration( connection, cursor, searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, requestNum, monitor, referralsInfo ); } catch ( Exception e ) { exception = toStudioLdapException( e ); } for ( ILdapLogger logger : getLdapLoggers() ) { if ( searchResultEnumeration != null ) { logger.logSearchRequest( connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, exception ); } else { logger.logSearchRequest( connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, exception ); logger.logSearchResultDone( connection, 0, requestNum, exception ); } } } }; try { checkConnectionAndRunAndMonitor( runnable, monitor ); } catch ( Exception e ) { monitor.reportError( e ); return null; } if ( runnable.isCanceled() ) { monitor.setCanceled( true ); } if ( runnable.getException() != null ) { monitor.reportError( runnable.getException() ); return null; } else { return runnable.getResult(); } } /** * Converts the search scope. * * @param searchControls * the search controls * @return * the associated search scope */ private SearchScope convertSearchScope( SearchControls searchControls ) { int scope = searchControls.getSearchScope(); if ( scope == SearchControls.OBJECT_SCOPE ) { return SearchScope.OBJECT; } else if ( scope == SearchControls.ONELEVEL_SCOPE ) { return SearchScope.ONELEVEL; } else if ( scope == SearchControls.SUBTREE_SCOPE ) { return SearchScope.SUBTREE; } else { return SearchScope.SUBTREE; } } /** * Converts the Alias Dereferencing method. * * @param aliasesDereferencingMethod * the Alias Dereferencing method. * @return * the converted Alias Dereferencing method. */ private AliasDerefMode convertAliasDerefMode( AliasDereferencingMethod aliasesDereferencingMethod ) { switch ( aliasesDereferencingMethod ) { case ALWAYS: return AliasDerefMode.DEREF_ALWAYS; case FINDING: return AliasDerefMode.DEREF_FINDING_BASE_OBJ; case NEVER: return AliasDerefMode.NEVER_DEREF_ALIASES; case SEARCH: return AliasDerefMode.DEREF_IN_SEARCHING; default: return AliasDerefMode.DEREF_ALWAYS; } } /** * {@inheritDoc} */ public void modifyEntry( final Dn dn, final Collection<Modification> modifications, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ) { if ( connection.isReadOnly() ) { monitor .reportError( new Exception( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) ) ); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // Preparing the modify request ModifyRequest request = new ModifyRequestImpl(); request.setName( dn ); if ( modifications != null ) { for ( Modification modification : modifications ) { request.addModification( modification ); } } if ( controls != null ) { request.addAllControls( controls ); } // Performing the modify operation ModifyResponse modifyResponse = ldapConnection.modify( request ); // Handle referral ReferralHandlingDataConsumer consumer = referralHandlingData -> referralHandlingData.connectionWrapper .modifyEntry( new Dn( referralHandlingData.referralDn ), modifications, controls, monitor, referralHandlingData.newReferralsInfo ); if ( checkAndHandleReferral( modifyResponse, monitor, referralsInfo, consumer ) ) { return; } // Checking the response checkResponse( modifyResponse ); } catch ( Exception e ) { exception = toStudioLdapException( e ); } for ( ILdapLogger logger : getLdapLoggers() ) { logger.logChangetypeModify( connection, dn, modifications, controls, exception ); } } }; try { checkConnectionAndRunAndMonitor( runnable, monitor ); } catch ( Exception e ) { monitor.reportError( e ); } if ( runnable.isCanceled() ) { monitor.setCanceled( true ); } if ( runnable.getException() != null ) { monitor.reportError( runnable.getException() ); } } /** * {@inheritDoc} */ public void renameEntry( final Dn oldDn, final Dn newDn, final boolean deleteOldRdn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo ) { if ( connection.isReadOnly() ) { monitor .reportError( new Exception( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) ) ); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // Preparing the rename request ModifyDnRequest request = new ModifyDnRequestImpl(); request.setName( oldDn ); request.setDeleteOldRdn( deleteOldRdn ); request.setNewRdn( newDn.getRdn() ); request.setNewSuperior( newDn.getParent() ); if ( controls != null ) { request.addAllControls( controls ); } // Performing the rename operation ModifyDnResponse modifyDnResponse = ldapConnection.modifyDn( request ); // Handle referral
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
true
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/LdifSearchLogger.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/LdifSearchLogger.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.connection.core.io.api; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javax.naming.directory.SearchControls; import org.apache.commons.lang3.StringUtils; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.Referral; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.ConnectionCoreConstants; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionManager; import org.apache.directory.studio.connection.core.ILdapLogger; import org.apache.directory.studio.connection.core.ReferralsInfo; import org.apache.directory.studio.connection.core.Utils; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.ldifparser.LdifFormatParameters; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine; import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine; import org.apache.directory.studio.ldifparser.model.lines.LdifLineBase; import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; /** * The LdifSearchLogger is used to log searches into a file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class LdifSearchLogger implements ILdapLogger { /** The ID. */ private String id; /** The name. */ private String name; /** The description. */ private String description; /** The file handlers. */ private Map<String, FileHandler> fileHandlers = new HashMap<String, FileHandler>(); /** The loggers. */ private Map<String, Logger> loggers = new HashMap<String, Logger>(); /** * Creates a new instance of LdifSearchLogger. */ public LdifSearchLogger() { IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode( ConnectionCoreConstants.PLUGIN_ID ); prefs.addPreferenceChangeListener( event -> { if ( ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_COUNT.equals( event.getKey() ) || ConnectionCoreConstants.PREFERENCE_SEARCHLOGS_FILE_SIZE.equals( event.getKey() ) ) { // dispose all loggers/handlers for ( Logger logger : loggers.values() ) { for ( Handler handler : logger.getHandlers() ) { handler.close(); } } // delete files with index greater than new file count Connection[] connections = ConnectionCorePlugin.getDefault().getConnectionManager().getConnections(); for ( Connection connection : connections ) { try { File[] logFiles = getLogFiles( connection ); for ( int i = getFileCount(); i < logFiles.length; i++ ) { if ( logFiles[i] != null && logFiles[i].exists() ) { logFiles[i].delete(); } } } catch ( Exception e ) { } } loggers.clear(); } } ); } /** * Inits the search logger. */ private void initSearchLogger( Connection connection ) { Logger logger = Logger.getAnonymousLogger(); loggers.put( connection.getId(), logger ); logger.setLevel( Level.ALL ); String logfileName = ConnectionManager.getSearchLogFileName( connection ); try { FileHandler fileHandler = new FileHandler( logfileName, getFileSizeInKb() * 1000, getFileCount(), true ); fileHandlers.put( connection.getId(), fileHandler ); fileHandler.setFormatter( new Formatter() { public String format( LogRecord record ) { return record.getMessage(); } } ); logger.addHandler( fileHandler ); } catch ( SecurityException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } /** * Disposes the search logger of the given connection. * * @param connection the connection */ public void dispose( Connection connection ) { String id = connection.getId(); if ( loggers.containsKey( id ) ) { Handler[] handlers = loggers.get( id ).getHandlers(); for ( Handler handler : handlers ) { handler.close(); } File[] files = getLogFiles( connection ); for ( File file : files ) { deleteFileWithRetry( file ); } loggers.remove( id ); } } private void log( String text, String type, StudioLdapException ex, Connection connection ) { String id = connection.getId(); if ( !loggers.containsKey( id ) ) { if ( connection.getName() != null ) { initSearchLogger( connection ); } } if ( loggers.containsKey( id ) ) { StringJoiner lines = new StringJoiner( "" ); DateFormat df = new SimpleDateFormat( ConnectionCoreConstants.DATEFORMAT ); df.setTimeZone( ConnectionCoreConstants.UTC_TIME_ZONE ); if ( ex != null ) { lines.add( LdifCommentLine.create( "#!" + type + " ERROR" ) //$NON-NLS-1$//$NON-NLS-2$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); } else { lines.add( LdifCommentLine.create( "#!" + type + " OK" ) //$NON-NLS-1$ //$NON-NLS-2$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); } lines.add( LdifCommentLine .create( "#!CONNECTION ldap://" + connection.getHost() + ":" + connection.getPort() ) //$NON-NLS-1$//$NON-NLS-2$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); lines.add( LdifCommentLine.create( "#!DATE " + df.format( new Date() ) ) //$NON-NLS-1$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); if ( ex != null ) { String errorComment = "#!ERROR " + ex.getMessage(); //$NON-NLS-1$ errorComment = errorComment.replaceAll( "\r", " " ); //$NON-NLS-1$ //$NON-NLS-2$ errorComment = errorComment.replaceAll( "\n", " " ); //$NON-NLS-1$ //$NON-NLS-2$ LdifCommentLine errorCommentLine = LdifCommentLine.create( errorComment ); lines.add( errorCommentLine.toFormattedString( LdifFormatParameters.DEFAULT ) ); } lines.add( text ); Logger logger = loggers.get( id ); logger.log( Level.ALL, lines.toString() ); } } /** * {@inheritDoc} */ public void logSearchRequest( Connection connection, String searchBase, String filter, SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls, long requestNum, StudioLdapException ex ) { if ( !isSearchRequestLogEnabled() ) { return; } String scopeAsString = searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "wholeSubtree (2)" //$NON-NLS-1$ : searchControls.getSearchScope() == SearchControls.ONELEVEL_SCOPE ? "singleLevel (1)" : "baseObject (0)"; //$NON-NLS-1$ //$NON-NLS-2$ String attributesAsString = searchControls.getReturningAttributes() == null ? "*" //$NON-NLS-1$ : searchControls .getReturningAttributes().length == 0 ? "1.1" //$NON-NLS-1$ : StringUtils.join( searchControls.getReturningAttributes(), " " ); String aliasAsString = aliasesDereferencingMethod == AliasDereferencingMethod.ALWAYS ? "derefAlways (3)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.FINDING ? "derefFindingBaseObj (2)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.SEARCH ? "derefInSearching (1)" //$NON-NLS-1$ : "neverDerefAliases (0)"; //$NON-NLS-1$ // build LDAP URL LdapUrl url = Utils.getLdapURL( connection, searchBase, searchControls.getSearchScope(), filter, searchControls .getReturningAttributes() ); // build command line String cmdLine = Utils.getLdapSearchCommandLine( connection, searchBase, searchControls.getSearchScope(), aliasesDereferencingMethod, searchControls.getCountLimit(), searchControls.getTimeLimit(), filter, searchControls.getReturningAttributes() ); // build Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>(); lines.add( LdifCommentLine.create( "# LDAP URL : " + url.toString() ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# command line : " + cmdLine.toString() ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# baseObject : " + searchBase ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# scope : " + scopeAsString ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# derefAliases : " + aliasAsString ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# sizeLimit : " + searchControls.getCountLimit() ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# timeLimit : " + searchControls.getTimeLimit() ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# typesOnly : " + "False" ) ); //$NON-NLS-1$ //$NON-NLS-2$ lines.add( LdifCommentLine.create( "# filter : " + filter ) ); //$NON-NLS-1$ lines.add( LdifCommentLine.create( "# attributes : " + attributesAsString ) ); //$NON-NLS-1$ if ( controls != null ) { for ( Control control : controls ) { lines.add( LdifCommentLine.create( "# control : " + control.getOid() ) ); //$NON-NLS-1$ } } lines.add( LdifSepLine.create() ); String formattedString = ""; //$NON-NLS-1$ for ( LdifLineBase line : lines ) { formattedString += line.toFormattedString( LdifFormatParameters.DEFAULT ); } log( formattedString, "SEARCH REQUEST (" + requestNum + ")", ex, connection ); //$NON-NLS-1$ //$NON-NLS-2$ } /** * {@inheritDoc} */ public void logSearchResultEntry( Connection connection, StudioSearchResult studioSearchResult, long requestNum, StudioLdapException ex ) { if ( !isSearchResultEntryLogEnabled() ) { return; } String formattedString; if ( studioSearchResult != null ) { Set<String> maskedAttributes = getMaskedAttributes(); Entry entry = studioSearchResult.getEntry(); LdifContentRecord record = new LdifContentRecord( LdifDnLine.create( entry.getDn().getName() ) ); for ( Attribute attribute : entry ) { String attributeName = attribute.getUpId(); for ( Value value : attribute ) { if ( maskedAttributes.contains( Strings.toLowerCaseAscii( attributeName ) ) ) { record.addAttrVal( LdifAttrValLine.create( attributeName, "**********" ) ); //$NON-NLS-1$ } else { if ( value.isHumanReadable() ) { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getString() ) ); } else { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getBytes() ) ); } } } } record.finish( LdifSepLine.create() ); formattedString = record.toFormattedString( LdifFormatParameters.DEFAULT ); } else { formattedString = LdifFormatParameters.DEFAULT.getLineSeparator(); } log( formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection ); //$NON-NLS-1$ //$NON-NLS-2$ } /** * {@inheritDoc} */ public void logSearchResultReference( Connection connection, Referral referral, ReferralsInfo referralsInfo, long requestNum, StudioLdapException ex ) { if ( !isSearchResultEntryLogEnabled() ) { return; } Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>(); lines .add( LdifCommentLine.create( "# reference : " + ( referral != null ? referral.getLdapUrls() : "null" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$ lines.add( LdifSepLine.create() ); String formattedString = ""; //$NON-NLS-1$ for ( LdifLineBase line : lines ) { formattedString += line.toFormattedString( LdifFormatParameters.DEFAULT ); } log( formattedString, "SEARCH RESULT REFERENCE (" + requestNum + ")", ex, connection ); //$NON-NLS-1$ //$NON-NLS-2$ } /** * {@inheritDoc} */ public void logSearchResultDone( Connection connection, long count, long requestNum, StudioLdapException ex ) { if ( !isSearchRequestLogEnabled() ) { return; } Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>(); lines.add( LdifCommentLine.create( "# numEntries : " + count ) ); //$NON-NLS-1$ lines.add( LdifSepLine.create() ); String formattedString = ""; //$NON-NLS-1$ for ( LdifLineBase line : lines ) { formattedString += line.toFormattedString( LdifFormatParameters.DEFAULT ); } log( formattedString, "SEARCH RESULT DONE (" + requestNum + ")", ex, connection ); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Gets the files. * * @param connection the connection * * @return the files */ public File[] getFiles( Connection connection ) { String id = connection.getId(); if ( !loggers.containsKey( id ) ) { if ( connection.getName() != null ) { initSearchLogger( connection ); } } try { return getLogFiles( connection ); } catch ( Exception e ) { return new File[0]; } } /** * Gets the log files. * * @param fileHandler the file handler * * @return the log files */ private static File[] getLogFiles( Connection connection ) { String logfileNamePattern = ConnectionManager.getSearchLogFileName( connection ); File file = new File( logfileNamePattern ); String pattern = file.getName().replace( "%u", "\\d+" ).replace( "%g", "\\d+" ); File dir = file.getParentFile(); File[] files = dir.listFiles( ( d, f ) -> { return f.matches( pattern ); } ); Arrays.sort( files ); return files; } /** * Checks if search request log is enabled. * * @return true, if search request log is enabled */ private boolean isSearchRequestLogEnabled() { return ConnectionCorePlugin.getDefault().isSearchRequestLogsEnabled(); } /** * Checks if search result entry log is enabled. * * @return true, if search result log is enabled */ private boolean isSearchResultEntryLogEnabled() { return ConnectionCorePlugin.getDefault().isSearchResultEntryLogsEnabled(); } /** * Gets the number of log files to use. * * @return the number of log files to use */ private int getFileCount() { return ConnectionCorePlugin.getDefault().getSearchLogsFileCount(); } /** * Gets the maximum file size in kB. * * @return the maximum file size in kB */ private int getFileSizeInKb() { return ConnectionCorePlugin.getDefault().getSearchLogsFileSize(); } public String getId() { return id; } public void setId( String id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/CancelException.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/CancelException.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.connection.core.io.api; import org.apache.directory.api.ldap.model.exception.LdapException; /** * A specific {@link LdapException} that represents the cancellation of an request. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CancelException extends LdapException { private static final long serialVersionUID = 1L; /** * Creates a new instance of CancelException. */ public CancelException() { super(); } /** * Creates a new instance of CancelException. * * @param message the message */ public CancelException( 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/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/LdifModificationLogger.java
plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/LdifModificationLogger.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.connection.core.io.api; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.apache.directory.api.ldap.model.entry.Attribute; 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.Value; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCoreConstants; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionManager; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.ILdapLogger; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.ldifparser.LdifFormatParameters; import org.apache.directory.studio.ldifparser.model.container.LdifChangeAddRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeDeleteRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeModDnRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeModifyRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeRecord; import org.apache.directory.studio.ldifparser.model.container.LdifModSpec; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine; import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine; import org.apache.directory.studio.ldifparser.model.lines.LdifControlLine; import org.apache.directory.studio.ldifparser.model.lines.LdifDeloldrdnLine; import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine; import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecSepLine; import org.apache.directory.studio.ldifparser.model.lines.LdifNewrdnLine; import org.apache.directory.studio.ldifparser.model.lines.LdifNewsuperiorLine; import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; /** * The LdifModificationLogger is used to log modifications in LDIF format into a file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class LdifModificationLogger implements ILdapLogger { /** The ID. */ private String id; /** The name. */ private String name; /** The description. */ private String description; /** The file handlers. */ private Map<String, FileHandler> fileHandlers = new HashMap<String, FileHandler>(); /** The loggers. */ private Map<String, Logger> loggers = new HashMap<String, Logger>(); /** * Creates a new instance of LdifModificationLogger. */ public LdifModificationLogger() { IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode( ConnectionCoreConstants.PLUGIN_ID ); prefs.addPreferenceChangeListener( event -> { if ( ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_COUNT.equals( event.getKey() ) || ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_SIZE.equals( event.getKey() ) ) { // dispose all loggers/handlers for ( Logger logger : loggers.values() ) { for ( Handler handler : logger.getHandlers() ) { handler.close(); } } // delete files with index greater than new file count Connection[] connections = ConnectionCorePlugin.getDefault().getConnectionManager().getConnections(); for ( Connection connection : connections ) { try { File[] logFiles = getLogFiles( connection ); for ( int i = getFileCount(); i < logFiles.length; i++ ) { if ( logFiles[i] != null && logFiles[i].exists() ) { logFiles[i].delete(); } } } catch ( Exception e ) { } } loggers.clear(); } } ); } /** * Inits the modification logger. */ private void initModificationLogger( Connection connection ) { Logger logger = Logger.getAnonymousLogger(); loggers.put( connection.getId(), logger ); logger.setLevel( Level.ALL ); String logfileName = ConnectionManager.getModificationLogFileName( connection ); try { FileHandler fileHandler = new FileHandler( logfileName, getFileSizeInKb() * 1000, getFileCount(), true ); fileHandlers.put( connection.getId(), fileHandler ); fileHandler.setFormatter( new Formatter() { public String format( LogRecord record ) { return record.getMessage(); } } ); logger.addHandler( fileHandler ); } catch ( SecurityException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } /** * Disposes the modification logger of the given connection. * * @param connection the connection */ public void dispose( Connection connection ) { String id = connection.getId(); if ( loggers.containsKey( id ) ) { Handler[] handlers = loggers.get( id ).getHandlers(); for ( Handler handler : handlers ) { handler.close(); } File[] files = getLogFiles( connection ); for ( File file : files ) { deleteFileWithRetry( file ); } loggers.remove( id ); } } private void log( String text, StudioLdapException ex, Connection connection ) { String id = connection.getId(); if ( !loggers.containsKey( id ) ) { if ( connection.getName() != null ) { initModificationLogger( connection ); } } if ( loggers.containsKey( id ) ) { StringJoiner lines = new StringJoiner( "" ); DateFormat df = new SimpleDateFormat( ConnectionCoreConstants.DATEFORMAT ); df.setTimeZone( ConnectionCoreConstants.UTC_TIME_ZONE ); if ( ex != null ) { lines.add( LdifCommentLine .create( "#!RESULT ERROR" ).toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NLS-1$ } else { lines.add( LdifCommentLine .create( "#!RESULT OK" ).toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NLS-1$ } lines.add( LdifCommentLine .create( "#!CONNECTION ldap://" + connection.getHost() + ":" + connection.getPort() ) //$NON-NLS-1$//$NON-NLS-2$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); lines.add( LdifCommentLine .create( "#!DATE " + df.format( new Date() ) ).toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NLS-1$ if ( ex != null ) { String errorComment = "#!ERROR " + ex.getMessage(); //$NON-NLS-1$ errorComment = errorComment.replaceAll( "\r", " " ); //$NON-NLS-1$ //$NON-NLS-2$ errorComment = errorComment.replaceAll( "\n", " " ); //$NON-NLS-1$ //$NON-NLS-2$ LdifCommentLine errorCommentLine = LdifCommentLine.create( errorComment ); lines.add( errorCommentLine.toFormattedString( LdifFormatParameters.DEFAULT ) ); } lines.add( text ); Logger logger = loggers.get( id ); logger.log( Level.ALL, lines.toString() ); } } /** * {@inheritDoc} */ public void logChangetypeAdd( Connection connection, final Entry entry, final Control[] controls, StudioLdapException ex ) { if ( !isModificationLogEnabled() ) { return; } Set<String> maskedAttributes = getMaskedAttributes(); LdifChangeAddRecord record = new LdifChangeAddRecord( LdifDnLine.create( entry.getDn().getName() ) ); addControlLines( record, controls ); record.setChangeType( LdifChangeTypeLine.createAdd() ); for ( Attribute attribute : entry ) { String attributeName = attribute.getUpId(); for ( Value value : attribute ) { if ( maskedAttributes.contains( Strings.toLowerCaseAscii( attributeName ) ) ) { record.addAttrVal( LdifAttrValLine.create( attributeName, "**********" ) ); //$NON-NLS-1$ } else { if ( value.isHumanReadable() ) { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getString() ) ); } else { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getBytes() ) ); } } } } record.finish( LdifSepLine.create() ); String formattedString = record.toFormattedString( LdifFormatParameters.DEFAULT ); log( formattedString, ex, connection ); } /** * {@inheritDoc} */ public void logChangetypeDelete( Connection connection, final Dn dn, final Control[] controls, StudioLdapException ex ) { if ( !isModificationLogEnabled() ) { return; } LdifChangeDeleteRecord record = new LdifChangeDeleteRecord( LdifDnLine.create( dn.getName() ) ); addControlLines( record, controls ); record.setChangeType( LdifChangeTypeLine.createDelete() ); record.finish( LdifSepLine.create() ); String formattedString = record.toFormattedString( LdifFormatParameters.DEFAULT ); log( formattedString, ex, connection ); } /** * {@inheritDoc} */ public void logChangetypeModify( Connection connection, final Dn dn, final Collection<Modification> modifications, final Control[] controls, StudioLdapException ex ) { if ( !isModificationLogEnabled() ) { return; } Set<String> maskedAttributes = getMaskedAttributes(); LdifChangeModifyRecord record = new LdifChangeModifyRecord( LdifDnLine.create( dn.getName() ) ); addControlLines( record, controls ); record.setChangeType( LdifChangeTypeLine.createModify() ); for ( Modification item : modifications ) { String attributeName = item.getAttribute().getUpId(); LdifModSpec modSpec; switch ( item.getOperation() ) { case ADD_ATTRIBUTE: modSpec = LdifModSpec.createAdd( attributeName ); break; case REMOVE_ATTRIBUTE: modSpec = LdifModSpec.createDelete( attributeName ); break; case REPLACE_ATTRIBUTE: modSpec = LdifModSpec.createReplace( attributeName ); break; default: continue; } for ( Value value : item.getAttribute() ) { if ( maskedAttributes.contains( Strings.toLowerCaseAscii( attributeName ) ) ) { modSpec.addAttrVal( LdifAttrValLine.create( attributeName, "**********" ) ); //$NON-NLS-1$ } else { if ( value.isHumanReadable() ) { modSpec.addAttrVal( LdifAttrValLine.create( attributeName, value.getString() ) ); } else { modSpec.addAttrVal( LdifAttrValLine.create( attributeName, value.getBytes() ) ); } } } modSpec.finish( LdifModSpecSepLine.create() ); record.addModSpec( modSpec ); } record.finish( LdifSepLine.create() ); String formattedString = record.toFormattedString( LdifFormatParameters.DEFAULT ); log( formattedString, ex, connection ); } /** * {@inheritDoc} */ public void logChangetypeModDn( Connection connection, final Dn oldDn, final Dn newDn, final boolean deleteOldRdn, final Control[] controls, StudioLdapException ex ) { if ( !isModificationLogEnabled() ) { return; } Rdn newrdn = newDn.getRdn(); Dn newsuperior = newDn.getParent(); LdifChangeModDnRecord record = new LdifChangeModDnRecord( LdifDnLine.create( oldDn.getName() ) ); addControlLines( record, controls ); record.setChangeType( LdifChangeTypeLine.createModDn() ); record.setNewrdn( LdifNewrdnLine.create( newrdn.getName() ) ); record.setDeloldrdn( deleteOldRdn ? LdifDeloldrdnLine.create1() : LdifDeloldrdnLine.create0() ); record.setNewsuperior( LdifNewsuperiorLine.create( newsuperior.getName() ) ); record.finish( LdifSepLine.create() ); String formattedString = record.toFormattedString( LdifFormatParameters.DEFAULT ); log( formattedString, ex, connection ); } /** * Adds control lines to the record * * @param record the recored * @param controls the controls */ private static void addControlLines( LdifChangeRecord record, Control[] controls ) { if ( controls != null ) { for ( Control control : controls ) { String oid = control.getOid(); boolean isCritical = control.isCritical(); byte[] bytes = Controls.getEncodedValue( control ); LdifControlLine controlLine = LdifControlLine.create( oid, isCritical, bytes ); record.addControl( controlLine ); } } } /** * Gets the files. * * @param connection the connection * * @return the files */ public File[] getFiles( Connection connection ) { String id = connection.getId(); if ( !loggers.containsKey( id ) ) { if ( connection.getName() != null ) { initModificationLogger( connection ); } } try { return getLogFiles( connection ); } catch ( Exception e ) { return new File[0]; } } /** * Gets the log files. * * @param fileHandler the file handler * * @return the log files */ private static File[] getLogFiles( Connection connection ) { String logfileNamePattern = ConnectionManager.getModificationLogFileName( connection ); File file = new File( logfileNamePattern ); String pattern = file.getName().replace( "%u", "\\d+" ).replace( "%g", "\\d+" ); File dir = file.getParentFile(); File[] files = dir.listFiles( ( d, f ) -> { return f.matches( pattern ); } ); Arrays.sort( files ); return files; } /** * Checks if modification log is enabled. * * @return true, if modification log is enabled */ private boolean isModificationLogEnabled() { return Platform.getPreferencesService().getBoolean( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_ENABLE, true, null ); } /** * Gets the number of log files to use. * * @return the number of log files to use */ private int getFileCount() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_COUNT, 10, null ); } /** * Gets the maximum file size in kB. * * @return the maximum file size in kB */ private int getFileSizeInKb() { return Platform.getPreferencesService().getInt( ConnectionCoreConstants.PLUGIN_ID, ConnectionCoreConstants.PREFERENCE_MODIFICATIONLOGS_FILE_SIZE, 100, null ); } public String getId() { return id; } public void setId( String id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
microg/GsfProxy
https://github.com/microg/GsfProxy/blob/ff1b9aa3e235904009f1d87113391abb51808af1/services-framework-proxy/src/main/java/org/microg/gms/gcm/PushRegisterProxy.java
services-framework-proxy/src/main/java/org/microg/gms/gcm/PushRegisterProxy.java
/* * SPDX-FileCopyrightText: 2013 microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.gcm; import android.app.IntentService; import android.content.Intent; public class PushRegisterProxy extends IntentService { private static final String TAG = "GsfGcmRegisterProxy"; public PushRegisterProxy() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { intent.setPackage("com.google.android.gms"); startService(intent); stopSelf(); } }
java
Apache-2.0
ff1b9aa3e235904009f1d87113391abb51808af1
2026-01-05T02:37:30.305915Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/DeferredGatewayStarter.java
src/test/java/com/github/zkclient/DeferredGatewayStarter.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import com.github.zkclient.Gateway; public class DeferredGatewayStarter extends Thread { private final Gateway _zkServer; private int _delay; public DeferredGatewayStarter(Gateway gateway, int delay) { _zkServer = gateway; _delay = delay; } @Override public void run() { try { Thread.sleep(_delay); _zkServer.start(); } catch (Exception e) { // ignore } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/PortUtils.java
src/test/java/com/github/zkclient/PortUtils.java
package com.github.zkclient; import java.io.IOException; import java.net.ServerSocket; /** * copy from https://github.com/adyliu/jafka/blob/master/src/test/java/com/sohu/jafka/PortUtils.java * * @author adyliu (imxylz@gmail.com) * @since 2013-04-25 */ public class PortUtils { public static int checkAvailablePort(int port) { while (port < 65500) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); return port; } catch (IOException e) { //ignore error } finally { try { if (serverSocket != null) serverSocket.close(); } catch (IOException e) { //ignore } } port++; } throw new RuntimeException("no available port"); } public static void main(String[] args) { int port = checkAvailablePort(80); System.out.println("The available port is " + port); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/GatewayThread.java
src/test/java/com/github/zkclient/GatewayThread.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GatewayThread extends Thread { protected final static Logger LOG = LoggerFactory.getLogger(GatewayThread.class); private final int _port; private final int _destinationPort; private ServerSocket _serverSocket; private Lock _lock = new ReentrantLock(); private Condition _runningCondition = _lock.newCondition(); private boolean _running = false; public GatewayThread(int port, int destinationPort) { _port = port; _destinationPort = destinationPort; setDaemon(true); } @Override public void run() { final List<Thread> runningThreads = new Vector<Thread>(); try { LOG.info("Starting gateway on port " + _port + " pointing to port " + _destinationPort); _serverSocket = new ServerSocket(_port); _lock.lock(); try { _running = true; _runningCondition.signalAll(); } finally { _lock.unlock(); } while (true) { final Socket socket = _serverSocket.accept(); LOG.info("new client is connected " + socket.getInetAddress().getHostAddress()); final InputStream incomingInputStream = socket.getInputStream(); final OutputStream incomingOutputStream = socket.getOutputStream(); final Socket outgoingSocket; try { outgoingSocket = new Socket("localhost", _destinationPort); } catch (Exception e) { LOG.warn("could not connect to " + _destinationPort); continue; } final InputStream outgoingInputStream = outgoingSocket.getInputStream(); final OutputStream outgoingOutputStream = outgoingSocket.getOutputStream(); Thread writeThread = new Thread() { @Override public void run() { runningThreads.add(this); try { int read = -1; while ((read = incomingInputStream.read()) != -1) { outgoingOutputStream.write(read); } } catch (IOException e) { // ignore } finally { closeQuietly(outgoingOutputStream); runningThreads.remove(this); } } @Override public void interrupt() { try { socket.close(); outgoingSocket.close(); } catch (IOException e) { LOG.error("error on stopping closing sockets", e); } super.interrupt(); } }; Thread readThread = new Thread() { @Override public void run() { runningThreads.add(this); try { int read = -1; while ((read = outgoingInputStream.read()) != -1) { incomingOutputStream.write(read); } } catch (IOException e) { // ignore } finally { closeQuietly(incomingOutputStream); runningThreads.remove(this); } } }; writeThread.setDaemon(true); readThread.setDaemon(true); writeThread.start(); readThread.start(); } } catch (SocketException e) { if (!_running) { throw new RuntimeException(e); } LOG.info("Stopping gateway"); } catch (Exception e) { LOG.error("error on gateway execution", e); } for (Thread thread : new ArrayList<Thread>(runningThreads)) { thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { // ignore } } } protected void closeQuietly(Closeable closable) { try { closable.close(); } catch (IOException e) { // ignore } } @Override public void interrupt() { try { _serverSocket.close(); } catch (Exception cE) { LOG.error("error on stopping gateway", cE); } super.interrupt(); } public void interruptAndJoin() throws InterruptedException { interrupt(); join(); } public void awaitUp() { _lock.lock(); try { while (!_running) { _runningCondition.await(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { _lock.unlock(); } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/TestUtil.java
src/test/java/com/github/zkclient/TestUtil.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.io.File; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.junit.Ignore; import com.github.zkclient.ZkServer; @Ignore public class TestUtil { static { System.setProperty("zookeeper.preAllocSize", "1024");//1M data log } /** * This waits until the provided {@link Callable} returns an object that is equals to the given expected value or * the timeout has been reached. In both cases this method will return the return value of the latest * {@link Callable} execution. * * @param expectedValue * The expected value of the callable. * @param callable * The callable. * @param <T> * The return type of the callable. * @param timeUnit * The timeout timeunit. * @param timeout * The timeout. * @return the return value of the latest {@link Callable} execution. * @throws Exception * @throws InterruptedException */ public static <T> T waitUntil(T expectedValue, Callable<T> callable, TimeUnit timeUnit, long timeout) throws Exception { long startTime = System.currentTimeMillis(); do { T actual = callable.call(); if (expectedValue.equals(actual)) { return actual; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { return actual; } Thread.sleep(50); } while (true); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/Gateway.java
src/test/java/com/github/zkclient/Gateway.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; public class Gateway { private GatewayThread _thread; private final int _port; private final int _destinationPort; public Gateway(int port, int destinationPort) { _port = port; _destinationPort = destinationPort; } public synchronized void start() { if (_thread != null) { throw new IllegalStateException("Gateway already running"); } _thread = new GatewayThread(_port, _destinationPort); _thread.start(); _thread.awaitUp(); } public synchronized void stop() { if (_thread != null) { try { _thread.interruptAndJoin(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } _thread = null; } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/ZkServerDemo.java
src/test/java/com/github/zkclient/ZkServerDemo.java
package com.github.zkclient; import java.io.File; import java.util.Arrays; public class ZkServerDemo { public static void main(String[] args) throws Exception{ File dataDir = new File("/tmp/zkdemo"); dataDir.mkdirs(); ZkServer server = new ZkServer(dataDir.getAbsolutePath(), dataDir.getAbsolutePath()); server.start(); ZkClient client = server.getZkClient(); client.createPersistent("/a", true); byte[] dat = client.readData("/a"); System.out.println(Arrays.toString(dat)); client.writeData("/a", "OK".getBytes()); System.out.println("agian="+Arrays.toString(dat)); //server.shutdown(); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/ZkClientUtilsTest.java
src/test/java/com/github/zkclient/ZkClientUtilsTest.java
/** * */ package com.github.zkclient; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * * @author adyliu(imxylz@gmail.com) * @since 2012-12-3 */ public class ZkClientUtilsTest { /** * Test method for * {@link com.github.zkclient.ZkClientUtils#leadingZeros(long, int)}. */ @Test public void testLeadingZeros() { assertEquals("99", ZkClientUtils.leadingZeros(99, 1)); assertEquals("99", ZkClientUtils.leadingZeros(99, 2)); assertEquals("099", ZkClientUtils.leadingZeros(99, 3)); assertEquals("0099", ZkClientUtils.leadingZeros(99, 4)); assertEquals("00099", ZkClientUtils.leadingZeros(99, 5)); assertEquals("0100", ZkClientUtils.leadingZeros(100, 4)); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/test/java/com/github/zkclient/ZkClientTest.java
src/test/java/com/github/zkclient/ZkClientTest.java
/** * */ package com.github.zkclient; import com.github.zkclient.exception.ZkNoNodeException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.data.Stat; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.LockSupport; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author adyliu (imxylz@gmail.com) * @since 2012-12-3 */ public class ZkClientTest { static { System.setProperty("zookeeper.preAllocSize", "1024");// 1M data log } final Logger logger = LoggerFactory.getLogger(ZkClientTest.class); private static final AtomicInteger counter = new AtomicInteger(); // private ZkServer server; private ZkClient client; final int TIMEOUT = 30;//30 second for loop timeout // private static void deleteFile(File f) throws IOException { if (f.isFile()) { f.delete(); //System.out.println("[DELETE FILE] "+f.getPath()); } else if (f.isDirectory()) { File[] files = f.listFiles(); if (files != null) { for (File fs : files) { deleteFile(fs); } } f.delete(); //System.out.println("[DELETE DIRECTORY] "+f.getPath()); } } private static ZkServer startZkServer(String testName, int port) throws IOException { String dataPath = "build/test/" + testName + "/data"; String logPath = "build/test/" + testName + "/log"; File dataDir = new File(".", dataPath).getCanonicalFile(); File logDir = new File(".", logPath).getCanonicalFile(); deleteFile(dataDir); deleteFile(logDir); //start the server with 100ms session timeout ZkServer zkServer = new ZkServer(dataDir.getPath(), logDir.getPath(), port, ZkServer.DEFAULT_TICK_TIME, 100); zkServer.start(); return zkServer; } @AfterClass public static void cleanup() throws IOException { deleteFile(new File(".", "build/test").getCanonicalFile()); } @Before public void setUp() throws Exception { this.server = startZkServer("server_" + counter.incrementAndGet(), 4711); this.client = this.server.getZkClient(); assertTrue(this.client.isConnected()); } @After public void tearDown() throws Exception { if (this.server != null) { this.server.shutdown(); } } /** * Test method for * {@link com.github.zkclient.ZkClient#subscribeChildChanges(java.lang.String, com.github.zkclient.IZkChildListener)} * . */ @Test public void testSubscribeChildChanges() throws Exception { final String path = "/a"; final AtomicInteger count = new AtomicInteger(0); final ArrayList<String> children = new ArrayList<String>(); IZkChildListener listener = new IZkChildListener() { public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception { count.incrementAndGet(); children.clear(); if (currentChildren != null) children.addAll(currentChildren); logger.info("handle childchange " + parentPath + ", " + currentChildren); } }; // client.subscribeChildChanges(path, listener); // logger.info("create the watcher node " + path); client.createPersistent(path); //wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return count.get(); } }, TimeUnit.SECONDS, TIMEOUT); // assertEquals(1, count.get()); assertEquals(0, children.size()); // //create a child node count.set(0); client.createPersistent(path + "/child1"); logger.info("create the first child node " + path + "/child1"); TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return count.get(); } }, TimeUnit.SECONDS, TIMEOUT); // assertEquals(1, count.get()); assertEquals(1, children.size()); assertEquals("child1", children.get(0)); // // create another child node and delete the node count.set(0); logger.info("create the second child node " + path + "/child2"); client.createPersistent(path + "/child2"); // logger.info("delete the watcher node " + path); client.deleteRecursive(path); // Boolean eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0 && children.size() == 0; } }, TimeUnit.SECONDS, TIMEOUT); assertTrue(eventReceived); assertEquals(0, children.size()); // =========================================== // do it again and check the listener validate // =========================================== count.set(0); // logger.info("create the watcher node again " + path); client.createPersistent(path); // eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0; } }, TimeUnit.SECONDS, TIMEOUT); assertTrue(eventReceived); assertEquals(0, children.size()); // // now create the first node count.set(0); final String child3 = "/child3"; client.createPersistent(path + child3); logger.info("create the first child node again " + path + child3); // eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0; } }, TimeUnit.SECONDS, 15); assertTrue(eventReceived); assertEquals(1, children.size()); assertEquals("child3", children.get(0)); // // delete root node count.set(0); logger.info("delete the watcher node again " + path); client.deleteRecursive(path); // This will receive two message: (1) child was deleted (2) parent was deleted // eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return children.isEmpty(); } }, TimeUnit.SECONDS, TIMEOUT); assertTrue(eventReceived); assertTrue(children.isEmpty()); } static class Holder<T> { T t; public void set(T t) { this.t = t; } public T get() { return t; } } static byte[] toBytes(String s) { try { return s != null ? s.getBytes("UTF-8") : null; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static String toString(byte[] b) { try { return b != null ? new String(b, "UTF-8") : null; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Test method for * {@link com.github.zkclient.ZkClient#subscribeDataChanges(java.lang.String, com.github.zkclient.IZkDataListener)} * . */ @Test public void testSubscribeDataChanges() throws Exception { String path = "/a"; final AtomicInteger countChanged = new AtomicInteger(0); final AtomicInteger countDeleted = new AtomicInteger(0); final Holder<String> holder = new Holder<String>(); IZkDataListener listener = new IZkDataListener() { public void handleDataDeleted(String dataPath) throws Exception { countDeleted.incrementAndGet(); holder.set(null); } public void handleDataChange(String dataPath, byte[] data) throws Exception { countChanged.incrementAndGet(); holder.set(ZkClientTest.toString(data)); } }; client.subscribeDataChanges(path, listener); // // create the node client.createPersistent(path, toBytes("aaa")); // //wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, TIMEOUT); assertEquals(1, countChanged.get()); assertEquals(0, countDeleted.get()); assertEquals("aaa", holder.get()); // countChanged.set(0); countDeleted.set(0); // client.delete(path); TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countDeleted.get(); } }, TimeUnit.SECONDS, TIMEOUT); assertEquals(0, countChanged.get()); assertEquals(1, countDeleted.get()); assertNull(holder.get()); // =========================================== // do it again and check the listener validate // =========================================== countChanged.set(0); countDeleted.set(0); client.createPersistent(path, toBytes("bbb")); TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, TIMEOUT); assertEquals(1, countChanged.get()); assertEquals("bbb", holder.get()); // countChanged.set(0); client.writeData(path, toBytes("ccc")); // TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, TIMEOUT); assertEquals(1, countChanged.get()); assertEquals("ccc", holder.get()); } /** * Test method for * {@link com.github.zkclient.ZkClient#createPersistent(java.lang.String, boolean)} * . */ @Test public void testCreatePersistent() { final String path = "/a/b"; try { client.createPersistent(path, false); fail("should throw exception"); } catch (ZkNoNodeException e) { assertFalse(client.exists(path)); } client.createPersistent(path, true); assertTrue(client.exists(path)); } /** * Test method for * {@link com.github.zkclient.ZkClient#createPersistent(java.lang.String, byte[])} * . */ @Test public void testCreatePersistentStringByteArray() { String path = "/a"; client.createPersistent(path, toBytes("abc")); assertEquals("abc", toString(client.readData(path))); // } /** * Test method for * {@link com.github.zkclient.ZkClient#createPersistentSequential(java.lang.String, byte[])} * . */ @Test public void testCreatePersistentSequential() { String path = "/a"; String npath = client.createPersistentSequential(path, toBytes("abc")); assertTrue(npath != null && npath.length() > 0); npath = client.createPersistentSequential(path, toBytes("abc")); assertEquals("abc", toString(client.readData(npath))); } /** * Test method for * {@link com.github.zkclient.ZkClient#createEphemeral(java.lang.String)}. */ @Test public void testCreateEphemeralString() { String path = "/a"; client.createEphemeral(path); Stat stat = new Stat(); client.readData(path, stat); assertTrue(stat.getEphemeralOwner() > 0); } /** * Test method for * {@link com.github.zkclient.ZkClient#create(java.lang.String, byte[], org.apache.zookeeper.CreateMode)} * . */ @Test public void testCreate() { String path = "/a"; client.create(path, toBytes("abc"), CreateMode.PERSISTENT); assertEquals("abc", toString(client.readData(path))); } @Test public void testCreateEphemeralSequential() { String path = "/a"; String npath = client.createEphemeralSequential(path, toBytes("abc")); assertTrue(npath != null && npath.startsWith("/a")); Stat stat = new Stat(); assertArrayEquals(toBytes("abc"), client.readData(npath, stat)); assertTrue(stat.getEphemeralOwner() > 0); } /** * Test method for * {@link com.github.zkclient.ZkClient#getChildren(java.lang.String)}. */ @Test public void testGetChildrenString() { String path = "/a"; client.createPersistent(path + "/ch1", true); client.createPersistent(path + "/ch2"); client.createPersistent(path + "/ch3"); List<String> children = client.getChildren(path); assertEquals(3, children.size()); assertEquals(3, client.countChildren(path)); assertNull(client.getChildren("/aaa")); } /** * Test method for * {@link com.github.zkclient.ZkClient#exists(java.lang.String)}. */ @Test public void testExistsString() { String path = "/a"; assertFalse(client.exists(path)); client.createPersistent(path); assertTrue(client.exists(path)); client.delete(path); assertFalse(client.exists(path)); } /** * Test method for * {@link com.github.zkclient.ZkClient#deleteRecursive(java.lang.String)}. */ @Test public void testDeleteRecursive() { String path = "/a/b/c"; client.createPersistent(path, true); assertTrue(client.exists(path)); assertTrue(client.deleteRecursive("/a")); assertFalse(client.exists(path)); assertFalse(client.exists("/a/b")); assertFalse(client.exists("/a")); } /** * Test method for * {@link com.github.zkclient.ZkClient#waitUntilExists(java.lang.String, java.util.concurrent.TimeUnit, long)} * . */ @Test public void testWaitUntilExists() { final String path = "/a"; new Thread() { public void run() { LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); client.createPersistent(path); } }.start(); assertTrue(client.waitUntilExists(path, TimeUnit.SECONDS, 10)); assertTrue(client.exists(path)); // assertFalse(client.waitUntilExists("/notexists", TimeUnit.SECONDS, 1)); } /** * Test method for {@link com.github.zkclient.ZkClient#waitUntilConnected()} * . */ @Test public void testWaitUntilConnected() { ZkClient client2 = new ZkClient("localhost:4711", 15000); assertTrue(client2.waitUntilConnected()); server.shutdown(); // assertTrue(client2.waitForKeeperState(KeeperState.Disconnected, 1, TimeUnit.SECONDS)); // assertFalse(client2.waitUntilConnected(1, TimeUnit.SECONDS)); client2.close(); } /** * Test method for * {@link com.github.zkclient.ZkClient#readData(java.lang.String, org.apache.zookeeper.data.Stat)} * . */ @Test public void testReadDataStringStat() { client.createPersistent("/a", "data".getBytes()); Stat stat = new Stat(); client.readData("/a", stat); assertEquals(0, stat.getVersion()); assertTrue(stat.getDataLength() > 0); } /** * Test method for {@link com.github.zkclient.ZkClient#numberOfListeners()}. */ @Test public void testNumberOfListeners() { IZkChildListener zkChildListener = new AbstractListener() { }; client.subscribeChildChanges("/", zkChildListener); assertEquals(1, client.numberOfListeners()); // IZkDataListener zkDataListener = new AbstractListener() { }; client.subscribeDataChanges("/a", zkDataListener); assertEquals(2, client.numberOfListeners()); // client.subscribeDataChanges("/b", zkDataListener); assertEquals(3, client.numberOfListeners()); // IZkStateListener zkStateListener = new AbstractListener() { }; client.subscribeStateChanges(zkStateListener); assertEquals(4, client.numberOfListeners()); // client.unsubscribeChildChanges("/", zkChildListener); assertEquals(3, client.numberOfListeners()); // client.unsubscribeAll(); assertEquals(0, client.numberOfListeners()); } /** * Test method for {@link com.github.zkclient.ZkClient#getZooKeeper()}. */ @Test public void testGetZooKeeper() { assertTrue(client.getZooKeeper() != null); } @Test public void testRetryUnitConnected_SessionExpiredException() { int sessionTimeout = 200; int port = PortUtils.checkAvailablePort(4712); int dport = this.server.getPort(); Gateway gateway = new Gateway(port, dport); gateway.start(); // final ZkClient client2 = new ZkClient("localhost:" + port, sessionTimeout, 15000); gateway.stop(); // //start the server after 600ms new DeferredGatewayStarter(gateway, sessionTimeout * 3).start(); // final Boolean connected = client2.retryUntilConnected(new Callable<Boolean>() { @Override public Boolean call() throws Exception { client2.createPersistent("/abc"); return Boolean.TRUE; } }); assertTrue(connected); assertTrue(client2.exists("/abc")); client2.close(); gateway.stop(); // } @Test public void testChildListenerAfterSessionExpiredException() throws Exception { final int sessionTimeout = 200; ZkClient connectedClient = server.getZkClient(); connectedClient.createPersistent("/root"); // int port = PortUtils.checkAvailablePort(4712); int dport = this.server.getPort(); Gateway gateway = new Gateway(port, dport); gateway.start(); // final ZkClient disconnectedClient = new ZkClient("localhost:" + port, sessionTimeout, 15000); final Holder<List<String>> children = new Holder<List<String>>(); disconnectedClient.subscribeChildChanges("/root", new IZkChildListener() { @Override public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception { children.set(currentChildren); } }); gateway.stop();// // // the connected client created a new child node connectedClient.createPersistent("/root/node1"); // // wait for 3x sessionTImeout, the session should have expired Thread.sleep(3 * sessionTimeout); // // now start the gateway gateway.start(); // Boolean hasOneChild = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return children.get() != null && children.get().size() == 1; } }, TimeUnit.SECONDS, TIMEOUT); // assertTrue(hasOneChild); assertEquals("node1", children.get().get(0)); assertEquals("node1", disconnectedClient.getChildren("/root").get(0)); // disconnectedClient.close(); gateway.stop(); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/AbstractListener.java
src/main/java/com/github/zkclient/AbstractListener.java
/** * */ package com.github.zkclient; import java.util.List; import org.apache.zookeeper.Watcher.Event.KeeperState; /** * An abstract class for zookeeper listner * @author adyliu (imxylz@gmail.com) * @since 2012-12-4 * @see IZkChildListener * @see IZkDataListener * @see IZkStateListener */ public abstract class AbstractListener implements IZkChildListener, IZkDataListener, IZkStateListener { @Override public void handleStateChanged(KeeperState state) throws Exception { } @Override public void handleNewSession() throws Exception { } @Override public void handleDataChange(String dataPath, byte[] data) throws Exception { } @Override public void handleDataDeleted(String dataPath) throws Exception { } @Override public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception { } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/IZkChildListener.java
src/main/java/com/github/zkclient/IZkChildListener.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.util.List; /** * An {@link IZkChildListener} can be registered at a {@link ZkClient} for listening on zk child changes for a given * path. * <p> * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not * guaranteed that events on the path are missing (see http://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkWatches). An * implementation of this class should take that into account. */ public interface IZkChildListener { /** * Called when the children of the given path changed. * <p> * NOTICE: if subscribing a node(not exists), the event will be triggered while the node(parent) were created. * </p> * * @param parentPath The parent path * @param currentChildren The children or null if the root node (parent path) was deleted. * @throws Exception any exception */ public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception; }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkLock.java
src/main/java/com/github/zkclient/ZkLock.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ZkLock extends ReentrantLock { private static final long serialVersionUID = 1L; private final Condition _dataChangedCondition = newCondition(); private final Condition _stateChangedCondition = newCondition(); private final Condition _zNodeEventCondition = newCondition(); /** * This condition will be signaled if a zookeeper event was processed and the event contains a data/child change. * * @return the condition. */ public Condition getDataChangedCondition() { return _dataChangedCondition; } /** * This condition will be signaled if a zookeeper event was processed and the event contains a state change * (connected, disconnected, session expired, etc ...). * * @return the condition. */ public Condition getStateChangedCondition() { return _stateChangedCondition; } /** * This condition will be signaled if any znode related zookeeper event was received. * * @return the condition. */ public Condition getZNodeEventCondition() { return _zNodeEventCondition; } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkServer.java
src/main/java/com/github/zkclient/ZkServer.java
/** * Copyright 2010 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.github.zkclient; import com.github.zkclient.exception.ZkException; import org.apache.zookeeper.client.FourLetterWordMain; import org.apache.zookeeper.server.ServerConfig; import org.apache.zookeeper.server.ZooKeeperServerMain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.File; import java.net.ConnectException; public class ZkServer extends ZooKeeperServerMain { private final static Logger LOG = LoggerFactory.getLogger(ZkServer.class); ; public static final int DEFAULT_PORT = 2181; public static final int DEFAULT_TICK_TIME = 5000; public static final int DEFAULT_MIN_SESSION_TIMEOUT = 2 * DEFAULT_TICK_TIME; private final String _dataDir; private final String _logDir; private ZkClient _zkClient; private final int _port; private final int _tickTime; private final int _minSessionTimeout; private volatile boolean shutdown = false; private boolean daemon = true; public ZkServer(String dataDir, String logDir) { this(dataDir, logDir, DEFAULT_PORT); } public ZkServer(String dataDir, String logDir, int port) { this(dataDir, logDir, port, DEFAULT_TICK_TIME); } public ZkServer(String dataDir, String logDir, int port, int tickTime) { this(dataDir, logDir, port, tickTime, DEFAULT_MIN_SESSION_TIMEOUT); } public ZkServer(String dataDir, String logDir, int port, int tickTime, int minSessionTimeout) { _dataDir = dataDir; _logDir = logDir; _port = port; _tickTime = tickTime; _minSessionTimeout = minSessionTimeout; } public int getPort() { return _port; } @PostConstruct public void start() { shutdown = false; startZkServer(); _zkClient = new ZkClient("localhost:" + _port, 10000); } private void startZkServer() { final int port = _port; if (ZkClientUtils.isPortFree(port)) { final File dataDir = new File(_dataDir); final File dataLogDir = new File(_logDir); dataDir.mkdirs(); // single zk server LOG.info("Start single zookeeper server, port={} data={} ", port, dataDir.getAbsolutePath()); // final ZooKeeperServerMain serverMain = this; final InnerServerConfig config = new InnerServerConfig(); config.parse(new String[]{"" + port, dataDir.getAbsolutePath(), "" + _tickTime, "60"}); config.setMinSessionTimeout(_minSessionTimeout); // final String threadName = "inner-zkserver-" + port; final Thread innerThread = new Thread(new Runnable() { @Override public void run() { try { serverMain.runFromConfig(config); } catch (Exception e) { throw new ZkException("Unable to start single ZooKeeper server.", e); } } }, threadName); innerThread.setDaemon(daemon); innerThread.start(); // waitForServerUp(port, 30000, false); } else { throw new IllegalStateException("Zookeeper port " + port + " was already in use. Running in single machine mode?"); } } @PreDestroy public void shutdown() { if (!shutdown) { shutdown = true; LOG.info("Shutting down ZkServer port={}...", _port); if (_zkClient != null) { try { _zkClient.close(); } catch (ZkException e) { LOG.warn("Error on closing zkclient: " + e.getClass().getName()); } _zkClient = null; } super.shutdown(); waitForServerDown(_port, 30000, false); LOG.info("Shutting down ZkServer port={}...done", _port); } } public ZkClient getZkClient() { return _zkClient; } class InnerServerConfig extends ServerConfig { public void setMinSessionTimeout(int minSessionTimeout) { this.minSessionTimeout = minSessionTimeout; } } public static boolean waitForServerUp(int port, long timeout, boolean secure) { long start = System.currentTimeMillis(); while (true) { try { // if there are multiple hostports, just take the first one String result = FourLetterWordMain.send4LetterWord("127.0.0.1", port, "stat"); if (result.startsWith("Zookeeper version:") && !result.contains("READ-ONLY")) { return true; } } catch (ConnectException e) { // ignore as this is expected, do not log stacktrace LOG.debug("server {} not up: {}", port, e.toString()); } catch (Exception e) { // ignore as this is expected LOG.info("server {} not up", port, e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; } public static boolean waitForServerDown(int port, long timeout, boolean secure) { long start = System.currentTimeMillis(); while (true) { try { FourLetterWordMain.send4LetterWord("127.0.0.1", port, "stat"); } catch (Exception e) { return true; } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkClient.java
src/main/java/com/github/zkclient/ZkClient.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import com.github.zkclient.ZkEventThread.ZkEvent; import com.github.zkclient.exception.ZkBadVersionException; import com.github.zkclient.exception.ZkException; import com.github.zkclient.exception.ZkInterruptedException; import com.github.zkclient.exception.ZkNoNodeException; import com.github.zkclient.exception.ZkNodeExistsException; import com.github.zkclient.exception.ZkTimeoutException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.ConnectionLossException; import org.apache.zookeeper.KeeperException.SessionExpiredException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooKeeper.States; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; /** * Zookeeper client * <p> * The client is thread-safety * </p> */ public class ZkClient implements Watcher, IZkClient { private final static Logger LOG = LoggerFactory.getLogger(ZkClient.class); protected ZkConnection _connection; private final Map<String, Set<IZkChildListener>> _childListener = new ConcurrentHashMap<String, Set<IZkChildListener>>(); private final Map<String, Set<IZkDataListener>> _dataListener = new ConcurrentHashMap<String, Set<IZkDataListener>>(); private final Set<IZkStateListener> _stateListener = new CopyOnWriteArraySet<IZkStateListener>(); private volatile KeeperState _currentState; private final ZkLock _zkEventLock = new ZkLock(); private volatile boolean _shutdownTriggered; private ZkEventThread _eventThread; private Thread _zookeeperEventThread; /** * Create a client with default connection timeout and default session timeout * * @param connectString zookeeper connection string * comma separated host:port pairs, each corresponding to a zk * server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002" If * the optional chroot suffix is used the example would look * like: "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002/app/a" * where the client would be rooted at "/app/a" and all paths * would be relative to this root - ie getting/setting/etc... * "/foo/bar" would result in operations being run on * "/app/a/foo/bar" (from the server perspective). * @see IZkClient#DEFAULT_CONNECTION_TIMEOUT * @see IZkClient#DEFAULT_SESSION_TIMEOUT */ public ZkClient(String connectString) { this(connectString, DEFAULT_CONNECTION_TIMEOUT); } /** * Create a client * * @param connectString zookeeper connection string * comma separated host:port pairs, each corresponding to a zk * server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002" If * the optional chroot suffix is used the example would look * like: "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002/app/a" * where the client would be rooted at "/app/a" and all paths * would be relative to this root - ie getting/setting/etc... * "/foo/bar" would result in operations being run on * "/app/a/foo/bar" (from the server perspective). * @param connectionTimeout connection timeout in milliseconds */ public ZkClient(String connectString, int connectionTimeout) { this(connectString, DEFAULT_SESSION_TIMEOUT, connectionTimeout); } /** * Create a client * * @param connectString zookeeper connection string * comma separated host:port pairs, each corresponding to a zk * server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002" If * the optional chroot suffix is used the example would look * like: "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002/app/a" * where the client would be rooted at "/app/a" and all paths * would be relative to this root - ie getting/setting/etc... * "/foo/bar" would result in operations being run on * "/app/a/foo/bar" (from the server perspective). * @param sessionTimeout session timeout in milliseconds * @param connectionTimeout connection timeout in milliseconds */ public ZkClient(String connectString, int sessionTimeout, int connectionTimeout) { this(new ZkConnection(connectString, sessionTimeout), connectionTimeout); } /** * Create a client with special implementation * * @param zkConnection special client * @param connectionTimeout connection timeout in milliseconds */ public ZkClient(ZkConnection zkConnection, int connectionTimeout) { _connection = zkConnection; connect(connectionTimeout, this); } public List<String> subscribeChildChanges(String path, IZkChildListener listener) { synchronized (_childListener) { Set<IZkChildListener> listeners = _childListener.get(path); if (listeners == null) { listeners = new CopyOnWriteArraySet<IZkChildListener>(); _childListener.put(path, listeners); } listeners.add(listener); } return watchForChilds(path); } public void unsubscribeChildChanges(String path, IZkChildListener childListener) { synchronized (_childListener) { final Set<IZkChildListener> listeners = _childListener.get(path); if (listeners != null) { listeners.remove(childListener); } } } public void subscribeDataChanges(String path, IZkDataListener listener) { Set<IZkDataListener> listeners; synchronized (_dataListener) { listeners = _dataListener.get(path); if (listeners == null) { listeners = new CopyOnWriteArraySet<IZkDataListener>(); _dataListener.put(path, listeners); } listeners.add(listener); } watchForData(path); LOG.debug("Subscribed data changes for " + path); } public void unsubscribeDataChanges(String path, IZkDataListener dataListener) { synchronized (_dataListener) { final Set<IZkDataListener> listeners = _dataListener.get(path); if (listeners != null) { listeners.remove(dataListener); } if (listeners == null || listeners.isEmpty()) { _dataListener.remove(path); } } } public void subscribeStateChanges(final IZkStateListener listener) { synchronized (_stateListener) { _stateListener.add(listener); } } public void unsubscribeStateChanges(IZkStateListener stateListener) { synchronized (_stateListener) { _stateListener.remove(stateListener); } } public void unsubscribeAll() { synchronized (_childListener) { _childListener.clear(); } synchronized (_dataListener) { _dataListener.clear(); } synchronized (_stateListener) { _stateListener.clear(); } } public void createPersistent(String path) { createPersistent(path, false); } public void createPersistent(String path, boolean createParents) { try { create(path, null, CreateMode.PERSISTENT); } catch (ZkNodeExistsException e) { if (!createParents) { throw e; } } catch (ZkNoNodeException e) { if (!createParents) { throw e; } String parentDir = path.substring(0, path.lastIndexOf('/')); createPersistent(parentDir, createParents); createPersistent(path, createParents); } } public void createPersistent(String path, byte[] data) { create(path, data, CreateMode.PERSISTENT); } public String createPersistentSequential(String path, byte[] data) { return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL); } public void createEphemeral(final String path) { create(path, null, CreateMode.EPHEMERAL); } public String create(final String path, byte[] data, final CreateMode mode) { if (path == null) { throw new NullPointerException("path must not be null."); } final byte[] bytes = data; return retryUntilConnected(new Callable<String>() { @Override public String call() throws Exception { return _connection.create(path, bytes, mode); } }); } public void createEphemeral(final String path, final byte[] data) { create(path, data, CreateMode.EPHEMERAL); } public String createEphemeralSequential(final String path, final byte[] data) { return create(path, data, CreateMode.EPHEMERAL_SEQUENTIAL); } public void process(WatchedEvent event) { LOG.debug("Received event: " + event); _zookeeperEventThread = Thread.currentThread(); boolean stateChanged = event.getPath() == null; boolean znodeChanged = event.getPath() != null; boolean dataChanged = event.getType() == EventType.NodeDataChanged || // event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated || // event.getType() == EventType.NodeChildrenChanged; getEventLock().lock(); try { // We might have to install child change event listener if a new node was created if (getShutdownTrigger()) { LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered"); return; } if (stateChanged) { processStateChanged(event); } if (dataChanged) { processDataOrChildChange(event); } } finally { if (stateChanged) { getEventLock().getStateChangedCondition().signalAll(); // If the session expired we have to signal all conditions, because watches might have been removed and // there is no guarantee that those // conditions will be signaled at all after an Expired event if (event.getState() == KeeperState.Expired) { getEventLock().getZNodeEventCondition().signalAll(); getEventLock().getDataChangedCondition().signalAll(); // We also have to notify all listeners that something might have changed fireAllEvents(); } } if (znodeChanged) { getEventLock().getZNodeEventCondition().signalAll(); } if (dataChanged) { getEventLock().getDataChangedCondition().signalAll(); } getEventLock().unlock(); LOG.debug("Leaving process event"); } } private void fireAllEvents() { for (Entry<String, Set<IZkChildListener>> entry : _childListener.entrySet()) { fireChildChangedEvents(entry.getKey(), entry.getValue()); } for (Entry<String, Set<IZkDataListener>> entry : _dataListener.entrySet()) { fireDataChangedEvents(entry.getKey(), entry.getValue()); } } public List<String> getChildren(String path) { return getChildren(path, hasListeners(path)); } protected List<String> getChildren(final String path, final boolean watch) { try { return retryUntilConnected(new Callable<List<String>>() { @Override public List<String> call() throws Exception { return _connection.getChildren(path, watch); } }); } catch (ZkNoNodeException e) { return null; } } public int countChildren(String path) { try { Stat stat = new Stat(); this.readData(path, stat); return stat.getNumChildren(); //return getChildren(path).size(); } catch (ZkNoNodeException e) { return -1; } } protected boolean exists(final String path, final boolean watch) { return retryUntilConnected(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return _connection.exists(path, watch); } }); } public boolean exists(final String path) { return exists(path, hasListeners(path)); } private void processStateChanged(WatchedEvent event) { LOG.info("zookeeper state changed (" + event.getState() + ")"); setCurrentState(event.getState()); if (getShutdownTrigger()) { return; } try { fireStateChangedEvent(event.getState()); if (event.getState() == KeeperState.Expired) { reconnect(); fireNewSessionEvents(); } } catch (final Exception e) { throw new RuntimeException("Exception while restarting zk client", e); } } private void fireNewSessionEvents() { for (final IZkStateListener stateListener : _stateListener) { _eventThread.send(new ZkEvent("New session event sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleNewSession(); } }); } } private void fireStateChangedEvent(final KeeperState state) { for (final IZkStateListener stateListener : _stateListener) { _eventThread.send(new ZkEvent("State changed to " + state + " sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleStateChanged(state); } }); } } private boolean hasListeners(String path) { Set<IZkDataListener> dataListeners = _dataListener.get(path); if (dataListeners != null && dataListeners.size() > 0) { return true; } Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && childListeners.size() > 0) { return true; } return false; } public boolean deleteRecursive(String path) { List<String> children; try { children = getChildren(path, false); } catch (ZkNoNodeException e) { return true; } if (children != null){ for (String subPath : children) { if (!deleteRecursive(path + "/" + subPath)) { return false; } } } return delete(path); } private void processDataOrChildChange(WatchedEvent event) { final String path = event.getPath(); if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && !childListeners.isEmpty()) { fireChildChangedEvents(path, childListeners); } } if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { Set<IZkDataListener> listeners = _dataListener.get(path); if (listeners != null && !listeners.isEmpty()) { fireDataChangedEvents(event.getPath(), listeners); } } } private void fireDataChangedEvents(final String path, Set<IZkDataListener> listeners) { for (final IZkDataListener listener : listeners) { _eventThread.send(new ZkEvent("Data of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { // reinstall watch exists(path, true); try { byte[] data = readData(path, null, true); listener.handleDataChange(path, data); } catch (ZkNoNodeException e) { listener.handleDataDeleted(path); } } }); } } private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners) { try { // reinstall the watch for (final IZkChildListener listener : childListeners) { _eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { try { // if the node doesn't exist we should listen for the root node to reappear exists(path); List<String> children = getChildren(path); listener.handleChildChange(path, children); } catch (ZkNoNodeException e) { listener.handleChildChange(path, null); } } }); } } catch (Exception e) { LOG.error("Failed to fire child changed event. Unable to getChildren. ", e); } } public boolean waitUntilExists(String path, TimeUnit timeUnit, long time) throws ZkInterruptedException { Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); LOG.debug("Waiting until znode '" + path + "' becomes available."); if (exists(path)) { return true; } acquireEventLock(); try { while (!exists(path, true)) { boolean gotSignal = getEventLock().getZNodeEventCondition().awaitUntil(timeout); if (!gotSignal) { return false; } } return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } } public boolean waitUntilConnected() throws ZkInterruptedException { return waitUntilConnected(Integer.MAX_VALUE, TimeUnit.MILLISECONDS); } public boolean waitUntilConnected(long time, TimeUnit timeUnit) throws ZkInterruptedException { return waitForKeeperState(KeeperState.SyncConnected, time, timeUnit); } public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); } Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); LOG.debug("Waiting for keeper state " + keeperState); acquireEventLock(); try { boolean stillWaiting = true; while (_currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); } LOG.debug("State is " + _currentState); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } } private void acquireEventLock() { try { getEventLock().lockInterruptibly(); } catch (InterruptedException e) { throw new ZkInterruptedException(e); } } /** * @param callable the callable object * @param <E> the runtime type of result * @return result of Callable * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException if any other exception occurs from invoking the Callable */ public <E> E retryUntilConnected(Callable<E> callable) { if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); } while (true) { try { return callable.call(); } catch (ConnectionLossException e) { // we give the event thread some time to update the status to 'Disconnected' Thread.yield(); waitUntilConnected(); } catch (SessionExpiredException e) { // we give the event thread some time to update the status to 'Expired' Thread.yield(); waitUntilConnected(); } catch (KeeperException e) { throw ZkException.create(e); } catch (InterruptedException e) { throw new ZkInterruptedException(e); } catch (Exception e) { throw ZkClientUtils.convertToRuntimeException(e); } } } public void setCurrentState(KeeperState currentState) { getEventLock().lock(); try { _currentState = currentState; } finally { getEventLock().unlock(); } } /** * Returns a mutex all zookeeper events are synchronized aginst. So in case you need to do * something without getting any zookeeper event interruption synchronize against this * mutex. Also all threads waiting on this mutex object will be notified on an event. * * @return the mutex. */ public ZkLock getEventLock() { return _zkEventLock; } public boolean delete(final String path) { try { retryUntilConnected(new Callable<byte[]>() { @Override public byte[] call() throws Exception { _connection.delete(path); return null; } }); return true; } catch (ZkNoNodeException e) { return false; } } public byte[] readData(String path) { return readData(path, false); } public byte[] readData(String path, boolean returnNullIfPathNotExists) { byte[] data = null; try { data = readData(path, null); } catch (ZkNoNodeException e) { if (!returnNullIfPathNotExists) { throw e; } } return data; } public byte[] readData(String path, Stat stat) { return readData(path, stat, hasListeners(path)); } protected byte[] readData(final String path, final Stat stat, final boolean watch) { byte[] data = retryUntilConnected(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return _connection.readData(path, stat, watch); } }); return data; } public Stat writeData(String path, byte[] object) { return writeData(path, object, -1); } public void cas(String path, DataUpdater updater) { Stat stat = new Stat(); boolean retry; do { retry = false; try { byte[] oldData = readData(path, stat); byte[] newData = updater.update(oldData); writeData(path, newData, stat.getVersion()); } catch (ZkBadVersionException e) { retry = true; } } while (retry); } public Stat writeData(final String path, final byte[] data, final int expectedVersion) { return retryUntilConnected(new Callable<Stat>() { @Override public Stat call() throws Exception { return _connection.writeData(path, data, expectedVersion); } }); } public void watchForData(final String path) { retryUntilConnected(new Callable<Object>() { @Override public Object call() throws Exception { _connection.exists(path, true); return null; } }); } public List<String> watchForChilds(final String path) { if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); } return retryUntilConnected(new Callable<List<String>>() { @Override public List<String> call() throws Exception { exists(path, true); try { return getChildren(path, true); } catch (ZkNoNodeException e) { // ignore, the "exists" watch will listen for the parent node to appear } return null; } }); } public synchronized void connect(final long maxMsToWaitUntilConnected, Watcher watcher) { if (_eventThread != null) { return; } boolean started = false; try { getEventLock().lockInterruptibly(); setShutdownTrigger(false); _eventThread = new ZkEventThread(_connection.getServers()); _eventThread.start(); _connection.connect(watcher); LOG.debug("Awaiting connection to Zookeeper server: " + maxMsToWaitUntilConnected); if (!waitUntilConnected(maxMsToWaitUntilConnected, TimeUnit.MILLISECONDS)) { throw new ZkTimeoutException(String.format( "Unable to connect to zookeeper server[%s] within timeout %dms", _connection.getServers(), maxMsToWaitUntilConnected)); } started = true; } catch (InterruptedException e) { States state = _connection.getZookeeperState(); throw new IllegalStateException("Not connected with zookeeper server yet. Current state is " + state); } finally { getEventLock().unlock(); // we should close the zookeeper instance, otherwise it would keep // on trying to connect if (!started) { close(); } } } public long getCreationTime(String path) { try { getEventLock().lockInterruptibly(); return _connection.getCreateTime(path); } catch (KeeperException e) { throw ZkException.create(e); } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } } public synchronized void close() throws ZkInterruptedException { if (_eventThread == null) { return; } LOG.debug("Closing ZkClient..."); getEventLock().lock(); try { setShutdownTrigger(true); _currentState = null; _eventThread.interrupt(); _eventThread.join(2000); _connection.close(); _eventThread = null; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } LOG.debug("Closing ZkClient...done"); } private void reconnect() { getEventLock().lock(); try { _connection.close(); _connection.connect(this); } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } } private void setShutdownTrigger(boolean triggerState) { _shutdownTriggered = triggerState; } private boolean getShutdownTrigger() { return _shutdownTriggered; } public int numberOfListeners() { int listeners = 0; for (Set<IZkChildListener> childListeners : _childListener.values()) { listeners += childListeners.size(); } for (Set<IZkDataListener> dataListeners : _dataListener.values()) { listeners += dataListeners.size(); } listeners += _stateListener.size(); return listeners; } @Override public List<?> multi(final Iterable<?> ops) { return retryUntilConnected(new Callable<List<?>>() { @Override public List<?> call() throws Exception { return _connection.multi(ops); } }); } @Override public ZooKeeper getZooKeeper() { return _connection != null ? _connection.getZooKeeper() : null; } @Override public boolean isConnected() { return _currentState == KeeperState.SyncConnected; } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ServerCnxnFactory.java
src/main/java/com/github/zkclient/ServerCnxnFactory.java
/** * */ package com.github.zkclient; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import org.apache.zookeeper.server.ZooKeeperServer; import com.github.zkclient.ZkClientUtils.ZkVersion; /** * Adapter for zookeeper 3.3.x/3.4.x * * @author adyliu (imxylz@gmail.com) * @since 2012-11-27 */ public class ServerCnxnFactory { private static final String zk33Factory = "org.apache.zookeeper.server.NIOServerCnxn$Factory"; private static final String zk34Factory = "org.apache.zookeeper.server.ServerCnxnFactory"; private Object target = null; private Method shutdownMethod = null; private Method joinMethod = null; private Method startupMethod = null; public void startup(ZooKeeperServer server) throws InterruptedException { try { startupMethod.invoke(target, server); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof InterruptedException) { throw (InterruptedException) t; } throw new RuntimeException(t); } } private static ServerCnxnFactory createFactory(final String hostname, int port, int maxcc) { ServerCnxnFactory factory = new ServerCnxnFactory(); try { if (ZkClientUtils.zkVersion == ZkVersion.V33) { Class<?> clazz = Class.forName(zk33Factory); factory.target = clazz.getDeclaredConstructor(InetSocketAddress.class).newInstance(new InetSocketAddress(port)); factory.shutdownMethod = clazz.getDeclaredMethod("shutdown", new Class[0]); factory.joinMethod = clazz.getMethod("join", new Class[0]); factory.startupMethod = clazz.getDeclaredMethod("startup", ZooKeeperServer.class); } else { Class<?> clazz = Class.forName(zk34Factory); factory.target = clazz.getMethod("createFactory", int.class, int.class).invoke(null, port, maxcc); factory.shutdownMethod = clazz.getDeclaredMethod("shutdown", new Class[0]); factory.joinMethod = clazz.getDeclaredMethod("join", new Class[0]); factory.startupMethod = clazz.getMethod("startup", ZooKeeperServer.class); } } catch (IllegalArgumentException e) { throw new RuntimeException("unsupported zookeeper version", e); } catch (SecurityException e) { throw new RuntimeException(e.getMessage(), e); } catch (InstantiationException e) { throw new RuntimeException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } catch (NoSuchMethodException e) { throw new RuntimeException("unsupported zookeeper version", e); } catch (ClassNotFoundException e) { throw new RuntimeException("unsupported zookeeper version", e); } return factory; } public static ServerCnxnFactory createFactory(int port, int maxcc) { return createFactory(null, port, maxcc); } public void shutdown() { try { shutdownMethod.invoke(target, new Object[0]); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); throw new RuntimeException(t); } } public void join() throws InterruptedException { try { joinMethod.invoke(target, new Object[0]); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof InterruptedException) { throw (InterruptedException) t; } throw new RuntimeException(t); } } public static void main(String[] args) throws Exception { ServerCnxnFactory factory = ServerCnxnFactory.createFactory(8123, 60); factory.shutdown(); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/IZkStateListener.java
src/main/java/com/github/zkclient/IZkStateListener.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import org.apache.zookeeper.Watcher.Event.KeeperState; public interface IZkStateListener { /** * Called when the zookeeper connection state has changed. * * @param state The new state. * @throws Exception On any error. */ public void handleStateChanged(KeeperState state) throws Exception; /** * Called after the zookeeper session has expired and a new session has been created. You would have to re-create * any ephemeral nodes here. * * @throws Exception On any error. */ public void handleNewSession() throws Exception; }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkEventThread.java
src/main/java/com/github/zkclient/ZkEventThread.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import com.github.zkclient.exception.ZkInterruptedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * All listeners registered at the {@link ZkClient} will be notified from this event thread. * This is to prevent dead-lock situations. The {@link ZkClient} pulls some information out of * the {@link org.apache.zookeeper.ZooKeeper} events to signal {@link ZkLock} conditions. Re-using the * {@link org.apache.zookeeper.ZooKeeper} event thread to also notify {@link ZkClient} listeners, would stop the * ZkClient from receiving events from {@link org.apache.zookeeper.ZooKeeper} as soon as one of the listeners blocks * (because it is waiting for something). {@link ZkClient} would then for instance not be able * to maintain it's connection state anymore. */ class ZkEventThread extends Thread { private static final Logger LOG = LoggerFactory.getLogger(ZkEventThread.class); private final BlockingQueue<ZkEvent> _events = new LinkedBlockingQueue<ZkEvent>(); private static final AtomicInteger _eventId = new AtomicInteger(0); private volatile boolean shutdown = false; static abstract class ZkEvent { private final String _description; public ZkEvent(String description) { _description = description; } public abstract void run() throws Exception; @Override public String toString() { return "ZkEvent[" + _description + "]"; } } ZkEventThread(String name) { setDaemon(true); setName("ZkClient-EventThread-" + getId() + "-" + name); } @Override public void run() { LOG.info("Starting ZkClient event thread."); try { while (!isShutdown()) { ZkEvent zkEvent = _events.take(); int eventId = _eventId.incrementAndGet(); LOG.debug("Delivering event #" + eventId + " " + zkEvent); try { zkEvent.run(); } catch (InterruptedException e) { shutdown(); } catch (ZkInterruptedException e) { shutdown(); } catch (Throwable e) { LOG.error("Error handling event " + zkEvent, e); } LOG.debug("Delivering event #" + eventId + " done"); } } catch (InterruptedException e) { LOG.info("Terminate ZkClient event thread."); } } /** * @return the shutdown */ public boolean isShutdown() { return shutdown || isInterrupted(); } public void shutdown() { this.shutdown = true; this.interrupt(); } public void send(ZkEvent event) { if (!isShutdown()) { LOG.debug("New event: " + event); _events.add(event); } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkConnection.java
src/main/java/com/github/zkclient/ZkConnection.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper.States; import org.apache.zookeeper.data.Stat; import com.github.zkclient.exception.ZkException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZkConnection { private static final Logger LOG = LoggerFactory.getLogger(ZkConnection.class); private ZooKeeper _zk = null; private final Lock _zookeeperLock = new ReentrantLock(); private final String _servers; private final int _sessionTimeOut; private static final Method method; static { Method[] methods = ZooKeeper.class.getDeclaredMethods(); Method m = null; for (Method method : methods) { if (method.getName().equals("multi")) { m = method; break; } } method = m; } /** * build a zookeeper connection * @param zkServers zookeeper connection string * @param sessionTimeOut session timeout in milliseconds */ public ZkConnection(String zkServers, int sessionTimeOut) { _servers = zkServers; _sessionTimeOut = sessionTimeOut; } public void connect(Watcher watcher) { _zookeeperLock.lock(); try { if (_zk != null) { throw new IllegalStateException("zk client has already been started"); } try { LOG.debug("Creating new ZookKeeper instance to connect to " + _servers + "."); _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); } catch (IOException e) { throw new ZkException("Unable to connect to " + _servers, e); } } finally { _zookeeperLock.unlock(); } } public void close() throws InterruptedException { _zookeeperLock.lock(); try { if (_zk != null) { LOG.debug("Closing ZooKeeper connected to " + _servers); _zk.close(); _zk = null; } } finally { _zookeeperLock.unlock(); } } public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { return _zk.create(path, data, Ids.OPEN_ACL_UNSAFE, mode); } public void delete(String path) throws InterruptedException, KeeperException { _zk.delete(path, -1); } public boolean exists(String path, boolean watch) throws KeeperException, InterruptedException { return _zk.exists(path, watch) != null; } public List<String> getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { return _zk.getChildren(path, watch); } public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException { return _zk.getData(path, watch, stat); } /** * wrapper for 3.3.x/3.4.x * * @param ops multi operations * @return OpResult list */ @SuppressWarnings("unchecked") public List<?> multi(Iterable<?> ops) { if (method == null) throw new UnsupportedOperationException("multi operation must use zookeeper 3.4+"); try { return (List<?>) method.invoke(_zk, ops); } catch (IllegalArgumentException e) { throw new UnsupportedOperationException("ops must be 'org.apache.zookeeper.Op'"); } catch (IllegalAccessException e) { throw new UnsupportedOperationException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } public Stat writeData(String path, byte[] data, int version) throws KeeperException, InterruptedException { return _zk.setData(path, data, version); } public States getZookeeperState() { return _zk != null ? _zk.getState() : null; } public long getCreateTime(String path) throws KeeperException, InterruptedException { Stat stat = _zk.exists(path, false); if (stat != null) { return stat.getCtime(); } return -1; } public String getServers() { return _servers; } public ZooKeeper getZooKeeper() { return _zk; } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/IZkClient.java
src/main/java/com/github/zkclient/IZkClient.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 com.github.zkclient; import com.github.zkclient.exception.ZkException; import com.github.zkclient.exception.ZkInterruptedException; import com.github.zkclient.exception.ZkNoNodeException; import com.github.zkclient.exception.ZkNodeExistsException; import com.github.zkclient.exception.ZkTimeoutException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import java.io.Closeable; import java.util.List; import java.util.concurrent.TimeUnit; /** * zookeeper client wrapper * * @author adyliu (imxylz@gmail.com) * @since 2.0 */ public interface IZkClient extends Closeable { int DEFAULT_CONNECTION_TIMEOUT = 10000; int DEFAULT_SESSION_TIMEOUT = 30000; /** * Close the client. * * @throws ZkInterruptedException if interrupted while closing */ void close(); /** * Connect to ZooKeeper. * * @param timeout max waiting time(ms) until connected * @param watcher default watcher * @throws ZkInterruptedException if the connection timed out due to thread interruption * @throws ZkTimeoutException if the connection timed out * @throws IllegalStateException if the connection timed out due to thread interruption */ void connect(final long timeout, Watcher watcher); /** * Counts number of children for the given path. * * @param path zk path * @return number of children or 0 if path does not exist. */ int countChildren(String path); /** * Create a node. * * @param path zk path * @param data node data * @param mode create mode {@link CreateMode} * @return created path * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred */ String create(final String path, byte[] data, final CreateMode mode); /** * Create an ephemeral node with empty data * * @param path zk path * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred */ void createEphemeral(final String path); /** * Create an ephemeral node. * * @param path the path for the node * @param data node data * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred */ void createEphemeral(final String path, final byte[] data); /** * Create an ephemeral, sequential node. * * @param path the path for the node * @param data the data for the node * @return created path * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred */ String createEphemeralSequential(final String path, final byte[] data); /** * Create a persistent node with empty data (null) * * @param path the path for the node * @throws ZkNodeExistsException if the node exists * @throws ZkNoNodeException if the parent node not exists * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException any other exception * @see #createPersistent(String, boolean) */ void createPersistent(String path); /** * Create a persistent node with empty data (null) * <p> * If the createParents is true, neither {@link ZkNodeExistsException} nor {@link com.github.zkclient.exception.ZkNoNodeException} were throwed. * </p> * * @param path the path for the node * @param createParents if true all parent dirs are created as well and no * {@link ZkNodeExistsException} is thrown in case the path already exists * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException any other exception */ void createPersistent(String path, boolean createParents); /** * Create a persistent node. * * @param path the path for the node * @param data node data * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException any other exception */ void createPersistent(String path, byte[] data); /** * Create a persistent, sequental node. * * @param path the path for the node * @param data node data * @return create node's path * @throws ZkInterruptedException if operation was interrupted, or a required reconnection * got interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event * thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException any other exception */ String createPersistentSequential(String path, byte[] data); /** * delete a node * * @param path the path for the node * @return true if deleted; otherwise false */ boolean delete(final String path); /** * delete a node with all children * * @param path the path for the node * @return true if all deleted; otherwise false */ boolean deleteRecursive(String path); /** * check the node exists * * @param path the path for the node * @return true if the node exists */ boolean exists(final String path); /** * get the children for the node * * @param path the path for the node * @return the children node names or null (then node not exists) */ List<String> getChildren(String path); /** * get the node creation time (unix milliseconds) * * @param path the path for the node * @return the unix milliseconds or -1 if node not exists */ long getCreationTime(String path); /** * all watcher number in this connection * * @return watcher number */ int numberOfListeners(); /** * read the data for the node * * @param path the path for the node * @return the data for the node * @throws com.github.zkclient.exception.ZkNoNodeException if the node not exists * @see #readData(String, boolean) */ byte[] readData(String path); /** * read the data for the node * * @param path the path for the node * @param returnNullIfPathNotExists if true no {@link com.github.zkclient.exception.ZkNoNodeException} thrown * @return the data for the node */ byte[] readData(String path, boolean returnNullIfPathNotExists); /** * read the data and stat for the node * * @param path the path for the node * @param stat the stat for the node * @return the data for the node * @see #readData(String, boolean) */ byte[] readData(String path, Stat stat); /** * subscribe the changing for children * * @param path the path for the node * @param listener the listener * @return the children list or null if the node not exists * @see IZkChildListener */ List<String> subscribeChildChanges(String path, IZkChildListener listener); /** * subscribe the data changing for the node * * @param path the path for the node * @param listener the data changing listener * @see IZkDataListener */ void subscribeDataChanges(String path, IZkDataListener listener); /** * subscribe the connection state * * @param listener the connection listener * @see IZkStateListener */ void subscribeStateChanges(IZkStateListener listener); /** * unsubscribe all listeners for all path and connection state */ void unsubscribeAll(); /** * unsubscribe the child listener * * @param path the path for the node * @param childListener the listener */ void unsubscribeChildChanges(String path, IZkChildListener childListener); /** * unsubscribe the data changing for the node * * @param path the path for the node * @param dataListener the data changing listener */ void unsubscribeDataChanges(String path, IZkDataListener dataListener); /** * unsubscribe the connection state * * @param stateListener the connection listener */ void unsubscribeStateChanges(IZkStateListener stateListener); /** * Updates data of an existing znode. The current content of the znode is passed to the * {@link DataUpdater} that is passed into this method, which returns the new content. The * new content is only written back to ZooKeeper if nobody has modified the given znode in * between. If a concurrent change has been detected the new data of the znode is passed to * the updater once again until the new contents can be successfully written back to * ZooKeeper. * * @param path the path for the node * @param updater Updater that creates the new contents. */ void cas(String path, DataUpdater updater); /** * wait some time for the state * * @param keeperState the state * @param time some time * @param timeUnit the time unit * @return true if the connection state is the <code>keeperState</code> before the end time */ boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit); /** * wait for the connected state. * <pre> * waitForKeeperState(KeeperState.SyncConnected, Integer.MAX_VALUE, TimeUnit.MILLISECONDS); * </pre> * * @return true if the client connects the server * @throws ZkInterruptedException the thread was interrupted * @see #waitForKeeperState(org.apache.zookeeper.Watcher.Event.KeeperState, long, java.util.concurrent.TimeUnit) */ boolean waitUntilConnected() throws ZkInterruptedException; /** * wait for the connected state * * @param time soem time * @param timeUnit the time unit * @return true if the client connects the server before the end time */ boolean waitUntilConnected(long time, TimeUnit timeUnit); /** * wait some unit until the node exists * * @param path the path for the node * @param timeUnit the time unit * @param time some time * @return true if the node exists */ boolean waitUntilExists(String path, TimeUnit timeUnit, long time); /** * write the data for the node * * @param path the path for the node * @param data the data for the node * @return the stat for the node */ Stat writeData(String path, byte[] data); /** * write the data for the node * * @param path the path for the node * @param data the data for the node * @param expectedVersion the version for the node * @return the stat for the node * @see #cas(String, com.github.zkclient.IZkClient.DataUpdater) */ Stat writeData(String path, byte[] data, int expectedVersion); /** * multi operation for zookeeper 3.4.x * * @param ops operations * @return op result * @see org.apache.zookeeper.ZooKeeper#multi(Iterable) * @see org.apache.zookeeper.Op * @see org.apache.zookeeper.OpResult */ List<?> multi(Iterable<?> ops); /** * get the inner zookeeper client * * @return the inner zookeeper client */ ZooKeeper getZooKeeper(); /** * check the connecting state of zookeeper client * @return true if connected */ boolean isConnected(); /** * A CAS operation */ interface DataUpdater { /** * Updates the current data of a znode. * * @param currentData The current contents. * @return the new data that should be written back to ZooKeeper. */ public byte[] update(byte[] currentData); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/ZkClientUtils.java
src/main/java/com/github/zkclient/ZkClientUtils.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.zkclient; import java.io.IOException; import java.net.*; import com.github.zkclient.exception.ZkInterruptedException; public class ZkClientUtils { private ZkClientUtils() {} public static enum ZkVersion { V33, V34 } public static final ZkVersion zkVersion; static { ZkVersion version = null; try { Class.forName("org.apache.zookeeper.OpResult"); version = ZkVersion.V34; } catch (ClassNotFoundException e) { version = ZkVersion.V33; } finally { zkVersion = version; } } public static RuntimeException convertToRuntimeException(Throwable e) { if (e instanceof RuntimeException) { return (RuntimeException) e; } retainInterruptFlag(e); return new RuntimeException(e); } /** * This sets the interrupt flag if the catched exception was an * {@link InterruptedException}. Catching such an exception always clears * the interrupt flag. * * @param catchedException * The catched exception. */ public static void retainInterruptFlag(Throwable catchedException) { if (catchedException instanceof InterruptedException) { Thread.currentThread().interrupt(); } } public static void rethrowInterruptedException(Throwable e) throws InterruptedException { if (e instanceof InterruptedException) { throw (InterruptedException) e; } if (e instanceof ZkInterruptedException) { throw (ZkInterruptedException) e; } } public static String leadingZeros(long number, int numberOfLeadingZeros) { return String.format("%0" + numberOfLeadingZeros + "d", number); } public final static String OVERWRITE_HOSTNAME_SYSTEM_PROPERTY = "zkclient.hostname.overwritten"; public static boolean isPortFree(int port) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress("localhost", port), 200); socket.close(); return false; } catch (SocketTimeoutException e) { return true; } catch (ConnectException e) { return true; } catch (SocketException e) { if (e.getMessage().equals("Connection reset by peer")) { return true; } throw new RuntimeException(e); } catch (UnknownHostException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public static String getLocalhostName() { String property = System.getProperty(OVERWRITE_HOSTNAME_SYSTEM_PROPERTY); if (property != null && property.trim().length() > 0) { return property; } try { return InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { throw new RuntimeException("unable to retrieve localhost name"); } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/IZkDataListener.java
src/main/java/com/github/zkclient/IZkDataListener.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient; /** * An {@link IZkDataListener} can be registered at a {@link ZkClient} for listening on zk data changes for a given path. * <p> * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not * guaranteed that events on the path are missing (see http://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkWatches). An * implementation of this class should take that into account. */ public interface IZkDataListener { public void handleDataChange(String dataPath, byte[] data) throws Exception; public void handleDataDeleted(String dataPath) throws Exception; }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkTimeoutException.java
src/main/java/com/github/zkclient/exception/ZkTimeoutException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; public class ZkTimeoutException extends ZkException { private static final long serialVersionUID = 1L; public ZkTimeoutException() { super(); } public ZkTimeoutException(String message, Throwable cause) { super(message, cause); } public ZkTimeoutException(String message) { super(message); } public ZkTimeoutException(Throwable cause) { super(cause); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkInterruptedException.java
src/main/java/com/github/zkclient/exception/ZkInterruptedException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; public class ZkInterruptedException extends ZkException { private static final long serialVersionUID = 1L; public ZkInterruptedException(InterruptedException e) { super(e); Thread.currentThread().interrupt(); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkNoNodeException.java
src/main/java/com/github/zkclient/exception/ZkNoNodeException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; import org.apache.zookeeper.KeeperException; public class ZkNoNodeException extends ZkException { private static final long serialVersionUID = 1L; public ZkNoNodeException() { super(); } public ZkNoNodeException(KeeperException cause) { super(cause); } public ZkNoNodeException(String message, KeeperException cause) { super(message, cause); } public ZkNoNodeException(String message) { super(message); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkException.java
src/main/java/com/github/zkclient/exception/ZkException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; import org.apache.zookeeper.KeeperException; public class ZkException extends RuntimeException { private static final long serialVersionUID = 1L; public ZkException() { super(); } public ZkException(String message, Throwable cause) { super(message, cause); } public ZkException(String message) { super(message); } public ZkException(Throwable cause) { super(cause); } public static ZkException create(KeeperException e) { switch (e.code()) { // case DATAINCONSISTENCY: // return new DataInconsistencyException(); // case CONNECTIONLOSS: // return new ConnectionLossException(); case NONODE: return new ZkNoNodeException(e); // case NOAUTH: // return new ZkNoAuthException(); case BADVERSION: return new ZkBadVersionException(e); // case NOCHILDRENFOREPHEMERALS: // return new NoChildrenForEphemeralsException(); case NODEEXISTS: return new ZkNodeExistsException(e); // case INVALIDACL: // return new ZkInvalidACLException(); // case AUTHFAILED: // return new AuthFailedException(); // case NOTEMPTY: // return new NotEmptyException(); // case SESSIONEXPIRED: // return new SessionExpiredException(); // case INVALIDCALLBACK: // return new InvalidCallbackException(); default: return new ZkException(e); } } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkNodeExistsException.java
src/main/java/com/github/zkclient/exception/ZkNodeExistsException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; import org.apache.zookeeper.KeeperException; public class ZkNodeExistsException extends ZkException { private static final long serialVersionUID = 1L; public ZkNodeExistsException() { super(); } public ZkNodeExistsException(KeeperException cause) { super(cause); } public ZkNodeExistsException(String message, KeeperException cause) { super(message, cause); } public ZkNodeExistsException(String message) { super(message); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkBadVersionException.java
src/main/java/com/github/zkclient/exception/ZkBadVersionException.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; import org.apache.zookeeper.KeeperException; public class ZkBadVersionException extends ZkException { private static final long serialVersionUID = 1L; public ZkBadVersionException() { super(); } public ZkBadVersionException(KeeperException cause) { super(cause); } public ZkBadVersionException(String message, KeeperException cause) { super(message, cause); } public ZkBadVersionException(String message) { super(message); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
adyliu/zkclient
https://github.com/adyliu/zkclient/blob/5afdc7668fa16c148b36b992ce42db8973414886/src/main/java/com/github/zkclient/exception/ZkMarshallingError.java
src/main/java/com/github/zkclient/exception/ZkMarshallingError.java
/** * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.zkclient.exception; public class ZkMarshallingError extends ZkException { private static final long serialVersionUID = 1L; public ZkMarshallingError() { super(); } public ZkMarshallingError(Throwable cause) { super(cause); } public ZkMarshallingError(String message, Throwable cause) { super(message, cause); } public ZkMarshallingError(String message) { super(message); } }
java
Apache-2.0
5afdc7668fa16c148b36b992ce42db8973414886
2026-01-05T02:37:31.139483Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/test/java/com/restfulbooker/api/ApiTest.java
java/restassured/src/test/java/com/restfulbooker/api/ApiTest.java
package com.restfulbooker.api; import com.restfulbooker.api.api.AuthApi; import com.restfulbooker.api.api.BookingApi; import com.restfulbooker.api.payloads.*; import io.restassured.response.Response; import org.approvaltests.Approvals; import org.junit.jupiter.api.Test; import java.util.Date; public class ApiTest { @Test public void getBookingShouldReturn200(){ Response response = BookingApi.getBookings(); Approvals.verify(response.getStatusCode()); } @Test public void getBookingIdShouldReturn200(){ Response response = BookingApi.getBooking(1, "application/json"); Approvals.verify(response.getStatusCode()); } @Test public void getBookingIdWithBadAcceptShouldReturn418(){ Response response = BookingApi.getBooking(1, "text/plain"); Approvals.verify(response.getStatusCode()); } @Test public void postBookingReturns200(){ BookingDates dates = new BookingDates.Builder() .setCheckin(new Date()) .setCheckout(new Date()) .build(); Booking payload = new Booking.Builder() .setFirstname("Mary") .setLastname("White") .setTotalprice(200) .setDepositpaid(true) .setBookingdates(dates) .setAdditionalneeds("None") .build(); Response response = BookingApi.postBooking(payload); Approvals.verify(response.getStatusCode()); } @Test public void deleteBookingReturns201(){ BookingDates dates = new BookingDates.Builder() .setCheckin(new Date()) .setCheckout(new Date()) .build(); Booking payload = new Booking.Builder() .setFirstname("Mary") .setLastname("White") .setTotalprice(200) .setDepositpaid(true) .setBookingdates(dates) .setAdditionalneeds("None") .build(); BookingResponse createdBookingResponse = BookingApi.postBooking(payload).as(BookingResponse.class); Auth auth = new Auth.Builder() .setUsername("admin") .setPassword("password123") .build(); AuthResponse authResponse = AuthApi.postAuth(auth).as(AuthResponse.class); Response deleteResponse = BookingApi.deleteBooking( createdBookingResponse.getBookingid(), authResponse.getToken()); Approvals.verify(deleteResponse.getStatusCode()); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/api/BaseApi.java
java/restassured/src/main/java/com/restfulbooker/api/api/BaseApi.java
package com.restfulbooker.api.api; public class BaseApi { protected static final String baseUrl = "https://restful-booker.herokuapp.com/"; }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/api/BookingApi.java
java/restassured/src/main/java/com/restfulbooker/api/api/BookingApi.java
package com.restfulbooker.api.api; import com.restfulbooker.api.payloads.Booking; import io.restassured.http.ContentType; import io.restassured.response.Response; import static io.restassured.RestAssured.given; public class BookingApi extends BaseApi { private static final String apiUrl = baseUrl + "booking/"; public static Response getBookings(){ return given().get(apiUrl); } public static Response getBooking(int id, String mediaType) { return given() .header("Accept", mediaType) .get(apiUrl + Integer.toString(id)); } public static Response postBooking(Booking payload) { return given() .contentType(ContentType.JSON) .body(payload) .when() .post(apiUrl); } public static Response deleteBooking(int id, String tokenValue) { return given() .header("Cookie", "token=" + tokenValue) .delete(apiUrl + Integer.toString(id)); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/api/AuthApi.java
java/restassured/src/main/java/com/restfulbooker/api/api/AuthApi.java
package com.restfulbooker.api.api; import com.restfulbooker.api.payloads.Auth; import io.restassured.http.ContentType; import io.restassured.response.Response; import static io.restassured.RestAssured.given; public class AuthApi extends BaseApi { private static final String apiUrl = baseUrl + "auth/"; public static Response postAuth(Auth payload){ return given() .contentType(ContentType.JSON) .body(payload) .when() .post(apiUrl); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/payloads/BookingDates.java
java/restassured/src/main/java/com/restfulbooker/api/payloads/BookingDates.java
package com.restfulbooker.api.payloads; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; public class BookingDates { @JsonProperty private Date checkin; @JsonProperty private Date checkout; public Date getCheckin() { return checkin; } public Date getCheckout() { return checkout; } // default constructor required by Jackson private BookingDates() { // nothing here } private BookingDates(Date checkin, Date checkout){ this.checkin = checkin; this.checkout = checkout; } public static class Builder { private Date checkin; private Date checkout; public Builder setCheckin(Date checkin) { this.checkin = checkin; return this; } public Builder setCheckout(Date checkout) { this.checkout = checkout; return this; } public BookingDates build() { return new BookingDates(checkin, checkout); } } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/payloads/BookingResponse.java
java/restassured/src/main/java/com/restfulbooker/api/payloads/BookingResponse.java
package com.restfulbooker.api.payloads; import com.fasterxml.jackson.annotation.JsonProperty; public class BookingResponse { @JsonProperty private int bookingid; @JsonProperty private Booking booking; public int getBookingid() { return bookingid; } public Booking getBooking() { return booking; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/payloads/Auth.java
java/restassured/src/main/java/com/restfulbooker/api/payloads/Auth.java
package com.restfulbooker.api.payloads; import com.fasterxml.jackson.annotation.JsonProperty; public class Auth { @JsonProperty private String username; @JsonProperty private String password; public String getUsername() { return username; } public String getPassword() { return password; } private Auth(String username, String password) { this.username = username; this.password = password; } public static class Builder { private String username; private String password; public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; return this; } public Auth build(){ return new Auth(username, password); } } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/payloads/AuthResponse.java
java/restassured/src/main/java/com/restfulbooker/api/payloads/AuthResponse.java
package com.restfulbooker.api.payloads; import com.fasterxml.jackson.annotation.JsonProperty; public class AuthResponse { @JsonProperty private String token; public String getToken() { return token; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/restassured/src/main/java/com/restfulbooker/api/payloads/Booking.java
java/restassured/src/main/java/com/restfulbooker/api/payloads/Booking.java
package com.restfulbooker.api.payloads; import com.fasterxml.jackson.annotation.JsonProperty; public class Booking { @JsonProperty private String firstname; @JsonProperty private String lastname; @JsonProperty private int totalprice; @JsonProperty private boolean depositpaid; @JsonProperty private BookingDates bookingdates; @JsonProperty private String additionalneeds; public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public int getTotalprice() { return totalprice; } public boolean isDepositpaid() { return depositpaid; } public BookingDates getBookingdates() { return bookingdates; } public String getAdditionalneeds() { return additionalneeds; } // default constructor required by Jackson private Booking() { // nothing here } private Booking(String firstname, String lastname, int totalprice, boolean depositpaid, BookingDates bookingdates, String additionalneeds) { this.firstname = firstname; this.lastname = lastname; this.totalprice = totalprice; this.depositpaid = depositpaid; this.bookingdates = bookingdates; this.additionalneeds = additionalneeds; } public static class Builder { private String firstname; private String lastname; private int totalprice; private boolean depositpaid; private BookingDates bookingdates; private String additionalneeds; public Builder setFirstname(String firstname) { this.firstname = firstname; return this; } public Builder setLastname(String lastname) { this.lastname = lastname; return this; } public Builder setTotalprice(int totalprice) { this.totalprice = totalprice; return this; } public Builder setDepositpaid(boolean depositpaid) { this.depositpaid = depositpaid; return this; } public Builder setBookingdates(BookingDates bookingdates) { this.bookingdates = bookingdates; return this; } public Builder setAdditionalneeds(String additionalneeds) { this.additionalneeds = additionalneeds; return this; } public Booking build(){ return new Booking(firstname, lastname, totalprice, depositpaid, bookingdates, additionalneeds); } } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/test/java/com/restfulbooker/api/ApiTest.java
java/springmvc/src/test/java/com/restfulbooker/api/ApiTest.java
package com.restfulbooker.api; import com.restfulbooker.api.api.Auth; import com.restfulbooker.api.api.Booking; import com.restfulbooker.api.payloads.request.AuthPayload; import com.restfulbooker.api.payloads.request.BookingPayload; import com.restfulbooker.api.payloads.response.AuthResponse; import com.restfulbooker.api.payloads.response.BookingResponse; import org.approvaltests.Approvals; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import java.util.Date; import static org.junit.jupiter.api.Assertions.fail; public class ApiTest { @Test public void getBookingShouldReturn200(){ ResponseEntity<String> response = Booking.getBookings(); Approvals.verify(response.getStatusCode()); } @Test public void getBookingIdShouldReturn200(){ ResponseEntity<String> response = Booking.getBooking(1, MediaType.APPLICATION_JSON); Approvals.verify(response.getStatusCode()); } @Test public void getBookingIdWithBadAcceptShouldReturn418(){ try{ Booking.getBooking(1, MediaType.TEXT_PLAIN); fail("HttpClientError not thrown"); } catch (HttpClientErrorException e){ Approvals.verify(e.getStatusCode()); } } @Test public void postBookingReturns200(){ BookingPayload payload = new BookingPayload.BookingPayloadBuilder() .setFirstname("Mary") .setLastname("White") .setTotalprice(200) .setDepositpaid(true) .setCheckin(new Date()) .setCheckout(new Date()) .setAdditionalneeds("None") .build(); ResponseEntity<BookingResponse> response = Booking.postBooking(payload); Approvals.verify(response.getStatusCode()); } @Test public void deleteBookingReturns201(){ BookingPayload payload = new BookingPayload.BookingPayloadBuilder() .setFirstname("Mary") .setLastname("White") .setTotalprice(200) .setDepositpaid(true) .setCheckin(new Date()) .setCheckout(new Date()) .setAdditionalneeds("None") .build(); ResponseEntity<BookingResponse> createdBookingResponse = Booking.postBooking(payload); AuthPayload authPayload = new AuthPayload.AuthPayloadBuilder() .setUsername("admin") .setPassword("password123") .build(); ResponseEntity<AuthResponse> authResponse = Auth.postAuth(authPayload); ResponseEntity<String> deleteResponse = Booking.deleteBooking( createdBookingResponse.getBody().getBookingid(), authResponse.getBody().getToken()); Approvals.verify(deleteResponse.getStatusCode()); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/api/Auth.java
java/springmvc/src/main/java/com/restfulbooker/api/api/Auth.java
package com.restfulbooker.api.api; import com.restfulbooker.api.payloads.request.AuthPayload; import com.restfulbooker.api.payloads.response.AuthResponse; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; public class Auth { private static RestTemplate restTemplate = new RestTemplate(); public static ResponseEntity<AuthResponse> postAuth(AuthPayload payload){ HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity<AuthPayload> httpEntity = new HttpEntity<AuthPayload>(payload, requestHeaders); return restTemplate.exchange("https://restful-booker.herokuapp.com/auth", HttpMethod.POST, httpEntity, AuthResponse.class); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/api/Booking.java
java/springmvc/src/main/java/com/restfulbooker/api/api/Booking.java
package com.restfulbooker.api.api; import com.restfulbooker.api.payloads.request.BookingPayload; import com.restfulbooker.api.payloads.response.BookingResponse; import org.springframework.http.*; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import java.util.Collections; public class Booking { private static RestTemplate restTemplate = new RestTemplate(); private static String baseUrl = "https://restful-booker.herokuapp.com"; public static ResponseEntity<String> getBookings(){ return restTemplate.getForEntity(baseUrl + "/booking", String.class); } public static ResponseEntity<String> getBooking(int id, MediaType accept) throws HttpClientErrorException { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(accept)); HttpEntity<String> httpEntity = new HttpEntity<String>(requestHeaders); return restTemplate.exchange(baseUrl + "/booking/" + Integer.toString(id), HttpMethod.GET, httpEntity, String.class); } public static ResponseEntity<BookingResponse> postBooking(BookingPayload payload) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); HttpEntity<BookingPayload> httpEntity = new HttpEntity<BookingPayload>(payload, requestHeaders); return restTemplate.exchange(baseUrl + "/booking", HttpMethod.POST, httpEntity, BookingResponse.class); } public static ResponseEntity<String> deleteBooking(int id, String tokenValue) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Cookie","token=" + tokenValue); HttpEntity<String> httpEntity = new HttpEntity<String>(requestHeaders); return restTemplate.exchange(baseUrl + "/booking/" + Integer.toString(id), HttpMethod.DELETE, httpEntity, String.class); } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingResponse.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingResponse.java
package com.restfulbooker.api.payloads.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class BookingResponse { @JsonProperty private int bookingid; @JsonProperty private BookingDetails booking; public void setBookingid(int bookingid) { this.bookingid = bookingid; } public void setBooking(BookingDetails booking) { this.booking = booking; } public int getBookingid() { return bookingid; } public BookingDetails getBooking() { return booking; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingDetailsDates.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingDetailsDates.java
package com.restfulbooker.api.payloads.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; @JsonIgnoreProperties(ignoreUnknown = true) public class BookingDetailsDates { @JsonProperty private Date checkin; @JsonProperty private Date checkout; public Date getCheckin() { return checkin; } public Date getCheckout() { return checkout; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/AuthResponse.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/AuthResponse.java
package com.restfulbooker.api.payloads.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class AuthResponse { @JsonProperty private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingDetails.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/response/BookingDetails.java
package com.restfulbooker.api.payloads.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class BookingDetails { @JsonProperty private String firstname; @JsonProperty private String lastname; @JsonProperty private int totalprice; @JsonProperty private boolean depositpaid; @JsonProperty private BookingDetailsDates bookingdates; @JsonProperty private String additionalneeds; public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public void setTotalprice(int totalprice) { this.totalprice = totalprice; } public void setDepositpaid(boolean depositpaid) { this.depositpaid = depositpaid; } public void setBookingdates(BookingDetailsDates bookingdates) { this.bookingdates = bookingdates; } public void setAdditionalneeds(String additionalneeds) { this.additionalneeds = additionalneeds; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/AuthPayload.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/AuthPayload.java
package com.restfulbooker.api.payloads.request; import com.fasterxml.jackson.annotation.JsonProperty; public class AuthPayload { @JsonProperty private String username; @JsonProperty private String password; private AuthPayload(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } public static class AuthPayloadBuilder{ private String username; private String password; public AuthPayloadBuilder setUsername(String username) { this.username = username; return this; } public AuthPayloadBuilder setPassword(String password) { this.password = password; return this; } public AuthPayload build(){ return new AuthPayload(username, password); } } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/BookingPayload.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/BookingPayload.java
package com.restfulbooker.api.payloads.request; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; public class BookingPayload { @JsonProperty private String firstname; @JsonProperty private String lastname; @JsonProperty private int totalprice; @JsonProperty private boolean depositpaid; @JsonProperty private BookingDatesPayload bookingdates; @JsonProperty private String additionalneeds; public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public int getTotalprice() { return totalprice; } public boolean isDepositpaid() { return depositpaid; } public BookingDatesPayload getBookingdates() { return bookingdates; } public String getAdditionalneeds() { return additionalneeds; } private BookingPayload(String firstname, String lastname, int totalprice, boolean depositpaid, BookingDatesPayload bookingdates, String additionalneeds) { this.firstname = firstname; this.lastname = lastname; this.totalprice = totalprice; this.depositpaid = depositpaid; this.bookingdates = bookingdates; this.additionalneeds = additionalneeds; } public static class BookingPayloadBuilder { private String firstname; private String lastname; private int totalprice; private boolean depositpaid; private Date checkin; private Date checkout; private String additionalneeds; public BookingPayloadBuilder setFirstname(String firstname) { this.firstname = firstname; return this; } public BookingPayloadBuilder setLastname(String lastname) { this.lastname = lastname; return this; } public BookingPayloadBuilder setTotalprice(int totalprice) { this.totalprice = totalprice; return this; } public BookingPayloadBuilder setDepositpaid(boolean depositpaid) { this.depositpaid = depositpaid; return this; } public BookingPayloadBuilder setCheckin(Date checkin) { this.checkin = checkin; return this; } public BookingPayloadBuilder setCheckout(Date checkout) { this.checkout = checkout; return this; } public BookingPayloadBuilder setAdditionalneeds(String additionalneeds) { this.additionalneeds = additionalneeds; return this; } public BookingPayload build(){ BookingDatesPayload bookingDates = new BookingDatesPayload(checkin, checkout); return new BookingPayload(firstname, lastname, totalprice, depositpaid, bookingDates, additionalneeds); } } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
mwinteringham/api-framework
https://github.com/mwinteringham/api-framework/blob/f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b/java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/BookingDatesPayload.java
java/springmvc/src/main/java/com/restfulbooker/api/payloads/request/BookingDatesPayload.java
package com.restfulbooker.api.payloads.request; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; public class BookingDatesPayload { @JsonProperty private Date checkin; @JsonProperty private Date checkout; public BookingDatesPayload(Date checkin, Date checkout){ this.checkin = checkin; this.checkout = checkout; } public Date getCheckin() { return checkin; } public Date getCheckout() { return checkout; } }
java
MIT
f33c7d8243af5561e5b18b0b2fb2f8a86e209a2b
2026-01-05T02:37:23.705284Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/app/src/test/java/it/michelelacorte/exampleretractabletoolbar/ExampleUnitTest.java
app/src/test/java/it/michelelacorte/exampleretractabletoolbar/ExampleUnitTest.java
package it.michele.retractabletoolbar; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/app/src/main/java/it/michelelacorte/exampleretractabletoolbar/MyAdapter.java
app/src/main/java/it/michelelacorte/exampleretractabletoolbar/MyAdapter.java
package it.michelelacorte.exampleretractabletoolbar; /** * Created by Michele on 15/11/2015. */ import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<ItemData> itemsData; public MyAdapter(List<ItemData> itemsData) { this.itemsData = itemsData; } // Create new views (invoked by the layout manager) @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View itemLayoutView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.common_item_layout, null); // create ViewHolder ViewHolder viewHolder = new ViewHolder(itemLayoutView); return viewHolder; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { // - get data from your itemsData at this position // - replace the contents of the view with that itemsData viewHolder.txtViewTitle.setText(itemsData.get(position).getTitle()); } // inner class to hold a reference to each item of RecyclerView public static class ViewHolder extends RecyclerView.ViewHolder { public TextView txtViewTitle; public ImageView imgViewIcon; public ViewHolder(View itemLayoutView) { super(itemLayoutView); txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title); } } // Return the size of your itemsData (invoked by the layout manager) @Override public int getItemCount() { return itemsData.size(); } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/app/src/main/java/it/michelelacorte/exampleretractabletoolbar/MainActivity.java
app/src/main/java/it/michelelacorte/exampleretractabletoolbar/MainActivity.java
package it.michelelacorte.exampleretractabletoolbar; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; import it.michelelacorte.retractabletoolbar.RetractableToolbarUtil; public class MainActivity extends AppCompatActivity { private RetractableToolbarUtil.ShowHideToolbarOnScrollingListener showHideToolbarListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.myList); List<ItemData> itemsData = new ArrayList<ItemData>(); for(int i = 0; i < 50; i++) { itemsData.add(new ItemData("Text " + i)); } recyclerView.setLayoutManager(new LinearLayoutManager(this)); MyAdapter mAdapter = new MyAdapter(itemsData); recyclerView.setAdapter(mAdapter); //Set scroll listener recyclerView.addOnScrollListener(showHideToolbarListener = new RetractableToolbarUtil.ShowHideToolbarOnScrollingListener(toolbar)); //Check state if (savedInstanceState != null) { showHideToolbarListener.onRestoreInstanceState((RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.State) savedInstanceState .getParcelable(RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE)); } } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/app/src/main/java/it/michelelacorte/exampleretractabletoolbar/ItemData.java
app/src/main/java/it/michelelacorte/exampleretractabletoolbar/ItemData.java
package it.michelelacorte.exampleretractabletoolbar; /** * Created by Michele on 15/11/2015. */ public class ItemData { private String title; public ItemData(String title){ this.title = title; } public String getTitle() { return title; } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/app/src/androidTest/java/it/michelelacorte/exampleretractabletoolbar/ApplicationTest.java
app/src/androidTest/java/it/michelelacorte/exampleretractabletoolbar/ApplicationTest.java
package it.michelelacorte.exampleretractabletoolbar; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
michelelacorte/RetractableToolbar
https://github.com/michelelacorte/RetractableToolbar/blob/2ec12a251974e7d83e8dc79dde9fed7850f058eb/library/src/main/java/it/michelelacorte/retractabletoolbar/RetractableToolbarUtil.java
library/src/main/java/it/michelelacorte/retractabletoolbar/RetractableToolbarUtil.java
package it.michelelacorte.retractabletoolbar; /** * Created by Michele on 15/11/2015. */ import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.animation.LinearInterpolator; public final class RetractableToolbarUtil { public static class ShowHideToolbarOnScrollingListener extends RecyclerView.OnScrollListener { public static final String SHOW_HIDE_TOOLBAR_LISTENER_STATE = "show-hide-toolbar-listener-state"; // Toolbar elevation when content is scrolled behind private static final float TOOLBAR_ELEVATION = 14f; private Toolbar toolbar; private State state; public ShowHideToolbarOnScrollingListener(Toolbar toolbar) { this.toolbar = toolbar; this.state = new State(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void toolbarSetElevation(float elevation) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { toolbar.setElevation(elevation == 0 ? 0 : TOOLBAR_ELEVATION); } } private void toolbarAnimateShow(final int verticalOffset) { toolbar.animate() .translationY(0) .setInterpolator(new LinearInterpolator()) .setDuration(180) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { toolbarSetElevation(verticalOffset == 0 ? 0 : TOOLBAR_ELEVATION); } }); } private void toolbarAnimateHide() { toolbar.animate() .translationY(-toolbar.getHeight()) .setInterpolator(new LinearInterpolator()) .setDuration(180) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { toolbarSetElevation(0); } }); } @Override public final void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { if (state.scrollingOffset > 0) { if (state.verticalOffset > toolbar.getHeight()) { toolbarAnimateHide(); } else { toolbarAnimateShow(state.verticalOffset); } } else if (state.scrollingOffset < 0) { if (toolbar.getTranslationY() < toolbar.getHeight() * -0.6 && state.verticalOffset > toolbar.getHeight()) { toolbarAnimateHide(); } else { toolbarAnimateShow(state.verticalOffset); } } } } @Override public final void onScrolled(RecyclerView recyclerView, int dx, int dy) { state.verticalOffset = recyclerView.computeVerticalScrollOffset(); state.scrollingOffset = dy; int toolbarYOffset = (int) (dy - toolbar.getTranslationY()); toolbar.animate().cancel(); if (state.scrollingOffset > 0) { if (toolbarYOffset < toolbar.getHeight()) { if (state.verticalOffset > toolbar.getHeight()) { toolbarSetElevation(TOOLBAR_ELEVATION); } toolbar.setTranslationY(state.translationY = -toolbarYOffset); } else { toolbarSetElevation(0); toolbar.setTranslationY(state.translationY = -toolbar.getHeight()); } } else if (state.scrollingOffset < 0) { if (toolbarYOffset < 0) { if (state.verticalOffset <= 0) { toolbarSetElevation(0); } toolbar.setTranslationY(state.translationY = 0); } else { if (state.verticalOffset > toolbar.getHeight()) { toolbarSetElevation(TOOLBAR_ELEVATION); } toolbar.setTranslationY(state.translationY = -toolbarYOffset); } } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void onRestoreInstanceState(State state) { this.state.verticalOffset = state.verticalOffset; this.state.scrollingOffset = state.scrollingOffset; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { toolbar.setElevation(state.elevation); toolbar.setTranslationY(state.translationY); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public State onSaveInstanceState() { state.translationY = toolbar.getTranslationY(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { state.elevation = toolbar.getElevation(); } return state; } /** * Saving and restoring current state. */ public static final class State implements Parcelable { public static Creator<State> CREATOR = new Creator<State>() { public State createFromParcel(Parcel parcel) { return new State(parcel); } public State[] newArray(int size) { return new State[size]; } }; // Vertical offset in the list private int verticalOffset; // Scroll UP/DOWN offset private int scrollingOffset; // Toolbar values private float translationY; private float elevation; State() { } State(Parcel parcel) { this.verticalOffset = parcel.readInt(); this.scrollingOffset = parcel.readInt(); this.translationY = parcel.readFloat(); this.elevation = parcel.readFloat(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(verticalOffset); parcel.writeInt(scrollingOffset); parcel.writeFloat(translationY); parcel.writeFloat(elevation); } } } private RetractableToolbarUtil() { } }
java
Apache-2.0
2ec12a251974e7d83e8dc79dde9fed7850f058eb
2026-01-05T02:37:31.182361Z
false
robinst/git-merge-repos
https://github.com/robinst/git-merge-repos/blob/741795fe3352144b840e3ec1702dca8ceb3c9514/src/main/java/org/nibor/git_merge_repos/MergedRef.java
src/main/java/org/nibor/git_merge_repos/MergedRef.java
package org.nibor.git_merge_repos; import java.util.Collection; /** * Info about a merged branch/tag and in which input repositories it was * present/missing. */ public class MergedRef { private final String refType; private final String refName; private final Collection<SubtreeConfig> configsWithRef; private final Collection<SubtreeConfig> configsWithoutRef; public MergedRef(String refType, String refName, Collection<SubtreeConfig> configsWithRef, Collection<SubtreeConfig> configsWithoutRef) { this.refType = refType; this.refName = refName; this.configsWithRef = configsWithRef; this.configsWithoutRef = configsWithoutRef; } public String getRefType() { return refType; } public String getRefName() { return refName; } public Collection<SubtreeConfig> getConfigsWithoutRef() { return configsWithoutRef; } public String getMessage() { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("Merge ").append(refType).append(" '").append(refName) .append("' from multiple repositories"); messageBuilder.append("\n\n"); messageBuilder.append("Repositories:"); appendRepositoryNames(messageBuilder, configsWithRef); if (!configsWithoutRef.isEmpty()) { messageBuilder.append("\n\nRepositories without this ").append(refType).append(":"); appendRepositoryNames(messageBuilder, configsWithoutRef); } messageBuilder.append("\n"); return messageBuilder.toString(); } private static void appendRepositoryNames(StringBuilder builder, Collection<SubtreeConfig> configs) { for (SubtreeConfig config : configs) { builder.append("\n\t"); builder.append(config.getRemoteName()); } } }
java
Apache-2.0
741795fe3352144b840e3ec1702dca8ceb3c9514
2026-01-05T02:37:34.276441Z
false
robinst/git-merge-repos
https://github.com/robinst/git-merge-repos/blob/741795fe3352144b840e3ec1702dca8ceb3c9514/src/main/java/org/nibor/git_merge_repos/RepoMerger.java
src/main/java/org/nibor/git_merge_repos/RepoMerger.java
package org.nibor.git_merge_repos; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefDatabase; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.RefUpdate.Result; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryBuilder; import org.eclipse.jgit.lib.TagBuilder; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTag; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.RefSpec; /** * Fetches original repos, merges original branches/tags of different repos and * creates branches/tags that point to new merge commits. */ public class RepoMerger { private final List<SubtreeConfig> subtreeConfigs; private final Repository repository; public RepoMerger(File outputRepositoryPath, List<SubtreeConfig> subtreeConfigs) throws IOException { this.subtreeConfigs = subtreeConfigs; repository = new RepositoryBuilder().setWorkTree(outputRepositoryPath).build(); if (!repository.getDirectory().exists()) { repository.create(); } } public List<MergedRef> run() throws IOException, GitAPIException { fetch(); List<MergedRef> mergedBranches = mergeBranches(); List<MergedRef> mergedTags = mergeTags(); List<MergedRef> mergedRefs = new ArrayList<>(); mergedRefs.addAll(mergedBranches); mergedRefs.addAll(mergedTags); deleteOriginalRefs(); resetToBranch(); return mergedRefs; } private void fetch() throws GitAPIException { for (SubtreeConfig config : subtreeConfigs) { RefSpec branchesSpec = new RefSpec( "refs/heads/*:refs/heads/original/" + config.getRemoteName() + "/*"); RefSpec tagsSpec = new RefSpec("refs/tags/*:refs/tags/original/" + config.getRemoteName() + "/*"); Git git = new Git(repository); git.fetch().setRemote(config.getFetchUri().toPrivateString()) .setRefSpecs(branchesSpec, tagsSpec).call(); } } private List<MergedRef> mergeBranches() throws IOException { List<MergedRef> mergedRefs = new ArrayList<>(); Collection<String> branches = getRefSet("refs/heads/original/"); for (String branch : branches) { MergedRef mergedBranch = mergeBranch(branch); mergedRefs.add(mergedBranch); } return mergedRefs; } private List<MergedRef> mergeTags() throws IOException { List<MergedRef> mergedRefs = new ArrayList<>(); Collection<String> tags = getRefSet("refs/tags/original/"); for (String tag : tags) { MergedRef mergedTag = mergeTag(tag); mergedRefs.add(mergedTag); } return mergedRefs; } private void deleteOriginalRefs() throws IOException { try (RevWalk revWalk = new RevWalk(repository)) { Collection<Ref> refs = new ArrayList<>(); RefDatabase refDatabase = repository.getRefDatabase(); List<Ref> originalBranches = refDatabase.getRefsByPrefix("refs/heads/original/"); List<Ref> originalTags = refDatabase.getRefsByPrefix("refs/tags/original/"); refs.addAll(originalBranches); refs.addAll(originalTags); for (Ref originalRef : refs) { RefUpdate refUpdate = repository.updateRef(originalRef.getName()); refUpdate.setForceUpdate(true); refUpdate.delete(revWalk); } } } private void resetToBranch() throws IOException, GitAPIException { for (String name : Arrays.asList("main", "master")) { Ref branch = repository.exactRef(Constants.R_HEADS + name); if (branch != null) { Git git = new Git(repository); git.reset().setMode(ResetType.HARD).setRef(branch.getName()).call(); break; } } } private MergedRef mergeBranch(String branch) throws IOException { Map<SubtreeConfig, ObjectId> resolvedRefs = resolveRefs( "refs/heads/original/", branch); Map<SubtreeConfig, RevCommit> parentCommits = new LinkedHashMap<>(); try (RevWalk revWalk = new RevWalk(repository)) { for (SubtreeConfig config : subtreeConfigs) { ObjectId objectId = resolvedRefs.get(config); if (objectId != null) { RevCommit commit = revWalk.parseCommit(objectId); parentCommits.put(config, commit); } } } MergedRef mergedRef = getMergedRef("branch", branch, parentCommits.keySet()); ObjectId mergeCommit = new SubtreeMerger(repository).createMergeCommit(parentCommits, mergedRef.getMessage()); RefUpdate refUpdate = repository.updateRef("refs/heads/" + branch); refUpdate.setNewObjectId(mergeCommit); refUpdate.update(); return mergedRef; } private MergedRef mergeTag(String tagName) throws IOException { Map<SubtreeConfig, ObjectId> resolvedRefs = resolveRefs( "refs/tags/original/", tagName); // Annotated tag that should be used for creating the merged tag, null // if only lightweight tags exist RevTag referenceTag = null; Map<SubtreeConfig, RevCommit> parentCommits = new LinkedHashMap<>(); try (RevWalk revWalk = new RevWalk(repository)) { for (Map.Entry<SubtreeConfig, ObjectId> entry : resolvedRefs .entrySet()) { SubtreeConfig config = entry.getKey(); ObjectId objectId = entry.getValue(); RevCommit commit; RevObject revObject = revWalk.parseAny(objectId); if (revObject instanceof RevCommit) { // Lightweight tag (ref points directly to commit) commit = (RevCommit) revObject; } else if (revObject instanceof RevTag) { // Annotated tag (ref points to tag object with message, // which in turn points to commit) RevTag tag = (RevTag) revObject; RevObject peeled = revWalk.peel(tag); if (peeled instanceof RevCommit) { commit = (RevCommit) peeled; if (referenceTag == null) { referenceTag = tag; } else { // We already have one, but use the last (latest) // tag as reference PersonIdent referenceTagger = referenceTag.getTaggerIdent(); PersonIdent thisTagger = tag.getTaggerIdent(); if (thisTagger != null && referenceTagger != null && thisTagger.getWhen().after(referenceTagger.getWhen())) { referenceTag = tag; } } } else { String msg = "Peeled tag " + tag.getTagName() + " does not point to a commit, but to the following object: " + peeled; throw new IllegalStateException(msg); } } else { throw new IllegalArgumentException("Object with ID " + objectId + " has invalid type for a tag: " + revObject); } parentCommits.put(config, commit); } } MergedRef mergedRef = getMergedRef("tag", tagName, parentCommits.keySet()); ObjectId mergeCommit = new SubtreeMerger(repository).createMergeCommit(parentCommits, mergedRef.getMessage()); ObjectId objectToReference; if (referenceTag != null) { TagBuilder tagBuilder = new TagBuilder(); tagBuilder.setTag(tagName); tagBuilder.setMessage(referenceTag.getFullMessage()); tagBuilder.setTagger(referenceTag.getTaggerIdent()); tagBuilder.setObjectId(mergeCommit, Constants.OBJ_COMMIT); try (ObjectInserter inserter = repository.newObjectInserter()) { objectToReference = inserter.insert(tagBuilder); inserter.flush(); } } else { objectToReference = mergeCommit; } String ref = Constants.R_TAGS + tagName; RefUpdate refUpdate = repository.updateRef(ref); refUpdate.setExpectedOldObjectId(ObjectId.zeroId()); refUpdate.setNewObjectId(objectToReference); Result result = refUpdate.update(); if (result != Result.NEW) { throw new IllegalStateException("Creating tag ref " + ref + " for " + objectToReference + " failed with result " + result); } return mergedRef; } private Collection<String> getRefSet(String prefix) throws IOException { List<Ref> refs = repository.getRefDatabase().getRefsByPrefix(prefix); TreeSet<String> result = new TreeSet<>(); for (Ref ref : refs) { // full: refs/heads/original/repo-one/main String full = ref.getName(); // unprefixed: repo-one/main String unprefixed = full.substring(prefix.length()); // branch name: main String branch = unprefixed.split("/", 2)[1]; result.add(branch); } return result; } private Map<SubtreeConfig, ObjectId> resolveRefs(String refPrefix, String name) throws IOException { Map<SubtreeConfig, ObjectId> result = new LinkedHashMap<>(); for (SubtreeConfig config : subtreeConfigs) { String repositoryName = config.getRemoteName(); String remoteBranch = refPrefix + repositoryName + "/" + name; ObjectId objectId = repository.resolve(remoteBranch); if (objectId != null) { result.put(config, objectId); } } return result; } private MergedRef getMergedRef(String refType, String refName, Set<SubtreeConfig> configsWithRef) { LinkedHashSet<SubtreeConfig> configsWithoutRef = new LinkedHashSet<>( subtreeConfigs); configsWithoutRef.removeAll(configsWithRef); return new MergedRef(refType, refName, configsWithRef, configsWithoutRef); } }
java
Apache-2.0
741795fe3352144b840e3ec1702dca8ceb3c9514
2026-01-05T02:37:34.276441Z
false
robinst/git-merge-repos
https://github.com/robinst/git-merge-repos/blob/741795fe3352144b840e3ec1702dca8ceb3c9514/src/main/java/org/nibor/git_merge_repos/SubtreeConfig.java
src/main/java/org/nibor/git_merge_repos/SubtreeConfig.java
package org.nibor.git_merge_repos; import org.eclipse.jgit.transport.URIish; /** * A configuration about which input repository should be merged into which * target directory. */ public class SubtreeConfig { private final String repositoryName; private final URIish fetchUri; private final String subtreeDirectory; /** * @param subtreeDirectory * the target directory into which the repository should be * merged, can be <code>"."</code> to not change the directory * layout on merge * @param fetchUri * the URI where the repository is located (a local one is * preferred while experimenting with conversion, so that it does * not have to be fetched multiple times) */ public SubtreeConfig(String subtreeDirectory, URIish fetchUri) { this.subtreeDirectory = subtreeDirectory; this.fetchUri = fetchUri; this.repositoryName = fetchUri.getHumanishName(); if (this.repositoryName.isEmpty()) { throw new IllegalArgumentException( "Could not determine repository name from fetch URI: " + fetchUri); } } public String getRemoteName() { return fetchUri.getHumanishName(); } public URIish getFetchUri() { return fetchUri; } public String getSubtreeDirectory() { return subtreeDirectory; } }
java
Apache-2.0
741795fe3352144b840e3ec1702dca8ceb3c9514
2026-01-05T02:37:34.276441Z
false
robinst/git-merge-repos
https://github.com/robinst/git-merge-repos/blob/741795fe3352144b840e3ec1702dca8ceb3c9514/src/main/java/org/nibor/git_merge_repos/SubtreeMerger.java
src/main/java/org/nibor/git_merge_repos/SubtreeMerger.java
package org.nibor.git_merge_repos; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.TreeWalk; /** * Merges the passed commit trees into one tree, adjusting directory structure * if necessary (depends on options from user). */ public class SubtreeMerger { private final Repository repository; public SubtreeMerger(Repository repository) { this.repository = repository; } public ObjectId createMergeCommit(Map<SubtreeConfig, RevCommit> parentCommits, String message) throws IOException { PersonIdent latestIdent = getLatestPersonIdent(parentCommits.values()); DirCache treeDirCache = createTreeDirCache(parentCommits, message); List<? extends ObjectId> parentIds = new ArrayList<>(parentCommits.values()); try (ObjectInserter inserter = repository.newObjectInserter()) { ObjectId treeId = treeDirCache.writeTree(inserter); PersonIdent repositoryUser = new PersonIdent(repository); PersonIdent ident = new PersonIdent(repositoryUser, latestIdent.getWhen().getTime(), latestIdent.getTimeZoneOffset()); CommitBuilder commitBuilder = new CommitBuilder(); commitBuilder.setTreeId(treeId); commitBuilder.setAuthor(ident); commitBuilder.setCommitter(ident); commitBuilder.setMessage(message); commitBuilder.setParentIds(parentIds); ObjectId mergeCommit = inserter.insert(commitBuilder); inserter.flush(); return mergeCommit; } } private PersonIdent getLatestPersonIdent(Collection<RevCommit> commits) { PersonIdent latest = null; for (RevCommit commit : commits) { PersonIdent ident = commit.getCommitterIdent(); Date when = ident.getWhen(); if (latest == null || when.after(latest.getWhen())) { latest = ident; } } return latest; } private DirCache createTreeDirCache(Map<SubtreeConfig, RevCommit> parentCommits, String commitMessage) throws IOException { try (TreeWalk treeWalk = new TreeWalk(repository)) { treeWalk.setRecursive(true); addTrees(parentCommits, treeWalk); DirCacheBuilder builder = DirCache.newInCore().builder(); while (treeWalk.next()) { AbstractTreeIterator iterator = getSingleTreeIterator(treeWalk, commitMessage); if (iterator == null) { throw new IllegalStateException( "Tree walker did not return a single tree (should not happen): " + treeWalk.getPathString()); } byte[] path = Arrays.copyOf(iterator.getEntryPathBuffer(), iterator.getEntryPathLength()); DirCacheEntry entry = new DirCacheEntry(path); entry.setFileMode(iterator.getEntryFileMode()); entry.setObjectId(iterator.getEntryObjectId()); builder.add(entry); } builder.finish(); return builder.getDirCache(); } } private void addTrees(Map<SubtreeConfig, RevCommit> parentCommits, TreeWalk treeWalk) throws IOException { for (Map.Entry<SubtreeConfig, RevCommit> entry : parentCommits.entrySet()) { String directory = entry.getKey().getSubtreeDirectory(); RevCommit parentCommit = entry.getValue(); if (".".equals(directory)) { treeWalk.addTree(parentCommit.getTree()); } else { byte[] prefix = directory.getBytes(StandardCharsets.UTF_8); CanonicalTreeParser treeParser = new CanonicalTreeParser(prefix, treeWalk.getObjectReader(), parentCommit.getTree()); treeWalk.addTree(treeParser); } } } private AbstractTreeIterator getSingleTreeIterator(TreeWalk treeWalk, String commitMessage) { AbstractTreeIterator result = null; int treeCount = treeWalk.getTreeCount(); for (int i = 0; i < treeCount; i++) { AbstractTreeIterator it = treeWalk.getTree(i, AbstractTreeIterator.class); if (it != null) { if (result != null) { String msg = "Trees of repositories overlap in path '" + it.getEntryPathString() + "'. " + "We can only merge non-overlapping trees, " + "so make sure the repositories have been prepared for that. " + "One possible way is to process each repository to move the root to a subdirectory first.\n" + "Current commit:\n" + commitMessage; throw new IllegalStateException(msg); } else { result = it; } } } return result; } }
java
Apache-2.0
741795fe3352144b840e3ec1702dca8ceb3c9514
2026-01-05T02:37:34.276441Z
false
robinst/git-merge-repos
https://github.com/robinst/git-merge-repos/blob/741795fe3352144b840e3ec1702dca8ceb3c9514/src/main/java/org/nibor/git_merge_repos/Main.java
src/main/java/org/nibor/git_merge_repos/Main.java
package org.nibor.git_merge_repos; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.transport.URIish; /** * Main class for merging repositories via command-line. */ public class Main { private static final String USAGE = "usage: program <repository_url>:<target_directory>..."; private static final Pattern REPO_AND_DIR = Pattern.compile("(.*):([^:]+)"); public static void main(String[] args) throws IOException, GitAPIException, URISyntaxException { if (args.length >= 1 && (args[0].equals("-h") || args[0].equals("--help"))) { exit(USAGE, 0); } List<SubtreeConfig> subtreeConfigs = new ArrayList<>(); for (String arg : args) { Matcher matcher = REPO_AND_DIR.matcher(arg); if (matcher.matches()) { String repositoryUrl = matcher.group(1); String directory = matcher.group(2); SubtreeConfig config = new SubtreeConfig(directory, new URIish(repositoryUrl)); subtreeConfigs.add(config); } else { exitInvalidUsage("invalid argument '" + arg + "', expected '<repository_url>:<target_directory>'"); } } if (subtreeConfigs.isEmpty()) { exitInvalidUsage(USAGE); } File outputDirectory = new File("merged-repo"); String outputPath = outputDirectory.getAbsolutePath(); if (outputDirectory.exists()) { exit("Error: Output directory already exists (please remove it and rerun): " + outputPath, 1); } System.out.println("Started merging " + subtreeConfigs.size() + " repositories into one, output directory: " + outputPath); long start = System.currentTimeMillis(); RepoMerger merger = new RepoMerger(outputDirectory, subtreeConfigs); List<MergedRef> mergedRefs = merger.run(); long end = System.currentTimeMillis(); long timeMs = (end - start); printIncompleteRefs(mergedRefs); System.out.println("Done, took " + timeMs + " ms"); System.out.println("Merged repository: " + outputPath); } private static void printIncompleteRefs(List<MergedRef> mergedRefs) { for (MergedRef mergedRef : mergedRefs) { if (!mergedRef.getConfigsWithoutRef().isEmpty()) { System.out.println(mergedRef.getRefType() + " '" + mergedRef.getRefName() + "' was not in: " + join(mergedRef.getConfigsWithoutRef())); } } } private static String join(Collection<SubtreeConfig> configs) { StringBuilder sb = new StringBuilder(); for (SubtreeConfig config : configs) { if (sb.length() != 0) { sb.append(", "); } sb.append(config.getRemoteName()); } return sb.toString(); } private static void exitInvalidUsage(String message) { exit(message, 64); } private static void exit(String message, int status) { System.err.println(message); System.exit(status); } }
java
Apache-2.0
741795fe3352144b840e3ec1702dca8ceb3c9514
2026-01-05T02:37:34.276441Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/AbstractDatabaseTest.java
src/test/java/org/ohdsi/webapi/AbstractDatabaseTest.java
package org.ohdsi.webapi; import com.github.mjeanroy.dbunit.core.dataset.DataSetFactory; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.rules.ExternalResource; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import org.dbunit.DatabaseUnitException; import org.dbunit.database.DatabaseConfig; import org.dbunit.database.DatabaseDataSourceConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.IDataSet; import org.dbunit.ext.postgresql.PostgresqlDataTypeFactory; import org.dbunit.operation.DatabaseOperation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @SpringBootTest @RunWith(SpringRunner.class) @TestPropertySource(locations = "/application-test.properties") public abstract class AbstractDatabaseTest { static class JdbcTemplateTestWrapper extends ExternalResource { @Override protected void before() throws Throwable { jdbcTemplate = new JdbcTemplate(getDataSource()); try { // note for future reference: should probably either define a TestContext DataSource with these params // or make it so this proparty is only set once (during database initialization) since the below will run for each test class (but only be effective once) System.setProperty("datasource.url", getDataSource().getConnection().getMetaData().getURL()); System.setProperty("flyway.datasource.url", System.getProperty("datasource.url")); } catch (Exception ex) { throw new RuntimeException(ex); } } } static class DriverExcludeTestWrapper extends ExternalResource { @Override protected void before() throws Throwable { // Put the redshift driver at the end so that it doesn't // conflict with postgres queries java.util.Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getName().contains("com.amazon.redshift.jdbc")) { try { DriverManager.deregisterDriver(driver); DriverManager.registerDriver(driver); } catch (SQLException e) { throw new RuntimeException("Could not deregister redshift driver", e); } } } } } @ClassRule public static TestRule chain = RuleChain.outerRule(new DriverExcludeTestWrapper()) .around(pg = new PostgresSingletonRule()) .around(new JdbcTemplateTestWrapper()); protected static PostgresSingletonRule pg; protected static JdbcTemplate jdbcTemplate; protected static DataSource getDataSource() { return pg.getEmbeddedPostgres().getPostgresDatabase(); } protected void truncateTable(String tableName) { jdbcTemplate.execute(String.format("TRUNCATE %s CASCADE", tableName)); } protected void resetSequence(String sequenceName) { jdbcTemplate.execute(String.format("ALTER SEQUENCE %s RESTART WITH 1", sequenceName)); } protected static IDatabaseConnection getConnection() throws SQLException { final IDatabaseConnection con = new DatabaseDataSourceConnection(getDataSource()); con.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true); con.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory()); return con; } protected void loadPrepData(String[] datasetPaths) throws Exception { loadPrepData(datasetPaths, DatabaseOperation.CLEAN_INSERT); } protected void loadPrepData(String[] datasetPaths, DatabaseOperation dbOp) throws Exception { final IDatabaseConnection dbUnitCon = getConnection(); final IDataSet ds = DataSetFactory.createDataSet(datasetPaths); assertNotNull("No dataset found", ds); try { dbOp.execute(dbUnitCon, ds); // clean load of the DB. Careful, clean means "delete the old stuff" } catch (final DatabaseUnitException e) { fail(e.getMessage()); } finally { dbUnitCon.close(); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/PostgresSingletonRule.java
src/test/java/org/ohdsi/webapi/PostgresSingletonRule.java
package org.ohdsi.webapi; /* * Copyright 2020 cknoll1. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import io.zonky.test.db.postgres.embedded.EmbeddedPostgres; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Based off of com.opentable.db.postgres.junit.SingleInstancePostgresRule, but * instantiates a single instance of an EmbeddedPostgres that cleans up when JVM * shuts down. */ public class PostgresSingletonRule extends ExternalResource { private static volatile EmbeddedPostgres epg; private static volatile Connection postgresConnection; private static final Logger LOG = LoggerFactory.getLogger(PostgresSingletonRule.class); PostgresSingletonRule() {} @Override protected void before() throws Throwable { super.before(); synchronized (PostgresSingletonRule.class) { if (epg == null) { LOG.info("Starting singleton Postgres instance..."); epg = pg(); postgresConnection = epg.getPostgresDatabase().getConnection(); Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown())); } } } private EmbeddedPostgres pg() throws IOException { return EmbeddedPostgres.builder().start(); } public EmbeddedPostgres getEmbeddedPostgres() { EmbeddedPostgres epg = this.epg; if (epg == null) { throw new AssertionError("JUnit tests not started yet!"); } return epg; } private static void shutdown() { LOG.info("Shutdown singleton Postgres instance..."); try { postgresConnection.close(); } catch (SQLException e) { throw new AssertionError(e); } try { epg.close(); } catch (IOException e) { throw new AssertionError(e); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/util/PreparedStatementRendererTest.java
src/test/java/org/ohdsi/webapi/util/PreparedStatementRendererTest.java
package org.ohdsi.webapi.util; import org.junit.Assert; import org.junit.Test; import org.ohdsi.webapi.source.Source; public class PreparedStatementRendererTest { private Source source = new Source(); private String resourcePath; private String tableQualifierName; private String tableQualifierValue; private String sourceDialect; private String[] sqlVariableNames; private Object[] sqlVariableValues; @org.junit.Before public void before() { sourceDialect = "sql server"; source.setSourceDialect(sourceDialect); resourcePath = "/resources/person/sql/getRecords.sql"; tableQualifierName = "tableQualifier"; tableQualifierValue = "omop_v5"; sqlVariableNames = new String[]{"personId"}; sqlVariableValues = new Object[]{"1230"}; } @Test(expected = IllegalArgumentException.class) public void validateArgumentsWithNullVariableValues() { this.sqlVariableValues = null; new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); } @Test(expected = IllegalArgumentException.class) public void validateArgumentsWithNullVariableNames() { this.sqlVariableNames = null; new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); } @Test() public void validateArgumentsWithNullSourceDialect() { sourceDialect = null; new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); } @Test(expected = IllegalArgumentException.class) public void validateArgumentsWithNullTableQualifierValue() { tableQualifierValue = null; new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); } @Test public void validateArguments() { PreparedStatementRenderer u = new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); Assert.assertNotNull(u); Assert.assertNotNull(u.getSql()); Assert.assertNotNull(u.getSetter()); Assert.assertNotNull(u.getOrderedParamsList()); } @Test(expected = RuntimeException.class) public void validateArgumentsWithInvalidResourcePath() { resourcePath += "res.sql"; new PreparedStatementRenderer(source, resourcePath, tableQualifierName, tableQualifierValue, sqlVariableNames, sqlVariableValues); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false