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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/LimitDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/LimitDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.openldap.config.editor.dialogs.SizeTimeLimitDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the TimeLimitWrapper class.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LimitDecorator extends TableDecorator<LimitWrapper>
{
/**
* Create a new instance of LimitDecorator
* @param parentShell The parent Shell
*/
public LimitDecorator( Shell parentShell, String title )
{
setDialog( new SizeTimeLimitDialog( parentShell ) );
}
/**
* Construct the label for a TimeLimit. It can be one of :
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof LimitWrapper )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none (may be we could add one for URLs ?)
*/
@Override
public Image getImage( Object element )
{
return null;
}
@Override
public int compare( LimitWrapper e1, LimitWrapper e2 )
{
// TODO Auto-generated method stub
return 0;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/RestrictOperationDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/RestrictOperationDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.openldap.common.ui.model.RestrictOperationEnum;
import org.apache.directory.studio.openldap.config.editor.dialogs.RestrictOperationDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the RestrictOperation table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RestrictOperationDecorator extends TableDecorator<RestrictOperationEnum>
{
/**
* Create a new instance of RestrictOperationDecorator
* @param parentShell The parent Shell
*/
public RestrictOperationDecorator( Shell parentShell )
{
setDialog( new RestrictOperationDialog( parentShell ) );
}
/**
* Construct the label for an RestrictOperation.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof RestrictOperationEnum )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( RestrictOperationEnum e1, RestrictOperationEnum e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.getName().compareTo( e2.getName() );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/TcpBufferDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/TcpBufferDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.openldap.config.editor.dialogs.TcpBufferDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the TcpBuffer table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TcpBufferDecorator extends TableDecorator<TcpBufferWrapper>
{
/**
* Create a new instance of TcpBufferDecorator
* @param parentShell The parent Shell
*/
public TcpBufferDecorator( Shell parentShell )
{
setDialog( new TcpBufferDialog( parentShell ) );
}
/**
* Construct the label for a TCPBuffer.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof TcpBufferWrapper )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none (may be we could add one for URLs ?)
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( TcpBufferWrapper e1, TcpBufferWrapper e2 )
{
if ( e1 != null )
{
return e1.compareTo( e2 );
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthIdRewriteWrapper.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthIdRewriteWrapper.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.openldap.config.editor.wrappers;
/**
* A wrapper class for the values stored in the olcAuthIDRewrite attribute.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AuthIdRewriteWrapper implements Cloneable, Comparable<AuthIdRewriteWrapper>
{
/** The rewrite */
private String rewrite;
/**
* Creates a new instance of AuthIdRewriteWrapper using a String value
*
* @param rewrite The value
*/
public AuthIdRewriteWrapper( String rewrite )
{
this.rewrite = rewrite;
}
/**
* @see Comparable#compareTo()
*/
public int compareTo( AuthIdRewriteWrapper that )
{
if ( that == null )
{
return 1;
}
//
return 0;
}
/**
* @see Object#toString()
*/
public String toString()
{
return rewrite;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/StringValueDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/StringValueDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.common.ui.wrappers.StringValueWrapper;
import org.apache.directory.studio.openldap.config.editor.dialogs.StringValueDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for a String Value table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StringValueDecorator extends TableDecorator<StringValueWrapper>
{
/** The associated image, if any */
private Image image;
/**
* Create a new instance of StringValueDecorator
* @param parentShell The parent Shell
* @param attributeName the name of the attribute which will contain the value
*/
public StringValueDecorator( Shell parentShell, String attributeName )
{
setDialog( new StringValueDialog( parentShell, attributeName ) );
}
/**
* Adds an Image to this decorator
* @param image The Image
*/
public void setImage( Image image )
{
this.image = image;
}
/**
* Construct the label for a String.
* @param element the Element for which we want the value
* @return a String representation of the element
*/
@Override
public String getText( Object element )
{
if ( element instanceof StringValueWrapper )
{
return ( ( StringValueWrapper ) element ).getValue();
}
return super.getText( element );
}
/**
* Get the image. Here, We have none
*
* @param element The element for which we want the image
* @return The associated Image, or Null
*/
@Override
public Image getImage( Object element )
{
return image;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( StringValueWrapper e1, StringValueWrapper e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.compareTo( e2 );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DatabaseWrapperViewerComparator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DatabaseWrapperViewerComparator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginUtils;
import org.apache.directory.studio.openldap.config.model.database.OlcDatabaseConfig;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
/**
* This class defines a sorter for a database wrapper viewer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DatabaseWrapperViewerComparator extends ViewerComparator
{
/**
* {@inheritDoc}
*/
@Override
public int compare( Viewer viewer, Object e1, Object e2 )
{
if ( ( e1 instanceof DatabaseWrapper ) && ( e2 instanceof DatabaseWrapper ) )
{
OlcDatabaseConfig database1 = ( ( DatabaseWrapper ) e1 ).getDatabase();
OlcDatabaseConfig database2 = ( ( DatabaseWrapper ) e2 ).getDatabase();
boolean db1HasOrderingPrefix = OpenLdapConfigurationPluginUtils.hasOrderingPrefix( database1
.getOlcDatabase() );
boolean db2HasOrderingPrefix = OpenLdapConfigurationPluginUtils.hasOrderingPrefix( database2
.getOlcDatabase() );
if ( db1HasOrderingPrefix && db2HasOrderingPrefix )
{
int orderingPrefix1 = OpenLdapConfigurationPluginUtils.getOrderingPrefix( database1
.getOlcDatabase() );
int orderingPrefix2 = OpenLdapConfigurationPluginUtils.getOrderingPrefix( database2
.getOlcDatabase() );
if ( orderingPrefix1 > orderingPrefix2 )
{
return Integer.MAX_VALUE;
}
else if ( orderingPrefix1 < orderingPrefix2 )
{
return Integer.MIN_VALUE;
}
else
{
return 0;
}
}
else if ( db1HasOrderingPrefix )
{
return Integer.MIN_VALUE;
}
else if ( db2HasOrderingPrefix )
{
return Integer.MAX_VALUE;
}
else
{
return 1;
}
}
return super.compare( viewer, e1, e2 );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/ServerIdWrapper.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/ServerIdWrapper.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.openldap.config.editor.wrappers;
import org.apache.directory.api.util.Strings;
/**
* A wrapper for a ServerID which can be either an integer between 0 and 4095
* (or from 0x0 to 0xFFF), and may be followed by an URL. We can't have both format,
* and if it's not an URL, then only one value is accepted. The syntax is :
* <pre>
* ServerId ::= ( INT | HEX ) [ ' ' URL ]
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ServerIdWrapper implements Cloneable, Comparable<ServerIdWrapper>
{
/** The server ID */
private int serverId;
/** The URL, if any */
private String url;
/**
* Creates a new instance of ServerIdWrapper.
*/
public ServerIdWrapper()
{
}
/**
* Creates a new instance of ServerIdWrapper.
*
* @param serverId the serverID
*/
public ServerIdWrapper( int serverId )
{
this.serverId = serverId;
}
/**
* Creates a new instance of ServerIdWrapper.
*
* @param serverId the serverID
* @param url the URL
*/
public ServerIdWrapper( int serverId, String url )
{
this.serverId = serverId;
this.url = url;
}
/**
* Parse a String that contains either a integer value or an hexa value
*/
private int parseInt( String str )
{
if ( str.startsWith( "0x" ) || str.startsWith( "0X" ) )
{
return Integer.parseInt( str.substring( 2 ), 16 );
}
else
{
return Integer.parseInt( str );
}
}
/**
* Creates a new instance of ServerIdWrapper.
*
* @param serverIdStr the serverID
*/
public ServerIdWrapper( String serverIdStr )
{
if ( !Strings.isEmpty( serverIdStr ) )
{
// Let's see if we have an URL, and if so, it's after the number
int pos = serverIdStr.indexOf( ' ' );
if ( pos == -1 )
{
// No URL
serverId = parseInt( serverIdStr );
}
else
{
// ServerID and URL
this.serverId = parseInt( serverIdStr.substring( 0, pos ) );
this.url = serverIdStr.substring( pos + 1 );
}
}
}
/**
* @return the serverId
*/
public int getServerId()
{
return serverId;
}
/**
* @param serverId the serverId to set
*/
public void setServerId( int serverId )
{
this.serverId = serverId;
}
/**
* @return the url
*/
public String getUrl()
{
return url;
}
/**
* @param url the url to set
*/
public void setUrl( String url )
{
this.url = url;
}
/**
* Clone the current object
*/
public ServerIdWrapper clone()
{
try
{
return (ServerIdWrapper)super.clone();
}
catch ( CloneNotSupportedException e )
{
return null;
}
}
/**
* @see Object#equals(Object)
*/
public boolean equals( Object that )
{
// Quick test
if ( this == that )
{
return true;
}
if ( that instanceof ServerIdWrapper )
{
ServerIdWrapper thatInstance = (ServerIdWrapper)that;
if ( serverId != thatInstance.serverId )
{
return false;
}
if ( url == thatInstance.url )
{
return true;
}
if ( url != null )
{
return url.equals( thatInstance.url );
}
else
{
return thatInstance.url == null;
}
}
else
{
return false;
}
}
/**
* @see Object#hashCode()
*/
public int hashCode()
{
int h = 37;
h += h*17 + serverId;
if ( url != null )
{
h += h*17 + url.hashCode();
}
return h;
}
/**
* @see Comparable#compareTo()
*/
public int compareTo( ServerIdWrapper that )
{
if ( that == null )
{
return 1;
}
// Check the serverId first
if ( serverId == that.serverId )
{
// Now, compare the url
if ( Strings.isEmpty( url ) )
{
return 0;
}
else
{
return url.compareToIgnoreCase( that.url );
}
}
else
{
return serverId - that.serverId;
}
}
/**
* @see Object#toString()
*/
public String toString()
{
if ( url == null )
{
return Integer.toString( serverId );
}
else
{
return Integer.toString( serverId ) + " " + 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthIdRewriteDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthIdRewriteDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the AuthIdRewrite table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AuthIdRewriteDecorator extends TableDecorator<AuthIdRewriteWrapper>
{
/**
* Create a new instance of AuthIdRewriteDecorator
* @param parentShell The parent Shell
*/
public AuthIdRewriteDecorator( Shell parentShell )
{
// Nothing to do
}
/**
* Construct the label for an AuthIdRewriteWrapper.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof AuthIdRewriteWrapper )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( AuthIdRewriteWrapper e1, AuthIdRewriteWrapper e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.compareTo( e2 );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DbIndexDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DbIndexDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.openldap.config.editor.dialogs.DbIndexDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the DbIndex table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DbIndexDecorator extends TableDecorator<DbIndexWrapper>
{
/**
* Create a new instance of DbIndexDecorator
* @param parentShell The parent Shell
*/
public DbIndexDecorator( Shell parentShell, IBrowserConnection browserConnection )
{
setDialog( new DbIndexDialog( parentShell, browserConnection ) );
}
/**
* Construct the label for an DbIndex.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof DbIndexWrapper )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none
*
* {@inheritDoc}
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( DbIndexWrapper e1, DbIndexWrapper e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.compareTo( e2 );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/OrderedStringValueWrapper.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/OrderedStringValueWrapper.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.openldap.config.editor.wrappers;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.OrderedElement;
/**
* A wrapper for an ordered String value. The value is prefixed by "{n}" where n is an integer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OrderedStringValueWrapper implements Cloneable, Comparable<OrderedStringValueWrapper>, OrderedElement
{
/** The value */
private String value;
/** A flag to tell if the compare should be case sensitive or not */
private boolean caseSensitive = true;
/** The prefix, used to order the values */
private Integer prefix;
/**
* Creates a new instance of StringValueWrapper.
*
* @param value the value
*/
public OrderedStringValueWrapper( int prefix, String value, boolean caseSensitive )
{
this.value = value;
this.caseSensitive = caseSensitive;
this.prefix = prefix;
}
/**
* @return the value
*/
public String getValue()
{
return value;
}
/**
* Sets a new value
*
* @param value the value to set
*/
public void setValue( String value )
{
this.value = value;
}
/**
* Sets a new prefix
*
* @param prefix the prefix to set
*/
public void setPrefix( int prefix )
{
this.prefix = prefix;
}
/**
* @return the prefix
*/
public int getPrefix()
{
return prefix;
}
/**
* {@inheritDoc}
*/
public void decrementPrefix()
{
prefix--;
}
/**
* {@inheritDoc}
*/
public void incrementPrefix()
{
prefix++;
}
/**
* Clone the current object
*/
public OrderedStringValueWrapper clone()
{
try
{
return (OrderedStringValueWrapper)super.clone();
}
catch ( CloneNotSupportedException e )
{
return null;
}
}
/**
* @see Comparable#compareTo()
*/
public int compareTo( OrderedStringValueWrapper that )
{
if ( that == null )
{
return 1;
}
// Check the prefix
if ( prefix < that.prefix )
{
return -1;
}
else if ( prefix > that.prefix )
{
return 1;
}
// Check the value
if ( Strings.isEmpty( value ) )
{
return -1;
}
else
{
return value.compareToIgnoreCase( that.value );
}
}
/**
* @see Object#equals(Object)
*/
public boolean equals( Object that )
{
// Quick test
if ( this == that )
{
return true;
}
if ( that instanceof OrderedStringValueWrapper )
{
OrderedStringValueWrapper thatInstance = (OrderedStringValueWrapper)that;
if ( ( prefix != null ) && ( prefix != thatInstance.prefix ) )
{
return false;
}
if ( caseSensitive )
{
return value.equals( thatInstance.value );
}
else
{
return value.equalsIgnoreCase( thatInstance.value );
}
}
else
{
return false;
}
}
/**
* @see Object#hashCode()
*/
public int hashCode()
{
int h = 37;
h += h*17 + prefix;
if ( value != null )
{
h += h*17 + value.hashCode();
}
return h;
}
/**
* @see Object#toString()
*/
public String toString()
{
return '{' + Integer.toString( prefix ) + '}' + value;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthzRegexpWrapper.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/AuthzRegexpWrapper.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.openldap.config.editor.wrappers;
/**
* A wrapper class for the values stored in the olcAuthzRegexp attribute. It contains
* two argument :
* <pre>
* <match> <replace>
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AuthzRegexpWrapper implements Cloneable, Comparable<AuthzRegexpWrapper>
{
/** The match part */
private String match;
/** The replace part */
private String replace;
/**
* Creates a new instance of AuthzRegexpWrapper using a String value
*
* @param regexp The value
*/
public AuthzRegexpWrapper( String authzRegexp )
{
this.match = authzRegexp;
}
/**
* @see Comparable#compareTo()
*/
public int compareTo( AuthzRegexpWrapper that )
{
if ( that == null )
{
return 1;
}
//
return 0;
}
/**
* @see Object#toString()
*/
public String toString()
{
return match + ' ' + replace;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DnDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/DnDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.openldap.common.ui.model.DisallowFeatureEnum;
import org.apache.directory.studio.openldap.config.editor.dialogs.DnValueDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the Dn table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DnDecorator extends TableDecorator<DnWrapper>
{
/**
* Create a new instance of DnDecorator
* @param parentShell The parent Shell
*/
public DnDecorator( Shell parentShell )
{
setDialog( new DnValueDialog( parentShell ) );
}
/**
* Construct the label for an DisallowFeature.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof DisallowFeatureEnum )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none
*
* {@inheritDoc}
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( DnWrapper e1, DnWrapper e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.compareTo( e2 );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/RequireConditionDecorator.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/wrappers/RequireConditionDecorator.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.openldap.config.editor.wrappers;
import org.apache.directory.studio.common.ui.TableDecorator;
import org.apache.directory.studio.openldap.common.ui.model.RequireConditionEnum;
import org.apache.directory.studio.openldap.config.editor.dialogs.RequireConditionDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
/**
* A decorator for the RequireCondition table.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RequireConditionDecorator extends TableDecorator<RequireConditionEnum>
{
/**
* Create a new instance of RequireConditionDecorator
* @param parentShell The parent Shell
*/
public RequireConditionDecorator( Shell parentShell )
{
setDialog( new RequireConditionDialog( parentShell ) );
}
/**
* Construct the label for an RequireCondition.
*
*/
@Override
public String getText( Object element )
{
if ( element instanceof RequireConditionEnum )
{
return element.toString();
}
return super.getText( element );
}
/**
* Get the image. We have none
*/
@Override
public Image getImage( Object element )
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare( RequireConditionEnum e1, RequireConditionEnum e2 )
{
if ( e1 != null )
{
if ( e2 == null )
{
return 1;
}
else
{
return e1.getName().compareTo( e2.getName() );
}
}
else
{
if ( e2 == null )
{
return 0;
}
else
{
return 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SizeLimitDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SizeLimitDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.SizeLimitWrapper;
/**
* The SizeLimitDialog is used to edit the SizeLimit parameter<br/>
* The SizeLimit grammar is :
* <pre>
* size ::= 'size' sizeLimit size-e
* size-e ::= ' size' sizeLimit size-e | e
* sizeLimit ::= '.soft=' limit | '.hard=' hardLimit | '.pr=' prLimit | '.prtotal=' prTLimit
* | '.unchecked=' uLimit | '=' limit
* limit ::= 'unlimited' | 'none' | INT
* hardLimit ::= 'soft' | limit
* ulimit ::= 'disabled' | limit
* prLimit ::= 'noEstimate' | limit
* prTLimit ::= ulimit | 'hard'
* </pre>
*
* The dialog overlay is like :
*
* <pre>
* +--------------------------------------------------------------------------+
* | Size Limit |
* | .----------------------------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global Limit : [----------] [] Unlimited | |
* | | | |
* | | Unchecked Limit : [----------] [] Unlimited [] Disabled | |
* | | | |
* | | Paged Results Limit : [----------] [] Unlimited [] No Estimate | |
* | | | |
* | | Paged Results Total : [----------] [] Unlimited [] Disabled [] Hard | |
* | '----------------------------------------------------------------------' |
* | Resulting Size Limit |
* | .----------------------------------------------------------------------. |
* | | Size Limit : <////////////////////////////////////////////////////> | |
* | '----------------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------------+
* </pre>
*
* A few rules :
* <ul>
* <li>When the global limit is set, the soft and hard limits are not used</li>
* <li>When the Unlimited button is checked, the integer value is discarded</li>
* <li>When the Soft checkbox for the hard limit is checked, the Global value is used </li>
* </ul>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SizeLimitDialog extends AbstractLimitDialog<SizeLimitWrapper>
{
/** The UncheckedLimit Text and checkboxes */
private Text uncheckedLimitText;
private Button uncheckedUnlimitedCheckbox;
private Button uncheckedDisabledCheckbox;
/** The prLimit Text and checkboxes */
private Text prLimitText;
private Button prUnlimitedCheckbox;
private Button prNoEstimateCheckbox;
/** The prTotalLimit Text and checkboxes */
private Text prTotalLimitText;
private Button prTotalUnlimitedCheckbox;
private Button prTotalDisabledCheckbox;
private Button prTotalHardCheckbox;
/**
* Create a new instance of the SizeLimitDialog
*
* @param parentShell The parent Shell
*/
public SizeLimitDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* Create a new instance of the SizeLimitDialog
*
* @param parentShell The parent Shell
* @param sizeLimitStr The instance containing the sizeLimit data
*/
public SizeLimitDialog( Shell parentShell, String sizeLimitStr )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
setEditedElement( new SizeLimitWrapper( sizeLimitStr ) );
}
/**
* Check if the global SizeLimit is valid :
* the values must be numeric, or "unlimited" or "none" or "soft" (for the hard limit). They
* also have to be >=0
*/
@Override
protected boolean isValid()
{
return super.isValid() && isValidUnchecked() && isValidPr() && isValidPrTotal();
}
/**
* Check if the unchecked value is valid or not
*/
protected boolean isValidUnchecked()
{
String uncheckedlLimitStr = uncheckedLimitText.getText();
if ( !Strings.isEmpty( uncheckedlLimitStr ) )
{
if ( !SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( uncheckedlLimitStr ) &&
!SizeLimitWrapper.NONE_STR.equalsIgnoreCase( uncheckedlLimitStr ) &&
!SizeLimitWrapper.DISABLED_STR.equalsIgnoreCase( uncheckedlLimitStr ) )
{
try
{
if ( Integer.parseInt( uncheckedlLimitStr ) < SizeLimitWrapper.UNLIMITED.intValue() )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* Check if the pr value is valid or not
*/
protected boolean isValidPr()
{
String prLimitStr = prLimitText.getText();
if ( !Strings.isEmpty( prLimitStr ) )
{
if ( !SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( prLimitStr ) &&
!SizeLimitWrapper.NONE_STR.equalsIgnoreCase( prLimitStr ) )
{
try
{
if ( Integer.parseInt( prLimitStr ) < SizeLimitWrapper.UNLIMITED.intValue() )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* Check if the prtotal value is valid or not
*/
protected boolean isValidPrTotal()
{
String prTotalLimitStr = prTotalLimitText.getText();
if ( !Strings.isEmpty( prTotalLimitStr ) )
{
if ( !SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( prTotalLimitStr ) &&
!SizeLimitWrapper.NONE_STR.equalsIgnoreCase( prTotalLimitStr ) &&
!SizeLimitWrapper.HARD_STR.equalsIgnoreCase( prTotalLimitStr ) &&
!SizeLimitWrapper.DISABLED_STR.equalsIgnoreCase( prTotalLimitStr ) )
{
try
{
if ( Integer.parseInt( prTotalLimitStr ) < SizeLimitWrapper.PR_DISABLED.intValue() )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* The listener for the Unchecked Limit Text
*/
private ModifyListener uncheckedLimitTextListener = event ->
{
Display display = uncheckedLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
boolean disabled = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
// The possible values are : 'unlimited' | 'none' | 'disabled' | INT
String uncheckedLimitStr = uncheckedLimitText.getText();
if ( Strings.isEmpty( uncheckedLimitStr ) )
{
// Check the case we don't have anything
sizeLimitWrapper.setUncheckedLimit( null );
}
else if ( SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( uncheckedLimitStr ) ||
SizeLimitWrapper.NONE_STR.equalsIgnoreCase( uncheckedLimitStr ) )
{
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else if ( SizeLimitWrapper.DISABLED_STR.equalsIgnoreCase( uncheckedLimitStr ) )
{
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.PR_DISABLED );
disabled = true;
}
else
{
// An integer
try
{
int value = Integer.parseInt( uncheckedLimitStr );
if ( value < SizeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
else if ( value == SizeLimitWrapper.UNLIMITED )
{
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else if ( value == SizeLimitWrapper.UC_DISABLED )
{
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.UC_DISABLED );
disabled = true;
}
else
{
sizeLimitWrapper.setUncheckedLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
}
uncheckedLimitText.setForeground( display.getSystemColor( color ) );
uncheckedUnlimitedCheckbox.setSelection( unlimited );
uncheckedDisabledCheckbox.setSelection( disabled );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
};
/**
* The listener for the pr Limit Text
*/
private ModifyListener prLimitTextListener = event ->
{
Display display = prLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
// The possible values are : 'unlimited' | 'none' | 'noEstimate' | INT
String prLimitStr = prLimitText.getText();
if ( Strings.isEmpty( prLimitStr ) )
{
// Check the case we don't have anything
sizeLimitWrapper.setPrLimit( null );
}
else if ( SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( prLimitStr ) ||
SizeLimitWrapper.NONE_STR.equalsIgnoreCase( prLimitStr ) )
{
sizeLimitWrapper.setPrLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
// An integer
try
{
int value = Integer.parseInt( prLimitStr );
if ( value < SizeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
else if ( value == SizeLimitWrapper.UNLIMITED )
{
sizeLimitWrapper.setPrLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
sizeLimitWrapper.setPrLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
}
prLimitText.setForeground( display.getSystemColor( color ) );
prUnlimitedCheckbox.setSelection( unlimited );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
};
/**
* The listener for the prTotal Limit Text
*/
private ModifyListener prTotalLimitTextListener = event ->
{
Display display = prTotalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
boolean disabled = false;
boolean hard = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
// The possible values are : 'unlimited' | 'none' | 'disabled' | 'hard' | INT
String prTotalLimitStr = prTotalLimitText.getText();
if ( Strings.isEmpty( prTotalLimitStr ) )
{
// Check the case we don't have anything
sizeLimitWrapper.setPrTotalLimit( null );
}
else if ( SizeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( prTotalLimitStr ) ||
SizeLimitWrapper.NONE_STR.equalsIgnoreCase( prTotalLimitStr ) )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else if ( SizeLimitWrapper.HARD_STR.equalsIgnoreCase( prTotalLimitStr ) )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_HARD );
hard = true;
}
else if ( SizeLimitWrapper.DISABLED_STR.equalsIgnoreCase( prTotalLimitStr ) )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_DISABLED );
disabled = true;
}
else
{
// An integer
try
{
int value = Integer.parseInt( prTotalLimitStr );
if ( value < SizeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
else if ( value == SizeLimitWrapper.PR_DISABLED )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_DISABLED );
disabled = true;
}
else if ( value == SizeLimitWrapper.UNLIMITED )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.UNLIMITED );
unlimited = true;
}
else if ( value == SizeLimitWrapper.PR_HARD )
{
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_HARD );
}
else
{
sizeLimitWrapper.setPrTotalLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
}
prTotalLimitText.setForeground( display.getSystemColor( color ) );
prTotalUnlimitedCheckbox.setSelection( unlimited );
prTotalDisabledCheckbox.setSelection( disabled );
prTotalHardCheckbox.setSelection( hard );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
};
/**
* The listener in charge of exposing the changes when the unchecked unlimited button is checked
*/
private SelectionListener uncheckedUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = uncheckedLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( uncheckedUnlimitedCheckbox.getSelection() )
{
uncheckedLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
uncheckedDisabledCheckbox.setSelection( false );
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.UNLIMITED );
}
else
{
uncheckedLimitText.setText( "" );
sizeLimitWrapper.setUncheckedLimit( null );
}
uncheckedLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the unchecked disabled button is checked
*/
private SelectionListener uncheckedDisabledCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = uncheckedLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( uncheckedDisabledCheckbox.getSelection() )
{
uncheckedLimitText.setText( SizeLimitWrapper.DISABLED_STR );
uncheckedUnlimitedCheckbox.setSelection( false );
sizeLimitWrapper.setUncheckedLimit( SizeLimitWrapper.UC_DISABLED );
}
else
{
uncheckedLimitText.setText( "" );
sizeLimitWrapper.setUncheckedLimit( null );
}
uncheckedLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the pr unlimited button is checked
*/
private SelectionListener prUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = prLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( prUnlimitedCheckbox.getSelection() )
{
prLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
sizeLimitWrapper.setPrLimit( SizeLimitWrapper.UNLIMITED );
}
else
{
prLimitText.setText( "" );
sizeLimitWrapper.setPrLimit( null );
}
prLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the pr noEstimate button is checked
*/
private SelectionListener prNoEstimateCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
sizeLimitWrapper.setNoEstimate( prNoEstimateCheckbox.getSelection() );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the prTotal unlimited button is checked
*/
private SelectionListener prTotalUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = prTotalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( prTotalUnlimitedCheckbox.getSelection() )
{
prTotalLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.UNLIMITED );
}
else
{
prTotalLimitText.setText( "" );
sizeLimitWrapper.setPrTotalLimit( null );
}
prTotalLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
prTotalDisabledCheckbox.setSelection( false );
prTotalHardCheckbox.setSelection( false );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the prTotal disabled button is checked
*/
private SelectionListener prTotalDisabledCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = prTotalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( prTotalDisabledCheckbox.getSelection() )
{
prTotalLimitText.setText( SizeLimitWrapper.DISABLED_STR );
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_DISABLED );
}
else
{
prTotalLimitText.setText( "" );
sizeLimitWrapper.setPrTotalLimit( null );
}
prTotalLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
prTotalUnlimitedCheckbox.setSelection( false );
prTotalHardCheckbox.setSelection( false );
limitText.setText( getEditedElement().toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the prTotal hard button is checked
*/
private SelectionListener prTotalHardCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = prTotalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
SizeLimitWrapper sizeLimitWrapper = getEditedElement();
if ( prTotalHardCheckbox.getSelection() )
{
String hardStr = hardLimitText.getText();
if ( Strings.isEmpty( hardStr ) )
{
prTotalLimitText.setText( "" );
}
else
{
prTotalLimitText.setText( SizeLimitWrapper.HARD_STR );
}
sizeLimitWrapper.setPrTotalLimit( SizeLimitWrapper.PR_HARD );
}
else
{
prTotalLimitText.setText( "" );
sizeLimitWrapper.setPrTotalLimit( null );
}
if ( isValid() )
{
okButton.setEnabled( true );
prTotalLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
else
{
okButton.setEnabled( false );
prTotalLimitText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
prTotalUnlimitedCheckbox.setSelection( false );
prTotalDisabledCheckbox.setSelection( false );
limitText.setText( getEditedElement().toString() );
}
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Size Limit" );
}
/**
* Create the Dialog for SizeLimit :
* <pre>
* +--------------------------------------------------------------------------+
* | SizeLimit |
* | .----------------------------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global Limit : [----------] [] Unlimited | |
* | | | |
* | | Unchecked Limit : [----------] [] Unlimited [] Disabled | |
* | | | |
* | | Paged Results Limit : [----------] [] Unlimited [] No Estimate | |
* | | | |
* | | Paged Results Total : [----------] [] Unlimited [] Disabled [] Hard | |
* | '----------------------------------------------------------------------' |
* | Resulting SizeLimit |
* | .----------------------------------------------------------------------. |
* | | Size Limit : <////////////////////////////////////////////////////> | |
* | '----------------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createSizeLimitEditGroup( composite );
createSizeLimitShowGroup( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the SizeLimit input group. This is the part of the dialog
* where one can insert the SizeLimit values
*
* <pre>
* Size Limit
* .----------------------------------------------------------------------.
* | Soft Limit : [----------] [] Unlimited |
* | |
* | Hard Limit : [----------] [] Unlimited [] Soft |
* | |
* | Global Limit : [----------] [] Unlimited |
* | |
* | Unchecked Limit : [----------] [] Unlimited [] Disabled |
* | |
* | Paged Results Limit : [----------] [] Unlimited [] No Estimate |
* | |
* | Paged Results Total : [----------] [] Unlimited [] Disabled [] Hard |
* '----------------------------------------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createSizeLimitEditGroup( Composite parent )
{
// SizeLimit Group
Group sizeLimitGroup = BaseWidgetUtils.createGroup( parent, "Size Limit input", 1 );
GridLayout sizeLimitGridLayout = new GridLayout( 8, false );
sizeLimitGroup.setLayout( sizeLimitGridLayout );
sizeLimitGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
//------------------------------------------------------------------------------------------------
// SoftLimit Text
BaseWidgetUtils.createLabel( sizeLimitGroup, "Soft Limit :", 1 );
softLimitText = BaseWidgetUtils.createText( sizeLimitGroup, "", 1 );
// Soft Limit unlimited checkbox Button
softUnlimitedCheckbox = BaseWidgetUtils.createCheckbox( sizeLimitGroup, "Unlimited", 2 );
// 4 tabs to fill the line
BaseWidgetUtils.createLabel( sizeLimitGroup, "", 4 );
//------------------------------------------------------------------------------------------------
// HardLimit Text
BaseWidgetUtils.createLabel( sizeLimitGroup, "Hard Limit :", 1 );
hardLimitText = BaseWidgetUtils.createText( sizeLimitGroup, "", 1 );
// Hard Limit unlimited checkbox Button
hardUnlimitedCheckbox = BaseWidgetUtils.createCheckbox( sizeLimitGroup, "Unlimited", 2 );
// HardLimit soft checkbox Button
hardSoftCheckbox = BaseWidgetUtils.createCheckbox( sizeLimitGroup, "Soft", 2 );
// 2 tabs to fill the line
BaseWidgetUtils.createLabel( sizeLimitGroup, "", 2 );
//------------------------------------------------------------------------------------------------
// GlobalLimit Text
BaseWidgetUtils.createLabel( sizeLimitGroup, "Global Limit :", 1 );
globalLimitText = BaseWidgetUtils.createText( sizeLimitGroup, "", 1 );
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AbstractLimitDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AbstractLimitDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.SizeLimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.TimeLimitWrapper;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* A class that share elements of configuration between the SizeLimitDialog
* and TimeLimitDialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractLimitDialog<E> extends AddEditDialog<E>
{
// UI widgets
/** The SoftLimit Text and checkboxes */
protected Text softLimitText;
protected Button softUnlimitedCheckbox;
/** The HardLimit Text and checkboxes */
protected Text hardLimitText;
protected Button hardUnlimitedCheckbox;
protected Button hardSoftCheckbox;
/** The GlobalLimit Text and checkboxes */
protected Text globalLimitText;
protected Button globalUnlimitedCheckbox;
/** The resulting Limit Text, or an error message */
protected Text limitText;
/** The modified Limit, as a String */
protected String newLimitStr;
/** The wrapper (either time or size) used to store the parameters */
//protected AbstractLimitWrapper limitWrapper;
/**
* Create a new instance of the TimeSizeLimitDialog
*
* @param parentShell The parent Shell
*/
protected AbstractLimitDialog( Shell parentShell )
{
super( parentShell );
}
/**
* Check if the soft value is valid or not
*/
protected boolean isValidSoft()
{
String softLimitStr = softLimitText.getText();
if ( !Strings.isEmpty( softLimitStr ) )
{
if ( !TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( softLimitStr ) &&
!TimeLimitWrapper.NONE_STR.equals( softLimitStr ) )
{
try
{
if ( Integer.parseInt( softLimitStr ) < -1 )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* Check if the hard value is valid or not
*/
protected boolean isValidHard()
{
String hardLimitStr = hardLimitText.getText();
if ( !Strings.isEmpty( hardLimitStr ) )
{
if ( !TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( hardLimitStr ) &&
!TimeLimitWrapper.NONE_STR.equals( hardLimitStr ) &&
!TimeLimitWrapper.SOFT_STR.equalsIgnoreCase( hardLimitStr ) )
{
try
{
if ( Integer.parseInt( hardLimitStr ) < -1 )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* Check if the global value is valid or not
*/
protected boolean isValidGlobal()
{
String globalLimitStr = hardLimitText.getText();
if ( !Strings.isEmpty( globalLimitStr ) )
{
if ( !TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( globalLimitStr ) &&
!TimeLimitWrapper.NONE_STR.equals( globalLimitStr ) )
{
try
{
if ( Integer.parseInt( globalLimitStr ) < -1 )
{
return false;
}
}
catch ( NumberFormatException nfe )
{
return false;
}
}
}
return true;
}
/**
* Check if the global TimeLimit is valid :
* the values must be numeric, or "unlimited" or "none" or "soft" (for the hard limit). They
* also have to be >=0
*/
protected boolean isValid()
{
return isValidSoft() && isValidHard() && isValidGlobal();
}
/**
* The listener for the Soft Limit Text
*/
protected ModifyListener softLimitTextListener = event ->
{
Display display = softLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The possible values are : 'unlimited' | 'none' | INT | -1
String softLimitStr = softLimitText.getText();
LimitWrapper limitWrapper = ((LimitWrapper)getEditedElement());
if ( Strings.isEmpty( softLimitStr ) )
{
// Check the case we don't have anything
limitWrapper.setSoftLimit( null );
}
else if ( TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( softLimitStr ) ||
TimeLimitWrapper.NONE_STR.equalsIgnoreCase( softLimitStr ) )
{
limitWrapper.setSoftLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
// An integer
try
{
int value = Integer.parseInt( softLimitStr );
if ( value < TimeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED ;
}
else if ( value == TimeLimitWrapper.UNLIMITED )
{
limitWrapper.setSoftLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
limitWrapper.setSoftLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED ;
}
}
softUnlimitedCheckbox.setSelection( unlimited );
softLimitText.setForeground( display.getSystemColor( color ) );
limitText.setText( limitWrapper.toString() );
// Update the Hard limit if the hardSoft checkbox is set
if ( hardSoftCheckbox.getSelection() )
{
if ( Strings.isEmpty( softLimitStr ) )
{
hardLimitText.setText( "" );
}
else
{
hardLimitText.setText( softLimitStr );
// Use the same color than for the soft
Display displayHard = softLimitText.getDisplay();
hardLimitText.setForeground( displayHard.getSystemColor( color ) );
}
}
okButton.setEnabled( isValid() );
};
/**
* The listener for the Hard Limit Text
*/
protected ModifyListener hardLimitTextListener = event ->
{
Display display = hardLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The possible values are : 'unlimited' | 'none' | 'soft' | INT | -1
String hardLimitStr = hardLimitText.getText();
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( Strings.isEmpty( hardLimitStr ) )
{
// Check the case we don't have anything
limitWrapper.setHardLimit( null );
}
else if ( TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( hardLimitStr ) ||
TimeLimitWrapper.NONE_STR.equalsIgnoreCase( hardLimitStr ) )
{
limitWrapper.setHardLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else if ( TimeLimitWrapper.SOFT_STR.equalsIgnoreCase( hardLimitStr ) )
{
limitWrapper.setHardLimit( limitWrapper.getSoftLimit() );
unlimited = softUnlimitedCheckbox.getSelection();
}
else
{
// An integer
try
{
int value = Integer.parseInt( hardLimitStr );
if ( value < TimeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
else if ( value == TimeLimitWrapper.UNLIMITED )
{
limitWrapper.setHardLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
limitWrapper.setHardLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
}
hardUnlimitedCheckbox.setSelection( unlimited );
hardLimitText.setForeground( display.getSystemColor( color ) );
limitText.setText( limitWrapper.toString() );
if ( isValidSoft() )
{
okButton.setEnabled( true );
}
else
{
okButton.setEnabled( isValid() );
}
};
/**
* The listener for the Global Limit Text
*/
protected ModifyListener globalLimitTextListener = event ->
{
Display display = globalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean unlimited = false;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The possible values are : 'unlimited' | 'none' | INT | -1
String globalLimitStr = globalLimitText.getText();
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( Strings.isEmpty( globalLimitStr ) )
{
// Check the case we don't have anything
limitWrapper.setGlobalLimit( null );
}
else if ( TimeLimitWrapper.UNLIMITED_STR.equalsIgnoreCase( globalLimitStr ) ||
TimeLimitWrapper.NONE_STR.equalsIgnoreCase( globalLimitStr ) )
{
limitWrapper.setGlobalLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
// An integer
try
{
int value = Integer.parseInt( globalLimitStr );
if ( value < TimeLimitWrapper.UNLIMITED )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
else if ( value == TimeLimitWrapper.UNLIMITED )
{
limitWrapper.setGlobalLimit( TimeLimitWrapper.UNLIMITED );
unlimited = true;
}
else
{
limitWrapper.setGlobalLimit( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
}
}
limitText.setText( limitWrapper.toString() );
globalLimitText.setForeground( display.getSystemColor( color ) );
globalUnlimitedCheckbox.setSelection( unlimited );
okButton.setEnabled( isValid() );
};
/**
* The listener in charge of exposing the changes when the soft unlimited button is checked
*/
protected SelectionListener softUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = softLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( softUnlimitedCheckbox.getSelection() )
{
softLimitText.setText( TimeLimitWrapper.UNLIMITED_STR );
limitWrapper.setSoftLimit( TimeLimitWrapper.UNLIMITED );
}
else
{
softLimitText.setText( "" );
limitWrapper.setSoftLimit( null );
}
if ( isValidSoft() )
{
softLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
else
{
softLimitText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
limitText.setText( limitWrapper.toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the hard unlimited button is checked
*/
protected SelectionListener hardUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = hardLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( hardUnlimitedCheckbox.getSelection() )
{
hardLimitText.setText( TimeLimitWrapper.UNLIMITED_STR );
limitWrapper.setHardLimit( TimeLimitWrapper.UNLIMITED );
hardSoftCheckbox.setSelection( false );
hardLimitText.setEnabled( true );
}
else
{
hardLimitText.setText( "" );
limitWrapper.setHardLimit( null );
}
hardLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
limitText.setText( limitWrapper.toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the hard unlimited button is checked.
* We will disable the hardLimitText.
*/
protected SelectionListener hardSoftCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = hardLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( hardSoftCheckbox.getSelection() )
{
hardLimitText.setEnabled( false );
String softStr = softLimitText.getText();
if ( softStr != null )
{
hardLimitText.setText( softStr );
}
else
{
hardLimitText.setText( "" );
}
limitWrapper.setHardLimit( limitWrapper.getSoftLimit() );
hardUnlimitedCheckbox.setSelection( TimeLimitWrapper.UNLIMITED.equals( limitWrapper.getSoftLimit() ) );
if ( isValidSoft() )
{
hardLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
else
{
hardLimitText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
}
else
{
hardLimitText.setText( "" );
hardLimitText.setEnabled( true );
limitWrapper.setHardLimit( null );
}
limitText.setText( limitWrapper.toString() );
okButton.setEnabled( isValid() );
}
};
/**
* The listener in charge of exposing the changes when the global unlimited button is checked
*/
protected SelectionListener globalUnlimitedCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = globalLimitText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( globalUnlimitedCheckbox.getSelection() )
{
globalLimitText.setText( TimeLimitWrapper.UNLIMITED_STR );
limitWrapper.setGlobalLimit( TimeLimitWrapper.UNLIMITED );
}
else
{
globalLimitText.setText( "" );
limitWrapper.setGlobalLimit( null );
}
globalLimitText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
limitText.setText( limitWrapper.toString() );
okButton.setEnabled( isValid() );
}
};
/**
* Construct the new TimeLimit from what we have in the dialog
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
newLimitStr = getEditedElement().toString();
super.okPressed();
}
/**
* {@inheritDoc}
*/
public String getNewLimit()
{
return newLimitStr;
}
/**
* Initializes the UI from the Limit
*/
protected void initDialog()
{
LimitWrapper limitWrapper = (LimitWrapper)getEditedElement();
if ( limitWrapper != null )
{
// The SoftLimit
Integer softLimit = limitWrapper.getSoftLimit();
if ( softLimit == null )
{
softLimitText.setText( "" );
softUnlimitedCheckbox.setSelection( false );
}
else if ( softLimit.equals( SizeLimitWrapper.UNLIMITED ) )
{
softLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
softUnlimitedCheckbox.setSelection( true );
}
else
{
softLimitText.setText( softLimit.toString() );
softUnlimitedCheckbox.setSelection( false );
}
// The HardLimit
Integer hardLimit = limitWrapper.getHardLimit();
if ( hardLimit == null )
{
hardLimitText.setText( "" );
hardUnlimitedCheckbox.setSelection( false );
hardSoftCheckbox.setSelection( false );
}
else if ( hardLimit.equals( SizeLimitWrapper.UNLIMITED ) )
{
hardLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
hardUnlimitedCheckbox.setSelection( true );
hardSoftCheckbox.setSelection( false );
}
else if ( hardLimit.equals( SizeLimitWrapper.HARD_SOFT ) )
{
hardLimitText.setText( SizeLimitWrapper.SOFT_STR );
hardUnlimitedCheckbox.setSelection( false );
hardSoftCheckbox.setSelection( true );
}
else
{
hardLimitText.setText( hardLimit.toString() );
hardUnlimitedCheckbox.setSelection( false );
hardSoftCheckbox.setSelection( false );
}
// The GlobalLimit
Integer globalLimit = limitWrapper.getGlobalLimit();
if ( globalLimit == null )
{
globalLimitText.setText( "" );
globalUnlimitedCheckbox.setSelection( false );
}
else if ( globalLimit.equals( SizeLimitWrapper.UNLIMITED ) )
{
globalLimitText.setText( SizeLimitWrapper.UNLIMITED_STR );
globalUnlimitedCheckbox.setSelection( true );
}
else
{
globalLimitText.setText( globalLimit.toString() );
globalUnlimitedCheckbox.setSelection( false );
}
limitText.setText( limitWrapper.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SsfDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SsfDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.openldap.common.ui.model.SsfFeatureEnum;
import org.apache.directory.studio.openldap.common.ui.model.SsfStrengthEnum;
import org.apache.directory.studio.openldap.config.editor.wrappers.SsfWrapper;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* A Dialog used to configure the OpenLDAP SSF. SSF (Security Strength Factors) associates
* a strength to a feature. Here is the list of feature that support a SSF :
* <ul>
* <li>ssf : global</li>
* <li>transport</li>
* <li>tls</li>
* <li>sasl</li>
* <li>simple_bind</li>
* <li>update_ssf</li>
* <li>update_transport</li>
* <li>update_tls</li>
* <li>update_sasl</li>
* </ul>
* The ssf value will generally depend on the number of bits used by the cipher to use,
* with two special values : 0 and 1. Here is a set of possible values :
* <ul>
* <li>0 : no protection</li>
* <li>1 : integrity check only</li>
* <li>56 : DES (key length is 56 bits)</li>
* <li>112 : 3DES (key length is 112 bits)</li>
* <li>128 : RC4, Blowish, AES-128</li>
* <li>256 : AES-256</li>
* </ul>
*
* We will allow the user to select the feature to configure, and the value to set. Here is
* the layout :
* <pre>
* +-----------------------------------------------+
* | Security |
* | .-------------------------------------------. |
* | | Feature : [----------------------------] | |
* | | [ ] No protection | |
* | | [ ] Integrity | |
* | | [ ] 56 bits (DES) | |
* | | [ ] 112 bits (3DES) | |
* | | [ ] 128 bits (RC4, Blowfish...) | |
* | | [ ] 256 bits (AES-256, ...) | |
* | | [ ] Other value | |
* | '-------------------------------------------' |
* | Resulting Security |
* | .-------------------------------------------. |
* | | Security : <///////////////////////////> | |
* | '-------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SsfDialog extends AddEditDialog<SsfWrapper>
{
// UI widgets
private Combo featureCombo;
/** The strength list */
private Button[] strengthCheckbox = new Button[6];
/** The other strength list */
private Text otherText;
// The resulting SSF
private Text ssfText;
// The list of options in the combo
private String[] features = new String[]
{
SsfFeatureEnum.NONE.getName(),
SsfFeatureEnum.SASL.getName(),
SsfFeatureEnum.SIMPLE_BIND.getName(),
SsfFeatureEnum.SSF.getName(),
SsfFeatureEnum.TLS.getName(),
SsfFeatureEnum.TRANSPORT.getName(),
SsfFeatureEnum.UPDATE_SASL.getName(),
SsfFeatureEnum.UPDATE_SSF.getName(),
SsfFeatureEnum.UPDATE_TLS.getName(),
SsfFeatureEnum.UPDATE_TRANSPORT.getName(),
};
// An empty space
protected static final String TABULATION = " ";
/**
* The listener in charge of exposing the changes when some buttons are checked
*/
private SelectionListener featureSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Combo )
{
Combo featureCombo = (Combo)object;
Display display = ssfText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
String feature = featureCombo.getText();
SsfWrapper ssfWrapper = getEditedElement();
SsfFeatureEnum ssfFeature = SsfFeatureEnum.getSsfFeature( feature );
// Check if it's not already part of the SSF
boolean present = false;
for ( SsfWrapper ssf : getElements() )
{
if ( ssfFeature == ssf.getFeature() )
{
present = true;
break;
}
}
if ( !present )
{
ssfWrapper.setFeature( SsfFeatureEnum.getSsfFeature( feature ) );
ssfText.setText( ssfWrapper.toString() );
if ( ssfWrapper.isValid() )
{
okButton.setEnabled( true );
ssfText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
else
{
okButton.setEnabled( false );
ssfText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
}
else
{
// Come back to NONE
featureCombo.setText( SsfFeatureEnum.NONE.getName() );
}
}
}
};
/**
* The listener in charge of exposing the changes when some buttons are checked
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
Display display = ssfText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
if ( object instanceof Button )
{
Button selectedButton = (Button)object;
SsfWrapper ssfWrapper = getEditedElement();
if ( selectedButton.getSelection() )
{
for ( int i = 0; i < strengthCheckbox.length; i++ )
{
if ( selectedButton.equals( strengthCheckbox[i] ) )
{
switch ( i )
{
case 0 :
ssfWrapper.setNbBits( SsfStrengthEnum.NO_PROTECTION.getNbBits() );
break;
case 1 :
ssfWrapper.setNbBits( SsfStrengthEnum.INTEGRITY_CHECK.getNbBits() );
break;
case 2 :
ssfWrapper.setNbBits( SsfStrengthEnum.DES.getNbBits() );
break;
case 3 :
ssfWrapper.setNbBits( SsfStrengthEnum.THREE_DES.getNbBits() );
break;
case 4 :
ssfWrapper.setNbBits( SsfStrengthEnum.AES_128.getNbBits() );
break;
case 5 :
ssfWrapper.setNbBits( SsfStrengthEnum.AES_256.getNbBits() );
break;
}
}
else
{
// Not selected, uncheck it.
strengthCheckbox[i].setSelection( false );
}
}
// Erase the content of the Other text
otherText.setText( "" );
}
ssfText.setText( ssfWrapper.toString() );
if ( ssfWrapper.isValid() )
{
okButton.setEnabled( true );
ssfText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
else
{
okButton.setEnabled( false );
ssfText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
}
}
};
/**
* The listener for the other Text
*/
private ModifyListener otherTextListener = event ->
{
Display display = otherText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
int nbBits = Integer.parseInt( otherText.getText() );
// The nbBits must be between >=0
if ( nbBits < 0L )
{
otherText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
return;
}
otherText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
getEditedElement().setNbBits( nbBits );
ssfText.setText( getEditedElement().toString() );
okButton.setEnabled( true );
}
catch ( NumberFormatException nfe )
{
// Not even a number
otherText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
ssfText.setText( getEditedElement().toString() );
okButton.setEnabled( false );
}
};
/**
* Creates a new instance of SsfDialog.
*
* @param parentShell the parent shell
*/
public SsfDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* {@inheritDoc}
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "OpenLDAP SSF" );
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
// Do nothing if the selected feature is NONE
if ( getEditedElement().getFeature() != SsfFeatureEnum.NONE )
{
super.okPressed();
}
}
/**
* Create the Dialog for the SSF :
* <pre>
* +-----------------------------------------------+
* | Security |
* | .-------------------------------------------. |
* | | Feature : [----------------------------] | |
* | | [ ] No protection | |
* | | [ ] Integrity | |
* | | [ ] 56 bits (DES) | |
* | | [ ] 112 bits (3DES) | |
* | | [ ] 128 bits (RC4, Blowfish...) | |
* | | [ ] 256 bits (AES-256, ...) | |
* | | [ ] Other value | |
* | '-------------------------------------------' |
* | Resulting Security |
* | .-------------------------------------------. |
* | | Security : <///////////////////////////> | |
* | '-------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------------------------+
* </pre>
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createSsfEditArea( composite );
createSsfShowArea( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Overriding the createButton method, so that we can disable the OK button if no feature is selected.
*
* {@inheritDoc}
*/
@Override
protected Button createButton(Composite parent, int id, String label, boolean defaultButton)
{
Button button = super.createButton( parent, id, label, defaultButton );
if ( id == IDialogConstants.OK_ID )
{
SsfWrapper ssfWrapper = getEditedElement();
if ( ssfWrapper != null )
{
SsfFeatureEnum feature = ssfWrapper.getFeature();
if ( feature == SsfFeatureEnum.NONE )
{
button.setEnabled( false );
}
}
}
return button;
}
/**
* Initializes the Dialog with the values
*/
protected void initDialog()
{
SsfWrapper ssfWrapper = getEditedElement();
if ( ssfWrapper != null )
{
SsfFeatureEnum feature = ssfWrapper.getFeature();
if ( feature == SsfFeatureEnum.NONE )
{
featureCombo.setText( SsfFeatureEnum.NONE.getName() );
// Remove the feature that are already part of the list
for ( SsfWrapper element : getElements() )
{
featureCombo.remove( element.getFeature().getName() );
}
}
else
{
// Remove all the other features, and inject the one being edited
featureCombo.removeAll();
featureCombo.add( feature.getName() );
featureCombo.setText( feature.getName() );
// Disable the combo
featureCombo.setEnabled( false );
}
SsfStrengthEnum ssfStrength = SsfStrengthEnum.getSsfStrength( ssfWrapper.getNbBits() );
switch ( ssfStrength )
{
case NO_PROTECTION :
strengthCheckbox[0].setSelection( true );
break;
case INTEGRITY_CHECK :
strengthCheckbox[1].setSelection( true );
break;
case DES :
strengthCheckbox[2].setSelection( true );
break;
case THREE_DES :
strengthCheckbox[3].setSelection( true );
break;
case AES_128 :
strengthCheckbox[4].setSelection( true );
break;
case AES_256 :
strengthCheckbox[5].setSelection( true );
break;
default :
otherText.setText( Integer.toString( ssfWrapper.getNbBits() ) );
break;
}
ssfText.setText( ssfWrapper.toString() );
}
}
/**
* Creates the Ssf edit area.
*
* @param parent the parent composite
*/
private void createSsfEditArea( Composite parent )
{
Group ssfEditGroup = BaseWidgetUtils.createGroup( parent, "Security Strength Factors", 1 );
ssfEditGroup.setLayout( new GridLayout( 2, false ) );
// The feature
featureCombo = BaseWidgetUtils.createCombo( ssfEditGroup, features, 0, 2 );
// No-protection checkbox
strengthCheckbox[0] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.NO_PROTECTION.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// Integrity checkbox
strengthCheckbox[1] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.INTEGRITY_CHECK.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// DES checkbox
strengthCheckbox[2] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.DES.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// 3DES checkbox
strengthCheckbox[3] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.THREE_DES.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// AES-128 checkbox
strengthCheckbox[4] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.AES_128.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// AES-256 checkbox
strengthCheckbox[5] = BaseWidgetUtils.createCheckbox( ssfEditGroup, SsfStrengthEnum.AES_256.getName(), 1 );
BaseWidgetUtils.createLabel( ssfEditGroup, TABULATION, 1 );
// Other Text
BaseWidgetUtils.createLabel( ssfEditGroup, "Other value :", 1 );
otherText = BaseWidgetUtils.createText( ssfEditGroup, "", 1 );
otherText.addModifyListener( otherTextListener );
}
/**
* Creates the SSF show area. It's not editable
*
* @param parent the parent composite
*/
private void createSsfShowArea( Composite parent )
{
Group ssfValueGroup = BaseWidgetUtils.createGroup( parent, "SSF Value", 1 );
ssfText = BaseWidgetUtils.createText( ssfValueGroup, "", 1 );
ssfText.setEditable( false );
}
/**
* Adds listeners.
*/
private void addListeners()
{
featureCombo.addSelectionListener( featureSelectionListener );
for ( Button checkbox : strengthCheckbox )
{
checkbox.addSelectionListener( checkboxSelectionListener );
}
otherText.addModifyListener( otherTextListener );
}
@Override
public void addNewElement()
{
setEditedElement( new SsfWrapper( "" ) );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RequireConditionDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RequireConditionDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.RequireConditionEnum;
/**
* The RestrictOperationDialog is used to select one required condition. The possible
* conditions are :
* <ul>
* <li>authc</li>
* <li>bind</li>
* <li>LDAPv3</li>
* <li>none</li>
* <li>sasl</li>
* <li>strong</li>
* </ul>
*
* The dialog overlay is like :
*
* <pre>
* +-----------------------------+
* | Required condition |
* | .-------------------------. |
* | | authc : [ ] bind : [] | |
* | | LDAPv3 : [ ] sasl : [] | |
* | | strong : [ ] none : [] | |
* | '-------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RequireConditionDialog extends AddEditDialog<RequireConditionEnum>
{
/** The array of buttons */
private Button[] requireConditionCheckboxes = new Button[6];
/** The already selected Required Conditions */
List<RequireConditionEnum> conditions = new ArrayList<>();
/**
* Create a new instance of the RequireConditionDialog
*
* @param parentShell The parent Shell
*/
public RequireConditionDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "RequireCondition.Title" ) );
}
/**
* The listener in charge of exposing the changes when some checkbox is selected
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedCheckbox = (Button)object;
for ( int i = 1; i < requireConditionCheckboxes.length; i++ )
{
if ( selectedCheckbox == requireConditionCheckboxes[i] )
{
setEditedElement( RequireConditionEnum.getCondition( i ) );
}
else if ( requireConditionCheckboxes[i].isEnabled() )
{
requireConditionCheckboxes[i].setSelection( false );
}
}
}
}
};
/**
* Create the Dialog for RequireCondition :
* <pre>
* +-----------------------------+
* | Required condition |
* | .-------------------------. |
* | | authc : [ ] bind : [] | |
* | | LDAPv3 : [ ] sasl : [] | |
* | | strong : [ ] none : [] | |
* | '-------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createRequireConditionEditGroup( composite );
initDialog();
applyDialogFont( composite );
return composite;
}
/**
* Creates the RequireCondition input group.
*
* <pre>
* Required condition
* .-------------------------.
* | authc : [ ] bind : [] |
* | LDAPv3 : [ ] sasl : [] |
* | strong : [ ] none : [] |
* '-------------------------'
* </pre>
* @param parent the parent composite
*/
private void createRequireConditionEditGroup( Composite parent )
{
// Require Condition Group
Group requireConditionGroup = BaseWidgetUtils.createGroup( parent, "", 2 );
GridLayout requireConditionGridLayout = new GridLayout( 2, false );
requireConditionGroup.setLayout( requireConditionGridLayout );
requireConditionGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The various buttons
for ( int i = 1; i < requireConditionCheckboxes.length; i++ )
{
String requireCondition = RequireConditionEnum.getCondition( i ).getName();
requireConditionCheckboxes[i] = BaseWidgetUtils.createCheckbox( requireConditionGroup, requireCondition, 1 );
requireConditionCheckboxes[i].addSelectionListener( checkboxSelectionListener );
}
}
protected void initDialog()
{
List<RequireConditionEnum> elements = getElements();
boolean allSelected = true;
okDisabled = false;
for ( int i = 1; i < requireConditionCheckboxes.length; i++ )
{
RequireConditionEnum value = RequireConditionEnum.getCondition( requireConditionCheckboxes[i].getText() );
// Disable the Conditions already selected
if ( elements.contains( value ) )
{
requireConditionCheckboxes[i].setSelection( true );
requireConditionCheckboxes[i].setEnabled( false );
}
else
{
allSelected = false;
}
}
if ( allSelected )
{
// Disable the OK button
okDisabled = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void addNewElement()
{
// Default to none
setEditedElement( RequireConditionEnum.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/PasswordHashDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/PasswordHashDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.PasswordHashEnum;
/**
* The PasswordHashDialog is used to select one hash method. The possible
* hash methods are :
* <ul>
* <li>{CLEARTEXT}</li>
* <li>{CRYPT}</li>
* <li>{LANMAN}</li>
* <li>{MD5}</li>
* <li>{SMD5}</li>
* <li>{SHA}</li>
* <li>{SSHA}</li>
* <li>{UNIX}</li>
*
* The dialog overlay is like :
*
* <pre>
* +-----------------------------------------+
* | Password hash |
* | .-------------------------------------. |
* | | CLear Text : [ ] Crypt : [ ] | |
* | | LANMAN : [ ] MD5 : [ ] | |
* | | SMD5 : [ ] SHA : [ ] | |
* | | SSHA : [ ] Unix : [ ] | |
* | '-------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PasswordHashDialog extends AddEditDialog<PasswordHashEnum>
{
/** The array of buttons */
private Button[] passwordHashCheckboxes = new Button[9];
/** The already selected hashes */
List<PasswordHashEnum> hashes = new ArrayList<>();
/**
* Create a new instance of the PasswordHashDialog
*
* @param parentShell The parent Shell
*/
public PasswordHashDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "PasswordHash.Title" ) );
}
/**
* The listener in charge of exposing the changes when some checkbox is selectionned
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedCheckbox = (Button)object;
for ( int i = 1; i < passwordHashCheckboxes.length; i++ )
{
if ( selectedCheckbox == passwordHashCheckboxes[i] )
{
setEditedElement( PasswordHashEnum.getPasswordHash( i ) );
}
else if ( passwordHashCheckboxes[i].isEnabled() )
{
passwordHashCheckboxes[i].setSelection( false );
}
}
}
}
};
/**
* Create the Dialog for PasswordHash :
* <pre>
* +-----------------------------------------+
* | Password hash |
* | .-------------------------------------. |
* | | CLear Text : [ ] Crypt : [ ] | |
* | | LANMAN : [ ] MD5 : [ ] | |
* | | SMD5 : [ ] SHA : [ ] | |
* | | SSHA : [ ] Unix : [ ] | |
* | '-------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-----------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createPasswordHashEditGroup( composite );
initDialog();
applyDialogFont( composite );
return composite;
}
/**
* Creates the PasswordHash input group. This is the part of the dialog
* where one can insert the TimeLimit values
*
* <pre>
* Password hash
* .------------------.
* | CLear Text : [ ] |
* | Crypt : [ ] |
* | LANMAN : [ ] |
* | MD5 : [ ] |
* | SMD5 : [ ] |
* | SHA : [ ] |
* | SSHA : [ ] |
* | Unix : [ ] |
* '------------------'
* </pre>
* @param parent the parent composite
*/
private void createPasswordHashEditGroup( Composite parent )
{
// Password Hash Group
Group passwordHashGroup = BaseWidgetUtils.createGroup( parent, "", 2 );
GridLayout passwordHashGridLayout = new GridLayout( 2, false );
passwordHashGroup.setLayout( passwordHashGridLayout );
passwordHashGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The various buttons
for ( int i = 1; i < passwordHashCheckboxes.length; i++ )
{
PasswordHashEnum passwordHash = PasswordHashEnum.getPasswordHash( i );
Button button = BaseWidgetUtils.createCheckbox( passwordHashGroup, passwordHash.getName(), 1 );
passwordHashCheckboxes[i] = button;
passwordHashCheckboxes[i].addSelectionListener( checkboxSelectionListener );
}
}
protected void initDialog()
{
List<PasswordHashEnum> elements = getElements();
boolean allSelected = true;
okDisabled = false;
for ( int i = 1; i < passwordHashCheckboxes.length; i++ )
{
PasswordHashEnum value = PasswordHashEnum.getPasswordHash( passwordHashCheckboxes[i].getText() );
// Disable the hashes already selected
if ( elements.contains( value ) )
{
passwordHashCheckboxes[i].setSelection( true );
passwordHashCheckboxes[i].setEnabled( false );
}
else
{
allSelected = false;
}
}
if ( allSelected )
{
// Disable the OK button
okDisabled = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void addNewElement()
{
// Default to none
setEditedElement( PasswordHashEnum.NO_CHOICE );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DnValueDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DnValueDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.openldap.config.editor.wrappers.DnWrapper;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* The DnValueDialog is used to edit a DN
*
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | DN : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
*
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DnValueDialog extends AddEditDialog<DnWrapper>
{
// UI widgets
/** The DN Text */
private Text dnText;
/**
* Create a new instance of the String
*
* @param parentShell The parent Shell
*/
public DnValueDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* The listener for the DN Text
*/
private ModifyListener dnValueTextListener = event ->
{
Display display = dnText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
Dn dn = new Dn( dnText.getText() );
getEditedElement().setDn( dn );
okButton.setEnabled( true );
dnText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
}
catch ( LdapInvalidDnException e1 )
{
okButton.setEnabled( false );
dnText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
}
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "DN" );
}
/**
* Create the Dialog for DnValue :
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | Dn : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// DnValue Group
Group dnValueGroup = BaseWidgetUtils.createGroup( parent, null, 1 );
GridLayout stringValueGroupGridLayout = new GridLayout( 2, false );
dnValueGroup.setLayout( stringValueGroupGridLayout );
dnValueGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// DN Text
BaseWidgetUtils.createLabel( dnValueGroup, "DN :", 1 );
dnText = BaseWidgetUtils.createText( dnValueGroup, "", 1 );
dnText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Initializes the UI from the String
*/
protected void initDialog()
{
DnWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
Dn dn = editedElement.getDn();
if ( dn == null )
{
dnText.setText( "" );
}
else
{
dnText.setText( dn.toString() );
}
}
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new DnWrapper( Dn.EMPTY_DN ) );
}
public void addNewElement( DnWrapper editedElement )
{
// No need to clone, the Dn is immutable
setEditedElement( editedElement );
}
/**
* Adds listeners.
*/
private void addListeners()
{
dnText.addModifyListener( dnValueTextListener );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DisallowFeatureDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DisallowFeatureDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.DisallowFeatureEnum;
/**
* The DisallowFeatureDialog is used to select one feature to allow. The possible
* features are :
* <ul>
* <li>bind_anon</li>
* <li>bind_simple</li>
* <li>tls_2_anon</li>
* <li>tls_authc</li>
* <li>proxy_authz_non_critical</li>
* <li>dontusecopy_non_critical</li>
* </ul>
*
* The dialog overlay is like :
*
* <pre>
* +------------------------------------+
* | Disallowed feature |
* | .--------------------------------. |
* | | bind_anon : [ ] | |
* | | bind_simple : [ ] | |
* | | tls_2_anon : [ ] | |
* | | tls_authc : [ ] | |
* | | proxy_authz_non_critical : [ ] | |
* | | dontusecopy_non_critical : [ ] | |
* | '--------------------------------' |
* | |
* | (Cancel) (OK) |
* +------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DisallowFeatureDialog extends AddEditDialog<DisallowFeatureEnum>
{
/** The array of buttons */
private Button[] disallowFeatureCheckboxes = new Button[6];
/** The already selected disaallowed features */
List<DisallowFeatureEnum> features = new ArrayList<>();
/**
* Create a new instance of the DisallowFeatureDialog
*
* @param parentShell The parent Shell
*/
public DisallowFeatureDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "DisallowFeature.Title" ) );
}
/**
* The listener in charge of exposing the changes when some checkbox is selected
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedCheckbox = (Button)object;
for ( int i = 1; i < disallowFeatureCheckboxes.length; i++ )
{
if ( selectedCheckbox == disallowFeatureCheckboxes[i] )
{
setEditedElement( DisallowFeatureEnum.getFeature( i ) );
}
else if ( disallowFeatureCheckboxes[i].isEnabled() )
{
disallowFeatureCheckboxes[i].setSelection( false );
}
}
}
}
};
/**
* Create the Dialog for DisallowFeature :
* <pre>
* +------------------------------------+
* | Disallowed feature |
* | .--------------------------------. |
* | | bind_anon : [ ] | |
* | | bind_simple : [ ] | |
* | | tls_2_anon : [ ] | |
* | | tls_authc : [ ] | |
* | | proxy_authz_non_critical : [ ] | |
* | | dontusecopy_non_critical : [ ] | |
* | '--------------------------------' |
* | |
* | (Cancel) (OK) |
* +------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createDisallowFeatureEditGroup( composite );
initDialog();
applyDialogFont( composite );
return composite;
}
/**
* Creates the DisallowFeature input group.
*
* <pre>
* Disallowed feature
* .--------------------------------.
* | bind_anon : [ ] |
* | bind_simple : [ ] |
* | tls_2_anon : [ ] |
* | tls_authc : [ ] |
* | proxy_authz_non_critical : [ ] |
* | dontusecopy_non_critical : [ ] |
* '--------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createDisallowFeatureEditGroup( Composite parent )
{
// Disallow Feature Group
Group disallowFeatureGroup = BaseWidgetUtils.createGroup( parent, "", 1 );
GridLayout disallowFeatureGridLayout = new GridLayout( 1, false );
disallowFeatureGroup.setLayout( disallowFeatureGridLayout );
disallowFeatureGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The various buttons
for ( int i = 1; i < disallowFeatureCheckboxes.length; i++ )
{
String disallowFeature = DisallowFeatureEnum.getFeature( i ).getName();
disallowFeatureCheckboxes[i] = BaseWidgetUtils.createCheckbox( disallowFeatureGroup, disallowFeature, 1 );
disallowFeatureCheckboxes[i].addSelectionListener( checkboxSelectionListener );
}
}
protected void initDialog()
{
List<DisallowFeatureEnum> elements = getElements();
boolean allSelected = true;
okDisabled = false;
for ( int i = 1; i < disallowFeatureCheckboxes.length; i++ )
{
DisallowFeatureEnum value = DisallowFeatureEnum.getFeature( disallowFeatureCheckboxes[i].getText() );
// Disable the features already selected
if ( elements.contains( value ) )
{
disallowFeatureCheckboxes[i].setSelection( true );
disallowFeatureCheckboxes[i].setEnabled( false );
}
else
{
allSelected = false;
}
}
if ( allSelected )
{
// Disable the OK button
okDisabled = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void addNewElement()
{
// Default to none
setEditedElement( DisallowFeatureEnum.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OpenLdapConfigDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OpenLdapConfigDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.openldap.config.model.OpenLdapConfigFormat;
import org.apache.directory.studio.openldap.config.model.OpenLdapVersion;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
/**
* A Dialog opened when a new OpenLDAP configuration is created.
* I asks for the OpenLDAP version and file format (slapd.d or slapd.conf).
*
* Here is what teh dialog looks like :
*
* <pre>
* .--------------------------------.
* | o o o |
* +--------------------------------+
* | OpenLDAP version [2.4.45|v] |
* | File Format |
* | .----------------------------. |
* | | ( ) Static (slapd.conf) | |
* | | (o) Dynamic (slapd.d) | |
* | `----------------------------' |
* | |
* | (Cancel) (Ok) |
* `--------------------------------'
* </pre>
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OpenLdapConfigDialog extends Dialog
{
/** The version combo. */
private Combo versionCombo;
/** The selected version */
private OpenLdapVersion openLdapVersion;
/** The static file format button */
private Button staticButton;
/** The file format*/
private OpenLdapConfigFormat openLdapConfigFormat;
/**
* Creates a new instance of AttributeDialog.
*
* @param parentShell the parent shell
* @param currentAttribute the current attribute, null if none
* @param attributeNamesAndOids the possible attribute names and OIDs
*/
public OpenLdapConfigDialog( Shell parentShell )
{
super( parentShell );
// Default to 2.4.45 and dynamic
openLdapVersion = OpenLdapVersion.VERSION_2_4_45;
openLdapConfigFormat = OpenLdapConfigFormat.DYNAMIC;
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "Configuration.Title" ) );
}
/**
* {@inheritDoc}
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
}
/**
* {@inheritDoc}
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite dialogComposite = ( Composite ) super.createDialogArea( parent );
Composite composite = BaseWidgetUtils.createColumnContainer( dialogComposite, 2, 1 );
BaseWidgetUtils.createLabel( composite, Messages.getString( "Configuration.Version" ), 1 ); //$NON-NLS-1$
versionCombo = BaseWidgetUtils.createCombo( composite, OpenLdapVersion.getVersions(), -1, 1 );
versionCombo.setText( OpenLdapVersion.VERSION_2_4_45.getValue() );
// The forat group
Group formatGroup = BaseWidgetUtils.createGroup( composite, Messages.getString( "Configuration.FileFormat" ), 2 );
// The static format button
staticButton = new Button( formatGroup, SWT.RADIO );
staticButton.setText( Messages.getString( "Configuration.Static" ) );
Button dynamicButton = new Button( formatGroup, SWT.RADIO );
dynamicButton.setText( Messages.getString( "Configuration.Dynamic" ) );
dynamicButton.setSelection( true );
return dialogComposite;
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
openLdapVersion = OpenLdapVersion.getVersion( versionCombo.getText() );
if ( staticButton.getSelection() )
{
openLdapConfigFormat = OpenLdapConfigFormat.STATIC;
}
else
{
openLdapConfigFormat = OpenLdapConfigFormat.DYNAMIC;
}
super.okPressed();
}
/**
* @return the openLdapVersion
*/
public OpenLdapVersion getOpenLdapVersion()
{
return openLdapVersion;
}
/**
* @param openLdapVersion the openLdapVersion to set
*/
public void setOpenLdapVersion( OpenLdapVersion openLdapVersion )
{
this.openLdapVersion = openLdapVersion;
}
/**
* @return the openLdapConfigFomat
*/
public OpenLdapConfigFormat getOpenLdapConfigFormat()
{
return openLdapConfigFormat;
}
/**
* @param openLdapConfigFomat the openLdapConfigFomat to set
*/
public void setOpenLdapConfigFomat( OpenLdapConfigFormat openLdapConfigFormat )
{
this.openLdapConfigFormat = openLdapConfigFormat;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DbIndexDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DbIndexDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.TableWidget;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.common.ui.wrappers.StringValueWrapper;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.utils.SchemaObjectLoader;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.DbIndexTypeEnum;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.wrappers.DbIndexWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.StringValueDecorator;
/**
* The IndexDialog is used to edit an index configuration.
* <pre>
* +--------------------------------------------------+
* | Attributes |
* | .----------------------------------------------. |
* | | +----------------------------+ | |
* | | (o) | | (Add...) | |
* | | | | (Delete) | |
* | | +----------------------------+ | |
* | | (o) Default | |
* | '----------------------------------------------' |
* | Indices |
* | .----------------------------------------------. |
* | | [] pres [] eq [] approx | |
* | | [] nolang [] noSubtypes [] notags | |
* | | [] sub | |
* | | [] subinitial | |
* | | [] subany | |
* | | [] subfinal | |
* | '----------------------------------------------' |
* +--------------------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DbIndexDialog extends AddEditDialog<DbIndexWrapper>
{
/** The Attribute list loader */
private SchemaObjectLoader attributeLoader;
// UI widgets
// The attribute's group
private Button attributesCheckbox;
private TableWidget<StringValueWrapper> attributeTable;
private Button defaultCheckbox;
// The index type section
private Button presCheckbox;
private Button eqCheckbox;
private Button approxCheckbox;
private Button subCheckbox;
private Button noLangCheckbox;
private Button noSubtypesCheckbox;
private Button noTagsCheckbox;
private Button subInitialCheckbox;
private Button subAnyCheckbox;
private Button subFinalCheckbox;
// The list of all the type buttons
private Button[] typeButtons = new Button[10];
/**
* Listeners for the Attributes radioButton. It will enable the Attributes table.
* */
private SelectionListener attributesCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
attributeTable.enable();
getEditedElement().setDefault( false );
checkAndUpdateOkButtonEnableState();
}
};
/**
* The attribute table listener
*/
private WidgetModifyListener attributeTableListener = event ->
{
getEditedElement().getAttributes().clear();
for ( StringValueWrapper attribute : attributeTable.getElements() )
{
getEditedElement().getAttributes().add( attribute.getValue() );
}
checkAndUpdateOkButtonEnableState();
};
/**
* A listener on the Default radio button. It will disable the Attributes table
* and the associated buttons.
*/
private SelectionListener defaultCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
attributeTable.disable();
getEditedElement().setDefault( true );
checkAndUpdateOkButtonEnableState();
}
};
/**
* A listener on one of the indexType checkboxes (but SUB and SUBxxx)
*/
private SelectionListener typeButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
checkAndUpdateOkButtonEnableState();
DbIndexWrapper indexWrapper = getEditedElement();
// Update the edited element
Button selectedCheckbox = (Button)e.getSource();
for ( int i = 0; i < typeButtons.length; i++ )
{
if ( typeButtons[i] == selectedCheckbox )
{
DbIndexTypeEnum indexType = DbIndexTypeEnum.getIndexType( i );
if ( selectedCheckbox.getSelection() )
{
indexWrapper.getTypes().add( indexType );
}
else
{
indexWrapper.getTypes().remove( indexType );
}
}
}
}
};
/**
* A listener on the SUB indice check box. If it's selected, we will grey all the sub-sub indexes.
* If it's delected, we will remove all the sub-sub indexes
*/
private SelectionListener subCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
DbIndexWrapper indexWrapper = getEditedElement();
if ( subCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
subInitialCheckbox.setSelection( true );
subAnyCheckbox.setSelection( true );
subFinalCheckbox.setSelection( true );
}
else
{
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
subInitialCheckbox.setSelection( false );
subAnyCheckbox.setSelection( false );
subFinalCheckbox.setSelection( false );
}
checkAndUpdateOkButtonEnableState();
}
};
/**
* A listener on the SUB related indices check boxes. We will disable the SUB checkbox, no matter what
*/
private SelectionListener subSubCheckboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// Check that we aren't coming from a modification of the SUB button
DbIndexWrapper indexWrapper = getEditedElement();
Button button = (Button)e.getSource();
// First, update the indexTypes set
if ( button == subAnyCheckbox )
{
if ( button.getSelection() )
{
if ( subInitialCheckbox.getSelection() && subFinalCheckbox.getSelection() )
{
// The three subXXX indexes are selected : select the SUB checkbox
subCheckbox.setSelection( true );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
else if ( subInitialCheckbox.getSelection() || subFinalCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBANY );
}
else
{
// Gray the sub checkbox, and select it
subCheckbox.setSelection( true );
subCheckbox.setGrayed( true );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
else
{
if ( !subInitialCheckbox.getSelection() && !subFinalCheckbox.getSelection() )
{
subCheckbox.setGrayed( false );
subCheckbox.setSelection( false );
}
else if ( subInitialCheckbox.getSelection() && subFinalCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBFINAL );
subCheckbox.setGrayed( true );
}
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
else if ( button == subInitialCheckbox )
{
if ( button.getSelection() )
{
if ( subAnyCheckbox.getSelection() && subFinalCheckbox.getSelection() )
{
// The three subXXX indexes are selected : select the SUB checkbox
subCheckbox.setSelection( true );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
else if ( subAnyCheckbox.getSelection() || subFinalCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBINITIAL );
}
else
{
// Gray the sub checkbox, and select it
subCheckbox.setSelection( true );
subCheckbox.setGrayed( true );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
else
{
if ( !subAnyCheckbox.getSelection() && !subFinalCheckbox.getSelection() )
{
subCheckbox.setGrayed( false );
subCheckbox.setSelection( false );
}
else if ( subAnyCheckbox.getSelection() && subFinalCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBFINAL );
subCheckbox.setGrayed( true );
}
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
else if ( button == subFinalCheckbox )
{
if ( button.getSelection() )
{
if ( subAnyCheckbox.getSelection() && subInitialCheckbox.getSelection() )
{
// The three subXXX indexes are selected : select the SUB checkbox
subCheckbox.setSelection( true );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBINITIAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
else if ( subAnyCheckbox.getSelection() || subInitialCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBFINAL );
}
else
{
// Gray the sub checkbox, and select it
subCheckbox.setSelection( true );
subCheckbox.setGrayed( true );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBFINAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
else
{
if ( !subAnyCheckbox.getSelection() && !subInitialCheckbox.getSelection() )
{
subCheckbox.setGrayed( false );
subCheckbox.setSelection( false );
}
else if ( subAnyCheckbox.getSelection() && subInitialCheckbox.getSelection() )
{
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBANY );
indexWrapper.getIndexTypes().add( DbIndexTypeEnum.SUBINITIAL );
subCheckbox.setGrayed( true );
}
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBFINAL );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUB );
indexWrapper.getIndexTypes().remove( DbIndexTypeEnum.SUBSTR );
}
}
// Last, update the subCheckbox state
checkAndUpdateOkButtonEnableState();
}
};
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param browserConnection the connection
*/
public DbIndexDialog( Shell parentShell, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
attributeLoader = new SchemaObjectLoader();
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Index" );
}
/**
* Creates the IndexDialog, which has two groups : attributes and indices.
* <pre>
* +--------------------------------------------------+
* | Attributes |
* | .----------------------------------------------. |
* | | +----------------------------+ | |
* | | (o) | | (Add...) | |
* | | | | (Delete) | |
* | | +----------------------------+ | |
* | | (o) Default | |
* | '----------------------------------------------' |
* | Indices |
* | .----------------------------------------------. |
* | | [] pres [] eq [] approx | |
* | | [] nolang [] noSubtypes [] notags | |
* | | [] sub | |
* | | [] subinitial | |
* | | [] subany | |
* | | [] subfinal | |
* | '----------------------------------------------' |
* +--------------------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// The attributes group
createAttributesGroup( composite );
// The indices grouo
createIndicesGroup( composite );
// Load the dialog if this was an Edit call
initDialog();
//addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the attributes group.
* <pre>
* Attributes
* .----------------------------------------------.
* | +----------------------------+ |
* | (o) | | (Add...) |
* | | | (Delete) |
* | +----------------------------+ |
* | (o) Default |
* '----------------------------------------------'
*
* @param parent the parent composite
*/
private void createAttributesGroup( Composite parent )
{
// Attributes Group
Group attributesGroup = BaseWidgetUtils.createGroup( parent, "Attributes", 1 );
GridLayout attributesGroupGridLayout = new GridLayout( 2, false );
attributesGroup.setLayout( attributesGroupGridLayout );
attributesGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Attributes Checkbox
attributesCheckbox = BaseWidgetUtils.createRadiobutton( attributesGroup, "", 1 );
attributesCheckbox.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) );
attributesCheckbox.setSelection( true );
attributesCheckbox.addSelectionListener( attributesCheckboxSelectionListener );
// Attributes table
StringValueDecorator decorator = new StringValueDecorator( parent.getShell(), "Attribute" );
decorator.setImage( OpenLdapConfigurationPlugin.getDefault().getImage(
OpenLdapConfigurationPluginConstants.IMG_ATTRIBUTE ) );
AttributeDialog attributeDialog = new AttributeDialog( parent.getShell() );
attributeDialog.setAttributeNamesAndOids( attributeLoader.getAttributeNamesAndOids() );
decorator.setDialog( attributeDialog );
attributeTable = new TableWidget<>( decorator );
attributeTable.createWidgetNoEdit( attributesGroup, null );
attributeTable.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
attributeTable.addWidgetModifyListener( attributeTableListener );
// Attributes Checkbox
defaultCheckbox = BaseWidgetUtils.createRadiobutton( attributesGroup, " Default", 2 );
defaultCheckbox.addSelectionListener( defaultCheckboxSelectionListener );
}
/**
* Creates the indices group.
* <pre>
* Indices
* .----------------------------------------------.
* | [] pres [] eq [] approx |
* | [] nolang [] noSubtypes [] notags |
* | [] sub |
* | [] subinitial |
* | [] subany |
* | [] subfinal |
* '----------------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createIndicesGroup( Composite parent )
{
// Indices Group
Group indicesGroup = BaseWidgetUtils.createGroup( parent, "Indices", 1 );
GridLayout indicesGroupGridLayout = new GridLayout( 3, true );
indicesGroupGridLayout.verticalSpacing = indicesGroupGridLayout.horizontalSpacing = 0;
indicesGroup.setLayout( indicesGroupGridLayout );
indicesGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Pres Checkbox
presCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "pres", 1 );
presCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.PRES.getNumber()] = presCheckbox;
// Eq Checkbox
eqCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "eq", 1 );
eqCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.EQ.getNumber()] = eqCheckbox;
// Approx Checkbox
approxCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "approx", 1 );
approxCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.APPROX.getNumber()] = approxCheckbox;
// NoLang Checkbox
noLangCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "nolang", 1 );
noLangCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.NOLANG.getNumber()] = noLangCheckbox;
// NoSybtypes Checkbox
noSubtypesCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "nosubtypes", 1 );
noSubtypesCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.NOSUBTYPES.getNumber()] = noSubtypesCheckbox;
// NoTags Checkbox
noTagsCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "notags", 1 );
noTagsCheckbox.addSelectionListener( typeButtonSelectionListener );
typeButtons[DbIndexTypeEnum.NOTAGS.getNumber()] = noTagsCheckbox;
// Sub Checkbox
subCheckbox = BaseWidgetUtils.createCheckbox( indicesGroup, "sub", 1 );
subCheckbox.addSelectionListener( subCheckboxSelectionListener );
typeButtons[DbIndexTypeEnum.SUB.getNumber()] = subCheckbox;
// Sub Composite
Composite subComposite = new Composite( indicesGroup, SWT.NONE );
GridLayout subCompositeGridLayout = new GridLayout( 2, false );
subCompositeGridLayout.marginHeight = subCompositeGridLayout.marginWidth = 0;
subCompositeGridLayout.verticalSpacing = subCompositeGridLayout.horizontalSpacing = 0;
subComposite.setLayout( subCompositeGridLayout );
// SubInitial Checkbox
BaseWidgetUtils.createRadioIndent( subComposite, 1 );
subInitialCheckbox = BaseWidgetUtils.createCheckbox( subComposite, "subinitial", 1 );
subInitialCheckbox.addSelectionListener( subSubCheckboxSelectionListener );
typeButtons[DbIndexTypeEnum.SUBINITIAL.getNumber()] = subInitialCheckbox;
// SubAny Checkbox
BaseWidgetUtils.createRadioIndent( subComposite, 1 );
subAnyCheckbox = BaseWidgetUtils.createCheckbox( subComposite, "subany", 1 );
subAnyCheckbox.addSelectionListener( subSubCheckboxSelectionListener );
typeButtons[DbIndexTypeEnum.SUBANY.getNumber()] = subAnyCheckbox;
// SubFinal Checkbox
BaseWidgetUtils.createRadioIndent( subComposite, 1 );
subFinalCheckbox = BaseWidgetUtils.createCheckbox( subComposite, "subfinal", 1 );
subFinalCheckbox.addSelectionListener( subSubCheckboxSelectionListener );
typeButtons[DbIndexTypeEnum.SUBFINAL.getNumber()] = subFinalCheckbox;
}
/**
* Sets the selection for sub checkboxes.
*
* @param selection the selection
*/
private void setSelectionForSubCheckboxes( boolean selection )
{
subCheckbox.setGrayed( false );
subInitialCheckbox.setSelection( selection );
subAnyCheckbox.setSelection( selection );
subFinalCheckbox.setSelection( selection );
}
/**
* Verifies and updates the selection state for the 'sub' checkbox.
*/
private void checkAndUpdateSubCheckboxSelectionState()
{
boolean atLeastOneSelected = subInitialCheckbox.getSelection()
|| subAnyCheckbox.getSelection() || subFinalCheckbox.getSelection();
boolean allSelected = subInitialCheckbox.getSelection()
&& subAnyCheckbox.getSelection() && subFinalCheckbox.getSelection();
subCheckbox.setGrayed( atLeastOneSelected && !allSelected );
subCheckbox.setSelection( atLeastOneSelected );
}
private void initAttributeTable( Set<String> attributes )
{
List<StringValueWrapper> attributeWrappers = new ArrayList<>();
if ( attributes != null )
{
for ( String attribute : attributes )
{
attributeWrappers.add( new StringValueWrapper( attribute, false ) );
}
}
attributeTable.setElements( attributeWrappers );
}
/**
* Inits the UI from the DbIndexWrapper
*/
protected void initDialog()
{
DbIndexWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
// Attributes
initAttributeTable( editedElement.getAttributes() );
// Default
if ( editedElement.isDefault() )
{
attributesCheckbox.setSelection( false );
attributeTable.disable();
defaultCheckbox.setSelection( true );
}
// Index types
Set<DbIndexTypeEnum> indexTypes = editedElement.getTypes();
if ( ( indexTypes != null ) && !indexTypes.isEmpty() )
{
presCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.PRES ) );
eqCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.EQ ) );
approxCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.APPROX ) );
if ( indexTypes.contains( DbIndexTypeEnum.SUB ) )
{
subCheckbox.setSelection( true );
setSelectionForSubCheckboxes( indexTypes.contains( DbIndexTypeEnum.SUB ) );
}
else
{
subInitialCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.SUBINITIAL ) );
subAnyCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.SUBANY ) );
subFinalCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.SUBFINAL ) );
checkAndUpdateSubCheckboxSelectionState();
}
noLangCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.NOLANG ) );
noSubtypesCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.NOSUBTYPES ) );
noTagsCheckbox.setSelection( indexTypes.contains( DbIndexTypeEnum.NOTAGS ) );
}
}
}
/**
* Add a new Element that will be edited
*/
protected void addNewElement( DbIndexWrapper editedElement )
{
DbIndexWrapper newElement = editedElement.clone();
setEditedElement( newElement );
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new DbIndexWrapper( "" ) );
}
/**
* Overriding the createButton method. The OK button is not enabled until
*
* {@inheritDoc}
*/
@Override
protected Button createButton(Composite parent, int id, String label, boolean defaultButton)
{
Button button = super.createButton(parent, id, label, defaultButton);
if ( id == IDialogConstants.OK_ID )
{
DbIndexWrapper dbIndexWrapper = getEditedElement();
if ( ( dbIndexWrapper == null ) || dbIndexWrapper.getAttributes().isEmpty() )
{
button.setEnabled( false );
}
}
return button;
}
/**
* Checks and updates the OK button 'enable' state. For the OK button to be enabled, either
* the default checkbox has to be selected, and one selection has to be made on the indices,
* or the attributes table should not be empty.
*/
private void checkAndUpdateOkButtonEnableState()
{
Button okButton = getButton( IDialogConstants.OK_ID );
if ( defaultCheckbox.getSelection() )
{
okButton.setEnabled(
presCheckbox.getSelection() ||
eqCheckbox.getSelection() ||
approxCheckbox.getSelection() ||
subCheckbox.getSelection() ||
subInitialCheckbox.getSelection() ||
subAnyCheckbox.getSelection() ||
subFinalCheckbox.getSelection() ||
noLangCheckbox.getSelection() ||
noTagsCheckbox.getSelection() ||
noSubtypesCheckbox.getSelection() );
}
else
{
okButton.setEnabled( !getEditedElement().getAttributes().isEmpty() );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/TcpBufferDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/TcpBufferDialog.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.openldap.config.editor.dialogs;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.wrappers.TcpBufferWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.TcpBufferWrapper.TcpTypeEnum;
/**
* The TcpBufferDialog is used to edit a TcpBuffer, which can contain an URL and a type of TCP buffer,
* plus the size.<br/>
* The dialog overlay is like :
*
* <pre>
* +---------------------------------------+
* | TcpBuffer |
* | .-----------------------------------. |
* | | Size : [ ] () read () write | |
* | | URL : [ ] | |
* | '-----------------------------------' |
* | .-----------------------------------. |
* | | TcpBuffer : <///////////////////> | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
*
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TcpBufferDialog extends AddEditDialog<TcpBufferWrapper>
{
/** The list of existing TcpBuffer */
List<TcpBufferWrapper> tcpBufferList;
// UI widgets
/** The Size Text */
private Text sizeText;
/** The Read and Write checkboxes */
private Button readCheckbox;
private Button writeCheckbox;
/** The Listener text */
private Text listenerText;
/** The resulting TcpBuffer Text, or an error message */
private Text tcpBufferText;
/**
* Create a new instance of the TcpBufferDialog
*
* @param parentShell The parent Shell
*/
public TcpBufferDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* The listener for the size Text
*/
private ModifyListener sizeTextListener = event ->
{
Display display = tcpBufferText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
long sizeValue = Long.parseLong( sizeText.getText() );
// The size must be between 0 and 2^32-1
if ( ( sizeValue < 0L ) || ( sizeValue > TcpBufferWrapper.MAX_TCP_BUFFER_SIZE ) )
{
sizeText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
tcpBufferText.setText( getEditedElement().toString() );
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
return;
}
sizeText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
getEditedElement().setSize( sizeValue );
tcpBufferText.setText( getEditedElement().toString() );
if ( TcpBufferWrapper.isValid( sizeText.getText(), listenerText.getText() ) )
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
okButton.setEnabled( true );
}
else
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
}
catch ( NumberFormatException nfe )
{
// Not even a number
sizeText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
tcpBufferText.setText( getEditedElement().toString() );
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
};
/**
* The listener for the URL Text
*/
private ModifyListener urlTextListener = event ->
{
Display display = tcpBufferText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
URI newUri = new URI( listenerText.getText() );
getEditedElement().setListener( newUri );
listenerText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
tcpBufferText.setText( getEditedElement().toString() );
if ( TcpBufferWrapper.isValid( sizeText.getText(), listenerText.getText() ) )
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
okButton.setEnabled( true );
}
else
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
}
catch ( URISyntaxException mue )
{
listenerText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
tcpBufferText.setText( getEditedElement().toString() );
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
};
/**
* The listener in charge of exposing the changes when the read or write buttons are checked
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Display display = tcpBufferText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
if ( readCheckbox.getSelection() )
{
if ( writeCheckbox.getSelection())
{
getEditedElement().setTcpType( TcpTypeEnum.BOTH );
}
else
{
getEditedElement().setTcpType( TcpTypeEnum.READ );
}
}
else if ( writeCheckbox.getSelection() )
{
if ( readCheckbox.getSelection() )
{
getEditedElement().setTcpType( TcpTypeEnum.BOTH );
}
else
{
getEditedElement().setTcpType( TcpTypeEnum.WRITE );
}
}
else
{
getEditedElement().setTcpType( TcpTypeEnum.BOTH );
}
// Set the TcpBuffer into the text box
tcpBufferText.setText( getEditedElement().toString() );
if ( TcpBufferWrapper.isValid( sizeText.getText(), listenerText.getText() ) )
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
okButton.setEnabled( true );
}
else
{
tcpBufferText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
}
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "TcpBuffer" );
}
/**
* Create the Dialog for TcpBuffer :
* <pre>
* +---------------------------------------+
* | TcpBuffer |
* | .-----------------------------------. |
* | | Size : [ ] () read () write | |
* | | URL : [ ] | |
* | '-----------------------------------' |
* | .-----------------------------------. |
* | | TcpBuffer : <///////////////////> | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createTcpBufferEditGroup( composite );
createTcpBufferShowGroup( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the TcpBuffer input group. This is the part of the dialog
* where one can insert the TcpBuffer size and URL
*
* <pre>
* TcpBuffer Input
* .-----------------------------------.
* | Size : [ ] () read () write |
* | URL : [ ] |
* '-----------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createTcpBufferEditGroup( Composite parent )
{
// TcpBuffer Group
Group tcpBufferGroup = BaseWidgetUtils.createGroup( parent, "TcpBuffer input", 1 );
GridLayout tcpBufferGroupGridLayout = new GridLayout( 6, false );
tcpBufferGroup.setLayout( tcpBufferGroupGridLayout );
tcpBufferGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Size Text
BaseWidgetUtils.createLabel( tcpBufferGroup, "Size :", 1 );
sizeText = BaseWidgetUtils.createText( tcpBufferGroup, "", 1 );
sizeText.addModifyListener( sizeTextListener );
// Read checkbox Button
readCheckbox = BaseWidgetUtils.createCheckbox( tcpBufferGroup, "read", 2 );
// Write checkbox Button
writeCheckbox = BaseWidgetUtils.createCheckbox( tcpBufferGroup, "write", 2 );
// URL Text
BaseWidgetUtils.createLabel( tcpBufferGroup, "URL:", 1 );
listenerText = BaseWidgetUtils.createText( tcpBufferGroup, "", 5 );
listenerText.addModifyListener( urlTextListener );
}
/**
* Creates the TcpBuffer show group. This is the part of the dialog
* where the real TcpBuffer is shown, or an error message if the TcpBuffer
* is invalid.
*
* <pre>
* .-----------------------------------.
* | TcpBuffer : <///////////////////> |
* '-----------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createTcpBufferShowGroup( Composite parent )
{
// TcpBuffer Group
Group tcpBufferGroup = BaseWidgetUtils.createGroup( parent, "", 1 );
GridLayout tcpBufferGroupGridLayout = new GridLayout( 2, false );
tcpBufferGroup.setLayout( tcpBufferGroupGridLayout );
tcpBufferGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// TcpBuffer Text
tcpBufferText = BaseWidgetUtils.createText( tcpBufferGroup, "", 1 );
tcpBufferText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
tcpBufferText.setEditable( false );
}
/**
* Initializes the UI from the TcpBuffer
*/
protected void initDialog()
{
TcpBufferWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
sizeText.setText( Long.toString( editedElement.getSize() ) );
URI listener = editedElement.getListener();
if ( listener == null )
{
listenerText.setText( "" );
}
else
{
listenerText.setText( listener.toString() );
}
tcpBufferText.setText( editedElement.toString() );
}
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new TcpBufferWrapper( "" ) );
}
/**
* Add a new Element that will be edited
*/
protected void addNewElement( TcpBufferWrapper editedElement )
{
TcpBufferWrapper newElement = editedElement.clone();
setEditedElement( newElement );
}
/**
* Adds listeners.
*/
private void addListeners()
{
readCheckbox.addSelectionListener( checkboxSelectionListener );
writeCheckbox.addSelectionListener( checkboxSelectionListener );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/LimitsDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/LimitsDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.TableWidget;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.ldapbrowser.core.utils.SchemaObjectLoader;
import org.apache.directory.studio.openldap.common.ui.model.DnSpecStyleEnum;
import org.apache.directory.studio.openldap.common.ui.model.DnSpecTypeEnum;
import org.apache.directory.studio.openldap.common.ui.model.LimitSelectorEnum;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitDecorator;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitsWrapper;
/**
* The LimitsDialog is used to edit the Limits parameter<br/>
*
* The dialog overlay is like :
*
* <pre>
* +-------------------------------------------------------+
* | Limits |
* | .---------------------------------------------------. |
* | | (o) Any | |
* | | (o) Anonymous | |
* | | (o) Users | |
* | | .------------------------------------. | |
* | | | Type : [--------------------|v] | | |
* | | (o) DN | Style : [--------------------|v] | | |
* | | | Pattern : [----------------------] | | |
* | | '------------------------------------' | |
* | | .------------------------------------. | |
* | | | ObjectClass : [--------------|v] | | |
* | | (o) Group | AttributeType : [--------------|v] | | |
* | | | Pattern : [----------------] | | |
* | | '------------------------------------' | |
* | | | |
* | | Limits : | |
* | | +-------------------------------------+ | |
* | | |{1}defxyz12 | (Add...) | |
* | | |{2}aaa | (Edit...) | |
* | | | | (Delete) | |
* | | | | --------- | |
* | | | | (Up...) | |
* | | | | (Down...) | |
* | | +-------------------------------------+ | |
* | '---------------------------------------------------' |
* | Resulting Limits |
* | .---------------------------------------------------. |
* | | <///////////////////////////////////////////////> | |
* | '---------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LimitsDialog extends AddEditDialog<LimitsWrapper>
{
/** The Any radio button */
private Button anyButton;
/** The Anonymous radio button */
private Button anonymousButton;
/** The Users radio button */
private Button usersButton;
/** The DNSpec radio button */
private Button dnSpecButton;
/** The DNSpec type */
private Combo dnSpecTypeCombo;
/** The DNSpec style */
private Combo dnSpecStyleCombo;
/** The DNSpec pattern */
private Text dnSpecPatternText;
/** The Group radio button */
private Button groupButton;
/** The Group ObjectClass type */
private Combo groupObjectClassCombo;
/** The Group AttributeType style */
private Combo groupAttributeTypeCombo;
/** The Group pattern */
private Text groupPatternText;
/** The (time/size)Limit parameter */
private TableWidget<LimitWrapper> limitsTableWidget;
/** The resulting Limits Text */
private Text limitsText;
/** The Attribute list loader */
private SchemaObjectLoader schemaObjectLoader;
/**
* Disable the DnSpec and Group widgets
*/
private void disableDnSpecGroupButtons()
{
dnSpecTypeCombo.setEnabled( false );
dnSpecStyleCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
}
/**
* Disable or enable the DnSpec and Group widgets
*/
private void setDnSpecGroupButtons( boolean dnSpecStatus, boolean groupStatus )
{
groupAttributeTypeCombo.setEnabled( groupStatus );
groupObjectClassCombo.setEnabled( groupStatus );
groupPatternText.setEnabled( groupStatus );
dnSpecTypeCombo.setEnabled( dnSpecStatus );
dnSpecStyleCombo.setEnabled( dnSpecStatus );
dnSpecPatternText.setEnabled( dnSpecStatus );
}
/**
* Reset the content of the edited element
*/
private void clearEditedElement()
{
getEditedElement().setDnSpecStyle( null );
getEditedElement().setDnSpecType( null );
getEditedElement().setAttributeType( null );
getEditedElement().setObjectClass( null );
getEditedElement().setSelectorPattern( null );
}
/**
* Listeners for the Selector radioButtons. It will enable or disable the dnSpec or Group accordingly
* to the selection.
**/
private SelectionListener selectorButtonsSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent event )
{
if ( event.getSource() instanceof Button )
{
Button button = (Button)event.getSource();
if ( button == anyButton )
{
if ( button.getSelection() )
{
disableDnSpecGroupButtons();
clearEditedElement();
getEditedElement().setSelector( LimitSelectorEnum.ANY );
limitsText.setText( getEditedElement().toString() );
}
}
else if ( button == anonymousButton )
{
if ( button.getSelection() )
{
disableDnSpecGroupButtons();
clearEditedElement();
getEditedElement().setSelector( LimitSelectorEnum.ANONYMOUS );
limitsText.setText( getEditedElement().toString() );
}
}
else if ( button == usersButton )
{
if ( button.getSelection() )
{
disableDnSpecGroupButtons();
clearEditedElement();
getEditedElement().setSelector( LimitSelectorEnum.USERS );
limitsText.setText( getEditedElement().toString() );
}
}
else if ( button == dnSpecButton )
{
setDnSpecGroupButtons( dnSpecButton.getSelection(), false );
clearEditedElement();
getEditedElement().setSelector( LimitSelectorEnum.DNSPEC );
limitsText.setText( getEditedElement().toString() );
}
else if ( button == groupButton )
{
setDnSpecGroupButtons( false, groupButton.getSelection() );
clearEditedElement();
getEditedElement().setSelector( LimitSelectorEnum.GROUP );
limitsText.setText( getEditedElement().toString() );
}
}
}
};
/**
* The dnSpecTypeCombo listener
*/
private SelectionListener dnSpecTypeComboListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
getEditedElement().setDnSpecType( DnSpecTypeEnum.getType( dnSpecTypeCombo.getText() ) );
limitsText.setText( getEditedElement().toString() );
}
};
/**
* The dnSpecTypeCombo listener
*/
private SelectionListener dnSpecStyleComboListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
getEditedElement().setDnSpecStyle( DnSpecStyleEnum.getStyle( dnSpecStyleCombo.getText() ) );
limitsText.setText( getEditedElement().toString() );
}
};
/**
* The groupAttributeTypeCombo listener
*/
private SelectionListener groupAttributeTypeComboListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
getEditedElement().setAttributeType( groupAttributeTypeCombo.getText() );
limitsText.setText( getEditedElement().toString() );
}
};
/**
* The groupObjectClassCombo listener
*/
private SelectionListener groupObjectClassComboListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
getEditedElement().setObjectClass( groupObjectClassCombo.getText() );
limitsText.setText( getEditedElement().toString() );
}
};
/**
* The dnSpecPatternText and groupPatternText listener
*/
private ModifyListener patternTextListener = event ->
{
if ( event.getSource() == dnSpecPatternText )
{
getEditedElement().setSelectorPattern( dnSpecPatternText.getText() );
}
else
{
getEditedElement().setSelectorPattern( groupPatternText.getText() );
}
limitsText.setText( getEditedElement().toString() );
};
/**
* The olcLimits listener
*/
private WidgetModifyListener limitsTableWidgetListener = event ->
{
getEditedElement().setLimits( limitsTableWidget.getElements() );
limitsText.setText( getEditedElement().toString() );
};
/**
* Create a new instance of the LimitsDialog
*
* @param parentShell The parent Shell
*/
public LimitsDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
schemaObjectLoader = new SchemaObjectLoader();
}
/**
* Create a new instance of the LimitsDialog
*
* @param parentShell The parent Shell
* @param timeLimitStr The instance containing the Limits data
*/
public LimitsDialog( Shell parentShell, String limitsStr )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
schemaObjectLoader = new SchemaObjectLoader();
setEditedElement( new LimitsWrapper( limitsStr ) );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Limits" );
}
/**
* Create the Dialog for TimeLimit :
* <pre>
* +-------------------------------------------------------+
* | Limits |
* | .---------------------------------------------------. |
* | | (o) Any | |
* | | (o) Anonymous | |
* | | (o) Users | |
* | | .------------------------------------. | |
* | | | Type : [--------------------|v] | | |
* | | (o) DN | Style : [--------------------|v] | | |
* | | | Pattern : [----------------------] | | |
* | | '------------------------------------' | |
* | | .------------------------------------. | |
* | | | ObjectClass : [--------------|v] | | |
* | | (o) Group | AttributeType : [--------------|v] | | |
* | | | Pattern : [----------------] | | |
* | | '------------------------------------' | |
* | | | |
* | | Limits : | |
* | | +-------------------------------------+ | |
* | | |{1}defxyz12 | (Add...) | |
* | | |{2}aaa | (Edit...) | |
* | | | | (Delete) | |
* | | | | --------- | |
* | | | | (Up...) | |
* | | | | (Down...) | |
* | | +-------------------------------------+ | |
* | '---------------------------------------------------' |
* | Resulting Limits |
* | .---------------------------------------------------. |
* | | Limits : <//////////////////////////////////////> | |
* | '---------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createLimitsEditGroup( composite );
createLimitsShowGroup( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the Limits input group.
*
* <pre>
* Limits
* .---------------------------------------------------.
* | (o) Any |
* | (o) Anonymous |
* | (o) Users |
* | .------------------------------------. |
* | | Type : [--------------------|v] | |
* | (o) DN | Style : [--------------------|v] | |
* | | Pattern : [----------------------] | |
* | '------------------------------------' |
* | .------------------------------------. |
* | | ObjectClass : [--------------|v] | |
* | (o) Group | AttributeType : [--------------|v] | |
* | | Pattern : [----------------] | |
* | '------------------------------------' |
* | |
* | Limits : |
* | +-------------------------------------+ |
* | |{1}defxyz12 | (Add...) |
* | |{2}aaa | (Edit...) |
* | | | (Delete) |
* | | | --------- |
* | | | (Up...) |
* | | | (Down...) |
* | +-------------------------------------+ |
* '---------------------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createLimitsEditGroup( Composite parent )
{
// Selector Group
Group selectorGroup = BaseWidgetUtils.createGroup( parent, "Limit input", 1 );
GridLayout selectorGridLayout = new GridLayout( 2, false );
selectorGroup.setLayout( selectorGridLayout );
selectorGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Any button
anyButton = BaseWidgetUtils.createRadiobutton( selectorGroup, "Any", 2 );
anyButton.addSelectionListener( selectorButtonsSelectionListener );
// Anonymous button
anonymousButton = BaseWidgetUtils.createRadiobutton( selectorGroup, "Anonymous", 2 );
anonymousButton.addSelectionListener( selectorButtonsSelectionListener );
// Users button
usersButton = BaseWidgetUtils.createRadiobutton( selectorGroup, "Users", 2 );
usersButton.addSelectionListener( selectorButtonsSelectionListener );
// DNSpec button
dnSpecButton = BaseWidgetUtils.createRadiobutton( selectorGroup, "DN", 1 );
dnSpecButton.addSelectionListener( selectorButtonsSelectionListener );
// The group associated with the DN Sepc
Group dnSpecGroup = BaseWidgetUtils.createGroup( selectorGroup, "", 2 );
GridLayout dnSpecGridLayout = new GridLayout( 2, false );
dnSpecGroup.setLayout( dnSpecGridLayout );
dnSpecGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The DNSpec type Combo
BaseWidgetUtils.createLabel( dnSpecGroup, "Type :", 1 );
dnSpecTypeCombo = BaseWidgetUtils.createCombo( dnSpecGroup, DnSpecTypeEnum.getNames(), -1, 1 );
dnSpecTypeCombo.setEnabled( false );
dnSpecTypeCombo.addSelectionListener( dnSpecTypeComboListener );
// The DNSpec style Combo
BaseWidgetUtils.createLabel( dnSpecGroup, "Style :", 1 );
dnSpecStyleCombo = BaseWidgetUtils.createCombo( dnSpecGroup, DnSpecStyleEnum.getNames(), -1, 1 );
dnSpecStyleCombo.setEnabled( false );
dnSpecStyleCombo.addSelectionListener( dnSpecStyleComboListener );
// The DNSpec pattern Text
BaseWidgetUtils.createLabel( dnSpecGroup, "Pattern :", 1 );
dnSpecPatternText = BaseWidgetUtils.createText( dnSpecGroup, "", 1 );
dnSpecPatternText.setEnabled( false );
dnSpecPatternText.addModifyListener( patternTextListener );
// Group button
groupButton = BaseWidgetUtils.createRadiobutton( selectorGroup, "Group", 1 );
groupButton.addSelectionListener( selectorButtonsSelectionListener );
// The group associated with the Group
Group groupGroup = BaseWidgetUtils.createGroup( selectorGroup, "", 2 );
GridLayout groupGridLayout = new GridLayout( 2, false );
groupGroup.setLayout( groupGridLayout );
groupGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
schemaObjectLoader = new SchemaObjectLoader();
// The ObjectClass Combo
BaseWidgetUtils.createLabel( groupGroup, "ObjectClass :", 1 );
groupObjectClassCombo = BaseWidgetUtils.createCombo( groupGroup, schemaObjectLoader.getObjectClassNamesAndOids(), -1, 1 );
groupObjectClassCombo.setEnabled( false );
groupObjectClassCombo.addSelectionListener( groupObjectClassComboListener );
// The AttributeType Combo
BaseWidgetUtils.createLabel( groupGroup, "Attribute Type :", 1 );
groupAttributeTypeCombo = BaseWidgetUtils.createCombo( groupGroup, schemaObjectLoader.getAttributeNamesAndOids(), -1, 1 );
groupAttributeTypeCombo.setEnabled( false );
groupAttributeTypeCombo.addSelectionListener( groupAttributeTypeComboListener );
// The Group pattern Text
BaseWidgetUtils.createLabel( groupGroup, "Pattern :", 1 );
groupPatternText = BaseWidgetUtils.createText( groupGroup, "", 1 );
groupPatternText.setEnabled( false );
dnSpecPatternText.addModifyListener( patternTextListener );
// The Limits table
BaseWidgetUtils.createLabel( selectorGroup, "Limits :", 1 );
limitsTableWidget = new TableWidget<>(
new LimitDecorator( parent.getShell() , "Limit") );
limitsTableWidget.createWidgetWithEdit( selectorGroup, null );
limitsTableWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
limitsTableWidget.addWidgetModifyListener( limitsTableWidgetListener );
}
/**
* Creates the TimeLimit show group. This is the part of the dialog
* where the real TimeLimit is shown, or an error message if the TimeLimit
* is invalid.
*
* <pre>
* Resulting Limits
* .------------------------------------.
* | <////////////////////////////////> |
* '------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createLimitsShowGroup( Composite parent )
{
// Limits Group
Group limitsGroup = BaseWidgetUtils.createGroup( parent, "Resulting Limits", 1 );
GridLayout limitsGroupGridLayout = new GridLayout( 2, false );
limitsGroup.setLayout( limitsGroupGridLayout );
limitsGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Limits Text
limitsText = BaseWidgetUtils.createText( limitsGroup, "", 1 );
limitsText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
limitsText.setEditable( false );
}
/**
* Adds listeners.
*/
private void addListeners()
{
/*
softLimitText.addModifyListener( softLimitTextListener );
softUnlimitedCheckbox.addSelectionListener( softUnlimitedCheckboxSelectionListener );
hardLimitText.addModifyListener( hardLimitTextListener );
hardUnlimitedCheckbox.addSelectionListener( hardUnlimitedCheckboxSelectionListener );
hardSoftCheckbox.addSelectionListener( hardSoftCheckboxSelectionListener );
globalLimitText.addModifyListener( globalLimitTextListener );
globalUnlimitedCheckbox.addSelectionListener( globalUnlimitedCheckboxSelectionListener );
*/
}
@Override
public void addNewElement()
{
setEditedElement( new LimitsWrapper( "" ) );
}
/**
* Initializes the UI from the Limits
*/
protected void initDialog()
{
LimitsWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
LimitSelectorEnum selector = editedElement.getSelector();
if ( selector != null )
{
switch ( editedElement.getSelector() )
{
case ANONYMOUS :
anonymousButton.setSelection( true );
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
break;
case ANY :
anyButton.setSelection( true );
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
break;
case USERS :
usersButton.setSelection( true );
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( true );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
break;
case DNSPEC :
dnSpecButton.setSelection( true );
dnSpecStyleCombo.setEnabled( true );
dnSpecTypeCombo.setEnabled( true );
dnSpecPatternText.setEnabled( true );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
break;
case GROUP :
groupButton.setSelection( true );
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( true );
groupObjectClassCombo.setEnabled( true );
groupPatternText.setEnabled( true );
break;
default :
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( false );
break;
}
}
else
{
dnSpecStyleCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecTypeCombo.setEnabled( false );
dnSpecPatternText.setEnabled( false );
groupAttributeTypeCombo.setEnabled( false );
groupObjectClassCombo.setEnabled( false );
groupPatternText.setEnabled( 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationSaslDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationSaslDialog.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.openldap.config.editor.dialogs;
import java.text.ParseException;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.syncrepl.SaslMechanism;
import org.apache.directory.studio.openldap.syncrepl.SyncRepl;
/**
* The ReplicationSaslDialog is used to edit the SASL configuration of a SyncRepl consumer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ReplicationSaslDialog extends Dialog
{
/** The SyncRepl value */
private SyncRepl syncRepl;
/** The connection */
private IBrowserConnection browserConnection;
// UI widgets
private ScrolledComposite scrolledComposite;
private Composite composite;
private ComboViewer saslMechanismComboViewer;
private Text realmText;
private Text authenticationIdText;
private Text authorizationIdText;
private Text credentialsText;
private Button showCredentialsCheckbox;
private Text secPropsText;
// Listeners
private SelectionListener showCredentialsCheckboxListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
if ( showCredentialsCheckbox.getSelection() )
{
credentialsText.setEchoChar( '\0' );
}
else
{
credentialsText.setEchoChar( '\u2022' );
}
}
};
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param index the index
* @param browserConnection the connection
*/
public ReplicationSaslDialog( Shell parentShell, SyncRepl syncRepl, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
if ( syncRepl != null )
{
this.syncRepl = syncRepl.copy();
}
else
{
this.syncRepl = createDefaultSyncRepl();
}
}
/**
* Creates a default SyncRepl configuration.
*
* @return a default SyncRepl configuration
*/
private SyncRepl createDefaultSyncRepl()
{
return new SyncRepl();
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Replication Options" );
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
saveToSyncRepl();
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// Creating the scrolled composite
scrolledComposite = new ScrolledComposite( parent, SWT.H_SCROLL | SWT.V_SCROLL );
scrolledComposite.setExpandHorizontal( true );
scrolledComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Creating the composite and attaching it to the scrolled composite
composite = new Composite( scrolledComposite, SWT.NONE );
composite.setLayout( new GridLayout() );
scrolledComposite.setContent( composite );
createSaslConfigurationGroup( composite );
initFromSyncRepl();
applyDialogFont( scrolledComposite );
composite.setSize( composite.computeSize( SWT.DEFAULT, SWT.DEFAULT ) );
return scrolledComposite;
}
/**
* Creates the SASL Configuration group.
*
* @param parent the parent composite
*/
private void createSaslConfigurationGroup( Composite parent )
{
// SASL Configuration Group
Group group = BaseWidgetUtils.createGroup( parent, "SASL Configuration", 1 );
group.setLayout( new GridLayout( 2, false ) );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// SASL Mechanism
BaseWidgetUtils.createLabel( group, "SASL Mechanism:", 1 );
saslMechanismComboViewer = new ComboViewer( group );
saslMechanismComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
saslMechanismComboViewer.setContentProvider( new ArrayContentProvider() );
saslMechanismComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof SaslMechanism )
{
return ( ( SaslMechanism ) element ).getTitle();
}
return super.getText( element );
}
} );
saslMechanismComboViewer.setInput( new SaslMechanism[]
{ SaslMechanism.DIGEST_MD5, SaslMechanism.GSSAPI } );
// Authentication ID
BaseWidgetUtils.createLabel( group, "Authentication ID:", 1 );
authenticationIdText = BaseWidgetUtils.createText( group, "", 1 );
// Authorization ID
BaseWidgetUtils.createLabel( group, "Authorization ID:", 1 );
authorizationIdText = BaseWidgetUtils.createText( group, "", 1 );
// Credentials
BaseWidgetUtils.createLabel( group, "Credentials:", 1 );
credentialsText = BaseWidgetUtils.createText( group, "", 1 );
credentialsText.setEchoChar( '\u2022' );
// Show Credentials Checkbox
BaseWidgetUtils.createLabel( group, "", 1 );
showCredentialsCheckbox = BaseWidgetUtils.createCheckbox( group, "Show Credentials", 1 );
// Realm
BaseWidgetUtils.createLabel( group, "Realm:", 1 );
realmText = BaseWidgetUtils.createText( group, "", 1 );
// Sec Props
BaseWidgetUtils.createLabel( group, "Sec Props:", 1 );
secPropsText = BaseWidgetUtils.createText( group, "", 1 );
}
/**
* Initializes the dialog using the SyncRepl object.
*/
private void initFromSyncRepl()
{
if ( syncRepl != null )
{
// SASL Mechanism
String saslMechanismString = syncRepl.getSaslMech();
if ( saslMechanismString != null )
{
try
{
saslMechanismComboViewer.setSelection( new StructuredSelection( SaslMechanism
.parse( saslMechanismString ) ) );
}
catch ( ParseException e )
{
// Silent
}
}
// Authentication ID
String authenticationId = syncRepl.getAuthcid();
if ( authenticationId != null )
{
authenticationIdText.setText( authenticationId );
}
// Authorization ID
String authorizationId = syncRepl.getAuthzid();
if ( authorizationId != null )
{
authorizationIdText.setText( authorizationId );
}
// Credentials
String credentials = syncRepl.getCredentials();
if ( credentials != null )
{
credentialsText.setText( credentials );
}
// Realm
String realm = syncRepl.getRealm();
if ( realm != null )
{
realmText.setText( realm );
}
// Sec Props
String secProps = syncRepl.getSecProps();
if ( secProps != null )
{
secPropsText.setText( secProps );
}
addListeners();
}
}
/**
* Adds listeners.
*/
private void addListeners()
{
showCredentialsCheckbox.addSelectionListener( showCredentialsCheckboxListener );
}
/**
* Saves the content of the dialog to the SyncRepl object.
*/
private void saveToSyncRepl()
{
if ( syncRepl != null )
{
// SASL Mechanism
syncRepl.setSaslMech( getSaslMechanism() );
// Authentication ID
String authenticationId = authenticationIdText.getText();
if ( ( authenticationId != null ) && ( !"".equals( authenticationId ) ) )
{
syncRepl.setAuthcid( authenticationId );
}
else
{
syncRepl.setAuthcid( null );
}
// Authorization ID
String authorizationId = authorizationIdText.getText();
if ( ( authorizationId != null ) && ( !"".equals( authorizationId ) ) )
{
syncRepl.setAuthzid( authorizationId );
}
else
{
syncRepl.setAuthzid( null );
}
// Credentials
String credentials = credentialsText.getText();
if ( ( credentials != null ) && ( !"".equals( credentials ) ) )
{
syncRepl.setCredentials( credentials );
}
else
{
syncRepl.setCredentials( null );
}
// Realm
String realm = realmText.getText();
if ( ( realm != null ) && ( !"".equals( realm ) ) )
{
syncRepl.setRealm( realm );
}
else
{
syncRepl.setRealm( null );
}
// Sec Props
String secProps = secPropsText.getText();
if ( ( secProps != null ) && ( !"".equals( secProps ) ) )
{
syncRepl.setSecProps( secProps );
}
else
{
syncRepl.setSecProps( null );
}
}
}
/**
* Gets the selected SASL mechanism.
*
* @return the selected SASL mechanism
*/
private String getSaslMechanism()
{
StructuredSelection selection = ( StructuredSelection ) saslMechanismComboViewer.getSelection();
if ( ( selection != null ) && ( !selection.isEmpty() ) )
{
return ( ( SaslMechanism ) selection.getFirstElement() ).getValue();
}
return null;
}
/**
* Gets the SyncRepl value.
*
* @return the SyncRepl value
*/
public SyncRepl getSyncRepl()
{
return syncRepl;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/StringValueDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/StringValueDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.wrappers.StringValueWrapper;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* The StringValueDialog is used to edit a String, which is a value for any simple multiple
* value attribute.
*
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | Value : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
*
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StringValueDialog extends AddEditDialog<StringValueWrapper>
{
// UI widgets
/** The attribute name */
private String attributeName;
/** The String value */
private Text stringValue;
/**
* Create a new instance of the String
*
* @param parentShell The parent Shell
*/
public StringValueDialog( Shell parentShell, String attributeName )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.attributeName = attributeName;
}
/**
* The listener for the String Text
*/
private ModifyListener stringValueTextListener = event ->
{
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
getEditedElement().setValue( stringValue.getText() );
okButton.setEnabled( true );
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( attributeName );
}
/**
* Create the Dialog for StringValue :
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | Value : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// StringValue Group
Group stringValueGroup = BaseWidgetUtils.createGroup( parent, null, 1 );
GridLayout stringValueGroupGridLayout = new GridLayout( 2, false );
stringValueGroup.setLayout( stringValueGroupGridLayout );
stringValueGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// String Text
BaseWidgetUtils.createLabel( stringValueGroup, attributeName + ":", 1 );
stringValue = BaseWidgetUtils.createText( stringValueGroup, "", 1 );
stringValue.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Initializes the UI from the String
*/
protected void initDialog()
{
StringValueWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
String value = editedElement.getValue();
if ( value == null )
{
stringValue.setText( "" );
}
else
{
stringValue.setText( editedElement.getValue() );
}
}
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new StringValueWrapper( "", true ) );
}
/**
* Add an Element that will be edited
*
* @param editedElement The element to edit
*/
public void addNewElement( StringValueWrapper editedElement )
{
StringValueWrapper newElement = editedElement.clone();
setEditedElement( newElement );
}
/**
* Adds listeners.
*/
private void addListeners()
{
stringValue.addModifyListener( stringValueTextListener );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RwmMappingDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RwmMappingDialog.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.openldap.config.editor.dialogs;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRwmMapValue;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRwmMapValueTypeEnum;
/**
* T
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RwmMappingDialog extends Dialog
{
/** The connection's attribute types */
private List<String> connectionAttributeTypes;
/** The connection's object classes */
private List<String> connectionObjectClasses;
/** The connection */
private IBrowserConnection browserConnection;
/** The value */
private OlcRwmMapValue value;
// UI widgets
private Button okButton;
private ComboViewer typeComboViewer;
private ComboViewer localNameComboViewer;
private ComboViewer foreignNameComboViewer;
// Listeners
private ModifyListener namesComboViewerListener = event -> checkAndUpdateOkButtonEnableState();
private ISelectionChangedListener typeComboViewerSelectionListener = event ->
{
OlcRwmMapValueTypeEnum selectedType = getSelectedType();
// Backing up the combos text
String localNameText = localNameComboViewer.getCombo().getText();
String foreignNameText = foreignNameComboViewer.getCombo().getText();
// Adding the correct suggestions to the viewers
if ( OlcRwmMapValueTypeEnum.ATTRIBUTE.equals( selectedType ) )
{
localNameComboViewer.setInput( connectionAttributeTypes );
foreignNameComboViewer.setInput( connectionAttributeTypes );
}
else if ( OlcRwmMapValueTypeEnum.OBJECTCLASS.equals( selectedType ) )
{
localNameComboViewer.setInput( connectionObjectClasses );
foreignNameComboViewer.setInput( connectionObjectClasses );
}
// Restoring the combos text
localNameComboViewer.getCombo().setText( localNameText );
foreignNameComboViewer.getCombo().setText( foreignNameText );
};
/**
* Creates a new instance of ValueSortingValueDialog.
*
* @param parentShell the parent shell
* @param browserConnection the connection
* @param value the value
*/
public RwmMappingDialog( Shell parentShell, IBrowserConnection browserConnection, String value )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
// Parsing the value
try
{
this.value = OlcRwmMapValue.parse( value );
if ( this.value == null )
{
this.value = new OlcRwmMapValue();
}
}
catch ( ParseException e )
{
this.value = new OlcRwmMapValue();
}
initAttributeTypesAndObjectClassesLists();
}
/**
* Creates a new instance of ValueSortingValueDialog.
*
* @param parentShell the parent shell
* @param browserConnection the connection
*/
public RwmMappingDialog( Shell parentShell, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
this.value = new OlcRwmMapValue();
initAttributeTypesAndObjectClassesLists();
}
/**
* Initializes the lists of attribute types and object classes.
*/
private void initAttributeTypesAndObjectClassesLists()
{
connectionAttributeTypes = new ArrayList<>();
connectionObjectClasses = new ArrayList<>();
if ( browserConnection != null )
{
// Attribute Types
Collection<AttributeType> atds = browserConnection.getSchema().getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
for ( String name : atd.getNames() )
{
connectionAttributeTypes.add( name );
}
}
// Object Classes
Collection<ObjectClass> ocds = browserConnection.getSchema().getObjectClassDescriptions();
for ( ObjectClass ocd : ocds )
{
for ( String name : ocd.getNames() )
{
connectionObjectClasses.add( name );
}
}
// Creating a case insensitive comparator
Comparator<String> ignoreCaseComparator = ( o1, o2 ) -> o1.compareToIgnoreCase( o2 );
// Sorting the lists
Collections.sort( connectionAttributeTypes, ignoreCaseComparator );
Collections.sort( connectionObjectClasses, ignoreCaseComparator );
// Adding the '*' special name
connectionAttributeTypes.add( 0, "*" );
connectionObjectClasses.add( 0, "*" );
}
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Mapping" );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
checkAndUpdateOkButtonEnableState();
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
// Type
value.setType( getSelectedType() );
// Local Name
String localName = localNameComboViewer.getCombo().getText();
if ( ( localName != null ) && ( !localName.isEmpty() ) )
{
value.setLocalName( localName );
}
else
{
value.setLocalName( null );
}
// Foreign Name
String foreignName = foreignNameComboViewer.getCombo().getText();
if ( ( foreignName != null ) && ( !foreignName.isEmpty() ) )
{
value.setForeignName( foreignName );
}
else
{
value.setForeignName( null );
}
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// Creating the dialog composites
Composite dialogComposite = ( Composite ) super.createDialogArea( parent );
GridData gridData = new GridData( SWT.FILL, SWT.FILL, true, true );
gridData.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH );
// gridData.heightHint = convertVerticalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 4 / 3;
dialogComposite.setLayoutData( gridData );
Composite composite = BaseWidgetUtils.createColumnContainer( dialogComposite, 2, 1 );
// Type
BaseWidgetUtils.createLabel( composite, "Type:", 1 );
typeComboViewer = new ComboViewer( composite );
typeComboViewer.getControl().setLayoutData(
new GridData( SWT.FILL, SWT.NONE, true, false ) );
typeComboViewer.setContentProvider( new ArrayContentProvider() );
typeComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof OlcRwmMapValueTypeEnum )
{
OlcRwmMapValueTypeEnum type = ( OlcRwmMapValueTypeEnum ) element;
switch ( type )
{
case ATTRIBUTE:
return "Attribute Type";
case OBJECTCLASS:
return "Object Class";
}
}
return super.getText( element );
}
} );
typeComboViewer.setInput( new OlcRwmMapValueTypeEnum[]
{
OlcRwmMapValueTypeEnum.ATTRIBUTE,
OlcRwmMapValueTypeEnum.OBJECTCLASS
} );
// Local Name
BaseWidgetUtils.createLabel( composite, "Local Name:", 1 );
localNameComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
localNameComboViewer.getControl()
.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
localNameComboViewer.setContentProvider( new ArrayContentProvider() );
// Foreign Name
BaseWidgetUtils.createLabel( composite, "Foreign Name:", 1 );
foreignNameComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
foreignNameComboViewer.getControl()
.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
foreignNameComboViewer.setContentProvider( new ArrayContentProvider() );
initFromValue();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Adds listeners to UI widgets.
*/
private void addListeners()
{
typeComboViewer.addSelectionChangedListener( typeComboViewerSelectionListener );
localNameComboViewer.getCombo().addModifyListener( namesComboViewerListener );
foreignNameComboViewer.getCombo().addModifyListener( namesComboViewerListener );
}
/**
* Inits the UI from the value.
*/
private void initFromValue()
{
// Type
OlcRwmMapValueTypeEnum type = value.getType();
if ( type != null )
{
typeComboViewer.setSelection( new StructuredSelection( type ) );
// Adding the correct suggestions to the viewers
if ( OlcRwmMapValueTypeEnum.ATTRIBUTE.equals( type ) )
{
localNameComboViewer.setInput( connectionAttributeTypes );
foreignNameComboViewer.setInput( connectionAttributeTypes );
}
else if ( OlcRwmMapValueTypeEnum.OBJECTCLASS.equals( type ) )
{
localNameComboViewer.setInput( connectionObjectClasses );
foreignNameComboViewer.setInput( connectionObjectClasses );
}
}
else
{
typeComboViewer.setSelection( new StructuredSelection( OlcRwmMapValueTypeEnum.ATTRIBUTE ) );
// Adding the suggestions to the viewers
localNameComboViewer.setInput( connectionAttributeTypes );
foreignNameComboViewer.setInput( connectionAttributeTypes );
}
// Local Name
String localName = value.getLocalName();
if ( localName != null )
{
localNameComboViewer.getCombo().setText( localName );
}
else
{
localNameComboViewer.getCombo().setText( "" );
}
// Local Name
String foreignName = value.getForeignName();
if ( foreignName != null )
{
foreignNameComboViewer.getCombo().setText( foreignName );
}
else
{
foreignNameComboViewer.getCombo().setText( "" );
}
}
/**
* Gets the selected sort method.
*
* @return the selected sort method
*/
private OlcRwmMapValueTypeEnum getSelectedType()
{
StructuredSelection selection = ( StructuredSelection ) typeComboViewer.getSelection();
if ( !selection.isEmpty() )
{
return ( OlcRwmMapValueTypeEnum ) selection.getFirstElement();
}
return null;
}
/**
* Checks and updates the OK button 'enable' state.
*/
private void checkAndUpdateOkButtonEnableState()
{
boolean enableOkButton = true;
do
{
// Type
if ( getSelectedType() == null )
{
enableOkButton = false;
break;
}
// Local Name can be omitted, so we don't check it
// Foreign Name can't be omitted
String foreignName = foreignNameComboViewer.getCombo().getText();
if ( ( foreignName == null ) || ( foreignName.isEmpty() ) )
{
enableOkButton = false;
break;
}
}
while ( false );
okButton.setEnabled( enableOkButton );
}
/**
* Gets the value.
*
* @return the value
*/
public String getValue()
{
return value.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AbstractOverlayDialogConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AbstractOverlayDialogConfigurationBlock.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.openldap.config.model.OlcOverlayConfig;
/**
* This interface represents a block for overlay configuration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractOverlayDialogConfigurationBlock<O extends OlcOverlayConfig> implements
OverlayDialogConfigurationBlock<O>
{
/** The dialog */
protected OverlayDialog dialog;
/** The overlay */
protected O overlay;
/** The connection */
protected IBrowserConnection browserConnection;
/**
* Creates a new instance of AbstractOverlayConfigurationBlock.
*
* @param dialog the dialog
*/
public AbstractOverlayDialogConfigurationBlock( OverlayDialog dialog )
{
this.dialog = dialog;
}
/**
* Creates a new instance of AbstractOverlayConfigurationBlock.
*
* @param dialog the dialog
* @param browserConnection the connection
*/
public AbstractOverlayDialogConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection )
{
this.dialog = dialog;
this.browserConnection = browserConnection;
}
/**
* {@inheritDoc}
*/
public OverlayDialog getDialog()
{
return dialog;
}
/**
* {@inheritDoc}
*/
public O getOverlay()
{
return overlay;
}
/**
* {@inheritDoc}
*/
public void setDialog( OverlayDialog dialog )
{
this.dialog = dialog;
}
/**
* {@inheritDoc}
*/
public void setOverlay( O overlay )
{
this.overlay = overlay;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationConsumerDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationConsumerDialog.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.openldap.config.editor.dialogs;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.EntryWidget;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.FilterWidget;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.syncrepl.BindMethod;
import org.apache.directory.studio.openldap.syncrepl.Provider;
import org.apache.directory.studio.openldap.syncrepl.SaslMechanism;
import org.apache.directory.studio.openldap.syncrepl.Scope;
import org.apache.directory.studio.openldap.syncrepl.StartTls;
import org.apache.directory.studio.openldap.syncrepl.SyncRepl;
import org.apache.directory.studio.openldap.syncrepl.Type;
/**
* The ReplicationConsumerDialog is used to edit the configuration of a SyncRepl consumer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ReplicationConsumerDialog extends Dialog
{
/** The Simple Authentication tab item index */
private static final int SIMPLE_AUTHENTICATION_TAB_ITEM_INDEX = 0;
/** The SASL Authentication tab item index */
private static final int SASL_AUTHENTICATION_TAB_ITEM_INDEX = 1;
/** The SyncRepl value */
private SyncRepl syncRepl;
/** The connection */
private IBrowserConnection browserConnection;
private List<String> attributes = new ArrayList<>();
// UI widgets
private Button okButton;
private ScrolledComposite scrolledComposite;
private Composite composite;
private Text replicaIdText;
private ComboViewer replicationTypeComboViewer;
private Button configureReplicationButton;
private Text hostText;
private Text portText;
private ComboViewer encryptionMethodComboViewer;
private Button configureStartTlsButton;
private TabFolder authenticationTabFolder;
private Text bindDnText;
private Text credentialsText;
private Button showCredentialsCheckbox;
private Label saslAuthenticationLabel;
private Button configureSaslAuthenticationButton;
private EntryWidget searchBaseDnEntryWidget;
private FilterWidget filterWidget;
private ComboViewer scopeComboViewer;
private TableViewer attributesTableViewer;
private Button addAttributeButton;
private Button editAttributeButton;
private Button deleteAttributeButton;
private Button attributesOnlyCheckbox;
// Listeners
private VerifyListener integerVerifyListener = event ->
{
if ( !event.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
event.doit = false;
}
};
private ModifyListener replicatIdTextListener = event ->
{
String replicaId = replicaIdText.getText();
if ( ( replicaId != null ) && ( !"".equals( replicaId ) ) )
{
syncRepl.setRid( replicaId );
}
else
{
syncRepl.setRid( null );
}
updateOkButtonEnableState();
};
private ISelectionChangedListener replicationTypeComboViewerListener = event -> syncRepl.setType( getReplicationType() );
private SelectionListener configureReplicationButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
ReplicationOptionsDialog dialog = new ReplicationOptionsDialog( getShell(), syncRepl, browserConnection );
if ( dialog.open() == ReplicationOptionsDialog.OK )
{
syncRepl = dialog.getSyncRepl();
refreshUI();
}
}
};
private ModifyListener hostTextListener = event ->
{
syncRepl.setProvider( getProvider() );
updateOkButtonEnableState();
};
private ModifyListener portTextListener = event -> syncRepl.setProvider( getProvider() );
private ISelectionChangedListener encryptionMethodComboViewerListener = event ->
{
syncRepl.setProvider( getProvider() );
// Getting the selected encryption method
EncryptionMethod encryptionMethod = getEncryptionMethod();
if ( ( encryptionMethod == EncryptionMethod.NO_ENCRYPTION )
|| ( encryptionMethod == EncryptionMethod.SSL_ENCRYPTION_LDAPS ) )
{
configureStartTlsButton.setEnabled( false );
}
else if ( encryptionMethod == EncryptionMethod.START_TLS_EXTENSION )
{
configureStartTlsButton.setEnabled( true );
}
};
private SelectionListener configureStartTlsButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// TODO
}
};
private SelectionListener authenticationTabFolderListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// Simple Authentication
if ( authenticationTabFolder.getSelectionIndex() == SIMPLE_AUTHENTICATION_TAB_ITEM_INDEX )
{
syncRepl.setBindMethod( BindMethod.SIMPLE );
// Reseting SASL authentication parameters
syncRepl.setSaslMech( null );
syncRepl.setAuthcid( null );
syncRepl.setAuthzid( null );
syncRepl.setCredentials( null );
syncRepl.setRealm( null );
syncRepl.setSecProps( null );
}
// SASL Authentication
else if ( authenticationTabFolder.getSelectionIndex() == SASL_AUTHENTICATION_TAB_ITEM_INDEX )
{
syncRepl.setBindMethod( BindMethod.SASL );
// Reseting simple authentication parameters
syncRepl.setBindDn( null );
syncRepl.setCredentials( null );
}
refreshUI();
}
};
private ModifyListener bindDnTextListener = event ->
{
String bindDn = bindDnText.getText();
if ( ( bindDn != null ) && ( !"".equals( bindDn ) ) )
{
syncRepl.setBindDn( bindDn );
}
else
{
syncRepl.setBindDn( null );
}
};
private ModifyListener credentialsTextListener = event ->
{
String credentials = credentialsText.getText();
if ( ( credentials != null ) && ( !"".equals( credentials ) ) )
{
syncRepl.setCredentials( credentials );
}
else
{
syncRepl.setCredentials( null );
}
};
private SelectionListener showCredentialsCheckboxListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
if ( showCredentialsCheckbox.getSelection() )
{
credentialsText.setEchoChar( '\0' );
}
else
{
credentialsText.setEchoChar( '\u2022' );
}
}
};
private SelectionListener configureSaslAuthenticationButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
ReplicationSaslDialog dialog = new ReplicationSaslDialog( getShell(), syncRepl, browserConnection );
if ( dialog.open() == ReplicationSaslDialog.OK )
{
syncRepl = dialog.getSyncRepl();
refreshUI();
}
}
};
private WidgetModifyListener searchBaseDnEntryWidgetListener = event ->
{
Dn searchBaseDn = searchBaseDnEntryWidget.getDn();
if ( ( searchBaseDn != null ) && ( !Dn.EMPTY_DN.equals( searchBaseDn ) ) )
{
syncRepl.setSearchBase( searchBaseDn.getName() );
}
else
{
syncRepl.setSearchBase( null );
}
updateOkButtonEnableState();
};
private WidgetModifyListener filterWidgetListener = event ->
{
String filter = filterWidget.getFilter();
if ( ( filter != null ) && ( !"".equals( filter ) ) )
{
syncRepl.setFilter( filter );
}
else
{
syncRepl.setFilter( null );
}
};
private ISelectionChangedListener scopeComboViewerListener = event -> syncRepl.setScope( getScope() );
private ISelectionChangedListener attributesTableViewerSelectionChangedListener = event -> updateAttributesTableButtonsState();
private IDoubleClickListener attributesTableViewerDoubleClickListener = event -> editAttributeButtonAction();
private SelectionListener addAttributeButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
addAttributeButtonAction();
}
};
private SelectionListener editAttributeButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
editAttributeButtonAction();
}
};
private SelectionListener deleteAttributeButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
deleteAttributeButtonAction();
}
};
private SelectionListener attributesOnlyCheckboxListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
syncRepl.setAttrsOnly( attributesOnlyCheckbox.getSelection() );
}
};
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param index the index
* @param browserConnection the connection
*/
public ReplicationConsumerDialog( Shell parentShell, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
this.syncRepl = createDefaultSyncRepl();
}
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param index the index
* @param browserConnection the connection
*/
public ReplicationConsumerDialog( Shell parentShell, SyncRepl syncRepl, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
if ( syncRepl != null )
{
this.syncRepl = syncRepl.copy();
}
else
{
this.syncRepl = createDefaultSyncRepl();
}
}
/**
* Creates a default SyncRepl configuration.
*
* @return a default SyncRepl configuration
*/
private SyncRepl createDefaultSyncRepl()
{
return new SyncRepl();
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Replication Consumer" );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
updateOkButtonEnableState();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// Creating the scrolled composite
scrolledComposite = new ScrolledComposite( parent, SWT.H_SCROLL | SWT.V_SCROLL );
scrolledComposite.setExpandHorizontal( true );
scrolledComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Creating the composite and attaching it to the scrolled composite
composite = new Composite( scrolledComposite, SWT.NONE );
composite.setLayout( new GridLayout() );
scrolledComposite.setContent( composite );
createReplicationConsumerGroup( composite );
createReplicationProviderGroup( composite );
createReplicationAuthenticationGroup( composite );
createReplicationDataGroup( composite );
refreshUI();
applyDialogFont( scrolledComposite );
composite.setSize( composite.computeSize( SWT.DEFAULT, SWT.DEFAULT ) );
return scrolledComposite;
}
/**
* Creates the replication consumer group.
*
* @param parent the parent composite
*/
private void createReplicationConsumerGroup( Composite parent )
{
// Replication Provider Group
Group group = BaseWidgetUtils.createGroup( parent, "Replication Consumer", 1 );
GridLayout groupGridLayout = new GridLayout( 2, false );
group.setLayout( groupGridLayout );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Replica ID
BaseWidgetUtils.createLabel( group, "Replica ID:", 1 );
replicaIdText = BaseWidgetUtils.createText( group, "", 1 );
replicaIdText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Replication Type
BaseWidgetUtils.createLabel( group, "Replication Type:", 1 );
replicationTypeComboViewer = new ComboViewer( group );
replicationTypeComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
replicationTypeComboViewer.setContentProvider( new ArrayContentProvider() );
replicationTypeComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof Type )
{
Type type = ( Type ) element;
switch ( type )
{
case REFRESH_AND_PERSIST:
return "Refresh And Persist";
case REFRESH_ONLY:
return "Refresh Only";
}
}
return super.getText( element );
}
} );
replicationTypeComboViewer.setInput( new Type[]
{ Type.REFRESH_AND_PERSIST, Type.REFRESH_ONLY } );
// Configure Replication Options Button
BaseWidgetUtils.createLabel( group, "", 1 );
configureReplicationButton = BaseWidgetUtils.createButton( group, "Configure Replication Options...", 1 );
configureReplicationButton.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) );
}
/**
* Creates the replication provider group.
*
* @param parent the parent composite
*/
private void createReplicationProviderGroup( Composite parent )
{
// Replication Provider Group
Group group = BaseWidgetUtils.createGroup( parent, "Replication Provider Connection", 1 );
GridLayout groupGridLayout = new GridLayout( 2, false );
group.setLayout( groupGridLayout );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Host
BaseWidgetUtils.createLabel( group, "Provider Host:", 1 );
hostText = BaseWidgetUtils.createText( group, "", 1 );
hostText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Port
BaseWidgetUtils.createLabel( group, "Provider Port:", 1 );
portText = BaseWidgetUtils.createText( group, "", 1 );
portText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Encryption Method
BaseWidgetUtils.createLabel( group, "Encryption Method:", 1 );
encryptionMethodComboViewer = new ComboViewer( group );
encryptionMethodComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
encryptionMethodComboViewer.setContentProvider( new ArrayContentProvider() );
encryptionMethodComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof EncryptionMethod )
{
EncryptionMethod encryptionMethod = ( EncryptionMethod ) element;
switch ( encryptionMethod )
{
case NO_ENCRYPTION:
return "No Encryption";
case SSL_ENCRYPTION_LDAPS:
return "Use SSL Encryption (ldaps://)";
case START_TLS_EXTENSION:
return "Use Start TLS Extension";
}
}
return super.getText( element );
}
} );
encryptionMethodComboViewer.setInput( new EncryptionMethod[]
{
EncryptionMethod.NO_ENCRYPTION,
EncryptionMethod.SSL_ENCRYPTION_LDAPS,
EncryptionMethod.START_TLS_EXTENSION } );
// Configure Start TLS Button
BaseWidgetUtils.createLabel( group, "", 1 );
configureStartTlsButton = BaseWidgetUtils.createButton( group, "Configure Start TLS...", 1 );
configureStartTlsButton.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) );
configureStartTlsButton.setEnabled( false );
}
/**
* Creates the replication authentication group.
*
* @param parent the parent composite
*/
private void createReplicationAuthenticationGroup( Composite parent )
{
// Replication Provider Group
Group group = BaseWidgetUtils.createGroup( parent, "Authentication", 1 );
GridLayout groupGridLayout = new GridLayout( 2, false );
group.setLayout( groupGridLayout );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Authentication
authenticationTabFolder = new TabFolder( group, SWT.TOP );
authenticationTabFolder.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 2, 1 ) );
// Simple Authentication Composite
Composite simpleAuthenticationComposite = new Composite( authenticationTabFolder, SWT.NONE );
simpleAuthenticationComposite.setLayout( new GridLayout( 2, false ) );
simpleAuthenticationComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Bind DN Text
BaseWidgetUtils.createLabel( simpleAuthenticationComposite, "Bind DN:", 1 );
bindDnText = BaseWidgetUtils.createText( simpleAuthenticationComposite, "", 1 );
bindDnText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Credentials Text
BaseWidgetUtils.createLabel( simpleAuthenticationComposite, "Credentials:", 1 );
credentialsText = BaseWidgetUtils.createText( simpleAuthenticationComposite, "", 1 );
credentialsText.setEchoChar( '\u2022' );
// Show Credentials Checkbox
BaseWidgetUtils.createLabel( simpleAuthenticationComposite, "", 1 );
showCredentialsCheckbox = BaseWidgetUtils.createCheckbox( simpleAuthenticationComposite, "Show Credentials", 1 );
// Simple Authentication TabItem
TabItem simpleAuthenticationTabItem = new TabItem( authenticationTabFolder, SWT.NONE,
SIMPLE_AUTHENTICATION_TAB_ITEM_INDEX );
simpleAuthenticationTabItem.setText( "Simple Authentication" );
simpleAuthenticationTabItem.setControl( simpleAuthenticationComposite );
// SASL Authentication Composite
Composite saslAuthenticationComposite = new Composite( authenticationTabFolder, SWT.NONE );
saslAuthenticationComposite.setLayout( new GridLayout() );
saslAuthenticationComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// SASL Authentication Wrapped Label
saslAuthenticationLabel = new Label( saslAuthenticationComposite, SWT.WRAP | SWT.CENTER );
saslAuthenticationLabel.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, true ) );
// Configure SASL Authentication Button
configureSaslAuthenticationButton = BaseWidgetUtils.createButton( saslAuthenticationComposite,
"Configure SASL Authentication...", 1 );
configureSaslAuthenticationButton.setLayoutData( new GridData( SWT.CENTER, SWT.BOTTOM, true, false ) );
// SASL Authentication TabItem
TabItem saslAuthenticationTabItem = new TabItem( authenticationTabFolder, SWT.NONE,
SASL_AUTHENTICATION_TAB_ITEM_INDEX );
saslAuthenticationTabItem.setText( "SASL Authentication" );
saslAuthenticationTabItem.setControl( saslAuthenticationComposite );
}
/**
* Creates the replication data group.
*
* @param parent the parent composite
*/
private void createReplicationDataGroup( Composite parent )
{
// Replication Data Group
Group group = BaseWidgetUtils.createGroup( parent, "Replication Data Configuration", 1 );
GridLayout groupGridLayout = new GridLayout( 3, false );
groupGridLayout.verticalSpacing = groupGridLayout.marginHeight = 0;
group.setLayout( groupGridLayout );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Search Base DN Text
BaseWidgetUtils.createLabel( group, "Search Base DN:", 1 );
searchBaseDnEntryWidget = new EntryWidget( browserConnection, Dn.EMPTY_DN );
searchBaseDnEntryWidget.createWidget( group );
// Filter Text
BaseWidgetUtils.createLabel( group, "Filter:", 1 );
filterWidget = new FilterWidget();
filterWidget.setBrowserConnection( browserConnection );
filterWidget.createWidget( group );
// Scope Combo Viewer
BaseWidgetUtils.createLabel( group, "Scope:", 1 );
scopeComboViewer = new ComboViewer( group );
scopeComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
scopeComboViewer.setContentProvider( new ArrayContentProvider() );
scopeComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof Scope )
{
Scope scope = ( Scope ) element;
switch ( scope )
{
case BASE:
return "Base";
case ONE:
return "One Level";
case SUB:
return "Subtree";
case SUBORD:
return "Subordinate Subtree";
}
}
return super.getText( element );
}
} );
scopeComboViewer.setInput( new Scope[]
{ Scope.SUB, Scope.SUBORD, Scope.ONE, Scope.BASE } );
// Attributes Table Viewer
BaseWidgetUtils.createLabel( group, "Attributes:", 1 );
Composite attributesTableComposite = new Composite( group, SWT.NONE );
attributesTableComposite.setLayout( new GridLayout( 2, false ) );
attributesTableComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 2, 1 ) );
attributesTableViewer = new TableViewer( attributesTableComposite );
attributesTableViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 ) );
attributesTableViewer.setContentProvider( new ArrayContentProvider() );
attributesTableViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES.equals( element ) )
{
return SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES + " " + "<all operational attributes>";
}
else if ( SchemaConstants.ALL_USER_ATTRIBUTES.equals( element ) )
{
return SchemaConstants.ALL_USER_ATTRIBUTES + " " + "<all user attributes>";
}
return super.getText( element );
}
@Override
public Image getImage( Object element )
{
return OpenLdapConfigurationPlugin.getDefault().getImage(
OpenLdapConfigurationPluginConstants.IMG_ATTRIBUTE );
}
} );
attributesTableViewer.setInput( attributes );
// Add Attribute Button
addAttributeButton = BaseWidgetUtils.createButton( attributesTableComposite, "Add...", 1 );
addAttributeButton.setLayoutData( createNewButtonGridData() );
// Edit Attribute Button
editAttributeButton = BaseWidgetUtils.createButton( attributesTableComposite, "Edit...", 1 );
editAttributeButton.setEnabled( false );
editAttributeButton.setLayoutData( createNewButtonGridData() );
// Delete Attribute Button
deleteAttributeButton = BaseWidgetUtils.createButton( attributesTableComposite, "Delete", 1 );
deleteAttributeButton.setEnabled( false );
deleteAttributeButton.setLayoutData( createNewButtonGridData() );
// Attributes Only Checkbox
BaseWidgetUtils.createLabel( group, "", 1 ); //$NON-NLS-1$
attributesOnlyCheckbox = BaseWidgetUtils.createCheckbox( group, "Attributes Only (no values)", 1 );
attributesOnlyCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) );
}
/**
* Updates the state of the attributes table buttons.
*/
private void updateAttributesTableButtonsState()
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
editAttributeButton.setEnabled( !selection.isEmpty() );
deleteAttributeButton.setEnabled( !selection.isEmpty() );
}
/**
* Action launched when the add attribute button is clicked.
*/
private void addAttributeButtonAction()
{
AttributeDialog dialog = new AttributeDialog( addAttributeButton.getShell(), browserConnection );
if ( dialog.open() == AttributeDialog.OK )
{
String attribute = dialog.getAttribute();
attributes.add( attribute );
syncRepl.setAttributes( attributes.toArray( new String[0] ) );
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( attribute ) );
}
}
/**
* Action launched when the edit attribute button is clicked.
*/
private void editAttributeButtonAction()
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
AttributeDialog dialog = new AttributeDialog( editAttributeButton.getShell(), browserConnection,
selectedAttribute );
if ( dialog.open() == AttributeDialog.OK )
{
String attribute = dialog.getAttribute();
int selectedAttributeIndex = attributes.indexOf( selectedAttribute );
attributes.remove( selectedAttributeIndex );
attributes.add( selectedAttributeIndex, attribute );
syncRepl.setAttributes( attributes.toArray( new String[0] ) );
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( attribute ) );
}
}
}
/**
* Action launched when the delete attribute button is clicked.
*/
private void deleteAttributeButtonAction()
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
attributes.remove( selectedAttribute );
syncRepl.setAttributes( attributes.toArray( new String[0] ) );
attributesTableViewer.refresh();
// updateAttributesTableButtonsState();
}
}
/**
* Create a new button grid data.
*
* @return the new button grid data
*/
private GridData createNewButtonGridData()
{
GridData gd = new GridData( SWT.FILL, SWT.BEGINNING, false, false );
gd.widthHint = IDialogConstants.BUTTON_WIDTH;
return gd;
}
private void refreshUI()
{
if ( syncRepl != null )
{
removeListeners();
//
// Replication Consumer
//
// Replica ID
String replicaId = syncRepl.getRid();
if ( replicaId != null )
{
replicaIdText.setText( replicaId );
}
else
{
replicaIdText.setText( "" );
}
// Replication Type
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RestrictOperationDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/RestrictOperationDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.RestrictOperationEnum;
/**
* The RestrictOperationDialog is used to select one restricted operation. The possible
* operations are :
* <ul>
* <li>add</li>
* <li>all</li>
* <li>bind</li>
* <li>compare</li>
* <li>delete</li>
* <li>extended</li>
* <li>extended=1.3.6.1.4.1.1466.20037</li>
* <li>extended=1.3.6.1.4.1.4203.1.11.1</li>
* <li>extended=1.3.6.1.4.1.4203.1.11.3</li>
* <li>extended=1.3.6.1.1.8</li>
* <li>modify</li>
* <li>modrdn</li>
* <li>read</li>
* <li>rename</li>
* <li>search</li>
* <li>write</li>
* </ul>
*
* The dialog overlay is like :
*
* <pre>
* +--------------------------------------------------------------------+
* | Restricted Operation |
* | .----------------------------------------------------------------. |
* | | add : [] all : [] bind : [] compare : [] | |
* | | delete : [] extended [] START_TLS : [] MODIFY_PASSWORD : [] | |
* | | WHOAMI : [] CANCEL : [] modify : [] modrdn : [] | |
* | | read : [] rename : [] search : [] write : [] | |
* | '----------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RestrictOperationDialog extends AddEditDialog<RestrictOperationEnum>
{
/** The array of buttons */
private Button[] restrictOperationCheckboxes = new Button[16];
/** The already selected Restricted Operations */
List<RestrictOperationEnum> operations = new ArrayList<>();
/**
* Create a new instance of the RestrictOperationDialog
*
* @param parentShell The parent Shell
*/
public RestrictOperationDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "RestrictOperation.Title" ) );
}
/**
* The listener in charge of exposing the changes when some checkbox is selected
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedCheckbox = (Button)object;
for ( int i = 1; i < restrictOperationCheckboxes.length; i++ )
{
if ( selectedCheckbox == restrictOperationCheckboxes[i] )
{
setEditedElement( RestrictOperationEnum.getOperation( i ) );
}
else if ( restrictOperationCheckboxes[i].isEnabled() )
{
restrictOperationCheckboxes[i].setSelection( false );
}
}
}
}
};
/**
* Create the Dialog for RestrictOperation :
* <pre>
* +--------------------------------------------------------------------+
* | Restricted Operation |
* | .----------------------------------------------------------------. |
* | | add : [] all : [] bind : [] compare : [] | |
* | | delete : [] extended [] START_TLS : [] MODIFY_PASSWORD : [] | |
* | | WHOAMI : [] CANCEL : [] modify : [] modrdn : [] | |
* | | read : [] rename : [] search : [] write : [] | |
* | '----------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createRestrictOperationEditGroup( composite );
initDialog();
applyDialogFont( composite );
return composite;
}
/**
* Creates the RestrictOperation input group.
*
* <pre>
* Restricted Operation
* .----------------------------------------------------------------.
* | add : [] all : [] bind : [] compare : [] |
* | delete : [] extended [] START_TLS : [] MODIFY_PASSWORD : [] |
* | WHOAMI : [] CANCEL : [] modify : [] modrdn : [] |
* | read : [] rename : [] search : [] write : [] |
* '----------------------------------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createRestrictOperationEditGroup( Composite parent )
{
// Require Condition Group
Group restrictOperationGroup = BaseWidgetUtils.createGroup( parent, "", 2 );
GridLayout restrictOperationGridLayout = new GridLayout( 2, false );
restrictOperationGroup.setLayout( restrictOperationGridLayout );
restrictOperationGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The various buttons
for ( int i = 1; i < restrictOperationCheckboxes.length; i++ )
{
String restrictOperation = RestrictOperationEnum.getOperation( i ).getExternalName();
restrictOperationCheckboxes[i] = BaseWidgetUtils.createCheckbox( restrictOperationGroup, restrictOperation, 1 );
restrictOperationCheckboxes[i].addSelectionListener( checkboxSelectionListener );
}
}
protected void initDialog()
{
List<RestrictOperationEnum> elements = getElements();
boolean allSelected = true;
okDisabled = false;
for ( int i = 1; i < restrictOperationCheckboxes.length; i++ )
{
RestrictOperationEnum value = RestrictOperationEnum.getRestrictOperation( restrictOperationCheckboxes[i].getText() );
// Disable the Conditions already selected
if ( elements.contains( value ) )
{
restrictOperationCheckboxes[i].setSelection( true );
restrictOperationCheckboxes[i].setEnabled( false );
}
else
{
allSelected = false;
}
}
if ( allSelected )
{
// Disable the OK button
okDisabled = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void addNewElement()
{
// Default to none
setEditedElement( RestrictOperationEnum.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/Messages.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.openldap.config.editor.dialogs;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* This class get messages from the resources file for the OpenLDAP pages.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private Messages()
{
// Nothing to do
}
/** The resource name */
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle( Messages.class.getPackage().getName() + ".messages" );
/**
* Get back a message from the resource file given a key
*
* @param key The key associated with the message
* @return The found message
*/
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DbConfigurationDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DbConfigurationDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginUtils;
/**
* The DbConfigurationDialog is used to edit the (BDB) database configuration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DbConfigurationDialog extends Dialog
{
/** The OS specific line separator character */
private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
/** The configuration */
private String[] configuration;
// UI widgets
private Text text;
/**
* Creates a new instance of DbConfigurationDialog.
*
* @param parentShell the parent shell
* @param initialConfiguration the initial configuration
*/
public DbConfigurationDialog( Shell parentShell, String[] initialConfiguration )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.configuration = initialConfiguration;
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Database Configuration Editor" );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed()
{
if ( ( text.getText() != null ) && ( text.getText().length() > 0 ) )
{
List<String> newConfiguration = new ArrayList<>();
String[] splittedConfiguration = text.getText().split( LINE_SEPARATOR );
for ( int i = 0; i < splittedConfiguration.length; i++ )
{
newConfiguration.add( "{" + i + "}" + splittedConfiguration[i] );
}
configuration = newConfiguration.toArray( new String[0] );
}
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// create composite
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// text widget
text = new Text( composite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL );
gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH );
gd.heightHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH / 2 );
text.setLayoutData( gd );
text.setText( prepareInitialConfiguration() );
applyDialogFont( composite );
return composite;
}
/**
* Prepares the initial configuration string.
*
* @return the initial configuration string
*/
private String prepareInitialConfiguration()
{
StringBuilder sb = new StringBuilder();
if ( ( configuration != null ) && ( configuration.length > 0 ) )
{
for ( String line : configuration )
{
sb.append( OpenLdapConfigurationPluginUtils.stripOrderingPrefix( line ) );
sb.append( LINE_SEPARATOR );
}
}
return sb.toString();
}
/**
* Gets the configuration.
*
* @return the configuration
*/
public String[] getConfiguration()
{
return configuration;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationOptionsDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ReplicationOptionsDialog.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.openldap.config.editor.dialogs;
import java.text.ParseException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.EntryWidget;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.FilterWidget;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.syncrepl.Interval;
import org.apache.directory.studio.openldap.syncrepl.KeepAlive;
import org.apache.directory.studio.openldap.syncrepl.Retry;
import org.apache.directory.studio.openldap.syncrepl.SchemaChecking;
import org.apache.directory.studio.openldap.syncrepl.SyncData;
import org.apache.directory.studio.openldap.syncrepl.SyncRepl;
import org.apache.directory.studio.openldap.syncrepl.Type;
/**
* The ReplicationOptionsDialog is used to edit the replication options of a SyncRepl consumer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ReplicationOptionsDialog extends Dialog
{
/** The SyncRepl value */
private SyncRepl syncRepl;
/** The connection */
private IBrowserConnection browserConnection;
// UI widgets
private ScrolledComposite scrolledComposite;
private Composite composite;
private ComboViewer replicationTypeComboViewer;
private Spinner intervalDaysSpinner;
private Spinner intervalHoursSpinner;
private Spinner intervalMinutesSpinner;
private Spinner intervalSecondsSpinner;
private Text retryText;
private Button editRetryButton;
private Spinner keepAliveIdleSpinner;
private Spinner keepAliveProbesSpinner;
private Spinner keepAliveIntervalSpinner;
private Text sizeLimitText;
private Text timeLimitText;
private Text networkTimeoutText;
private Text timeoutText;
private Button enableSchemaCheckingCheckbox;
private Button enableDeltaSyncReplCheckbox;
private ComboViewer syncDataComboViewer;
private EntryWidget logBaseDnEntryWidget;
private FilterWidget logFilterWidget;
// Listeners
private VerifyListener integerVerifyListener = event ->
{
if ( !event.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
event.doit = false;
}
};
private SelectionListener editRetryButtonListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// Getting the retry value
String retryValue = null;
if ( syncRepl != null )
{
Retry retry = syncRepl.getRetry();
if ( retry != null )
{
retryValue = retry.toString();
}
}
// Creating and displaying a dialog to edit the retry value
InputDialog dialog = new InputDialog( editRetryButton.getShell(), "Edit Retry Value", "Specify the retry value as a list of the <retry interval> and <# of retries> pairs:",
retryValue, newText ->
{
try
{
Retry.parse( newText );
}
catch ( ParseException pe )
{
return pe.getMessage();
}
return null;
} );
if ( InputDialog.OK == dialog.open() )
{
try
{
syncRepl.setRetry( Retry.parse( dialog.getValue() ) );
}
catch ( ParseException e1 )
{
syncRepl.setRetry( null );
}
retryText.setText( getRetryValue() );
}
}
};
private SelectionListener enableDeltaSyncReplCheckboxListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
boolean isChecked = enableDeltaSyncReplCheckbox.getSelection();
syncDataComboViewer.getControl().setEnabled( isChecked );
logBaseDnEntryWidget.setEnabled( isChecked );
logFilterWidget.setEnabled( isChecked );
}
};
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param index the index
* @param browserConnection the connection
*/
public ReplicationOptionsDialog( Shell parentShell, SyncRepl syncRepl, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
if ( syncRepl != null )
{
this.syncRepl = syncRepl.copy();
}
else
{
this.syncRepl = createDefaultSyncRepl();
}
}
/**
* Creates a default SyncRepl configuration.
*
* @return a default SyncRepl configuration
*/
private SyncRepl createDefaultSyncRepl()
{
return new SyncRepl();
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Replication Options" );
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
saveToSyncRepl();
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// Creating the scrolled composite
scrolledComposite = new ScrolledComposite( parent, SWT.H_SCROLL | SWT.V_SCROLL );
scrolledComposite.setExpandHorizontal( true );
scrolledComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Creating the composite and attaching it to the scrolled composite
composite = new Composite( scrolledComposite, SWT.NONE );
composite.setLayout( new GridLayout() );
scrolledComposite.setContent( composite );
createReplicationConsumerGroup( composite );
createDeltaSyncReplGroup( composite );
initFromSyncRepl();
applyDialogFont( scrolledComposite );
composite.setSize( composite.computeSize( SWT.DEFAULT, SWT.DEFAULT ) );
return scrolledComposite;
}
/**
* Creates the replication consumer group.
*
* @param parent the parent composite
*/
private void createReplicationConsumerGroup( Composite parent )
{
// Replication Provider Group
Group group = BaseWidgetUtils.createGroup( parent, "Replication Consumer", 1 );
group.setLayout( new GridLayout( 3, false ) );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Replication Type
BaseWidgetUtils.createLabel( group, "Replication Type:", 1 );
replicationTypeComboViewer = new ComboViewer( group );
replicationTypeComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
replicationTypeComboViewer.setContentProvider( new ArrayContentProvider() );
replicationTypeComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof Type )
{
Type type = ( Type ) element;
switch ( type )
{
case REFRESH_AND_PERSIST:
return "Refresh And Persist";
case REFRESH_ONLY:
return "Refresh Only";
}
}
return super.getText( element );
}
} );
replicationTypeComboViewer.setInput( new Type[]
{ Type.REFRESH_AND_PERSIST, Type.REFRESH_ONLY } );
// Interval
createIntervalComposites( group );
// Retry
BaseWidgetUtils.createLabel( group, "Retry:", 1 );
retryText = BaseWidgetUtils.createReadonlyText( group, "", 1 );
retryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 1, 1 ) );
editRetryButton = BaseWidgetUtils.createButton( group, "Edit...", 1 );
editRetryButton.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 1, 1 ) );
// Keep Alive
createKeepAliveComposites( group );
// Size Limit
BaseWidgetUtils.createLabel( group, "Size Limit:", 1 );
sizeLimitText = BaseWidgetUtils.createText( group, "", 1 );
sizeLimitText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
// Time Limit
BaseWidgetUtils.createLabel( group, "Time Limit:", 1 );
timeLimitText = BaseWidgetUtils.createText( group, "", 1 );
timeLimitText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
// Network Timeout
BaseWidgetUtils.createLabel( group, "Network Timeout:", 1 );
networkTimeoutText = BaseWidgetUtils.createText( group, "", 1 );
networkTimeoutText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
// Timeout
BaseWidgetUtils.createLabel( group, "Timeout:", 1 );
timeoutText = BaseWidgetUtils.createText( group, "", 1 );
timeoutText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
// Schema Checking
enableSchemaCheckingCheckbox = BaseWidgetUtils.createCheckbox( group, "Enable Schema Checking", 2 );
}
private void createIntervalComposites( Composite parent )
{
// Interval Label Composite
Composite intervalLabelComposite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
intervalLabelComposite.setLayoutData( new GridData() );
// Interval Label
BaseWidgetUtils.createLabel( intervalLabelComposite, "Interval:", 1 );
BaseWidgetUtils.createLabel( intervalLabelComposite, "", 1 );
// Interval Composite
Composite intervalComposite = BaseWidgetUtils.createColumnContainer( parent, 2, 2 );
GridLayout intervalCompositeGridLayout = new GridLayout( 4, false );
intervalCompositeGridLayout.marginWidth = intervalCompositeGridLayout.marginHeight = 0;
intervalCompositeGridLayout.verticalSpacing = 0;
intervalComposite.setLayout( intervalCompositeGridLayout );
// Interval Days Spinner
intervalDaysSpinner = new Spinner( intervalComposite, SWT.BORDER );
intervalDaysSpinner.setMinimum( 0 );
intervalDaysSpinner.setMaximum( 99999 );
// Interval Hours Spinner
intervalHoursSpinner = new Spinner( intervalComposite, SWT.BORDER );
intervalHoursSpinner.setMinimum( 0 );
intervalHoursSpinner.setMaximum( 23 );
// Interval Minutes Spinner
intervalMinutesSpinner = new Spinner( intervalComposite, SWT.BORDER );
intervalMinutesSpinner.setMinimum( 0 );
intervalMinutesSpinner.setMaximum( 59 );
// Interval Seconds Spinner
intervalSecondsSpinner = new Spinner( intervalComposite, SWT.BORDER );
intervalSecondsSpinner.setMinimum( 0 );
intervalSecondsSpinner.setMaximum( 59 );
// Days Hours Minutes Seconds Labels
BaseWidgetUtils.createLabel( intervalComposite, "Days", 1 );
BaseWidgetUtils.createLabel( intervalComposite, "Hours", 1 );
BaseWidgetUtils.createLabel( intervalComposite, "Minutes", 1 );
BaseWidgetUtils.createLabel( intervalComposite, "Seconds", 1 );
}
private void createKeepAliveComposites( Composite parent )
{
// Keep Alive Label Composite
Composite keepAliveLabelComposite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
keepAliveLabelComposite.setLayoutData( new GridData() );
// Keep Alive Label
BaseWidgetUtils.createLabel( keepAliveLabelComposite, "Keep Alive:", 1 );
BaseWidgetUtils.createLabel( keepAliveLabelComposite, "", 1 );
// Keep Alive Composite
Composite keepAliveComposite = BaseWidgetUtils.createColumnContainer( parent, 2, 2 );
GridLayout keepAliveCompositeGridLayout = new GridLayout( 3, false );
keepAliveCompositeGridLayout.marginWidth = keepAliveCompositeGridLayout.marginHeight = 0;
keepAliveCompositeGridLayout.verticalSpacing = 0;
keepAliveComposite.setLayout( keepAliveCompositeGridLayout );
// Keep Alive Idle Spinner
keepAliveIdleSpinner = new Spinner( keepAliveComposite, SWT.BORDER );
keepAliveIdleSpinner.setMinimum( 0 );
keepAliveIdleSpinner.setMaximum( 99999 );
// Keep Alive Probes Spinner
keepAliveProbesSpinner = new Spinner( keepAliveComposite, SWT.BORDER );
keepAliveProbesSpinner.setMinimum( 0 );
keepAliveProbesSpinner.setMaximum( 99999 );
// Keep Alive Interval Spinner
keepAliveIntervalSpinner = new Spinner( keepAliveComposite, SWT.BORDER );
keepAliveIntervalSpinner.setMinimum( 0 );
keepAliveIntervalSpinner.setMaximum( 99999 );
// Idle Probes Interval Labels
BaseWidgetUtils.createLabel( keepAliveComposite, "Idle", 1 );
BaseWidgetUtils.createLabel( keepAliveComposite, "Probes", 1 );
BaseWidgetUtils.createLabel( keepAliveComposite, "Interval", 1 );
}
private void createDeltaSyncReplGroup( Composite parent )
{
// Replication Provider Group
Group group = BaseWidgetUtils.createGroup( parent, "Delta SyncRepl Configuration", 1 );
group.setLayout( new GridLayout( 3, false ) );
group.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Enable Delta SyncRepl Checkbox
enableDeltaSyncReplCheckbox = BaseWidgetUtils.createCheckbox( group, "Enable Delta SyncRepl", 3 );
// Sync Data Combo Viewer
BaseWidgetUtils.createLabel( group, "Sync Data:", 1 );
syncDataComboViewer = new ComboViewer( group );
syncDataComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
syncDataComboViewer.setContentProvider( new ArrayContentProvider() );
syncDataComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof SyncData )
{
SyncData syncData = ( SyncData ) element;
switch ( syncData )
{
case ACCESSLOG:
return "Access Log";
case CHANGELOG:
return "Change Log";
case DEFAULT:
return "Default";
}
}
return super.getText( element );
}
} );
syncDataComboViewer.setInput( new SyncData[]
{ SyncData.ACCESSLOG, SyncData.CHANGELOG } );
// Log Base DN Text
BaseWidgetUtils.createLabel( group, "Log Base DN:", 1 );
logBaseDnEntryWidget = new EntryWidget( browserConnection, Dn.EMPTY_DN );
logBaseDnEntryWidget.createWidget( group );
// Log Filter Text
BaseWidgetUtils.createLabel( group, "Log Filter:", 1 );
logFilterWidget = new FilterWidget();
logFilterWidget.setBrowserConnection( browserConnection );
logFilterWidget.createWidget( group );
}
/**
* Initializes the dialog using the SyncRepl object.
*/
private void initFromSyncRepl()
{
if ( syncRepl != null )
{
// Replication Type
Type replicationType = syncRepl.getType();
if ( replicationType != null )
{
replicationTypeComboViewer.setSelection( new StructuredSelection( replicationType ) );
}
else
{
replicationTypeComboViewer.setSelection( new StructuredSelection( Type.REFRESH_AND_PERSIST ) );
}
// Interval
Interval interval = syncRepl.getInterval();
if ( interval != null )
{
intervalDaysSpinner.setSelection( interval.getDays() );
intervalHoursSpinner.setSelection( interval.getHours() );
intervalMinutesSpinner.setSelection( interval.getMinutes() );
intervalSecondsSpinner.setSelection( interval.getSeconds() );
}
// Retry
retryText.setText( getRetryValue() );
// Keep Alive
KeepAlive keepAlive = syncRepl.getKeepAlive();
if ( keepAlive != null )
{
keepAliveIdleSpinner.setSelection( keepAlive.getIdle() );
keepAliveProbesSpinner.setSelection( keepAlive.getProbes() );
keepAliveIntervalSpinner.setSelection( keepAlive.getInterval() );
}
// Size Limit
int sizeLimit = syncRepl.getSizeLimit();
if ( sizeLimit != -1 )
{
sizeLimitText.setText( Integer.toString( sizeLimit ) );
}
// Time Limit
int timeLimit = syncRepl.getTimeLimit();
if ( timeLimit != -1 )
{
timeLimitText.setText( Integer.toString( timeLimit ) );
}
// Network Timeout
int networkTimeout = syncRepl.getNetworkTimeout();
if ( networkTimeout != -1 )
{
networkTimeoutText.setText( Integer.toString( networkTimeout ) );
}
// Timeout
int timeout = syncRepl.getTimeout();
if ( timeout != -1 )
{
timeoutText.setText( Integer.toString( timeout ) );
}
// Enable Schema Checking
SchemaChecking schemaChecking = syncRepl.getSchemaChecking();
if ( schemaChecking != null )
{
enableSchemaCheckingCheckbox.setSelection( schemaChecking == SchemaChecking.ON );
}
// Sync Data
SyncData syncData = syncRepl.getSyncData();
if ( syncData != null && ( ( syncData == SyncData.ACCESSLOG ) || ( syncData == SyncData.CHANGELOG ) ) )
{
enableDeltaSyncReplCheckbox.setSelection( true );
syncDataComboViewer.setSelection( new StructuredSelection( syncData ) );
}
else
{
syncDataComboViewer.setSelection( new StructuredSelection( SyncData.ACCESSLOG ) );
syncDataComboViewer.getControl().setEnabled( false );
logBaseDnEntryWidget.setEnabled( false );
logFilterWidget.setEnabled( false );
}
// Log Base DN
String logBaseDn = syncRepl.getLogBase();
if ( logBaseDn != null )
{
try
{
logBaseDnEntryWidget.setInput( browserConnection, new Dn( logBaseDn ) );
}
catch ( LdapInvalidDnException e )
{
// Silent
}
}
// Log Filter
String logFilter = syncRepl.getLogFilter();
if ( logFilter != null )
{
logFilterWidget.setFilter( logFilter );
}
addListeners();
}
}
/**
* Gets the retry value.
*
* @return the retry value
*/
private String getRetryValue()
{
if ( syncRepl != null )
{
Retry retry = syncRepl.getRetry();
if ( retry != null )
{
return retry.toString();
}
}
return "(none)";
}
/**
* Adds listeners.
*/
private void addListeners()
{
editRetryButton.addSelectionListener( editRetryButtonListener );
sizeLimitText.addVerifyListener( integerVerifyListener );
timeLimitText.addVerifyListener( integerVerifyListener );
networkTimeoutText.addVerifyListener( integerVerifyListener );
timeoutText.addVerifyListener( integerVerifyListener );
enableDeltaSyncReplCheckbox.addSelectionListener( enableDeltaSyncReplCheckboxListener );
}
/**
* Saves the content of the dialog to the SyncRepl object.
*/
private void saveToSyncRepl()
{
if ( syncRepl != null )
{
// Replication Type
syncRepl.setType( getReplicationType() );
// Interval
syncRepl.setInterval( getInterval() );
// Retry
// TODO
// Keep Alive
syncRepl.setKeepAlive( getKeepAlive() );
// Size Limit
String sizeLimitString = sizeLimitText.getText();
if ( ( sizeLimitString != null ) && ( !"".equals( sizeLimitString ) ) )
{
try
{
int sizeLimit = Integer.parseInt( sizeLimitString );
syncRepl.setSizeLimit( sizeLimit );
}
catch ( NumberFormatException e )
{
// Silent (will never happen)
}
}
else
{
syncRepl.setSizeLimit( -1 );
}
// Time Limit
String timeLimitString = timeLimitText.getText();
if ( ( timeLimitString != null ) && ( !"".equals( timeLimitString ) ) )
{
try
{
int timeLimit = Integer.parseInt( timeLimitString );
syncRepl.setTimeLimit( timeLimit );
}
catch ( NumberFormatException e )
{
// Silent (will never happen)
}
}
else
{
syncRepl.setTimeLimit( -1 );
}
// Network Timeout
String networkTimeoutString = networkTimeoutText.getText();
if ( ( networkTimeoutString != null ) && ( !"".equals( networkTimeoutString ) ) )
{
try
{
int networkTimeout = Integer.parseInt( networkTimeoutString );
syncRepl.setNetworkTimeout( networkTimeout );
}
catch ( NumberFormatException e )
{
// Silent (will never happen)
}
}
else
{
syncRepl.setNetworkTimeout( -1 );
}
// Timeout
String timeoutString = timeoutText.getText();
if ( ( timeoutString != null ) && ( !"".equals( timeoutString ) ) )
{
try
{
int timeout = Integer.parseInt( timeoutString );
syncRepl.setTimeout( timeout );
}
catch ( NumberFormatException e )
{
// Silent (will never happen)
}
}
else
{
syncRepl.setTimeout( -1 );
}
// Enable Schema Checking
syncRepl.setSchemaChecking( getSchemaChecking() );
// Sync Data
syncRepl.setSyncData( getSyncData() );
// Log Base DN
Dn logBaseDn = logBaseDnEntryWidget.getDn();
if ( ( logBaseDn != null ) && ( !Dn.EMPTY_DN.equals( logBaseDn ) ) )
{
syncRepl.setLogBase( logBaseDn.getName() );
}
else
{
syncRepl.setLogBase( null );
}
// Log Filter
String logFilter = logFilterWidget.getFilter();
if ( ( logBaseDn != null ) && ( !"".equals( logFilter ) ) )
{
syncRepl.setLogFilter( logFilter );
}
else
{
syncRepl.setLogFilter( null );
}
}
}
/**
* Gets the replication type.
*
* @return the replication type
*/
private Type getReplicationType()
{
StructuredSelection selection = ( StructuredSelection ) replicationTypeComboViewer.getSelection();
if ( ( selection != null ) && ( !selection.isEmpty() ) )
{
return ( Type ) selection.getFirstElement();
}
return null;
}
/**
* Gets the interval.
*
* @return the interval
*/
private Interval getInterval()
{
int days = intervalDaysSpinner.getSelection();
int hours = intervalHoursSpinner.getSelection();
int minutes = intervalMinutesSpinner.getSelection();
int seconds = intervalSecondsSpinner.getSelection();
if ( ( days != 0 ) || ( hours != 0 ) || ( minutes != 0 ) || ( seconds != 0 ) )
{
return new Interval( days, hours, minutes, seconds );
}
return null;
}
/**
* Gets the keep alive.
*
* @return the keep alive
*/
private KeepAlive getKeepAlive()
{
int idle = keepAliveIdleSpinner.getSelection();
int probes = keepAliveProbesSpinner.getSelection();
int interval = keepAliveIntervalSpinner.getSelection();
if ( ( idle != 0 ) || ( probes != 0 ) || ( interval != 0 ) )
{
return new KeepAlive( idle, probes, interval );
}
return null;
}
/**
* Gets the schema checking.
*
* @return the schema checking
*/
private SchemaChecking getSchemaChecking()
{
if ( enableSchemaCheckingCheckbox.getSelection() )
{
return SchemaChecking.ON;
}
else
{
return SchemaChecking.OFF;
}
}
/**
* Gets the sync data.
*
* @return the sync data
*/
private SyncData getSyncData()
{
if ( enableDeltaSyncReplCheckbox.getSelection() )
{
StructuredSelection selection = ( StructuredSelection ) syncDataComboViewer.getSelection();
if ( ( selection != null ) && ( !selection.isEmpty() ) )
{
return ( SyncData ) selection.getFirstElement();
}
}
return null;
}
/**
* Gets the SyncRepl value.
*
* @return the SyncRepl value
*/
public SyncRepl getSyncRepl()
{
return syncRepl;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ValueSortingValueDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ValueSortingValueDialog.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.openldap.config.editor.dialogs;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.widgets.EntryWidget;
import org.apache.directory.studio.openldap.config.model.overlay.OlcValSortMethodEnum;
import org.apache.directory.studio.openldap.config.model.overlay.OlcValSortValue;
/**
* The ValueSortingValueDialog is used to edit a value from the Value Sorting overlay configuration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ValueSortingValueDialog extends Dialog
{
/** The 'weighted' combo viewer option */
private static final String WEIGHTED_OPTION = "Weighted";
/** The '<none>' combo viewer option */
private static final String NONE_OPTION = "<none>";
/** The connection's attribute types */
private List<String> connectionAttributeTypes;
/** The connection */
private IBrowserConnection browserConnection;
/** The value */
private OlcValSortValue value;
// UI widgets
private Button okButton;
private ComboViewer attributeComboViewer;
private EntryWidget baseDnEntryWidget;
private ComboViewer sortMethodComboViewer;
private ComboViewer secondarySortMethodComboViewer;
// Listeners
private ModifyListener attributeComboViewerListener = event -> checkAndUpdateOkButtonEnableState();
private WidgetModifyListener baseDnEntryWidgetListener = event -> checkAndUpdateOkButtonEnableState();
private ISelectionChangedListener sortMethodComboViewerListener = event ->
{
Object selectedSortMethod = getSelectedSortMethod();
if ( WEIGHTED_OPTION.equals( selectedSortMethod ) )
{
secondarySortMethodComboViewer.getCombo().setEnabled( true );
}
else
{
secondarySortMethodComboViewer.getCombo().setEnabled( false );
secondarySortMethodComboViewer.setSelection( new StructuredSelection( NONE_OPTION ) );
}
};
/**
* Creates a new instance of ValueSortingValueDialog.
*
* @param parentShell the parent shell
* @param browserConnection the connection
* @param value the value
*/
public ValueSortingValueDialog( Shell parentShell, IBrowserConnection browserConnection, String value )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
// Parsing the value
try
{
this.value = OlcValSortValue.parse( value );
if ( this.value == null )
{
this.value = new OlcValSortValue();
}
}
catch ( ParseException e )
{
this.value = new OlcValSortValue();
}
initAttributeTypesList();
}
/**
* Creates a new instance of ValueSortingValueDialog.
*
* @param parentShell the parent shell
* @param browserConnection the connection
*/
public ValueSortingValueDialog( Shell parentShell, IBrowserConnection browserConnection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.browserConnection = browserConnection;
this.value = new OlcValSortValue();
initAttributeTypesList();
}
/**
* Initializes the list of attribute types.
*/
private void initAttributeTypesList()
{
connectionAttributeTypes = new ArrayList<>();
if ( browserConnection != null )
{
// Attribute Types
Collection<AttributeType> atds = browserConnection.getSchema().getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
for ( String name : atd.getNames() )
{
connectionAttributeTypes.add( name );
}
}
// Sorting the list
Collections.sort( connectionAttributeTypes, ( o1, o2 ) -> o1.compareToIgnoreCase( o2 ) );
}
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Value Sort" );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
checkAndUpdateOkButtonEnableState();
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
// Attribute
value.setAttribute( attributeComboViewer.getCombo().getText() );
// Base DN
value.setBaseDn( baseDnEntryWidget.getDn() );
// Sort Method
Object selectedSortMethod = getSelectedSortMethod();
if ( WEIGHTED_OPTION.equals( selectedSortMethod ) )
{
value.setWeighted( true );
// Secondary Sort Method
Object selectedSecondarySortMethod = getSelectedSecondarySortMethod();
if ( NONE_OPTION.equals( selectedSecondarySortMethod ) )
{
value.setSortMethod( null );
}
else
{
value.setSortMethod( ( OlcValSortMethodEnum ) selectedSecondarySortMethod );
}
}
else
{
value.setSortMethod( ( OlcValSortMethodEnum ) selectedSortMethod );
}
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// Creating the dialog composites
Composite dialogComposite = ( Composite ) super.createDialogArea( parent );
GridData gridData = new GridData( SWT.FILL, SWT.FILL, true, true );
gridData.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH );
// gridData.heightHint = convertVerticalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 4 / 3;
dialogComposite.setLayoutData( gridData );
Composite composite = BaseWidgetUtils.createColumnContainer( dialogComposite, 2, 1 );
// Attribute
BaseWidgetUtils.createLabel( composite, "Attribute:", 1 );
attributeComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
attributeComboViewer.getControl()
.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
attributeComboViewer.setContentProvider( new ArrayContentProvider() );
attributeComboViewer.setInput( connectionAttributeTypes );
// Base DN
BaseWidgetUtils.createLabel( composite, "Base DN:", 1 );
baseDnEntryWidget = new EntryWidget( browserConnection );
baseDnEntryWidget.createWidget( composite );
baseDnEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Sort Method
BaseWidgetUtils.createLabel( composite, "Sort Method:", 1 );
sortMethodComboViewer = new ComboViewer( composite );
sortMethodComboViewer.getControl().setLayoutData(
new GridData( SWT.FILL, SWT.NONE, true, false ) );
sortMethodComboViewer.setContentProvider( new ArrayContentProvider() );
sortMethodComboViewer.setLabelProvider( new OlcValSortMethodEnumLabelProvider() );
sortMethodComboViewer.setInput( new Object[]
{
OlcValSortMethodEnum.ALPHA_ASCEND,
OlcValSortMethodEnum.ALPHA_DESCEND,
OlcValSortMethodEnum.NUMERIC_ASCEND,
OlcValSortMethodEnum.NUMERIC_DESCEND,
WEIGHTED_OPTION
} );
// Secondary Sort Method
BaseWidgetUtils.createLabel( composite, "Secondary Sort Method:", 1 );
secondarySortMethodComboViewer = new ComboViewer( composite );
secondarySortMethodComboViewer.getControl().setLayoutData(
new GridData( SWT.FILL, SWT.NONE, true, false ) );
secondarySortMethodComboViewer.setContentProvider( new ArrayContentProvider() );
secondarySortMethodComboViewer.setLabelProvider( new OlcValSortMethodEnumLabelProvider() );
secondarySortMethodComboViewer.setInput( new Object[]
{
NONE_OPTION,
OlcValSortMethodEnum.ALPHA_ASCEND,
OlcValSortMethodEnum.ALPHA_DESCEND,
OlcValSortMethodEnum.NUMERIC_ASCEND,
OlcValSortMethodEnum.NUMERIC_DESCEND
} );
initFromValue();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Adds listeners to UI widgets.
*/
private void addListeners()
{
attributeComboViewer.getCombo().addModifyListener( attributeComboViewerListener );
baseDnEntryWidget.addWidgetModifyListener( baseDnEntryWidgetListener );
sortMethodComboViewer.addSelectionChangedListener( sortMethodComboViewerListener );
}
/**
* Inits the UI from the value.
*/
private void initFromValue()
{
// Attribute
String attribute = value.getAttribute();
if ( attribute != null )
{
attributeComboViewer.getCombo().setText( attribute );
}
else
{
attributeComboViewer.getCombo().setText( "" );
}
// Base DN
Dn baseDn = value.getBaseDn();
if ( baseDn != null )
{
baseDnEntryWidget.setInput( baseDn );
}
else
{
baseDnEntryWidget.setInput( Dn.EMPTY_DN );
}
// Sort Method
if ( value.isWeighted() )
{
sortMethodComboViewer.setSelection( new StructuredSelection( WEIGHTED_OPTION ) );
}
else
{
OlcValSortMethodEnum secondarySortMethod = value.getSortMethod();
if ( secondarySortMethod != null )
{
sortMethodComboViewer.setSelection( new StructuredSelection( secondarySortMethod ) );
}
else
{
sortMethodComboViewer
.setSelection( new StructuredSelection( OlcValSortMethodEnum.ALPHA_ASCEND ) );
}
}
// Secondary Sort Method
if ( value.isWeighted() )
{
OlcValSortMethodEnum secondarySortMethod = value.getSortMethod();
if ( secondarySortMethod != null )
{
secondarySortMethodComboViewer.setSelection( new StructuredSelection( secondarySortMethod ) );
}
else
{
secondarySortMethodComboViewer.setSelection( new StructuredSelection( NONE_OPTION ) );
}
}
else
{
secondarySortMethodComboViewer.setSelection( new StructuredSelection( NONE_OPTION ) );
secondarySortMethodComboViewer.getControl().setEnabled( false );
}
}
/**
* Gets the selected sort method.
*
* @return the selected sort method
*/
private Object getSelectedSortMethod()
{
StructuredSelection selection = ( StructuredSelection ) sortMethodComboViewer.getSelection();
if ( !selection.isEmpty() )
{
return selection.getFirstElement();
}
return null;
}
/**
* Gets the selected secondary sort method.
*
* @return the selected secondary sort method
*/
private Object getSelectedSecondarySortMethod()
{
StructuredSelection selection = ( StructuredSelection ) secondarySortMethodComboViewer.getSelection();
if ( !selection.isEmpty() )
{
return selection.getFirstElement();
}
return null;
}
/**
* Checks and updates the OK button 'enable' state.
*/
private void checkAndUpdateOkButtonEnableState()
{
boolean enableOkButton = true;
// Attribute
String attribute = attributeComboViewer.getCombo().getText();
if ( ( attribute == null ) || ( attribute.isEmpty() ) )
{
enableOkButton = false;
}
// Base DN
if ( enableOkButton )
{
Dn baseDn = baseDnEntryWidget.getDn();
if ( ( baseDn == null ) || ( Dn.EMPTY_DN.equals( baseDn ) ) )
{
enableOkButton = false;
}
}
okButton.setEnabled( enableOkButton );
}
/**
* Gets the value.
*
* @return the value
*/
public String getValue()
{
return value.toString();
}
/**
* This class implement a {@link LabelProvider} for {@link OlcValSortMethodEnum} objects.
*/
private class OlcValSortMethodEnumLabelProvider extends LabelProvider
{
@Override
public String getText( Object element )
{
if ( element instanceof OlcValSortMethodEnum )
{
OlcValSortMethodEnum sortMethod = ( OlcValSortMethodEnum ) element;
switch ( sortMethod )
{
case ALPHA_ASCEND:
return "Alpha Ascendant";
case ALPHA_DESCEND:
return "Alpha Descendant";
case NUMERIC_ASCEND:
return "Numeric Ascendant";
case NUMERIC_DESCEND:
return "Numeric Descendant";
}
}
return super.getText( element );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OrderedStringValueDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OrderedStringValueDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.wrappers.OrderedStringValueWrapper;
/**
* The StringValueDialog is used to edit a String, which is a value for any simple multiple
* value attribute.
*
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | Value : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
*
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OrderedStringValueDialog extends AddEditDialog<OrderedStringValueWrapper>
{
// UI widgets
/** The attribute name */
private String attributeName;
/** The String value */
private Text stringValue;
/**
* Create a new instance of the String
*
* @param parentShell The parent Shell
* @param attributeName The name of the attribute being editaed
*/
public OrderedStringValueDialog( Shell parentShell, String attributeName )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.attributeName = attributeName;
}
/**
* The listener for the String Text
*/
private ModifyListener stringValueTextListener = event ->
{
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
getEditedElement().setValue( stringValue.getText() );
okButton.setEnabled( true );
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( attributeName );
}
/**
* Create the Dialog for StringValue :
* <pre>
* +---------------------------------------+
* | .-----------------------------------. |
* | | Value : [ ] | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// StringValue Group
Group stringValueGroup = BaseWidgetUtils.createGroup( parent, null, 1 );
GridLayout stringValueGroupGridLayout = new GridLayout( 2, false );
stringValueGroup.setLayout( stringValueGroupGridLayout );
stringValueGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// String Text
BaseWidgetUtils.createLabel( stringValueGroup, attributeName + ":", 1 );
stringValue = BaseWidgetUtils.createText( stringValueGroup, "", 1 );
stringValue.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Initializes the UI from the String
*/
protected void initDialog()
{
OrderedStringValueWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
String value = editedElement.getValue();
if ( value == null )
{
stringValue.setText( "" );
}
else
{
stringValue.setText( editedElement.getValue() );
}
}
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new OrderedStringValueWrapper( Integer.MAX_VALUE, "", true ) );
}
public void addNewElement( OrderedStringValueWrapper editedElement )
{
OrderedStringValueWrapper newElement = editedElement.clone();
setEditedElement( newElement );
}
/**
* Adds listeners.
*/
private void addListeners()
{
stringValue.addModifyListener( stringValueTextListener );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SaslSecPropsDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SaslSecPropsDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.openldap.common.ui.model.SaslSecPropEnum;
import org.apache.directory.studio.openldap.config.editor.wrappers.SaslSecPropsWrapper;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* The SaslSecPropsDialog is used to edit the Sasl Security Properties. We manage
* two kind of properties : with or without parameters. Here is the list of those properties
*
* <ul>
* <li>none : the flag properties default, "noanonymous,noplain", will be cleared</li>
* <li>noplain : disables mechanisms susceptible to simple passive attacks</li>
* <li>noactive : disables mechanisms susceptible to active attacks</li>
* <li>nodict : disables mechanisms susceptible to passive dictionary attacks.</li>
* <li>noanonymous : disables mechanisms which support anonymous login</li>
* <li>forwardsec : requires forward secrecy between sessions.</li>
* <li>passcred : requirse mechanisms which pass client credentials</li>
* <li>minssf=<factor> : specifies the minimum acceptable security strength factor</li>
* <li>maxssf=<factor> : specifies the maximum acceptable security strength factor</li>
* <li>maxbufsize=<size>: specifies the maximum security layer receive buffer size</li>
* </ul>
*
* Here is what it looks like :
* <pre>
* +--------------------------------------+
* | SASL Security Properties |
* | .----------------------------------. |
* | | none [ ] noplain [ ] | |
* | | noactive [ ] nodict [ ] | |
* | | noanonymous [ ] forwardsec [ ] | |
* | | passcred [ ] | |
* | | | |
* | | minSSF [ ] | |
* | | maxSSF [ ] | |
* | | maxBufSizeSSF [ ] | |
* | '----------------------------------' |
* | SASL security Properties Value |
* | .----------------------------------. |
* | | [//////////////////////////////] | |
* | '----------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SaslSecPropsDialog extends Dialog
{
/** The SaslSecProps string value */
private SaslSecPropsWrapper saslSecPropsWrapper;
// UI widgets
private Button noneCheckbox;
private Button noPlainCheckbox;
private Button noActiveCheckbox;
private Button noDictCheckbox;
private Button noAnonymousCheckbox;
private Button forwardSecCheckbox;
private Button passCredCheckbox;
private Text minSsfText;
private Text maxSsfText;
private Text maxBufSizeText;
/** An array of all the checkboxes */
private Button[] buttons = new Button[7];
// The resulting String
private Text saslSecPropsText;
// An empty space
protected static final String TABULATION = " ";
/**
* The listener in charge of exposing the changes when some buttons are checked
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedButton = (Button)object;
// none
if ( selectedButton.equals( noneCheckbox ) )
{
if ( noneCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.NONE );
// Uncheck the noplain and noanonymous checkboxes
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_PLAIN );
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_ANONYMOUS );
noPlainCheckbox.setSelection( false );
noAnonymousCheckbox.setSelection( false );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NONE );
}
}
// noplain
else if ( selectedButton.equals( noPlainCheckbox ) )
{
if ( noPlainCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.NO_PLAIN );
// Uncheck the none checkbox
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NONE );
noneCheckbox.setSelection( false );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_PLAIN );
}
}
// noactive
else if ( selectedButton.equals( noActiveCheckbox ) )
{
if ( noActiveCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.NO_ACTIVE );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_ACTIVE );
}
}
// nodict
else if ( selectedButton.equals( noDictCheckbox ) )
{
if ( noDictCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.NO_DICT );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_DICT );
}
}
// noanonymous
else if ( selectedButton.equals( noAnonymousCheckbox ) )
{
if ( noAnonymousCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.NO_ANONYMOUS );
// Uncheck the none checkbox
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NONE );
noneCheckbox.setSelection( false );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.NO_ANONYMOUS );
}
}
// forwardsec
else if ( selectedButton.equals( forwardSecCheckbox ) )
{
if ( forwardSecCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.FORWARD_SEC );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.FORWARD_SEC );
}
}
// passcred
else if ( selectedButton.equals( passCredCheckbox ) )
{
if ( passCredCheckbox.getSelection() )
{
saslSecPropsWrapper.addFlag( SaslSecPropEnum.PASS_CRED );
}
else
{
saslSecPropsWrapper.removeFlag( SaslSecPropEnum.PASS_CRED );
}
}
}
setSaslSecPropsText();
}
};
/**
* The listener for the minSsf Limit Text
*/
private ModifyListener minSsfListener = event ->
{
Display display = minSsfText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean valid = true;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The value must be an integer >= 0
String minSsfStr = minSsfText.getText();
if ( Strings.isEmpty( minSsfStr ) )
{
saslSecPropsWrapper.setMinSsf( null );
}
else
{
// An integer
try
{
int value = Integer.parseInt( minSsfStr );
if ( value < 0 )
{
// The value must be >= 0
color = SWT.COLOR_RED;
valid = false;
}
else
{
saslSecPropsWrapper.setMinSsf( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
valid = false;
}
}
minSsfText.setForeground( display.getSystemColor( color ) );
saslSecPropsText.setText( saslSecPropsWrapper.toString() );
okButton.setEnabled( valid );
};
/**
* The listener for the maxSsf Limit Text
*/
private ModifyListener maxSsfListener = event ->
{
Display display = maxSsfText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean valid = true;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The value must be an integer >= 0
String maxSsfStr = maxSsfText.getText();
if ( Strings.isEmpty( maxSsfStr ) )
{
saslSecPropsWrapper.setMaxSsf( null );
}
else
{
// An integer
try
{
int value = Integer.parseInt( maxSsfStr );
if ( value < 0 )
{
// The value must be >= 0
color = SWT.COLOR_RED;
valid = false;
}
else
{
saslSecPropsWrapper.setMaxSsf( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
valid = false;
}
}
maxSsfText.setForeground( display.getSystemColor( color ) );
saslSecPropsText.setText( saslSecPropsWrapper.toString() );
okButton.setEnabled( valid );
};
/**
* The listener for the maxBufSize Limit Text
*/
private ModifyListener maxBufSizeListener = event ->
{
Display display = maxBufSizeText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
boolean valid = true;
int color = SWT.COLOR_BLACK;
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The value must be an integer >= 0
String maxBufSizeStr = maxBufSizeText.getText();
if ( Strings.isEmpty( maxBufSizeStr ) )
{
saslSecPropsWrapper.setMaxBufSize( null );
}
else
{
// An integer
try
{
int value = Integer.parseInt( maxBufSizeStr );
if ( value < 0 )
{
// The value must be >= 0
color = SWT.COLOR_RED;
valid = false;
}
else
{
saslSecPropsWrapper.setMaxBufSize( value );
}
}
catch ( NumberFormatException nfe )
{
// The value must be either -1 (unlimited) or a positive number
color = SWT.COLOR_RED;
valid = false;
}
}
maxBufSizeText.setForeground( display.getSystemColor( color ) );
saslSecPropsText.setText( saslSecPropsWrapper.toString() );
okButton.setEnabled( valid );
};
/**
* Creates a new instance of SaslSecPropsDialog.
*
* @param parentShell the parent shell
*/
public SaslSecPropsDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* Creates a new instance of SaslSecPropsDialog.
*
* @param parentShell the parent shell
* @param value the initial value
*/
public SaslSecPropsDialog( Shell parentShell, String value )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
saslSecPropsWrapper = new SaslSecPropsWrapper( value );
}
/**
* {@inheritDoc}
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "OpenLDAP SASL Security Properties" );
}
/**
* {@inheritDoc}
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createSaslSecPropsArea( composite );
createSaslSecPropsValueArea( composite );
initDialog();
setSaslSecPropsText();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Initializes the Dialog with the values
*/
private void initDialog()
{
// The checkboxes
noneCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.NONE ) );
noPlainCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.NO_PLAIN ) );
noActiveCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.NO_ACTIVE ) );
noDictCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.NO_DICT ) );
noAnonymousCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.NO_ANONYMOUS ) );
forwardSecCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.FORWARD_SEC ) );
passCredCheckbox.setSelection( saslSecPropsWrapper.getFlags().contains( SaslSecPropEnum.PASS_CRED ) );
// The properties with values
if ( saslSecPropsWrapper.getMinSsf() != null )
{
minSsfText.setText( Integer.toString( saslSecPropsWrapper.getMinSsf() ) );
}
if ( saslSecPropsWrapper.getMaxSsf() != null )
{
maxSsfText.setText( Integer.toString( saslSecPropsWrapper.getMaxSsf() ) );
}
if ( saslSecPropsWrapper.getMaxBufSize() != null )
{
maxBufSizeText.setText( Integer.toString( saslSecPropsWrapper.getMaxBufSize() ) );
}
}
/**
* Sets the SaslSecProps value.
*/
private void setSaslSecPropsText()
{
saslSecPropsText.setText( saslSecPropsWrapper.toString() );
}
/**
* Creates the SaslSecProps area.
*
* | SASL Security Properties |
* | .----------------------------------. |
* | | none [ ] noplain [ ] | |
* | | noactive [ ] nodict [ ] | |
* | | noanonymous [ ] forwardsec [ ] | |
* | | passcred [ ] | |
* | | | |
* | | minSSF [ ] | |
* | | maxSSF [ ] | |
* | | maxBufSizeSSF [ ] | |
* | '----------------------------------' |
*
* @param parent the parent composite
*/
private void createSaslSecPropsArea( Composite parent )
{
Group saslSecPropsGroup = BaseWidgetUtils.createGroup( parent, "SASL Security Properties", 1 );
saslSecPropsGroup.setLayout( new GridLayout( 2, false ) );
int pos = 0;
// Line 1 : none and noplain
noneCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "none", 1 );
noPlainCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "noplain", 1 );
buttons[pos++] = noneCheckbox;
buttons[pos++] = noPlainCheckbox;
// Line 2 : noactive and nodict
noActiveCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "noactive", 1 );
noDictCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "nodict", 1 );
buttons[pos++] = noActiveCheckbox;
buttons[pos++] = noDictCheckbox;
// Line 2 : noanonymous and nforwardsec
noAnonymousCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "noanonymous", 1 );
forwardSecCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "forwardsec", 1 );
buttons[pos++] = noAnonymousCheckbox;
buttons[pos++] = forwardSecCheckbox;
// Line 4 : passcred
passCredCheckbox = BaseWidgetUtils.createCheckbox( saslSecPropsGroup, "passcred", 1 );
BaseWidgetUtils.createLabel( saslSecPropsGroup, TABULATION, 1 );
buttons[pos++] = passCredCheckbox;
// A blank line
BaseWidgetUtils.createLabel( saslSecPropsGroup, TABULATION, 1 );
BaseWidgetUtils.createLabel( saslSecPropsGroup, TABULATION, 1 );
// Min SSF
BaseWidgetUtils.createLabel( saslSecPropsGroup, "minssf", 1 );
minSsfText = BaseWidgetUtils.createText( saslSecPropsGroup, "", 1 );
minSsfText.addModifyListener( minSsfListener );
// Max SSF
BaseWidgetUtils.createLabel( saslSecPropsGroup, "maxssf", 1 );
maxSsfText = BaseWidgetUtils.createText( saslSecPropsGroup, "", 1 );
maxSsfText.addModifyListener( maxSsfListener );
// Max Buf Size
BaseWidgetUtils.createLabel( saslSecPropsGroup, "maxbufsize", 1 );
maxBufSizeText = BaseWidgetUtils.createText( saslSecPropsGroup, "", 1 );
maxBufSizeText.addModifyListener( maxBufSizeListener );
}
/**
* Creates the SASL Security Properties value area. It's not editable
*
* <pre>
* | SASL security Properties Value |
* | .----------------------------------. |
* | | [//////////////////////////////] | |
* | '----------------------------------' |
* </pre>
*
* @param parent the parent composite
*/
private void createSaslSecPropsValueArea( Composite parent )
{
Group saslSecPropsValueGroup = BaseWidgetUtils.createGroup( parent, "SASL Security Properties Value", 1 );
saslSecPropsText = BaseWidgetUtils.createText( saslSecPropsValueGroup, saslSecPropsWrapper.toString(), 1 );
saslSecPropsText.setEditable( false );
}
/**
* Adds listeners.
*/
private void addListeners()
{
for ( Button button : buttons )
{
button.addSelectionListener( checkboxSelectionListener );
}
}
/**
* @return The SASL Security Properties parameter value
*/
public String getSaslSecPropsValue()
{
return saslSecPropsWrapper.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/TimeLimitDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/TimeLimitDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.config.editor.wrappers.TimeLimitWrapper;
/**
* The TimeLimitDialog is used to edit the TimeLimit parameter<br/>
* The TimeLimit grammar is :
* <pre>
* time ::= 'time' timeLimit time-e
* time-e ::= 'time' timeLimit time-e | e
* timeLimit ::= '.soft=' limit | '.hard=' hardLimit | '=' limit
* limit ::= 'unlimited' | 'none' | INT
* hardLimit ::= 'soft' | limit
* </pre>
*
* The dialog overlay is like :
*
* <pre>
* +-------------------------------------------------------+
* | Time Limit |
* | .---------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global : [----------] [] Unlimited | |
* | '---------------------------------------------------' |
* | Resulting Time Limit |
* | .---------------------------------------------------. |
* | | Time Limit : </////////////////////////////////> | |
* | '---------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------------------------+
* </pre>
*
* A few rules :
* <ul>
* <li>When the global limit is set, the soft and hard limits are not used</li>
* <li>When the Unlimited button is checked, the integer value is discarded</li>
* <li>When the Soft checkbox for the hard limit is checked, the Global value is used </li>
* </ul>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TimeLimitDialog extends AbstractLimitDialog<TimeLimitWrapper>
{
/**
* Create a new instance of the TimeLimitDialog
*
* @param parentShell The parent Shell
*/
public TimeLimitDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* Create a new instance of the TimeLimitDialog
*
* @param parentShell The parent Shell
* @param timeLimitStr The instance containing the timeLimit data
*/
public TimeLimitDialog( Shell parentShell, String timeLimitStr )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
setEditedElement( new TimeLimitWrapper( timeLimitStr ) );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Time Limit" );
}
/**
* Create the Dialog for TimeLimit :
* <pre>
* +-------------------------------------------------------+
* | Time Limit |
* | .---------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global : [----------] [] Unlimited | |
* | '---------------------------------------------------' |
* | Resulting Time Limit |
* | .---------------------------------------------------. |
* | | Time Limit : </////////////////////////////////> | |
* | '---------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createTimeLimitEditGroup( composite );
createTimeLimitShowGroup( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the TimeLimit input group. This is the part of the dialog
* where one can insert the TimeLimit values
*
* <pre>
* TcpBuffer Input
* .---------------------------------------------------.
* | Soft Limit : [----------] [] Unlimited |
* | |
* | Hard Limit : [----------] [] Unlimited [] Soft |
* | |
* | Global : [----------] [] Unlimited |
* '---------------------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createTimeLimitEditGroup( Composite parent )
{
// TimeLimit Group
Group timeLimitGroup = BaseWidgetUtils.createGroup( parent, "Time Limit input", 1 );
GridLayout timeLimitGridLayout = new GridLayout( 6, false );
timeLimitGroup.setLayout( timeLimitGridLayout );
timeLimitGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// SoftLimit Text
BaseWidgetUtils.createLabel( timeLimitGroup, "Soft Limit :", 1 );
softLimitText = BaseWidgetUtils.createText( timeLimitGroup, "", 1 );
// Soft Limit unlimited checkbox Button
softUnlimitedCheckbox = BaseWidgetUtils.createCheckbox( timeLimitGroup, "Unlimited", 2 );
// 2 tabs to fill the line
BaseWidgetUtils.createLabel( timeLimitGroup, "", 2 );
// HardLimit Text
BaseWidgetUtils.createLabel( timeLimitGroup, "Hard Limit :", 1 );
hardLimitText = BaseWidgetUtils.createText( timeLimitGroup, "", 1 );
// Hard Limit unlimited checkbox Button
hardUnlimitedCheckbox = BaseWidgetUtils.createCheckbox( timeLimitGroup, "Unlimited", 2 );
// HardLimit soft checkbox Button
hardSoftCheckbox = BaseWidgetUtils.createCheckbox( timeLimitGroup, "Soft", 2 );
// GlobalLimit Text
BaseWidgetUtils.createLabel( timeLimitGroup, "Global Limit :", 1 );
globalLimitText = BaseWidgetUtils.createText( timeLimitGroup, "", 1 );
// GLobal Limit unlimited checkbox Button
globalUnlimitedCheckbox = BaseWidgetUtils.createCheckbox( timeLimitGroup, "Unlimited", 2 );
// 2 tabs to fill the line
BaseWidgetUtils.createLabel( timeLimitGroup, "", 2 );
}
/**
* Creates the TimeLimit show group. This is the part of the dialog
* where the real TimeLimit is shown, or an error message if the TimeLimit
* is invalid.
*
* <pre>
* Resulting Time Limit
* .------------------------------------.
* | Time Limit : <///////////////////> |
* '------------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createTimeLimitShowGroup( Composite parent )
{
// TimeLimit Group
Group timeLimitGroup = BaseWidgetUtils.createGroup( parent, "Resulting Time Limit", 1 );
GridLayout timeLimitGroupGridLayout = new GridLayout( 2, false );
timeLimitGroup.setLayout( timeLimitGroupGridLayout );
timeLimitGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// TimeLimit Text
limitText = BaseWidgetUtils.createText( timeLimitGroup, "", 1 );
limitText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
limitText.setEditable( false );
}
/**
* Adds listeners.
*/
private void addListeners()
{
softLimitText.addModifyListener( softLimitTextListener );
softUnlimitedCheckbox.addSelectionListener( softUnlimitedCheckboxSelectionListener );
hardLimitText.addModifyListener( hardLimitTextListener );
hardUnlimitedCheckbox.addSelectionListener( hardUnlimitedCheckboxSelectionListener );
hardSoftCheckbox.addSelectionListener( hardSoftCheckboxSelectionListener );
globalLimitText.addModifyListener( globalLimitTextListener );
globalUnlimitedCheckbox.addSelectionListener( globalUnlimitedCheckboxSelectionListener );
}
@Override
public void addNewElement()
{
setEditedElement( new TimeLimitWrapper( "" ) );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SizeTimeLimitDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/SizeTimeLimitDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.CommonUIConstants;
import org.apache.directory.studio.common.ui.CommonUIPlugin;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.wrappers.LimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.SizeLimitWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.TimeLimitWrapper;
/**
* The LimitDialog is used to edit the size and time limit parameter<br/>
*
* The dialog overlay is like :
*
* <pre>
* +--------------------------------------------------------------------------+
* | Limit |
* | .----------------------------------------------------------------------. |
* | | (o) Size Limit : [ ] (Edit...) | |
* | | (o) TimeLimit : [ ] (Edit...) | |
* | '----------------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------------+
* </pre>
*
* A second option for the Dialog would be like :
*
* +--------------------------------------------------------------------------+
* | Limit |
* | .----------------------------------------------------------------------. |
* | | (o) Size Limit (o) TimeLimit | |
* | '----------------------------------------------------------------------' |
* ............................................................................
*
* SizeLimit :
* ............................................................................
* | .----------------------------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global Limit : [----------] [] Unlimited | |
* | | | |
* | | Unchecked Limit : [----------] [] Unlimited [] Disabled | |
* | | | |
* | | Paged Results Limit : [----------] [] Unlimited [] No Estimate | |
* | | | |
* | | Paged Results Total : [----------] [] Unlimited [] Disabled [] Hard | |
* | '----------------------------------------------------------------------' |
* ............................................................................
* TimeLimit :
* ............................................................................
* | .----------------------------------------------------------------------. |
* | | Soft Limit : [----------] [] Unlimited | |
* | | | |
* | | Hard Limit : [----------] [] Unlimited [] Soft | |
* | | | |
* | | Global : [----------] [] Unlimited | |
* | '----------------------------------------------------------------------' |
* ............................................................................
* End :
* ............................................................................
* | Resulting Limit |
* | .----------------------------------------------------------------------. |
* | | <//////////////////////////////////////////////////////////////////> | |
* | '----------------------------------------------------------------------' |
* | |
* | (Cancel) (OK) |
* +--------------------------------------------------------------------------+
* </pre>
*
* But this would mean a duplication of code.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SizeTimeLimitDialog extends AddEditDialog<LimitWrapper>
{
/** The TimeLimit radio button */
private Button timeLimitButton;
/** The Text that contains the TimeLimit (either as typed or as built from the TimeLimitDialog) */
private Text timeLimitText;
/** A Button used to edit the TimeLimit value */
private Button timeLimitEditButton;
/** The SizeLimit radio button */
private Button sizeLimitButton;
/** The Text that contains the SizeLimit (either as typed or as built from the SizeLimitDialog) */
private Text sizeLimitText;
/** A Button used to edit the SizeLimit value */
private Button sizeLimitEditButton;
/**
* Listeners for the Selector radioButtons. It will enable or disable the dnSpec or Group accordingly
* to the selection.
**/
private SelectionListener sizeTimeButtonsSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent event )
{
if ( event.getSource() instanceof Button )
{
Button button = (Button)event.getSource();
if ( button == sizeLimitButton )
{
if ( button.getSelection() )
{
setEditedElement( new SizeLimitWrapper( "" ) );
// Enable the SizeLimit elements, disable the TimeLimit ones
sizeLimitEditButton.setEnabled( true );
sizeLimitText.setEnabled( true );
timeLimitEditButton.setEnabled( false );
timeLimitText.setEnabled( false );
timeLimitText.clearSelection();
}
}
else
{
setEditedElement( new TimeLimitWrapper( "" ) );
// Enable the TimeLimit elements, disable the SizeLimit ones
timeLimitEditButton.setEnabled( true );
timeLimitText.setEnabled( true );
sizeLimitEditButton.setEnabled( false );
sizeLimitText.setEnabled( false );
sizeLimitText.clearSelection();
}
}
}
};
/**
* The listener for the sizeLimit Text
*/
private SelectionListener sizeLimitEditSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
SizeLimitDialog dialog = new SizeLimitDialog( sizeLimitText.getShell(), sizeLimitText.getText() );
if ( dialog.open() == OverlayDialog.OK )
{
String newSizeLimitStr = dialog.getNewLimit();
if ( newSizeLimitStr != null )
{
sizeLimitText.setText( newSizeLimitStr );
}
}
}
};
/**
* The listener for the timeLimit Text
*/
private SelectionListener timeLimitEditSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
TimeLimitDialog dialog = new TimeLimitDialog( timeLimitText.getShell(), timeLimitText.getText() );
if ( dialog.open() == OverlayDialog.OK )
{
String newTimeLimitStr = dialog.getNewLimit();
if ( newTimeLimitStr != null )
{
timeLimitText.setText( newTimeLimitStr );
}
}
}
};
protected ModifyListener sizeLimitTextListener = event ->
{
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The String must be a valid SizeLimit
String sizeLimitStr = sizeLimitText.getText();
SizeLimitWrapper sizeLimitWrapper = new SizeLimitWrapper( sizeLimitStr );
if ( sizeLimitWrapper.isValid() )
{
sizeLimitText.setForeground( CommonUIPlugin.getDefault().getColor( CommonUIConstants.DEFAULT_COLOR ) );
setEditedElement( sizeLimitWrapper );
okButton.setEnabled( true );
}
else
{
sizeLimitText.setForeground( CommonUIPlugin.getDefault().getColor( CommonUIConstants.ERROR_COLOR ) );
okButton.setEnabled( false );
}
};
protected ModifyListener timeLimitTextListener = event ->
{
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
// The String must be a valid TimeLimit
String timeLimitStr = timeLimitText.getText();
TimeLimitWrapper timeLimitWrapper = new TimeLimitWrapper( timeLimitStr );
if ( timeLimitWrapper.isValid() )
{
timeLimitText.setForeground( CommonUIPlugin.getDefault().getColor( CommonUIConstants.DEFAULT_COLOR ) );
setEditedElement( timeLimitWrapper );
okButton.setEnabled( true );
}
else
{
timeLimitText.setForeground( CommonUIPlugin.getDefault().getColor( CommonUIConstants.ERROR_COLOR ) );
okButton.setEnabled( false );
}
};
/**
* Create a new instance of the SizeTimeLimitsDialog
*
* @param parentShell The parent Shell
*/
public SizeTimeLimitDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* Create a new instance of the SizeTimeLimitDialog
*
* @param parentShell The parent Shell
* @param timeLimitStr The instance containing the Limits data
*/
public SizeTimeLimitDialog( Shell parentShell, String limitStr )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Size/Time Limit" );
}
/**
* Create the Dialog for TimeLimit :
* <pre>
* Limit
* .----------------------------------------------------------------------.
* | (o) Size Limit : [ ] (Edit...) |
* | (o) TimeLimit : [ ] (Edit...) |
* '----------------------------------------------------------------------'
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
// Create the selection group
Group selectionGroup = BaseWidgetUtils.createGroup( parent, "Limit selection", 1 );
GridLayout selectionGridLayout = new GridLayout( 3, false );
selectionGroup.setLayout( selectionGridLayout );
selectionGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// SizeLimit button
sizeLimitButton = BaseWidgetUtils.createRadiobutton( selectionGroup, "SizeLimit", 1 );
sizeLimitButton.addSelectionListener( sizeTimeButtonsSelectionListener );
// SizeLimit Text
sizeLimitText = BaseWidgetUtils.createText( selectionGroup, "", 1 );
sizeLimitText.addModifyListener( sizeLimitTextListener );
// SizeLimit Edit button
sizeLimitEditButton = BaseWidgetUtils.createButton( selectionGroup, "Edit...", 1 );
sizeLimitEditButton.addSelectionListener( sizeLimitEditSelectionListener );
// TimeLimit button
timeLimitButton = BaseWidgetUtils.createRadiobutton( selectionGroup, "TimeLimit", 1 );
timeLimitButton.addSelectionListener( sizeTimeButtonsSelectionListener );
// TimeLimit Text
timeLimitText = BaseWidgetUtils.createText( selectionGroup, "", 1 );
timeLimitText.addModifyListener( timeLimitTextListener );
// TimeLimit Edit button
timeLimitEditButton = BaseWidgetUtils.createButton( selectionGroup, "Edit...", 1 );
timeLimitEditButton.addSelectionListener( timeLimitEditSelectionListener );
// create the SizeLimit
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Adds listeners.
*/
private void addListeners()
{
/*
softLimitText.addModifyListener( softLimitTextListener );
softUnlimitedCheckbox.addSelectionListener( softUnlimitedCheckboxSelectionListener );
hardLimitText.addModifyListener( hardLimitTextListener );
hardUnlimitedCheckbox.addSelectionListener( hardUnlimitedCheckboxSelectionListener );
hardSoftCheckbox.addSelectionListener( hardSoftCheckboxSelectionListener );
globalLimitText.addModifyListener( globalLimitTextListener );
globalUnlimitedCheckbox.addSelectionListener( globalUnlimitedCheckboxSelectionListener );
*/
}
@Override
public void addNewElement()
{
setEditedElement( null );
}
/**
* Initializes the UI from the Limit
*/
protected void initDialog()
{
LimitWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
if ( editedElement instanceof SizeLimitWrapper )
{
sizeLimitButton.setSelection( true );
// Enable the SizeLimit elements, disable the TimeLimit ones
sizeLimitEditButton.setEnabled( true );
sizeLimitText.setEnabled( true );
sizeLimitText.setText( editedElement.toString() );
timeLimitEditButton.setEnabled( false );
timeLimitText.setEnabled( false );
}
else
{
timeLimitButton.setSelection( true );
// Enable the TimeLimit elements, disable the SizeLimit ones
timeLimitEditButton.setEnabled( true );
timeLimitText.setEnabled( true );
timeLimitText.setText( editedElement.toString() );
sizeLimitEditButton.setEnabled( false );
sizeLimitText.setEnabled( false );
}
}
else
{
// Nothing selected, disable the Text and Button
timeLimitEditButton.setEnabled( false );
timeLimitText.setEnabled( false );
timeLimitText.clearSelection();
sizeLimitEditButton.setEnabled( false );
sizeLimitText.setEnabled( false );
sizeLimitText.clearSelection();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/PurgeTimeSpan.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/PurgeTimeSpan.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.openldap.config.editor.dialogs;
import java.text.ParseException;
/**
* This class represents the time span used for purge age and interval.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PurgeTimeSpan
{
/** The days */
protected int days = 0;
/** The hours */
protected int hours = 0;
/** The minutes */
protected int minutes = 0;
/** The seconds */
protected int seconds = 0;
/**
* Creates a new instance of PurgeTimeSpan.
*/
public PurgeTimeSpan()
{
}
/**
* Creates a new instance of PurgeTimeSpan.
*
* @param s the string
*/
public PurgeTimeSpan( String s ) throws ParseException
{
parse( s );
}
/**
* Creates a new instance of PurgeTimeSpan.
*
* @param days the days
* @param hours the hours
* @param minutes the minutes
* @param seconds the seconds
*/
public PurgeTimeSpan( int days, int hours, int minutes, int seconds )
{
checkDaysArgument( days );
checkHoursArgument( hours );
checkMinutesSecondsArgument( minutes );
checkMinutesSecondsArgument( seconds );
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
/**
* Checks the days argument.
*
* @param value the days argument
* @throws IllegalArgumentException
*/
private void checkDaysArgument( int value ) throws IllegalArgumentException
{
if ( checkDays( value ) )
{
throw new IllegalArgumentException( "Days need to be comprised between 0 and 99999." );
}
}
/**
* Checks the days value.
*
* @param value the days value
* @return <code>true</code> if the days value is correct,
* <code>false</code> if not.
*/
private boolean checkDays( int value )
{
return ( value < 0 ) || ( value > 99999 );
}
/**
* Checks the hours argument.
*
* @param value the hours argument
*/
private void checkHoursArgument( int value )
{
if ( checkHours( value ) )
{
throw new IllegalArgumentException( "Hours, minutes, or seconds need to be comprised between 0 and 99999." );
}
}
/**
* Checks the hours value.
*
* @param value the hours value
* @return <code>true</code> if the hours value is correct,
* <code>false</code> if not.
*/
private boolean checkHours( int value )
{
return ( value < 0 ) || ( value > 23 );
}
/**
* Checks the minutes or seconds argument.
*
* @param value the minutes or seconds argument
*/
private void checkMinutesSecondsArgument( int value )
{
if ( checkMinutesSeconds( value ) )
{
throw new IllegalArgumentException( "Hours, minutes, or seconds need to be comprised between 0 and 99999." );
}
}
/**
* Checks the minutes or seconds value.
*
* @param value the minutes or seconds value
* @return <code>true</code> if the minutes or seconds value is correct,
* <code>false</code> if not.
*/
private boolean checkMinutesSeconds( int value )
{
return ( value < 0 ) || ( value > 59 );
}
/**
* Parse the given string.
*
* @param s the string
* @throws ParseException in case of error during parsing.
*/
private void parse( String s ) throws ParseException
{
if ( s == null )
{
throw new ParseException( "The string is null.", 0 );
}
// Removing leading and trailing whitespaces
s = s.trim();
// Checking the minimum size of the string
// It should be at least 5 chars ("HH:MM")
if ( s.length() < 5 )
{
throw new ParseException( "The string is too short.", 0 );
}
// Initializing parsing objects
int position = 0;
char c;
StringBuilder buffer = new StringBuilder();
boolean hoursParsed = false;
boolean minutesParsed = false;
try
{
while ( ( position < s.length() ) )
{
c = s.charAt( position );
// Figure
if ( ( '0' <= c ) && ( c <= '9' ) )
{
buffer.append( c );
}
// Plus sign
else if ( '+' == c )
{
int days = Integer.parseInt( buffer.toString() );
if ( checkDays( days ) )
{
throw new ParseException( "Days need to be comprised between 0 and 99999.", position );
}
else
{
this.days = days;
}
buffer = new StringBuilder();
}
// Colon sign
else if ( ':' == c )
{
if ( !hoursParsed )
{
int hours = Integer.parseInt( buffer.toString() );
if ( checkHours( hours ) )
{
throw new ParseException( "Hours need to be comprised between 0 and 23.", position );
}
else
{
this.hours = hours;
}
hoursParsed = true;
buffer = new StringBuilder();
}
else
{
int minutes = Integer.parseInt( buffer.toString() );
if ( checkMinutesSeconds( minutes ) )
{
throw new ParseException( "Minutes need to be comprised between 0 and 59.", position );
}
else
{
this.minutes = minutes;
}
minutesParsed = true;
buffer = new StringBuilder();
}
}
else
{
throw new ParseException( "Illegal character", position );
}
position++;
}
}
catch ( NumberFormatException e )
{
throw new ParseException( e.getMessage(), position );
}
if ( !hoursParsed )
{
throw new ParseException( "Hours need to be comprised between 0 and 23.", position );
}
else if ( !minutesParsed )
{
int minutes = Integer.parseInt( buffer.toString() );
if ( checkMinutesSeconds( minutes ) )
{
throw new ParseException( "Minutes need to be comprised between 0 and 59.", position );
}
else
{
this.minutes = minutes;
}
}
else
{
int seconds = Integer.parseInt( buffer.toString() );
if ( checkMinutesSeconds( seconds ) )
{
throw new ParseException( "Seconds need to be comprised between 0 and 59.", position );
}
else
{
this.seconds = seconds;
}
}
}
/**
* @return the days
*/
public int getDays()
{
return days;
}
/**
* @return the hours
*/
public int getHours()
{
return hours;
}
/**
* @return the minutes
*/
public int getMinutes()
{
return minutes;
}
/**
* @return the seconds
*/
public int getSeconds()
{
return seconds;
}
/**
* @param days the days to set
*/
public void setDays( int days )
{
this.days = days;
}
/**
* @param hours the hours to set
*/
public void setHours( int hours )
{
this.hours = hours;
}
/**
* @param minutes the minutes to set
*/
public void setMinutes( int minutes )
{
this.minutes = minutes;
}
/**
* @param seconds the seconds to set
*/
public void setSeconds( int seconds )
{
this.seconds = seconds;
}
/**
* {@inheritDoc}
*/
public String toString()
{
StringBuilder sb = new StringBuilder();
// Days (if needed)
if ( days > 0 )
{
sb.append( days );
sb.append( '+' );
}
// Hours
sb.append( toString( hours ) );
sb.append( ':' );
// Minutes
sb.append( toString( minutes ) );
// Seconds (if needed)
if ( seconds > 0 )
{
sb.append( ':' );
sb.append( toString( seconds ) );
}
return sb.toString();
}
/**
* Gets the string representation of an int
* (prefixed with a 0 if needed).
*
* @param value the value
* @return the string equivalent
*/
private String toString( int value )
{
if ( ( value < 0 ) || ( value > 60 ) )
{
return "00";
}
else if ( value < 10 )
{
return "0" + value;
}
else
{
return Integer.toString( value );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AllowFeatureDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/AllowFeatureDialog.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.openldap.config.editor.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.AllowFeatureEnum;
/**
* The AllowFeatureDialog is used to select one feature to allow. The possible
* features are :
* <ul>
* <li>bind_v2</li>
* <li>bind_anon_cred</li>
* <li>bind_anon_dn</li>
* <li>update_anon</li>
* <li>proxy_authz_anon</li>
* </ul>
*
* The dialog overlay is like :
*
* <pre>
* +----------------------------+
* | Allowed feature |
* | .------------------------. |
* | | bind_v2 : [ ] | |
* | | bond_anon_cred : [ ] | |
* | | bind_anon_dn : [ ] | |
* | | update_anon : [ ] | |
* | | proxy_authz_anon : [ ] | |
* | '------------------------' |
* | |
* | (Cancel) (OK) |
* +----------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AllowFeatureDialog extends AddEditDialog<AllowFeatureEnum>
{
/** The array of buttons */
private Button[] allowFeatureCheckboxes = new Button[5];
/** The already selected allowed features */
List<AllowFeatureEnum> features = new ArrayList<>();
/**
* Create a new instance of the AllowFeatureDialog
*
* @param parentShell The parent Shell
*/
public AllowFeatureDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( Messages.getString( "AllowFeature.Title" ) );
}
/**
* The listener in charge of exposing the changes when some checkbox is selected
*/
private SelectionListener checkboxSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Button )
{
Button selectedCheckbox = (Button)object;
for ( int i = 1; i < allowFeatureCheckboxes.length; i++ )
{
if ( selectedCheckbox == allowFeatureCheckboxes[i] )
{
setEditedElement( AllowFeatureEnum.getAllowFeature( i ) );
}
else if ( allowFeatureCheckboxes[i].isEnabled() )
{
allowFeatureCheckboxes[i].setSelection( false );
}
}
}
}
};
/**
* Create the Dialog for AllowFeature :
* <pre>
* +----------------------------+
* | Allowed feature |
* | .------------------------. |
* | | bind_v2 : [ ] | |
* | | bond_anon_cred : [ ] | |
* | | bind_anon_dn : [ ] | |
* | | update_anon : [ ] | |
* | | proxy_authz_anon : [ ] | |
* | '------------------------' |
* | |
* | (Cancel) (OK) |
* +----------------------------+
* </pre>
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createAllowFeatureEditGroup( composite );
initDialog();
applyDialogFont( composite );
return composite;
}
/**
* Creates the AllowFeature input group.
*
* <pre>
* Allowed feature
* .------------------------.
* | bind_v2 : [ ] |
* | bond_anon_cred : [ ] |
* | bind_anon_dn : [ ] |
* | update_anon : [ ] |
* | proxy_authz_anon : [ ] |
* '------------------------'
* </pre>
* @param parent the parent composite
*/
private void createAllowFeatureEditGroup( Composite parent )
{
// Allow Feature Group
Group allowFeatureGroup = BaseWidgetUtils.createGroup( parent, "", 1 );
GridLayout allowFeatureGridLayout = new GridLayout( 1, false );
allowFeatureGroup.setLayout( allowFeatureGridLayout );
allowFeatureGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// The various buttons
for ( int i = 1; i < allowFeatureCheckboxes.length; i++ )
{
String allowFeature = AllowFeatureEnum.getAllowFeature( i ).getName();
allowFeatureCheckboxes[i] = BaseWidgetUtils.createCheckbox( allowFeatureGroup, allowFeature, 1 );
allowFeatureCheckboxes[i].addSelectionListener( checkboxSelectionListener );
}
}
protected void initDialog()
{
List<AllowFeatureEnum> elements = getElements();
boolean allSelected = true;
okDisabled = false;
for ( int i = 1; i < allowFeatureCheckboxes.length; i++ )
{
AllowFeatureEnum value = AllowFeatureEnum.getAllowFeature( allowFeatureCheckboxes[i].getText() );
// Disable the features already selected
if ( elements.contains( value ) )
{
allowFeatureCheckboxes[i].setSelection( true );
allowFeatureCheckboxes[i].setEnabled( false );
}
else
{
allSelected = false;
}
}
if ( allSelected )
{
// Disable the OK button
okDisabled = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void addNewElement()
{
// Default to none
setEditedElement( AllowFeatureEnum.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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OverlayDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OverlayDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.apache.directory.studio.openldap.common.ui.model.OverlayTypeEnum;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.AccessLogOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.AuditLogOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.MemberOfOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.PasswordPolicyOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.ReferentialIntegrityOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.RewriteRemapOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.SyncProvOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.overlays.ValueSortingOverlayConfigurationBlock;
import org.apache.directory.studio.openldap.config.model.OlcOverlayConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcAccessLogConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcAuditlogConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcMemberOf;
import org.apache.directory.studio.openldap.config.model.overlay.OlcPPolicyConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRefintConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRwmConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcSyncProvConfig;
import org.apache.directory.studio.openldap.config.model.overlay.OlcValSortConfig;
/**
* The OverlayDialog is used to edit the configuration of an overlay. The user will
* select the overlay to configure in a Combo :
*
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OverlayDialog extends Dialog
{
/** The instance */
private OverlayDialog instance;
/** The flag to allow the overlay type selection */
private boolean allowOverlayTypeSelection;
/** The overlay configuration */
private OlcOverlayConfig overlay;
/** The configuration block */
private OverlayDialogConfigurationBlock<? extends OlcOverlayConfig> configurationBlock;
/** The connection */
private IBrowserConnection browserConnection;
// UI widgets
private Combo overlayTypeCombo;
private Composite configurationComposite;
private Composite configurationInnerComposite;
// Listeners
private SelectionListener overlayTypeComboViewerSelectionChangedListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent event )
{
OverlayTypeEnum type = OverlayTypeEnum.getOverlay( overlayTypeCombo.getText() );
switch ( type )
{
case AUDIT_LOG:
overlay = new OlcAuditlogConfig();
configurationBlock = new AuditLogOverlayConfigurationBlock( instance, ( OlcAuditlogConfig ) overlay );
break;
case MEMBER_OF:
overlay = new OlcMemberOf();
configurationBlock = new MemberOfOverlayConfigurationBlock( instance, browserConnection,
( OlcMemberOf ) overlay );
break;
case PASSWORD_POLICY:
overlay = new OlcPPolicyConfig();
configurationBlock = new PasswordPolicyOverlayConfigurationBlock( instance, browserConnection,
( OlcPPolicyConfig ) overlay );
break;
case REFERENTIAL_INTEGRITY:
overlay = new OlcRefintConfig();
configurationBlock = new ReferentialIntegrityOverlayConfigurationBlock( instance,
browserConnection, ( OlcRefintConfig ) overlay );
break;
case REWRITE_REMAP:
overlay = new OlcRwmConfig();
configurationBlock = new RewriteRemapOverlayConfigurationBlock( instance,
browserConnection, ( OlcRwmConfig ) overlay );
break;
case SYNC_PROV:
overlay = new OlcSyncProvConfig();
configurationBlock = new SyncProvOverlayConfigurationBlock( instance, ( OlcSyncProvConfig ) overlay );
break;
case VALUE_SORTING:
overlay = new OlcValSortConfig();
configurationBlock = new ValueSortingOverlayConfigurationBlock( instance, browserConnection,
( OlcValSortConfig ) overlay );
break;
case ACCESS_LOG:
default:
overlay = new OlcAccessLogConfig();
configurationBlock = new AccessLogOverlayConfigurationBlock( instance, browserConnection,
( OlcAccessLogConfig ) overlay );
break;
}
refreshOverlayContent();
autoresizeDialog();
}
};
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
*/
public OverlayDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
instance = this;
}
/**
* Creates a new instance of OverlayDialog.
*
* @param parentShell the parent shell
* @param allowOverlayTypeSelection the flag to allow the overlay type selection
*/
public OverlayDialog( Shell parentShell, boolean allowOverlayTypeSelection )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
instance = this;
this.allowOverlayTypeSelection = allowOverlayTypeSelection;
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( getDialogText() );
}
/**
* Gets the dialog text.
*
* @return the dialog text
*/
private String getDialogText()
{
if ( overlay != null )
{
return NLS.bind( "{0} Overlay Configuration", getOverlayType( overlay ) );
}
else
{
return "Overlay Configuration";
}
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
if ( configurationBlock != null )
{
configurationBlock.save();
}
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH );
composite.setLayoutData( gd );
// Checking if we need to show the overlay type selection
if ( allowOverlayTypeSelection )
{
createOverlayTypeSelection( composite );
BaseWidgetUtils.createSeparator( composite, 1 );
}
// Creating the configuration composites
configurationComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
createConfigurationInnerComposite();
// Checking for empty overlay
if ( overlay == null )
{
// Assigning a default one
overlay = new OlcAccessLogConfig();
// Select the correct value on the combo viewer (if required)
if ( allowOverlayTypeSelection )
{
overlayTypeCombo.setText( OverlayTypeEnum.ACCESS_LOG.getName() );
}
}
// Initializing the dialog with the overlay
initWithOverlay();
// Adding the listener on the combo viewer (if required)
if ( allowOverlayTypeSelection )
{
overlayTypeCombo.addSelectionListener( overlayTypeComboViewerSelectionChangedListener );
}
applyDialogFont( composite );
return composite;
}
/**
* Creates the UI widgets for the overlay type selection.
*
* @param parent the parent composite
*/
private void createOverlayTypeSelection( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
BaseWidgetUtils.createLabel( composite, "Type:", 1 );
overlayTypeCombo = BaseWidgetUtils.createCombo( composite, OverlayTypeEnum.getNames(), 1, 1 );
}
/**
* Gets the overlay type.
*
* @param overlay the overlay
* @return the overlay type
*/
public static OverlayTypeEnum getOverlayType( OlcOverlayConfig overlay )
{
if ( overlay instanceof OlcAccessLogConfig )
{
return OverlayTypeEnum.ACCESS_LOG;
}
else if ( overlay instanceof OlcAuditlogConfig )
{
return OverlayTypeEnum.AUDIT_LOG;
}
else if ( overlay instanceof OlcMemberOf )
{
return OverlayTypeEnum.MEMBER_OF;
}
else if ( overlay instanceof OlcPPolicyConfig )
{
return OverlayTypeEnum.PASSWORD_POLICY;
}
else if ( overlay instanceof OlcRefintConfig )
{
return OverlayTypeEnum.REFERENTIAL_INTEGRITY;
}
else if ( overlay instanceof OlcRwmConfig )
{
return OverlayTypeEnum.REWRITE_REMAP;
}
else if ( overlay instanceof OlcSyncProvConfig )
{
return OverlayTypeEnum.SYNC_PROV;
}
else if ( overlay instanceof OlcValSortConfig )
{
return OverlayTypeEnum.VALUE_SORTING;
}
return null;
}
/**
* Creates the configuration inner composite.
*/
private void createConfigurationInnerComposite()
{
configurationInnerComposite = BaseWidgetUtils.createColumnContainer( configurationComposite, 1, 1 );
}
/**
* Disposes the configuration inner composite.
*/
private void disposeConfigurationInnerComposite()
{
if ( configurationInnerComposite != null )
{
configurationInnerComposite.dispose();
configurationInnerComposite = null;
}
}
/**
* Initializes the dialog with the overlay.
*/
private void initWithOverlay()
{
if ( overlay instanceof OlcAccessLogConfig )
{
configurationBlock = new AccessLogOverlayConfigurationBlock( this, browserConnection,
( OlcAccessLogConfig ) overlay );
}
else if ( overlay instanceof OlcAuditlogConfig )
{
configurationBlock = new AuditLogOverlayConfigurationBlock( this, ( OlcAuditlogConfig ) overlay );
}
else if ( overlay instanceof OlcMemberOf )
{
configurationBlock = new MemberOfOverlayConfigurationBlock( this, browserConnection,
( OlcMemberOf ) overlay );
}
else if ( overlay instanceof OlcPPolicyConfig )
{
configurationBlock = new PasswordPolicyOverlayConfigurationBlock( this, browserConnection,
( OlcPPolicyConfig ) overlay );
}
else if ( overlay instanceof OlcRefintConfig )
{
configurationBlock = new ReferentialIntegrityOverlayConfigurationBlock( this, browserConnection,
( OlcRefintConfig ) overlay );
}
else if ( overlay instanceof OlcRwmConfig )
{
configurationBlock = new RewriteRemapOverlayConfigurationBlock( this, browserConnection,
( OlcRwmConfig ) overlay );
}
else if ( overlay instanceof OlcSyncProvConfig )
{
configurationBlock = new SyncProvOverlayConfigurationBlock( this, ( OlcSyncProvConfig ) overlay );
}
else if ( overlay instanceof OlcValSortConfig )
{
configurationBlock = new ValueSortingOverlayConfigurationBlock( this, browserConnection,
( OlcValSortConfig ) overlay );
}
refreshOverlayContent();
}
/**
* Gets the overlay.
*
* @return the overlay
*/
public OlcOverlayConfig getOverlay()
{
return overlay;
}
/**
* Sets the overlay.
*
* @param overlay the overlay to set
*/
public void setOverlay( OlcOverlayConfig overlay )
{
this.overlay = overlay;
}
/**
* Calls the pack() method on the current shell, which forces the dialog to be resized.
*/
private void autoresizeDialog()
{
this.getShell().pack();
}
/**
* Refreshes the overlay content.
*/
private void refreshOverlayContent()
{
// Disposing existing configuration inner composite and creating a new one
disposeConfigurationInnerComposite();
createConfigurationInnerComposite();
// Displaying the specific settings
configurationBlock.createBlockContent( configurationInnerComposite );
configurationBlock.refresh();
configurationComposite.layout();
// Changing the dialog title
getShell().setText( getDialogText() );
}
/**
* Gets the browser connection.
*
* @return the browser connection
*/
public IBrowserConnection getBrowserConnection()
{
return browserConnection;
}
/**
* Sets the browser connection.
*
* @param browserConnection the browser connection
*/
public void setBrowserConnection( IBrowserConnection browserConnection )
{
this.browserConnection = browserConnection;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.api.ldap.model.exception.LdapURLEncodingException;
import org.apache.directory.api.ldap.model.url.LdapUrl;
import org.apache.directory.studio.common.ui.AddEditDialog;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.wrappers.ServerIdWrapper;
/**
* The ServerIdDialog is used to edit a ServerID, which can be an integer, an hexadecimal number,
* optionally followed by an URL. The dialog overlay is like :
*
* <pre>
* +---------------------------------------+
* | ServerID Input |
* | .-----------------------------------. |
* | | ID : [ ] | |
* | | URL : [ ] | |
* | '-----------------------------------' |
* | .-----------------------------------. |
* | | ServerId : <////////////////////> | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
*
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ServerIdDialog extends AddEditDialog<ServerIdWrapper>
{
// UI widgets
/** The ID Text */
private Text idText;
/** The URL text */
private Text urlText;
/** The resulting serverID Text, or an error message */
private Text serverIdText;
/**
* Create a new instance of the ServerIdDialog
*
* @param parentShell The parent Shell
*/
public ServerIdDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* The listener for the ID Text
*/
private ModifyListener idTextListener = event ->
{
Display display = serverIdText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
int idValue = Integer.parseInt( idText.getText() );
serverIdText.setText( getEditedElement().toString() );
// The value must be between 0 and 4095, and it must not already exists
if ( ( idValue < 0 ) || ( idValue > 4096 ) )
{
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
return;
}
else
{
// Be sure the value is not already taken
for ( ServerIdWrapper serverIdWrapper : getElements() )
{
if ( serverIdWrapper.getServerId() == idValue )
{
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
return;
}
}
}
serverIdText.setText( idText.getText() + ' ' + urlText.getText() );
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
getEditedElement().setServerId( idValue );
okButton.setEnabled( true );
}
catch ( NumberFormatException nfe )
{
// Not even a number
serverIdText.setText( getEditedElement().toString() );
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
};
/**
* The listener for the URL Text
*/
private ModifyListener urlTextListener = event ->
{
Display display = serverIdText.getDisplay();
Button okButton = getButton( IDialogConstants.OK_ID );
// This button might be null when the dialog is called.
if ( okButton == null )
{
return;
}
try
{
String urlStr = urlText.getText();
new LdapUrl( urlStr );
getEditedElement().setUrl( urlStr );
serverIdText.setText( idText.getText() + ' ' + urlStr );
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
okButton.setEnabled( true );
}
catch ( LdapURLEncodingException luee )
{
serverIdText.setForeground( display.getSystemColor( SWT.COLOR_RED ) );
okButton.setEnabled( false );
}
};
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "ServerId" );
}
/**
* Create the Dialog for ServerID :
* <pre>
* +---------------------------------------+
* | ServerID |
* | .-----------------------------------. |
* | | ID : [ ] | |
* | | URL : [ ] | |
* | '-----------------------------------' |
* | .-----------------------------------. |
* | | ServerId : <////////////////////> | |
* | '-----------------------------------' |
* | |
* | (cancel) (OK) |
* +---------------------------------------+
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
createServerIdEditGroup( composite );
createServerIdShowGroup( composite );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Creates the ServerID input group. This is the part of the dialog
* where one can insert the ServerID values:
*
* <pre>
* ServerID Input
* .-----------------------------------.
* | ID : [ ] |
* | URL : [ ] |
* '-----------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createServerIdEditGroup( Composite parent )
{
// ServerID Group
Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "ServerID input", 1 );
GridLayout serverIdGroupGridLayout = new GridLayout( 2, false );
serverIdGroup.setLayout( serverIdGroupGridLayout );
serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// ServerID Text
BaseWidgetUtils.createLabel( serverIdGroup, "ID:", 1 );
idText = BaseWidgetUtils.createText( serverIdGroup, "", 1 );
idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// URL Text
BaseWidgetUtils.createLabel( serverIdGroup, "URL:", 1 );
urlText = BaseWidgetUtils.createText( serverIdGroup, "", 1 );
urlText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* Creates the ServerID show group. This is the part of the dialog
* where the real ServerID is shown, or an error message if the ServerID
* is invalid.
*
* <pre>
* .-----------------------------------.
* | ServerID : <///////////////////> |
* '-----------------------------------'
* </pre>
* @param parent the parent composite
*/
private void createServerIdShowGroup( Composite parent )
{
// ServerId Group
Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "", 1 );
GridLayout serverIdGroupGridLayout = new GridLayout( 2, false );
serverIdGroup.setLayout( serverIdGroupGridLayout );
serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// ServerID Text
serverIdText = BaseWidgetUtils.createText( serverIdGroup, "", 1 );
serverIdText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* Initializes the UI from the ServerId
*/
protected void initDialog()
{
ServerIdWrapper editedElement = getEditedElement();
if ( editedElement != null )
{
idText.setText( Integer.toString( editedElement.getServerId() ) );
String url = editedElement.getUrl();
if ( url == null )
{
urlText.setText( "" );
}
else
{
urlText.setText( editedElement.getUrl() );
}
}
}
/**
* Add a new Element that will be edited
*/
public void addNewElement()
{
setEditedElement( new ServerIdWrapper( "" ) );
}
public void addNewElement( ServerIdWrapper editedElement )
{
ServerIdWrapper newElement = editedElement.clone();
setEditedElement( newElement );
}
/**
* Adds listeners.
*/
private void addListeners()
{
idText.addModifyListener( idTextListener );
urlText.addModifyListener( urlTextListener );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OverlayDialogConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/OverlayDialogConfigurationBlock.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.openldap.config.editor.dialogs;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.config.model.OlcOverlayConfig;
/**
* This interface represents a configuration block for Overlay Dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface OverlayDialogConfigurationBlock<O extends OlcOverlayConfig>
{
/**
* Creates the block content.
*
* @param parent the parent composite
*/
void createBlockContent( Composite parent );
/**
* Gets the dialog.
*
* @return the dialog
*/
OverlayDialog getDialog();
/**
* Gets the overlay.
*
* @return the overlay
*/
O getOverlay();
/**
* Refreshes the UI based on the input.
*/
void refresh();
/**
* Saves the data to the overlay.
*/
void save();
/**
* Sets the dialog.
*
* @param dialog the dialog
*/
void setDialog( OverlayDialog dialog );
/**
* Sets the overlay.
*
* @param overlay the overlay
*/
void setOverlay( O overlay );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DatabaseTypeDialog.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/DatabaseTypeDialog.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.openldap.config.editor.dialogs;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.openldap.common.ui.model.DatabaseTypeEnum;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
/**
* A Dialog used to select the DatabaseType for newly created Database. It
* offers a choice in :
* <ul>
* <li>None (not exposed)</li>
* <li>Frontend DB</li>
* <li>Config DB</li>
* <li>BDB</li>
* <li>DB Perl (not exposed)</li>
* <li>DB_Socket</li>
* <li>HDB</li>
* <li>LDAP</li>
* <li>LDIF</li>
* <li>META</li>
* <li>MDB</li>
* <li>MONITOR</li>
* <li>NDB (not exposed)</li>
* <li>PASSWORD (not exposed)</li>
* <li>RELAY</li>
* <li>SHELL (not exposed)</li>
* <li>SQL DB (not exposed)</li>
* <li>NULL</li>
* </ul>
*
* Here is the layout :
* <pre>
* +-------------------------------------+
* | Database Type |
* | .---------------------------------. |
* | | [----------------------------] | |
* | '---------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DatabaseTypeDialog extends Dialog
{
// UI widgets
private Combo databaseTypeCombo;
/** The selected Database type in the combo */
private DatabaseTypeEnum selectedDatabaseType;
/**
* The listener in charge of exposing the changes when some buttons are checked
*/
private SelectionListener databaseTypeSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
Object object = e.getSource();
if ( object instanceof Combo )
{
Combo databaseTypeCombo = (Combo)object;
Button okButton = getButton( IDialogConstants.OK_ID );
DatabaseTypeEnum databaseType = DatabaseTypeEnum.getDatabaseType( databaseTypeCombo.getText() );
selectedDatabaseType = databaseType;
okButton.setEnabled( databaseType != DatabaseTypeEnum.NONE );
}
}
};
/**
* Creates a new instance of DatabaseBaseDialog.
*
* @param parentShell the parent shell
*/
public DatabaseTypeDialog( Shell parentShell )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
}
/**
* {@inheritDoc}
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( "Database Type" );
}
/**
* {@inheritDoc}
*/
@Override
protected void okPressed()
{
// Do nothing if the selected feature is NONE
if ( DatabaseTypeEnum.getDatabaseType( databaseTypeCombo.getText() ) != DatabaseTypeEnum.NONE )
{
super.okPressed();
}
}
/**
* Create the Dialog for the SSF :
* <pre>
* +-------------------------------------+
* | Database Type |
* | .---------------------------------. |
* | | [----------------------------] | |
* | '---------------------------------' |
* | |
* | (Cancel) (OK) |
* +-------------------------------------+
* </pre>
*/
@Override
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
Group databaseTypeEditGroup = BaseWidgetUtils.createGroup( composite, "Database Type", 1 );
databaseTypeEditGroup.setLayout( new GridLayout( 2, false ) );
// The DatabaseTypes
databaseTypeCombo = BaseWidgetUtils.createCombo( databaseTypeEditGroup, DatabaseTypeEnum.getNames(), 0, 2 );
initDialog();
addListeners();
applyDialogFont( composite );
return composite;
}
/**
* Overriding the createButton method, so that we can disable the OK button if no feature is selected.
*
* {@inheritDoc}
*/
@Override
protected Button createButton(Composite parent, int id, String label, boolean defaultButton)
{
Button button = super.createButton( parent, id, label, defaultButton );
// Disable the OK button at startup
if ( id == IDialogConstants.OK_ID )
{
button.setEnabled( false );
}
return button;
}
/**
* Initializes the Dialog with the values
*/
protected void initDialog()
{
databaseTypeCombo.setText( DatabaseTypeEnum.NONE.getName() );
}
/**
* Adds listeners.
*/
private void addListeners()
{
databaseTypeCombo.addSelectionListener( databaseTypeSelectionListener );
}
/**
* @return The selected DatabaseType
*/
public DatabaseTypeEnum getDatabaseType()
{
return selectedDatabaseType;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/AuditLogOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/AuditLogOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.util.List;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.widgets.FileBrowserWidget;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcAuditlogConfig;
/**
* This class implements a block for the configuration of the Audit Log overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AuditLogOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcAuditlogConfig>
{
// UI widgets
private FileBrowserWidget fileBrowserWidget;
public AuditLogOverlayConfigurationBlock( OverlayDialog dialog )
{
super( dialog );
setOverlay( new OlcAuditlogConfig() );
}
public AuditLogOverlayConfigurationBlock( OverlayDialog dialog, OlcAuditlogConfig overlay )
{
super( dialog );
if ( overlay == null )
{
setOverlay( new OlcAuditlogConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 3, 1 );
BaseWidgetUtils.createLabel( composite, "Log File:", 1 );
fileBrowserWidget = new FileBrowserWidget( "", new String[]
{ ".ldif", ".log" }, FileBrowserWidget.TYPE_OPEN );
fileBrowserWidget.createWidget( composite );
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
List<String> auditLogFilesList = overlay.getOlcAuditlogFile();
if ( auditLogFilesList != null && !auditLogFilesList.isEmpty() )
{
fileBrowserWidget.setFilename( auditLogFilesList.get( 0 ) );
}
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
overlay.clearOlcAuditlogFile();
String filename = fileBrowserWidget.getFilename();
if ( !Strings.isEmpty( filename ) )
{
overlay.addOlcAuditlogFile( filename );
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/PasswordPolicyOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/PasswordPolicyOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.widgets.EntryWidget;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcPPolicyConfig;
/**
* This class implements a block for the configuration of the Password Policy Log overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PasswordPolicyOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcPPolicyConfig>
{
// UI widgets
private EntryWidget defaultPolicyEntryWidget;
private Button forwardUpdatesCheckbox;
private Button hashCleartextCheckbox;
private Button useLockoutCheckbox;
public PasswordPolicyOverlayConfigurationBlock( OverlayDialog dialog )
{
super( dialog );
setOverlay( new OlcPPolicyConfig() );
}
public PasswordPolicyOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection,
OlcPPolicyConfig overlay )
{
super( dialog, browserConnection );
if ( overlay == null )
{
setOverlay( new OlcPPolicyConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 3, 1 );
// Default Policy
BaseWidgetUtils.createLabel( composite, "Default Policy:", 1 );
defaultPolicyEntryWidget = new EntryWidget( browserConnection, Dn.EMPTY_DN );
defaultPolicyEntryWidget.createWidget( composite );
defaultPolicyEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) );
// Forward Updates
forwardUpdatesCheckbox = BaseWidgetUtils.createCheckbox( composite, "Forward Updates", 3 );
// Hash Cleartext
hashCleartextCheckbox = BaseWidgetUtils.createCheckbox( composite, "Hash Cleartext", 3 );
// Use Lockout
useLockoutCheckbox = BaseWidgetUtils.createCheckbox( composite, "Use Lockout", 3 );
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
// Default Policy
defaultPolicyEntryWidget.setInput( overlay.getOlcPPolicyDefault() );
// Forward Updates
Boolean forwardUpdates = overlay.getOlcPPolicyForwardUpdates();
if ( forwardUpdates != null )
{
forwardUpdatesCheckbox.setSelection( forwardUpdates.booleanValue() );
}
else
{
forwardUpdatesCheckbox.setSelection( false );
}
// Hash Cleartext
Boolean hashCleartext = overlay.getOlcPPolicyHashCleartext();
if ( hashCleartext != null )
{
hashCleartextCheckbox.setSelection( hashCleartext.booleanValue() );
}
else
{
hashCleartextCheckbox.setSelection( false );
}
// Use Lockout
Boolean useLockout = overlay.getOlcPPolicyUseLockout();
if ( useLockout != null )
{
useLockoutCheckbox.setSelection( useLockout.booleanValue() );
}
else
{
useLockoutCheckbox.setSelection( false );
}
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
// Default Policy
overlay.setOlcPPolicyDefault( defaultPolicyEntryWidget.getDn() );
// Forward Updates
overlay.setOlcPPolicyForwardUpdates( forwardUpdatesCheckbox.getSelection() );
// Hash Cleartext
overlay.setOlcPPolicyHashCleartext( hashCleartextCheckbox.getSelection() );
// Use Lockout
overlay.setOlcPPolicyUseLockout( useLockoutCheckbox.getSelection() );
}
// Saving dialog settings
defaultPolicyEntryWidget.saveDialogSettings();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/MemberOfOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/MemberOfOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.widgets.EntryWidget;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcMemberOf;
import org.apache.directory.studio.openldap.config.model.overlay.OlcMemberOfDanglingReferenceBehaviorEnum;
/**
* This class implements a block for the configuration of the Member Of overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class MemberOfOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcMemberOf>
{
/** The connection's attribute types */
private List<String> connectionAttributeTypes;
/** The connection's objectClasses */
private List<String> connectionObjectClasses;
/** The list of result codes */
private List<ResultCodeEnum> resultCodes;
// UI widgets
private ComboViewer groupObjectClassComboViewer;
private ComboViewer groupAttributeTypeComboViewer;
private ComboViewer entryAttributeTypeComboViewer;
private EntryWidget modifierNameEntryWidget;
private ComboViewer danglingReferenceBehaviorComboViewer;
private ComboViewer danglingReferenceErrorCodeComboViewer;
private Button maintianReferentialIntegrityCheckbox;
/**
* Creates a new instance of MemberOfOverlayConfigurationBlock.
*
* @param dialog the dialog
* @param browserConnection the connection
*/
public MemberOfOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection )
{
super( dialog, browserConnection );
setOverlay( new OlcMemberOf() );
init();
}
/**
* Creates a new instance of MemberOfOverlayConfigurationBlock.
*
* @param dialog the dialog
* @param browserConnection the connection
* @param overlay the overlay
*/
public MemberOfOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection,
OlcMemberOf overlay )
{
super( dialog, browserConnection );
if ( overlay == null )
{
setOverlay( new OlcMemberOf() );
}
else
{
setOverlay( overlay );
}
init();
}
/**
* Initializes the list of attribute types and object class.
*/
private void init()
{
initAttributeTypesAndObjectClassesLists();
initResultCodesList();
}
/**
* Initializes the lists of attribute types and object classes.
*/
private void initAttributeTypesAndObjectClassesLists()
{
connectionAttributeTypes = new ArrayList<>();
connectionObjectClasses = new ArrayList<>();
if ( browserConnection != null )
{
// Attribute Types
Collection<AttributeType> atds = browserConnection.getSchema().getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
for ( String name : atd.getNames() )
{
connectionAttributeTypes.add( name );
}
}
// Object Classes
Collection<ObjectClass> ocds = browserConnection.getSchema().getObjectClassDescriptions();
for ( ObjectClass ocd : ocds )
{
for ( String name : ocd.getNames() )
{
connectionObjectClasses.add( name );
}
}
// Creating a case insensitive comparator
Comparator<String> ignoreCaseComparator = ( o1, o2 ) -> o1.compareToIgnoreCase( o2 );
// Sorting the lists
Collections.sort( connectionAttributeTypes, ignoreCaseComparator );
Collections.sort( connectionObjectClasses, ignoreCaseComparator );
}
}
/**
* Initializes the list of result codes.
*/
private void initResultCodesList()
{
// Initializing the list
resultCodes = new ArrayList<>();
// Adding all result codes to the list
resultCodes.add( ResultCodeEnum.SUCCESS );
resultCodes.add( ResultCodeEnum.PARTIAL_RESULTS );
resultCodes.add( ResultCodeEnum.COMPARE_FALSE );
resultCodes.add( ResultCodeEnum.COMPARE_TRUE );
resultCodes.add( ResultCodeEnum.REFERRAL );
resultCodes.add( ResultCodeEnum.SASL_BIND_IN_PROGRESS );
resultCodes.add( ResultCodeEnum.AUTH_METHOD_NOT_SUPPORTED );
resultCodes.add( ResultCodeEnum.STRONG_AUTH_REQUIRED );
resultCodes.add( ResultCodeEnum.CONFIDENTIALITY_REQUIRED );
resultCodes.add( ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM );
resultCodes.add( ResultCodeEnum.INAPPROPRIATE_AUTHENTICATION );
resultCodes.add( ResultCodeEnum.INVALID_CREDENTIALS );
resultCodes.add( ResultCodeEnum.INSUFFICIENT_ACCESS_RIGHTS );
resultCodes.add( ResultCodeEnum.OPERATIONS_ERROR );
resultCodes.add( ResultCodeEnum.PROTOCOL_ERROR );
resultCodes.add( ResultCodeEnum.TIME_LIMIT_EXCEEDED );
resultCodes.add( ResultCodeEnum.SIZE_LIMIT_EXCEEDED );
resultCodes.add( ResultCodeEnum.ADMIN_LIMIT_EXCEEDED );
resultCodes.add( ResultCodeEnum.UNAVAILABLE_CRITICAL_EXTENSION );
resultCodes.add( ResultCodeEnum.BUSY );
resultCodes.add( ResultCodeEnum.UNAVAILABLE );
resultCodes.add( ResultCodeEnum.UNWILLING_TO_PERFORM );
resultCodes.add( ResultCodeEnum.LOOP_DETECT );
resultCodes.add( ResultCodeEnum.NO_SUCH_ATTRIBUTE );
resultCodes.add( ResultCodeEnum.UNDEFINED_ATTRIBUTE_TYPE );
resultCodes.add( ResultCodeEnum.INAPPROPRIATE_MATCHING );
resultCodes.add( ResultCodeEnum.CONSTRAINT_VIOLATION );
resultCodes.add( ResultCodeEnum.ATTRIBUTE_OR_VALUE_EXISTS );
resultCodes.add( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX );
resultCodes.add( ResultCodeEnum.NO_SUCH_OBJECT );
resultCodes.add( ResultCodeEnum.ALIAS_PROBLEM );
resultCodes.add( ResultCodeEnum.INVALID_DN_SYNTAX );
resultCodes.add( ResultCodeEnum.NAMING_VIOLATION );
resultCodes.add( ResultCodeEnum.OBJECT_CLASS_VIOLATION );
resultCodes.add( ResultCodeEnum.NOT_ALLOWED_ON_NON_LEAF );
resultCodes.add( ResultCodeEnum.NOT_ALLOWED_ON_RDN );
resultCodes.add( ResultCodeEnum.ENTRY_ALREADY_EXISTS );
resultCodes.add( ResultCodeEnum.OBJECT_CLASS_MODS_PROHIBITED );
resultCodes.add( ResultCodeEnum.AFFECTS_MULTIPLE_DSAS );
resultCodes.add( ResultCodeEnum.OTHER );
resultCodes.add( ResultCodeEnum.CANCELED );
resultCodes.add( ResultCodeEnum.NO_SUCH_OPERATION );
resultCodes.add( ResultCodeEnum.TOO_LATE );
resultCodes.add( ResultCodeEnum.CANNOT_CANCEL );
resultCodes.add( ResultCodeEnum.UNKNOWN );
// Sorting the list
Collections.sort( resultCodes, ( o1, o2 ) -> Integer.compare( o1.getResultCode(), o2.getResultCode() ) );
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
// Group Object Class
BaseWidgetUtils.createLabel( composite, "Group Object Class:", 1 );
groupObjectClassComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
groupObjectClassComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
groupObjectClassComboViewer.setContentProvider( new ArrayContentProvider() );
groupObjectClassComboViewer.setInput( connectionObjectClasses );
// Group Attribute Type
BaseWidgetUtils.createLabel( composite, "Group Attribute Type:", 1 );
groupAttributeTypeComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
groupAttributeTypeComboViewer.getControl()
.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
groupAttributeTypeComboViewer.setContentProvider( new ArrayContentProvider() );
groupAttributeTypeComboViewer.setInput( connectionAttributeTypes );
// Entry Attribute Type
BaseWidgetUtils.createLabel( composite, "Entry Attribute Type:", 1 );
entryAttributeTypeComboViewer = new ComboViewer( new Combo( composite, SWT.DROP_DOWN ) );
entryAttributeTypeComboViewer.getControl()
.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
entryAttributeTypeComboViewer.setContentProvider( new ArrayContentProvider() );
entryAttributeTypeComboViewer.setInput( connectionAttributeTypes );
// Modifier Name
BaseWidgetUtils.createLabel( composite, "Modifier's Name:", 1 );
modifierNameEntryWidget = new EntryWidget( browserConnection );
modifierNameEntryWidget.createWidget( composite );
modifierNameEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Dangling Reference Behavior
BaseWidgetUtils.createLabel( composite, "Dangling Ref. Behavior:", 1 );
danglingReferenceBehaviorComboViewer = new ComboViewer( composite );
danglingReferenceBehaviorComboViewer.getControl().setLayoutData(
new GridData( SWT.FILL, SWT.NONE, true, false ) );
danglingReferenceBehaviorComboViewer.setContentProvider( new ArrayContentProvider() );
danglingReferenceBehaviorComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof OlcMemberOfDanglingReferenceBehaviorEnum )
{
OlcMemberOfDanglingReferenceBehaviorEnum behavior = ( OlcMemberOfDanglingReferenceBehaviorEnum ) element;
switch ( behavior )
{
case IGNORE:
return "Ignore";
case DROP:
return "Drop";
case ERROR:
return "Error";
}
}
return super.getText( element );
}
} );
danglingReferenceBehaviorComboViewer.setInput( new OlcMemberOfDanglingReferenceBehaviorEnum[]
{
OlcMemberOfDanglingReferenceBehaviorEnum.IGNORE,
OlcMemberOfDanglingReferenceBehaviorEnum.DROP,
OlcMemberOfDanglingReferenceBehaviorEnum.ERROR
} );
// Dangling Reference Error Code
BaseWidgetUtils.createLabel( composite, "Dangling Ref. Error Code:", 1 );
danglingReferenceErrorCodeComboViewer = new ComboViewer( composite );
danglingReferenceErrorCodeComboViewer.getControl().setLayoutData(
new GridData( SWT.FILL, SWT.NONE, true, false ) );
danglingReferenceErrorCodeComboViewer.setContentProvider( new ArrayContentProvider() );
danglingReferenceErrorCodeComboViewer.setLabelProvider( new LabelProvider()
{
@Override
public String getText( Object element )
{
if ( element instanceof ResultCodeEnum )
{
ResultCodeEnum resultCode = ( ResultCodeEnum ) element;
return NLS.bind( "{0} ({1})", new Object[]
{ resultCode.getResultCode(), resultCode.getMessage() } );
}
return super.getText( element );
}
} );
danglingReferenceErrorCodeComboViewer.setInput( resultCodes );
// Maintain Referential Integrity
maintianReferentialIntegrityCheckbox = BaseWidgetUtils.createCheckbox( composite,
"Maintain Referential Integrity", 2 );
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
// Group Object Class
setComboViewerText( groupObjectClassComboViewer, overlay.getOlcMemberOfGroupOC() );
// Group Attribute Type
setComboViewerText( groupAttributeTypeComboViewer, overlay.getOlcMemberOfMemberAD() );
// Entry Attribute Type
setComboViewerText( entryAttributeTypeComboViewer, overlay.getOlcMemberOfMemberOfAD() );
// Modifier Name
Dn modifierName = overlay.getOlcMemberOfDN();
if ( modifierName != null )
{
modifierNameEntryWidget.setInput( modifierName );
}
else
{
modifierNameEntryWidget.setInput( Dn.EMPTY_DN );
}
// Dangling Reference Behavior
String danglingReferenceBehaviorString = overlay.getOlcMemberOfDangling();
if ( danglingReferenceBehaviorString != null )
{
OlcMemberOfDanglingReferenceBehaviorEnum danglingReferenceBehavior = OlcMemberOfDanglingReferenceBehaviorEnum
.fromString( danglingReferenceBehaviorString );
if ( danglingReferenceBehavior != null )
{
danglingReferenceBehaviorComboViewer.setSelection( new StructuredSelection(
danglingReferenceBehavior ) );
}
else
{
danglingReferenceBehaviorComboViewer.setSelection( new StructuredSelection(
OlcMemberOfDanglingReferenceBehaviorEnum.IGNORE ) );
}
}
else
{
danglingReferenceBehaviorComboViewer.setSelection( new StructuredSelection(
OlcMemberOfDanglingReferenceBehaviorEnum.IGNORE ) );
}
// Dangling Reference Error Code
String danglingReferenceErrorCode = overlay.getOlcMemberOfDanglingError();
if ( danglingReferenceErrorCode != null )
{
try
{
// Getting the error code as a ResultCodeEnum value
ResultCodeEnum resultCode = ResultCodeEnum.getResultCode( Integer
.parseInt( danglingReferenceErrorCode ) );
danglingReferenceErrorCodeComboViewer.setSelection( new StructuredSelection( resultCode ) );
}
catch ( NumberFormatException e )
{
// The error code is not an int value
danglingReferenceErrorCodeComboViewer.setSelection( new StructuredSelection(
ResultCodeEnum.CONSTRAINT_VIOLATION ) );
}
}
else
{
danglingReferenceErrorCodeComboViewer.setSelection( new StructuredSelection(
ResultCodeEnum.CONSTRAINT_VIOLATION ) );
}
// Maintain Referential Integrity
Boolean maintainReferentialIntegrity = overlay.getOlcMemberOfRefInt();
if ( maintainReferentialIntegrity != null )
{
maintianReferentialIntegrityCheckbox.setSelection( maintainReferentialIntegrity );
}
else
{
maintianReferentialIntegrityCheckbox.setSelection( false );
}
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
// Group Object Class
String groupObjectClass = getComboViewerText( groupObjectClassComboViewer );
if ( ( groupObjectClass != null ) && ( !groupObjectClass.isEmpty() ) )
{
overlay.setOlcMemberOfGroupOC( groupObjectClass );
}
else
{
overlay.setOlcMemberOfGroupOC( null );
}
// Group Attribute Type
String groupAttributeType = getComboViewerText( groupAttributeTypeComboViewer );
if ( ( groupAttributeType != null ) && ( !groupAttributeType.isEmpty() ) )
{
overlay.setOlcMemberOfMemberAD( groupAttributeType );
}
else
{
overlay.setOlcMemberOfMemberAD( null );
}
// Entry Attribute Type
String entryAttributeType = getComboViewerText( entryAttributeTypeComboViewer );
if ( ( entryAttributeType != null ) && ( !entryAttributeType.isEmpty() ) )
{
overlay.setOlcMemberOfMemberOfAD( entryAttributeType );
}
else
{
overlay.setOlcMemberOfMemberOfAD( null );
}
// Modifier Name
Dn modifierName = modifierNameEntryWidget.getDn();
if ( ( modifierName != null ) && ( !Dn.EMPTY_DN.equals( modifierName ) ) )
{
overlay.setOlcMemberOfDN( modifierName );
}
else
{
overlay.setOlcMemberOfDN( null );
}
// Dangling Reference Behavior
OlcMemberOfDanglingReferenceBehaviorEnum danglingReferenceBehavior = getSelectedDanglingReferenceBehavior();
if ( danglingReferenceBehavior != null )
{
overlay.setOlcMemberOfDangling( danglingReferenceBehavior.toString() );
}
else
{
overlay.setOlcMemberOfDangling( null );
}
// Dangling Reference Error Code
ResultCodeEnum danglingReferenceErrorCode = getSelectedDanglingReferenceErrorCode();
if ( ( danglingReferenceErrorCode != null )
&& ( !ResultCodeEnum.CONSTRAINT_VIOLATION.equals( danglingReferenceErrorCode ) ) )
{
overlay.setOlcMemberOfDanglingError( Integer.toString( danglingReferenceErrorCode.getResultCode() ) );
}
else
{
overlay.setOlcMemberOfDanglingError( null );
}
// Maintain Referential Integrity
overlay.setOlcMemberOfRefInt( maintianReferentialIntegrityCheckbox.getSelection() );
}
}
/**
* Gets the text selection of the combo viewer.
*
* @param viewer the viewer
* @return the text selection of the viewer
*/
private String getComboViewerText( ComboViewer viewer )
{
return viewer.getCombo().getText();
}
/**
* Sets the text selection of the combo viewer.
*
* @param viewer the viewer
* @param text the text
*/
private void setComboViewerText( ComboViewer viewer, String text )
{
if ( text != null )
{
viewer.getCombo().setText( text );
}
else
{
viewer.getCombo().setText( "" );
}
}
/**
* Gets the selected dangling reference behavior.
*
* @return the selected dangling reference behavior
*/
private OlcMemberOfDanglingReferenceBehaviorEnum getSelectedDanglingReferenceBehavior()
{
StructuredSelection selection = ( StructuredSelection ) danglingReferenceBehaviorComboViewer.getSelection();
if ( ( selection != null ) && ( !selection.isEmpty() ) )
{
Object firstElement = selection.getFirstElement();
if ( firstElement instanceof OlcMemberOfDanglingReferenceBehaviorEnum )
{
return ( OlcMemberOfDanglingReferenceBehaviorEnum ) firstElement;
}
else
{
return null;
}
}
return null;
}
/**
* Gets the selected dangling reference error code.
*
* @return the selected dangling reference error code
*/
private ResultCodeEnum getSelectedDanglingReferenceErrorCode()
{
StructuredSelection selection = ( StructuredSelection ) danglingReferenceErrorCodeComboViewer.getSelection();
if ( ( selection != null ) && ( !selection.isEmpty() ) )
{
Object firstElement = selection.getFirstElement();
if ( firstElement instanceof ResultCodeEnum )
{
return ( ResultCodeEnum ) firstElement;
}
else
{
return null;
}
}
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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/SyncProvOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/SyncProvOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcSyncProvConfig;
/**
* This class implements a block for the configuration of the Audit Log overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SyncProvOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcSyncProvConfig>
{
// UI widgets
private Text checkpointOperationsText;
private Text checkpointMinutesText;
private Text sessionLogOperationsText;
private Button skipPresentPhaseButton;
private Button honorReloadHintFlagButton;
public SyncProvOverlayConfigurationBlock( OverlayDialog dialog )
{
super( dialog );
setOverlay( new OlcSyncProvConfig() );
}
public SyncProvOverlayConfigurationBlock( OverlayDialog dialog, OlcSyncProvConfig overlay )
{
super( dialog );
if ( overlay == null )
{
setOverlay( new OlcSyncProvConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// Checkpoint
Composite checkpointComposite = BaseWidgetUtils.createColumnContainer( composite, 5, 1 );
BaseWidgetUtils.createLabel( checkpointComposite, "New checkpoint after", 1 );
checkpointOperationsText = createIntegerText( checkpointComposite, "", 1 );
BaseWidgetUtils.createLabel( checkpointComposite, "operations or", 1 );
checkpointMinutesText = createIntegerText( checkpointComposite, "", 1 );
BaseWidgetUtils.createLabel( checkpointComposite, "minutes", 1 );
// Session Log
Composite sessionLogComposite = BaseWidgetUtils.createColumnContainer( composite, 3, 1 );
BaseWidgetUtils.createLabel( sessionLogComposite, "Session log holds", 1 );
sessionLogOperationsText = createIntegerText( sessionLogComposite, "", 1 );
BaseWidgetUtils.createLabel( sessionLogComposite, "operations", 1 );
// No Present
skipPresentPhaseButton = BaseWidgetUtils.createCheckbox( composite, "Skip Present Phase", 1 );
// Reload Hint
honorReloadHintFlagButton = BaseWidgetUtils.createCheckbox( composite, "Honor Reload Hint flag", 1 );
}
/**
* Create a Text widget only accepting integers.
*
* @param parent the parent
* @param text the initial text
* @param span the horizontal span
* @return a Text widget only accepting integers
*/
private Text createIntegerText( Composite parent, String text, int span )
{
Text integerText = BaseWidgetUtils.createText( parent, text, span );
integerText.addVerifyListener( event ->
{
if ( !event.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
event.doit = false;
}
} );
GridData gd = new GridData();
gd.widthHint = 40;
integerText.setLayoutData( gd );
return integerText;
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
// Checkpoint
String checkpointConfiguration = overlay.getOlcSpCheckpoint();
if ( ( checkpointConfiguration != null ) && ( !checkpointConfiguration.isEmpty() ) )
{
String[] checkpointConfigurationElements = checkpointConfiguration.split( " " );
if ( checkpointConfigurationElements.length == 2 )
{
// Checkpoint Operations
try
{
int checkpointOperations = Integer.parseInt( checkpointConfigurationElements[0] );
checkpointOperationsText.setText( Integer.toString( checkpointOperations ) );
}
catch ( NumberFormatException e )
{
// TODO
checkpointOperationsText.setText( "" );
}
// Checkpoint Minutes
try
{
int checkpointMinutes = Integer.parseInt( checkpointConfigurationElements[1] );
checkpointMinutesText.setText( Integer.toString( checkpointMinutes ) );
}
catch ( NumberFormatException e )
{
// TODO
checkpointMinutesText.setText( "" );
}
}
else
{
// TODO
checkpointOperationsText.setText( "" );
checkpointMinutesText.setText( "" );
}
}
else
{
// TODO
checkpointOperationsText.setText( "" );
checkpointMinutesText.setText( "" );
}
// Session Log
Integer sessionLogOperations = overlay.getOlcSpSessionlog();
if ( sessionLogOperations != null )
{
sessionLogOperationsText.setText( "" + sessionLogOperations );
}
else
{
// TODO
sessionLogOperationsText.setText( "" );
}
// No Present
skipPresentPhaseButton.setSelection( overlay.getOlcSpNoPresent() );
// Reload Hint
honorReloadHintFlagButton.setSelection( overlay.getOlcSpReloadHint() );
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
// Checkpoint
String checkpointOperations = checkpointOperationsText.getText();
String checkpointMinutes = checkpointMinutesText.getText();
if ( ( checkpointOperations != null ) && ( !checkpointOperations.isEmpty() )
&& ( checkpointMinutes != null ) && ( !checkpointMinutes.isEmpty() ) )
{
overlay.setOlcSpCheckpoint( checkpointOperations + " " + checkpointMinutes );
}
else
{
overlay.setOlcSpCheckpoint( null );
}
// Session Log
String sessionLogOperations = sessionLogOperationsText.getText();
if ( ( sessionLogOperations != null ) && ( !sessionLogOperations.isEmpty() ) )
{
try
{
overlay.setOlcSpSessionlog( Integer.parseInt( sessionLogOperations ) );
}
catch ( NumberFormatException e )
{
overlay.setOlcSpSessionlog( null );
}
}
else
{
overlay.setOlcSpSessionlog( null );
}
// No Present
overlay.setOlcSpNoPresent( skipPresentPhaseButton.getSelection() );
// Reload Hint
overlay.setOlcSpReloadHint( honorReloadHintFlagButton.getSelection() );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/ReferentialIntegrityOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/ReferentialIntegrityOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.openldap.common.ui.widgets.EntryWidget;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRefintConfig;
/**
* This class implements a block for the configuration of the Referential Integrity overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ReferentialIntegrityOverlayConfigurationBlock extends
AbstractOverlayDialogConfigurationBlock<OlcRefintConfig>
{
/** The default modifier name */
private static final String DEFAULT_MODIFIER_NAME = "cn=Referential Integrity Overlay";
/** The attributes list */
private List<String> attributes = new ArrayList<>();
// UI widgets
private TableViewer attributesTableViewer;
private Button addAttributeButton;
private Button deleteAttributeButton;
private EntryWidget placeholderValueEntryWidget;
private EntryWidget modifierNameEntryWidget;
// Listeners
private ISelectionChangedListener attributesTableViewerSelectionChangedListener = event ->
deleteAttributeButton.setEnabled( !attributesTableViewer.getSelection().isEmpty() );
private SelectionListener addAttributeButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
AttributeDialog dialog = new AttributeDialog( addAttributeButton.getShell(), browserConnection );
if ( dialog.open() == AttributeDialog.OK )
{
String attribute = dialog.getAttribute();
if ( !attributes.contains( attribute ) )
{
attributes.add( attribute );
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( attribute ) );
}
}
}
};
private SelectionListener deleteAttributeButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
attributes.remove( selectedAttribute );
attributesTableViewer.refresh();
}
}
};
public ReferentialIntegrityOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection )
{
super( dialog, connection );
setOverlay( new OlcRefintConfig() );
}
public ReferentialIntegrityOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection,
OlcRefintConfig overlay )
{
super( dialog, connection );
if ( overlay == null )
{
setOverlay( new OlcRefintConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
// Attributes
BaseWidgetUtils.createLabel( composite, "Attributes:", 1 );
Composite attributesComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
// Attributes TableViewer
attributesTableViewer = new TableViewer( attributesComposite );
GridData tableViewerGridData = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 );
tableViewerGridData.heightHint = 20;
tableViewerGridData.widthHint = 100;
attributesTableViewer.getControl().setLayoutData( tableViewerGridData );
attributesTableViewer.setContentProvider( new ArrayContentProvider() );
attributesTableViewer.setLabelProvider( new LabelProvider()
{
@Override
public Image getImage( Object element )
{
return OpenLdapConfigurationPlugin.getDefault().getImage(
OpenLdapConfigurationPluginConstants.IMG_ATTRIBUTE );
}
} );
attributesTableViewer.setInput( attributes );
attributesTableViewer.addSelectionChangedListener( attributesTableViewerSelectionChangedListener );
// Attribute Add Button
addAttributeButton = BaseWidgetUtils.createButton( attributesComposite, "Add...", 1 );
addAttributeButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
addAttributeButton.addSelectionListener( addAttributeButtonSelectionListener );
// Attribute Delete Button
deleteAttributeButton = BaseWidgetUtils.createButton( attributesComposite, "Delete", 1 );
deleteAttributeButton.setEnabled( false );
deleteAttributeButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
deleteAttributeButton.addSelectionListener( deleteAttributeButtonSelectionListener );
// Placeholder Value
BaseWidgetUtils.createLabel( composite, "Placeholder Value:", 1 );
placeholderValueEntryWidget = new EntryWidget( getDialog().getBrowserConnection() );
placeholderValueEntryWidget.createWidget( composite );
placeholderValueEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Modifier Name
BaseWidgetUtils.createLabel( composite, "Modifier's Name:", 1 );
modifierNameEntryWidget = new EntryWidget( getDialog().getBrowserConnection() );
modifierNameEntryWidget.createWidget( composite );
modifierNameEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
// Attributes
List<String> attributeValues = overlay.getOlcRefintAttribute();
if ( ( attributeValues != null ) && attributeValues.isEmpty() )
{
for ( String attribute : attributeValues )
{
attributes.add( attribute );
}
}
attributesTableViewer.refresh();
// Placeholder Value
Dn placeholderValue = overlay.getOlcRefintNothing();
if ( placeholderValue != null )
{
placeholderValueEntryWidget.setInput( placeholderValue );
}
else
{
placeholderValueEntryWidget.setInput( Dn.EMPTY_DN );
}
// Modifier Name
Dn modifierName = overlay.getOlcRefintModifiersName();
if ( modifierName != null )
{
modifierNameEntryWidget.setInput( modifierName );
}
else
{
try
{
modifierNameEntryWidget.setInput( new Dn( DEFAULT_MODIFIER_NAME ) );
}
catch ( LdapInvalidDnException e )
{
// Nothing to do.
}
}
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
// Attributes
overlay.setOlcRefintAttribute( attributes );
// Placeholder Value
Dn placeholderValue = placeholderValueEntryWidget.getDn();
if ( ( placeholderValue != null ) && ( !Dn.EMPTY_DN.equals( placeholderValue ) ) )
{
overlay.setOlcRefintNothing( placeholderValue );
}
else
{
overlay.setOlcRefintNothing( null );
}
// Modifier Name
Dn modifierName = modifierNameEntryWidget.getDn();
if ( ( modifierName != null ) && ( !Dn.EMPTY_DN.equals( modifierName ) )
&& ( !modifierName.toString().equals( DEFAULT_MODIFIER_NAME ) ) )
{
overlay.setOlcRefintModifiersName( modifierName );
}
else
{
overlay.setOlcRefintModifiersName( 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/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/RewriteRemapOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/RewriteRemapOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.editor.dialogs.RwmMappingDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcRwmConfig;
/**
* This class implements a block for the configuration of the Audit Log overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RewriteRemapOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcRwmConfig>
{
/** The mappings list */
private List<String> mappings = new ArrayList<>();
// UI widgets
private TableViewer mappingsTableViewer;
private Button addMappingButton;
private Button editMappingButton;
private Button deleteMappingButton;
// Listeners
private ISelectionChangedListener mappingsTableViewerSelectionChangedListener = event ->
deleteMappingButton.setEnabled( !mappingsTableViewer.getSelection().isEmpty() );
private IDoubleClickListener mappingsTableViewerDoubleClickListener = event -> editMappingButtonAction();
private SelectionListener addMappingButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
RwmMappingDialog dialog = new RwmMappingDialog( addMappingButton.getShell(), browserConnection, "" );
if ( dialog.open() == AttributeDialog.OK )
{
String value = dialog.getValue();
mappings.add( value );
mappingsTableViewer.refresh();
mappingsTableViewer.setSelection( new StructuredSelection( value ) );
}
}
};
private SelectionListener editMappingButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
editMappingButtonAction();
}
};
private SelectionListener deleteMappingButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
StructuredSelection selection = ( StructuredSelection ) mappingsTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
mappings.remove( selectedAttribute );
mappingsTableViewer.refresh();
}
}
};
public RewriteRemapOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection )
{
super( dialog, connection );
setOverlay( new OlcRwmConfig() );
}
public RewriteRemapOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection,
OlcRwmConfig overlay )
{
super( dialog, connection );
if ( overlay == null )
{
setOverlay( new OlcRwmConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// Mappings
BaseWidgetUtils.createLabel( composite, "Mappings:", 1 );
Composite mappingsComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
// Mappings TableViewer
mappingsTableViewer = new TableViewer( mappingsComposite );
GridData tableViewerGridData = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 );
tableViewerGridData.heightHint = 20;
tableViewerGridData.widthHint = 100;
mappingsTableViewer.getControl().setLayoutData( tableViewerGridData );
mappingsTableViewer.setContentProvider( new ArrayContentProvider() );
mappingsTableViewer.setInput( mappings );
mappingsTableViewer.addSelectionChangedListener( mappingsTableViewerSelectionChangedListener );
mappingsTableViewer.addDoubleClickListener( mappingsTableViewerDoubleClickListener );
// Mapping Add Button
addMappingButton = BaseWidgetUtils.createButton( mappingsComposite, "Add...", 1 );
addMappingButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
addMappingButton.addSelectionListener( addMappingButtonSelectionListener );
// Mapping Add Button
editMappingButton = BaseWidgetUtils.createButton( mappingsComposite, "Edit...", 1 );
editMappingButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
editMappingButton.addSelectionListener( editMappingButtonSelectionListener );
// Mapping Delete Button
deleteMappingButton = BaseWidgetUtils.createButton( mappingsComposite, "Delete", 1 );
deleteMappingButton.setEnabled( false );
deleteMappingButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
deleteMappingButton.addSelectionListener( deleteMappingButtonSelectionListener );
}
/**
* Action launched when the edit mapping button is clicked, or
* when the value sorts table viewer is double-clicked.
*/
private void editMappingButtonAction()
{
StructuredSelection selection = ( StructuredSelection ) mappingsTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedMapping = ( String ) selection.getFirstElement();
RwmMappingDialog dialog = new RwmMappingDialog( addMappingButton.getShell(),
browserConnection, selectedMapping );
if ( dialog.open() == AttributeDialog.OK )
{
String value = dialog.getValue();
int index = mappings.indexOf( selectedMapping );
mappings.remove( selectedMapping );
mappings.add( index, value );
mappingsTableViewer.refresh();
mappingsTableViewer.setSelection( new StructuredSelection( value ) );
}
}
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
mappings.clear();
List<String> olcRwmMap = overlay.getOlcRwmMap();
if ( olcRwmMap != null )
{
for ( String value : olcRwmMap )
{
mappings.add( value );
}
}
mappingsTableViewer.refresh();
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
overlay.clearOlcRwmMap();
for ( String mapping : mappings )
{
overlay.addOlcRwmMap( mapping );
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/AccessLogOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/AccessLogOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.FilterWidget;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Spinner;
import org.apache.directory.studio.openldap.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.openldap.common.ui.model.LogOperationEnum;
import org.apache.directory.studio.openldap.common.ui.widgets.EntryWidget;
import org.apache.directory.studio.openldap.common.ui.widgets.LogOperationsWidget;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.editor.dialogs.PurgeTimeSpan;
import org.apache.directory.studio.openldap.config.model.overlay.OlcAccessLogConfig;
/**
* This class implements a block for the configuration of the Access Log overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AccessLogOverlayConfigurationBlock extends AbstractOverlayDialogConfigurationBlock<OlcAccessLogConfig>
{
/** The attributes list */
private List<String> attributes = new ArrayList<>();
// UI widgets
private EntryWidget databaseEntryWidget;
private Button onlyLogSuccessfulRequestsCheckbox;
private LogOperationsWidget logOperationsWidget;
private TableViewer attributesTableViewer;
private Button addAttributeButton;
private Button deleteAttributeButton;
private FilterWidget filterWidget;
private Spinner purgeAgeDaysSpinner;
private Spinner purgeAgeHoursSpinner;
private Spinner purgeAgeMinutesSpinner;
private Spinner purgeAgeSecondsSpinner;
private Spinner purgeIntervalDaysSpinner;
private Spinner purgeIntervalHoursSpinner;
private Spinner purgeIntervalMinutesSpinner;
private Spinner purgeIntervalSecondsSpinner;
// Listeners
private ISelectionChangedListener attributesTableViewerSelectionChangedListener = event ->
deleteAttributeButton.setEnabled( !attributesTableViewer.getSelection().isEmpty() );
private SelectionListener addAttributeButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
AttributeDialog dialog = new AttributeDialog( addAttributeButton.getShell(), browserConnection );
if ( dialog.open() == AttributeDialog.OK )
{
String attribute = dialog.getAttribute();
if ( !attributes.contains( attribute ) )
{
attributes.add( attribute );
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( attribute ) );
}
}
}
};
private SelectionListener deleteAttributeButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
attributes.remove( selectedAttribute );
attributesTableViewer.refresh();
}
}
};
/**
* Creates a new instance of AccessLogOverlayConfigurationBlock.
*
* @param dialog the overlay dialog
* @param browserConnection the browser connection
*/
public AccessLogOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection )
{
super( dialog, browserConnection );
setOverlay( new OlcAccessLogConfig() );
}
/**
* Creates a new instance of AccessLogOverlayConfigurationBlock.
*
* @param dialog the overlay dialog
* @param browserConnection the browser connection
* @param overlay the access log overlay
*/
public AccessLogOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection browserConnection,
OlcAccessLogConfig overlay )
{
super( dialog, browserConnection );
if ( overlay == null )
{
setOverlay( new OlcAccessLogConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 3, 1 );
// Database
BaseWidgetUtils.createLabel( composite, "Database:", 1 );
databaseEntryWidget = new EntryWidget( getDialog().getBrowserConnection() );
databaseEntryWidget.createWidget( composite );
databaseEntryWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Successful requests
onlyLogSuccessfulRequestsCheckbox = BaseWidgetUtils.createCheckbox( composite, "Only log successful requests",
3 );
createLogOperationsGroup( composite );
createAttributesGroup( composite );
createFilterGroup( composite );
createPurgeGroup( composite );
}
/**
* Creates the log operations group.
*
* @param parent the parent composite
*/
private void createLogOperationsGroup( Composite parent )
{
// Log Operations Group
Group logOperationsGroup = BaseWidgetUtils.createGroup( parent, "Log Operations", 3 );
// Log Operations Widget
logOperationsWidget = new LogOperationsWidget();
logOperationsWidget.create( logOperationsGroup );
logOperationsWidget.getControl().setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) );
List<LogOperationEnum> logOperations = new ArrayList<>();
logOperations.add( LogOperationEnum.ADD );
logOperations.add( LogOperationEnum.ABANDON );
logOperations.add( LogOperationEnum.SESSION );
logOperationsWidget.setInput( logOperations );
}
/**
* Creates the attributes group.
*
* @param parent the parent composite
*/
private void createAttributesGroup( Composite parent )
{
// Attributes Group
Group attributesGroup = BaseWidgetUtils.createGroup( parent, "Attributes", 3 );
GridLayout attributesCompositeGridLayout = new GridLayout( 2, false );
attributesCompositeGridLayout.verticalSpacing = 0;
attributesGroup.setLayout( attributesCompositeGridLayout );
// Attributes TableViewer
attributesTableViewer = new TableViewer( attributesGroup );
GridData tableViewerGridData = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 );
tableViewerGridData.heightHint = 20;
tableViewerGridData.widthHint = 100;
attributesTableViewer.getControl().setLayoutData( tableViewerGridData );
attributesTableViewer.setContentProvider( new ArrayContentProvider() );
attributesTableViewer.setLabelProvider( new LabelProvider()
{
@Override
public Image getImage( Object element )
{
return OpenLdapConfigurationPlugin.getDefault().getImage(
OpenLdapConfigurationPluginConstants.IMG_ATTRIBUTE );
}
} );
attributesTableViewer.setInput( attributes );
attributesTableViewer.addSelectionChangedListener( attributesTableViewerSelectionChangedListener );
// Attribute Add Button
addAttributeButton = BaseWidgetUtils.createButton( attributesGroup, "Add...", 1 );
addAttributeButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
addAttributeButton.addSelectionListener( addAttributeButtonSelectionListener );
// Attribute Delete Button
deleteAttributeButton = BaseWidgetUtils.createButton( attributesGroup, "Delete", 1 );
deleteAttributeButton.setEnabled( false );
deleteAttributeButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
deleteAttributeButton.addSelectionListener( deleteAttributeButtonSelectionListener );
}
/**
* Creates the filter group.
*
* @param parent the parent composite
*/
private void createFilterGroup( Composite parent )
{
// Filter Group
Group filterGroup = BaseWidgetUtils.createGroup( parent, "Filter", 3 );
GridLayout filterGroupGridLayout = new GridLayout( 2, false );
filterGroupGridLayout.marginHeight = 0;
filterGroupGridLayout.verticalSpacing = 0;
filterGroup.setLayout( filterGroupGridLayout );
filterWidget = new FilterWidget();
filterWidget.setFilter( "" );
filterWidget.setBrowserConnection( getDialog().getBrowserConnection() );
filterWidget.createWidget( filterGroup );
}
/**
* Creates the purge group.
*
* @param parent the parent composite
*/
private void createPurgeGroup( Composite parent )
{
// Purge Group
Group purgeGroup = BaseWidgetUtils.createGroup( parent, "Log Purge", 3 );
GridLayout purgeCompositeGridLayout = new GridLayout( 5, false );
purgeCompositeGridLayout.verticalSpacing = 0;
purgeGroup.setLayout( purgeCompositeGridLayout );
// Age Label
BaseWidgetUtils.createLabel( purgeGroup, "Age:", 1 );
// Age Days Spinner
purgeAgeDaysSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeAgeDaysSpinner.setMinimum( 0 );
purgeAgeDaysSpinner.setMaximum( 99999 );
// Age Hours Spinner
purgeAgeHoursSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeAgeHoursSpinner.setMinimum( 0 );
purgeAgeHoursSpinner.setMaximum( 23 );
// Age Minutes Spinner
purgeAgeMinutesSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeAgeMinutesSpinner.setMinimum( 0 );
purgeAgeMinutesSpinner.setMaximum( 59 );
// Age Seconds Spinner
purgeAgeSecondsSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeAgeSecondsSpinner.setMinimum( 0 );
purgeAgeSecondsSpinner.setMaximum( 59 );
// Interval Label
BaseWidgetUtils.createLabel( purgeGroup, "Interval:", 1 );
// Interval Days Spinner
purgeIntervalDaysSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeIntervalDaysSpinner.setMinimum( 0 );
purgeIntervalDaysSpinner.setMaximum( 99999 );
// Interval Hours Spinner
purgeIntervalHoursSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeIntervalHoursSpinner.setMinimum( 0 );
purgeIntervalHoursSpinner.setMaximum( 23 );
// Interval Minutes Spinner
purgeIntervalMinutesSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeIntervalMinutesSpinner.setMinimum( 0 );
purgeIntervalMinutesSpinner.setMaximum( 59 );
// Interval Seconds Spinner
purgeIntervalSecondsSpinner = new Spinner( purgeGroup, SWT.BORDER );
purgeIntervalSecondsSpinner.setMinimum( 0 );
purgeIntervalSecondsSpinner.setMaximum( 59 );
// Days Hours Minutes Seconds Labels
BaseWidgetUtils.createSpacer( purgeGroup, 1 );
BaseWidgetUtils.createLabel( purgeGroup, "Days", 1 );
BaseWidgetUtils.createLabel( purgeGroup, "Hours", 1 );
BaseWidgetUtils.createLabel( purgeGroup, "Minutes", 1 );
BaseWidgetUtils.createLabel( purgeGroup, "Seconds", 1 );
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
// Database
databaseEntryWidget.setInput( overlay.getOlcAccessLogDB() );
//
// Only log successful requests
//
Boolean onlyLogSuccessfulRequests = overlay.getOlcAccessLogSuccess();
if ( onlyLogSuccessfulRequests != null )
{
onlyLogSuccessfulRequestsCheckbox.setSelection( onlyLogSuccessfulRequests.booleanValue() );
}
else
{
onlyLogSuccessfulRequestsCheckbox.setSelection( false );
}
//
// Log operations
//
List<String> logOperationsValues = overlay.getOlcAccessLogOps();
if ( ( logOperationsValues != null ) && !logOperationsValues.isEmpty() )
{
logOperationsWidget.setInput( getAccessLogOperations( logOperationsValues ) );
}
else
{
logOperationsWidget.setInput( null );
}
//
// Attributes
//
List<String> attributeValues = overlay.getOlcAccessLogOldAttr();
if ( ( attributeValues != null ) && !attributeValues.isEmpty() )
{
for ( String attribute : attributeValues )
{
attributes.add( attribute );
}
}
attributesTableViewer.refresh();
//
// Filter
//
String filter = overlay.getOlcAccessLogOld();
if ( filter != null )
{
filterWidget.setFilter( filter );
}
//
// Purge
//
String accessLogPurge = overlay.getOlcAccessLogPurge();
if ( !Strings.isEmpty( accessLogPurge ) )
{
// Splitting age and interval purge time spans
String[] accessLogPurgeValues = accessLogPurge.split( " " );
// Checking if we got the appropriate number of members
if ( accessLogPurgeValues.length == 2 )
{
try
{
// Purge age time span
PurgeTimeSpan purgeAgeTimeSpan = new PurgeTimeSpan( accessLogPurgeValues[0] );
purgeAgeDaysSpinner.setSelection( purgeAgeTimeSpan.getDays() );
purgeAgeHoursSpinner.setSelection( purgeAgeTimeSpan.getHours() );
purgeAgeMinutesSpinner.setSelection( purgeAgeTimeSpan.getMinutes() );
purgeAgeSecondsSpinner.setSelection( purgeAgeTimeSpan.getSeconds() );
// Purge interval time span
PurgeTimeSpan purgeIntervalTimeSpan = new PurgeTimeSpan( accessLogPurgeValues[1] );
purgeIntervalDaysSpinner.setSelection( purgeIntervalTimeSpan.getDays() );
purgeIntervalHoursSpinner.setSelection( purgeIntervalTimeSpan.getHours() );
purgeIntervalMinutesSpinner.setSelection( purgeIntervalTimeSpan.getMinutes() );
purgeIntervalSecondsSpinner.setSelection( purgeIntervalTimeSpan.getSeconds() );
}
catch ( ParseException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
// We didn't have 2 members in the string
// TODO error
}
}
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
// Database
overlay.setOlcAccessLogDB( databaseEntryWidget.getDn() );
// Only log successful requests
overlay.setOlcAccessLogSuccess( onlyLogSuccessfulRequestsCheckbox.getSelection() );
// Log operations
overlay.setOlcAccessLogOps( getAccessLogOperationsValues() );
// Attributes
overlay.setOlcAccessLogOldAttr( attributes );
// Filter
overlay.setOlcAccessLogOld( filterWidget.getFilter() );
// Purge
overlay.setOlcAccessLogPurge( getPurgeValue() );
}
// Saving dialog settings
databaseEntryWidget.saveDialogSettings();
filterWidget.saveDialogSettings();
}
/**
* Gets the access log operations values.
*
* @return the access log operations values
*/
private List<String> getAccessLogOperationsValues()
{
List<String> accessLogOperations = new ArrayList<>();
List<LogOperationEnum> logOperations = logOperationsWidget.getSelectedOperationsList();
for ( LogOperationEnum logOperation : logOperations )
{
// Converting log operation to string
accessLogOperations.add( logOperation.toString() );
}
return accessLogOperations;
}
/**
* Gets the access log operations.
*
* @return the access log operations
*/
private List<LogOperationEnum> getAccessLogOperations( List<String> logOperationsValues )
{
List<LogOperationEnum> logOperations = new ArrayList<>();
for ( String logOperationValue : logOperationsValues )
{
// Converting log operation from a string
LogOperationEnum logOperation = LogOperationEnum.fromString( logOperationValue );
if ( logOperation != null )
{
logOperations.add( logOperation );
}
}
return logOperations;
}
/**
* Gets the purge value.
*
* @return the purge value
*/
private String getPurgeValue()
{
return getPurgeAgeTimeSpan().toString() + " " + getPurgeIntervalTimeSpan().toString();
}
/**
* Gets the purge age time span.
*
* @return the purge age time span
*/
private PurgeTimeSpan getPurgeAgeTimeSpan()
{
PurgeTimeSpan purgeAgeTimeSpan = new PurgeTimeSpan();
purgeAgeTimeSpan.setDays( purgeAgeDaysSpinner.getSelection() );
purgeAgeTimeSpan.setHours( purgeAgeHoursSpinner.getSelection() );
purgeAgeTimeSpan.setMinutes( purgeAgeMinutesSpinner.getSelection() );
purgeAgeTimeSpan.setSeconds( purgeAgeSecondsSpinner.getSelection() );
return purgeAgeTimeSpan;
}
/**
* Gets the purge interval time span.
*
* @return the purge interval time span
*/
private PurgeTimeSpan getPurgeIntervalTimeSpan()
{
PurgeTimeSpan purgeInternalTimeSpan = new PurgeTimeSpan();
purgeInternalTimeSpan.setDays( purgeIntervalDaysSpinner.getSelection() );
purgeInternalTimeSpan.setHours( purgeIntervalHoursSpinner.getSelection() );
purgeInternalTimeSpan.setMinutes( purgeIntervalMinutesSpinner.getSelection() );
purgeInternalTimeSpan.setSeconds( purgeIntervalSecondsSpinner.getSelection() );
return purgeInternalTimeSpan;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/ValueSortingOverlayConfigurationBlock.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/overlays/ValueSortingOverlayConfigurationBlock.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.openldap.config.editor.dialogs.overlays;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.apache.directory.studio.openldap.common.ui.dialogs.AttributeDialog;
import org.apache.directory.studio.openldap.config.editor.dialogs.AbstractOverlayDialogConfigurationBlock;
import org.apache.directory.studio.openldap.config.editor.dialogs.OverlayDialog;
import org.apache.directory.studio.openldap.config.editor.dialogs.ValueSortingValueDialog;
import org.apache.directory.studio.openldap.config.model.overlay.OlcValSortConfig;
/**
* This class implements a block for the configuration of the Value Sorting overlay.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ValueSortingOverlayConfigurationBlock extends
AbstractOverlayDialogConfigurationBlock<OlcValSortConfig>
{
/** The value sorts list */
private List<String> valueSorts = new ArrayList<>();
// UI widgets
private TableViewer valueSortsTableViewer;
private Button addValueSortButton;
private Button editValueSortButton;
private Button deleteValueSortButton;
// Listeners
private ISelectionChangedListener valueSortsTableViewerSelectionChangedListener = event ->
deleteValueSortButton.setEnabled( !valueSortsTableViewer.getSelection().isEmpty() );
private IDoubleClickListener valueSortsTableViewerDoubleClickListener = event -> editValueSortButtonAction();
private SelectionListener addValueSortButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
ValueSortingValueDialog dialog = new ValueSortingValueDialog( addValueSortButton.getShell(),
browserConnection, "" );
if ( dialog.open() == AttributeDialog.OK )
{
String value = dialog.getValue();
valueSorts.add( value );
valueSortsTableViewer.refresh();
valueSortsTableViewer.setSelection( new StructuredSelection( value ) );
}
}
};
private SelectionListener editValueSortButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
editValueSortButtonAction();
}
};
private SelectionListener deleteValueSortButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
StructuredSelection selection = ( StructuredSelection ) valueSortsTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedAttribute = ( String ) selection.getFirstElement();
valueSorts.remove( selectedAttribute );
valueSortsTableViewer.refresh();
}
}
};
public ValueSortingOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection )
{
super( dialog, connection );
setOverlay( new OlcValSortConfig() );
}
public ValueSortingOverlayConfigurationBlock( OverlayDialog dialog, IBrowserConnection connection,
OlcValSortConfig overlay )
{
super( dialog, connection );
if ( overlay == null )
{
setOverlay( new OlcValSortConfig() );
}
else
{
setOverlay( overlay );
}
}
/**
* {@inheritDoc}
*/
public void createBlockContent( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
// Value Sorts
BaseWidgetUtils.createLabel( composite, "Value Sorts:", 1 );
Composite valueSortsComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
// Value Sorts TableViewer
valueSortsTableViewer = new TableViewer( valueSortsComposite );
GridData tableViewerGridData = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 );
tableViewerGridData.heightHint = 20;
tableViewerGridData.widthHint = 100;
valueSortsTableViewer.getControl().setLayoutData( tableViewerGridData );
valueSortsTableViewer.setContentProvider( new ArrayContentProvider() );
valueSortsTableViewer.setInput( valueSorts );
valueSortsTableViewer.addSelectionChangedListener( valueSortsTableViewerSelectionChangedListener );
valueSortsTableViewer.addDoubleClickListener( valueSortsTableViewerDoubleClickListener );
// Value Sort Add Button
addValueSortButton = BaseWidgetUtils.createButton( valueSortsComposite, "Add...", 1 );
addValueSortButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
addValueSortButton.addSelectionListener( addValueSortButtonSelectionListener );
// Value Sort Add Button
editValueSortButton = BaseWidgetUtils.createButton( valueSortsComposite, "Edit...", 1 );
editValueSortButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
editValueSortButton.addSelectionListener( editValueSortButtonSelectionListener );
// Value Sort Delete Button
deleteValueSortButton = BaseWidgetUtils.createButton( valueSortsComposite, "Delete", 1 );
deleteValueSortButton.setEnabled( false );
deleteValueSortButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) );
deleteValueSortButton.addSelectionListener( deleteValueSortButtonSelectionListener );
}
/**
* Action launched when the edit value sort button is clicked, or
* when the value sorts table viewer is double-clicked.
*/
private void editValueSortButtonAction()
{
StructuredSelection selection = ( StructuredSelection ) valueSortsTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String selectedValueSort = ( String ) selection.getFirstElement();
ValueSortingValueDialog dialog = new ValueSortingValueDialog( addValueSortButton.getShell(),
browserConnection, selectedValueSort );
if ( dialog.open() == AttributeDialog.OK )
{
String value = dialog.getValue();
int index = valueSorts.indexOf( selectedValueSort );
valueSorts.remove( selectedValueSort );
valueSorts.add( index, value );
valueSortsTableViewer.refresh();
valueSortsTableViewer.setSelection( new StructuredSelection( value ) );
}
}
}
/**
* {@inheritDoc}
*/
public void refresh()
{
if ( overlay != null )
{
valueSorts.clear();
List<String> olcValSortAttr = overlay.getOlcValSortAttr();
if ( olcValSortAttr != null )
{
for ( String value : olcValSortAttr )
{
valueSorts.add( value );
}
}
valueSortsTableViewer.refresh();
}
}
/**
* {@inheritDoc}
*/
public void save()
{
if ( overlay != null )
{
overlay.clearOlcValSortAttr();
for ( String valueSort : valueSorts )
{
overlay.addOlcValSortAttr( valueSort );
}
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/EditorImportConfigurationAction.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/EditorImportConfigurationAction.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.openldap.config.actions;
import java.io.File;
import org.apache.directory.studio.common.ui.CommonUIUtils;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
import org.apache.directory.studio.openldap.config.model.OpenLdapConfiguration;
import org.apache.directory.studio.openldap.config.model.io.ConfigurationReader;
/**
* This class implements the create connection action for an OpenLDAP server.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorImportConfigurationAction extends Action
{
/** The associated editor */
private OpenLdapServerConfigurationEditor editor;
/**
* Creates a new instance of EditorImportConfigurationAction.
*
* @param editor
* the associated editor
*/
public EditorImportConfigurationAction( OpenLdapServerConfigurationEditor editor )
{
this.editor = editor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return OpenLdapConfigurationPlugin.getDefault().getImageDescriptor(
OpenLdapConfigurationPluginConstants.IMG_IMPORT );
}
/**
* {@inheritDoc}
*/
public String getText()
{
return "Import Configuration";
}
/**
* {@inheritDoc}
*/
public void run()
{
try
{
// Checking if the editor has unsaved modifications
if ( editor.isDirty() )
{
// Requiring a confirmation from the user before discarding the unsaved modifications
if ( !MessageDialog
.openConfirm(
editor.getSite().getShell(),
"Unsaved Modifications",
"The configuration has unsaved modifications. All recent changes will be lost. Are you sure you want to continue?" ) )
{
return;
}
}
// The path of the directory
String path = null;
// Opening a dialog for directory selection
DirectoryDialog dialog = new DirectoryDialog( editor.getSite().getShell() );
dialog.setText( "Select Configuration Directory" );
dialog.setFilterPath( System.getProperty( "user.home" ) );
while ( true )
{
// Opening the dialog
path = dialog.open();
// Checking the returned path
if ( path == null )
{
// Cancel button has been clicked
return;
}
// Getting the directory indicated by the user
final File directory = new File( path );
// Checking if the directory exists
if ( !directory.exists() )
{
CommonUIUtils.openErrorDialog( "The directory does not exist." );
continue;
}
// Checking if the location is a directory
if ( !directory.isDirectory() )
{
CommonUIUtils.openErrorDialog( "The location is not a directory." );
continue;
}
// Checking if the directory is writable
if ( !directory.canRead() )
{
CommonUIUtils.openErrorDialog( "The directory is not writable." );
continue;
}
// The directory meets all requirements
break;
}
// Checking the directory
File configurationDirectory = new File( path );
if ( !configurationDirectory.exists() || !configurationDirectory.isDirectory()
|| !configurationDirectory.canRead() )
{
// This is not a valid directory
return;
}
// Requiring a confirmation from the user
if ( !MessageDialog
.openConfirm(
editor.getSite().getShell(),
"Overwrite Existing Configuration",
"Are you sure you want to overwrite the existing configuration with the contents of the selected file?" ) )
{
return;
}
// Reading the configuration of the file
OpenLdapConfiguration configuration = ConfigurationReader.readConfiguration( configurationDirectory );
// Resetting the configuration back to the editor
editor.resetConfiguration( configuration );
}
catch ( Exception e )
{
MessageDialog
.openError(
editor.getSite().getShell(),
"Error Importing Configuration File",
NLS.bind(
"An error occurred when importing the selected file:\n{0}\n\nIt does not seem to be a correct LDIF configuration file.",
e.getMessage() ) );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/OpenDirectoryConfigurationAction.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/OpenDirectoryConfigurationAction.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.openldap.config.actions;
import java.io.File;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.apache.directory.studio.openldap.config.editor.DirectoryServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
/**
* This class implements the action that opens a directory based OpenLDAP configuration
* (asking the user the location of the 'slapd.d' directory).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OpenDirectoryConfigurationAction extends Action implements IWorkbenchWindowActionDelegate
{
/** The window */
private IWorkbenchWindow window;
/**
* {@inheritDoc}
*/
public void init( IWorkbenchWindow window )
{
this.window = window;
}
/**
* {@inheritDoc}
*/
public void run( IAction action )
{
// Creating a directory dialog for the user
// to select the "slapd.d" directory
DirectoryDialog dialog = new DirectoryDialog( window.getShell(), SWT.OPEN );
dialog.setText( "Choose 'slapd.d' folder..." );
dialog.setFilterPath( System.getProperty( "user.home" ) );
// Getting the directory selected by the user
String selectedDirectory = dialog.open();
if ( selectedDirectory != null )
{
try
{
window.getActivePage().openEditor( new DirectoryServerConfigurationInput( new File(
selectedDirectory ) ), OpenLdapServerConfigurationEditor.ID );
}
catch ( PartInitException e )
{
// Should never happen
}
}
}
/**
* {@inheritDoc}
*/
public void selectionChanged( IAction action, ISelection selection )
{
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
public void dispose()
{
// TODO Auto-generated method stub
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/OpenConfigurationAction.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/OpenConfigurationAction.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.openldap.config.actions;
import org.apache.directory.studio.connection.core.Connection;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.apache.directory.studio.openldap.config.editor.ConnectionServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
/**
* This class implements the action which open the OpenLDAP configuration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OpenConfigurationAction implements IObjectActionDelegate
{
/** The selected connection */
private Connection selectedConnection;
/**
* {@inheritDoc}
*/
public void run( IAction action )
{
if ( selectedConnection != null )
{
try
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.openEditor( new ConnectionServerConfigurationInput( selectedConnection ),
OpenLdapServerConfigurationEditor.ID );
}
catch ( Exception e )
{
// Will never occur.
}
}
}
/**
* {@inheritDoc}
*/
public void selectionChanged( IAction action, ISelection selection )
{
StructuredSelection structuredSelection = ( StructuredSelection ) selection;
if ( ( structuredSelection.size() == 1 ) && ( structuredSelection.getFirstElement() instanceof Connection ) )
{
selectedConnection = ( Connection ) structuredSelection.getFirstElement();
}
else
{
selectedConnection = null;
}
}
/**
* {@inheritDoc}
*/
public void setActivePart( IAction action, IWorkbenchPart targetPart )
{
// Nothing to do
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/EditorExportConfigurationAction.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/actions/EditorExportConfigurationAction.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.openldap.config.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.osgi.util.NLS;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPlugin;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditorUtils;
/**
* This class implements the create connection action for an OpenLDAP server.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditorExportConfigurationAction extends Action
{
/** The associated editor */
private OpenLdapServerConfigurationEditor editor;
/**
* Creates a new instance of EditorExportConfigurationAction.
*
* @param editor
* the associated editor
*/
public EditorExportConfigurationAction( OpenLdapServerConfigurationEditor editor )
{
this.editor = editor;
}
/**
* {@inheritDoc}
*/
@Override
public ImageDescriptor getImageDescriptor()
{
return OpenLdapConfigurationPlugin.getDefault().getImageDescriptor(
OpenLdapConfigurationPluginConstants.IMG_EXPORT );
}
/**
* {@inheritDoc}
*/
@Override
public String getText()
{
return "Export Configuration";
}
/**
* {@inheritDoc}
*/
@Override
public void run()
{
try
{
OpenLdapServerConfigurationEditorUtils.saveAs( editor.getConfiguration(), editor.getSite()
.getShell(), false );
}
catch ( Exception e )
{
MessageDialog.openError( editor.getSite().getShell(), "Error Exporting Configuration File",
NLS.bind( "An error occurred when exporting the selected file:\n{0}", e.getMessage() ) );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/wizards/NewOpenLdapConfigurationFileWizard.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/wizards/NewOpenLdapConfigurationFileWizard.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.openldap.config.wizards;
import org.apache.directory.studio.ldapbrowser.common.dialogs.preferences.AttributeValueEditorDialog;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginConstants;
import org.apache.directory.studio.openldap.config.editor.NewServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
import org.apache.directory.studio.openldap.config.editor.dialogs.OpenLdapConfigDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
/**
* This class implements the New OpenLDAP Configuration File Wizard.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewOpenLdapConfigurationFileWizard extends Wizard implements INewWizard
{
/** The window. */
private IWorkbenchWindow window;
/**
* Creates a new instance of NewOpenLDAPConfigurationFileWizard.
*/
public NewOpenLdapConfigurationFileWizard()
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench, IStructuredSelection selection )
{
window = workbench.getActiveWorkbenchWindow();
}
/**
* {@inheritDoc}
*/
public void dispose()
{
window = null;
}
/**
* Gets the id.
*
* @return the id
*/
public static String getId()
{
return OpenLdapConfigurationPluginConstants.WIZARD_NEW_OPENLDAP_CONFIG;
}
/**
* {@inheritDoc}
*/
public void addPages()
{
// This wizard has no page
}
/**
* {@inheritDoc}
*/
public boolean performFinish()
{
try
{
OpenLdapConfigDialog dialog = new OpenLdapConfigDialog( getShell() );
if ( dialog.open() == AttributeValueEditorDialog.OK )
{
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
NewServerConfigurationInput configInput = new NewServerConfigurationInput();
configInput.setOpenLdapConfigFormat( dialog.getOpenLdapConfigFormat() );
configInput.setOpenLdapVersion( dialog.getOpenLdapVersion() );
page.openEditor( configInput, OpenLdapServerConfigurationEditor.ID );
}
}
catch ( PartInitException e )
{
// Should never happen
return false;
}
return true;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/wizards/Messages.java | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/wizards/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.openldap.config.wizards;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
private static final String BUNDLE_NAME = "org.apache.directory.studio.openldap.config.wizards"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME );
private Messages()
{
}
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/RepairAction.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/RepairAction.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.ldapservers.apacheds;
import org.apache.directory.studio.ldapservers.jobs.StudioLdapServerJob;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.model.LdapServerStatus;
import org.apache.directory.studio.ldapservers.views.ServersView;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
/**
* This class implements the repair action for an ApacheDS 2.0.0 server.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RepairAction implements IObjectActionDelegate
{
/** The {@link ServersView} */
private ServersView view;
@Override
public void run( IAction action )
{
LdapServer server = getSelectedServer();
if ( server != null )
{
// Checking that the server is really an ApacheDS 2.0.0 server
if ( !ExtensionUtils.verifyApacheDs200OrPrintError( server, view ) )
{
return;
}
// Creating and scheduling the job to start the server
StudioLdapServerJob job = new StudioLdapServerJob( new RepairRunnable( server ) );
job.schedule();
}
}
/**
* {@inheritDoc}
*/
public void selectionChanged( IAction action, ISelection selection )
{
LdapServer server = getSelectedServer();
action.setEnabled( server != null && server.getStatus() == LdapServerStatus.STOPPED );
}
/**
* {@inheritDoc}
*/
public void setActivePart( IAction action, IWorkbenchPart targetPart )
{
// Storing the Servers view
if ( targetPart instanceof ServersView )
{
view = ( ServersView ) targetPart;
}
}
private LdapServer getSelectedServer()
{
if ( view != null )
{
// Getting the selection
StructuredSelection selection = ( StructuredSelection ) view.getViewer().getSelection();
if ( ( !selection.isEmpty() ) && ( selection.size() == 1 ) )
{
// Getting the server
LdapServer server = ( LdapServer ) selection.getFirstElement();
return server;
}
}
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/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/Messages.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapservers.apacheds;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* This class get messages from the resources file.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class Messages
{
/** The resource name */
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle( Messages.class.getPackage().getName() + ".messages" );
/**
* Get back a message from the resource file given a key
*
* @param key The key associated with the message
* @return The found message
*/
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/CreateConnectionAction.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/CreateConnectionAction.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.ldapservers.apacheds;
import org.apache.directory.server.config.beans.ConfigBean;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.apache.directory.studio.connection.core.ConnectionParameter.AuthenticationMethod;
import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod;
import org.apache.directory.studio.connection.core.ConnectionServerType;
import org.apache.directory.studio.connection.core.DetectedConnectionProperties;
import org.apache.directory.studio.connection.core.PasswordsKeyStoreManager;
import org.apache.directory.studio.connection.ui.PasswordsKeyStoreManagerUtils;
import org.apache.directory.studio.ldapservers.actions.CreateConnectionActionHelper;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.views.ServersView;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
/**
* This class implements the create connection action for an ApacheDS 2.0.0 server.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class CreateConnectionAction implements IObjectActionDelegate
{
/** The {@link ServersView} */
private ServersView view;
/**
* {@inheritDoc}
*/
public void run( IAction action )
{
if ( view != null )
{
// Getting the selection
StructuredSelection selection = ( StructuredSelection ) view.getViewer().getSelection();
if ( ( !selection.isEmpty() ) && ( selection.size() == 1 ) )
{
// Getting the server
LdapServer server = ( LdapServer ) selection.getFirstElement();
// Checking that the server is really an ApacheDS 2.0.0 server
if(!ExtensionUtils.verifyApacheDs200OrPrintError( server, view )) {
return;
}
// Parsing the 'config.ldif' file
ConfigBean configuration = null;
try
{
configuration = ApacheDS200LdapServerAdapter.getServerConfiguration( server ).getConfigBean();
}
catch ( Exception e )
{
String message = Messages.getString( "CreateConnectionAction.UnableReadServerConfiguration" ) //$NON-NLS-1$
+ "\n\n" //$NON-NLS-1$
+ Messages.getString( "CreateConnectionAction.FollowingErrorOccurred" ) + e.getMessage(); //$NON-NLS-1$
reportErrorReadingServerConfiguration( view, message );
return;
}
// Checking if we could read the 'server.xml' file
if ( configuration == null )
{
reportErrorReadingServerConfiguration( view,
Messages.getString( "CreateConnectionAction.UnableReadServerConfiguration" ) ); //$NON-NLS-1$
return;
}
// Checking is LDAP and/or LDAPS is/are enabled
if ( ( ApacheDS200LdapServerAdapter.isEnableLdap( configuration ) )
|| ( ApacheDS200LdapServerAdapter.isEnableLdaps( configuration ) ) )
{
// Creating the connection using the helper class
createConnection( server, configuration );
}
else
{
// LDAP and LDAPS protocols are disabled, we report this error to the user
MessageDialog dialog = new MessageDialog( view.getSite().getShell(),
Messages.getString( "CreateConnectionAction.UnableCreateConnection" ), null, //$NON-NLS-1$
Messages.getString( "CreateConnectionAction.LDAPAndLDAPSDisabled" ), MessageDialog.ERROR, //$NON-NLS-1$
new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
}
}
}
}
/**
* Reports to the user an error message indicating the server
* configuration could not be read correctly.
*
* @param message
* the message
*/
private void reportErrorReadingServerConfiguration( ServersView view, String message )
{
MessageDialog dialog = new MessageDialog( view.getSite().getShell(),
Messages.getString( "CreateConnectionAction.UnableReadServerConfiguration" ), //$NON-NLS-1$
null, message, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
}
/**
* Creates the connection
*/
private void createConnection( LdapServer server, ConfigBean configuration )
{
// Creating the connection parameter object
ConnectionParameter connectionParameter = new ConnectionParameter();
// Authentication method
connectionParameter.setAuthMethod( AuthenticationMethod.SIMPLE );
// LDAP or LDAPS?
if ( ApacheDS200LdapServerAdapter.isEnableLdap( configuration ) )
{
connectionParameter.setEncryptionMethod( EncryptionMethod.NONE );
connectionParameter.setPort( ApacheDS200LdapServerAdapter.getLdapPort( configuration ) );
}
else if ( ApacheDS200LdapServerAdapter.isEnableLdaps( configuration ) )
{
connectionParameter.setEncryptionMethod( EncryptionMethod.LDAPS );
connectionParameter.setPort( ApacheDS200LdapServerAdapter.getLdapsPort( configuration ) );
}
// Bind password
// Checking of the connection passwords keystore is enabled
if ( PasswordsKeyStoreManagerUtils.isPasswordsKeystoreEnabled() )
{
// Getting the password keystore manager
PasswordsKeyStoreManager passwordsKeyStoreManager = ConnectionCorePlugin.getDefault()
.getPasswordsKeyStoreManager();
// Checking if the keystore is loaded
if ( passwordsKeyStoreManager.isLoaded() )
{
passwordsKeyStoreManager.storeConnectionPassword( connectionParameter.getId(), "secret" ); //$NON-NLS-1$
}
else
{
// Asking the user to load the keystore
if ( PasswordsKeyStoreManagerUtils.askUserToLoadKeystore() )
{
passwordsKeyStoreManager.storeConnectionPassword( connectionParameter.getId(), "secret" ); //$NON-NLS-1$
}
}
}
else
{
connectionParameter.setBindPassword( "secret" ); //$NON-NLS-1$
}
// Bind principal
connectionParameter.setBindPrincipal( "uid=admin,ou=system" ); //$NON-NLS-1$
// Host
connectionParameter.setHost( "localhost" ); //$NON-NLS-1$
// Name
connectionParameter.setName( server.getName() );
// Extended Properties
connectionParameter.setExtendedProperty( DetectedConnectionProperties.CONNECTION_PARAMETER_SERVER_TYPE,
ConnectionServerType.APACHEDS.toString() );
connectionParameter.setExtendedProperty( DetectedConnectionProperties.CONNECTION_PARAMETER_VENDOR_NAME,
"Apache Software Foundation" ); //$NON-NLS-1$
connectionParameter.setExtendedProperty( DetectedConnectionProperties.CONNECTION_PARAMETER_VENDOR_VERSION,
"2.0.0" ); //$NON-NLS-1$
// Creating the connection
CreateConnectionActionHelper.createLdapBrowserConnection( server, new Connection( connectionParameter ) );
}
/**
* {@inheritDoc}
*/
public void selectionChanged( IAction action, ISelection selection )
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
public void setActivePart( IAction action, IWorkbenchPart targetPart )
{
// Storing the Servers view
if ( targetPart instanceof ServersView )
{
view = ( ServersView ) targetPart;
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ApacheDS200LdapServerAdapter.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ApacheDS200LdapServerAdapter.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.ldapservers.apacheds;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.server.config.beans.ChangePasswordServerBean;
import org.apache.directory.server.config.beans.ConfigBean;
import org.apache.directory.server.config.beans.DirectoryServiceBean;
import org.apache.directory.server.config.beans.DnsServerBean;
import org.apache.directory.server.config.beans.KdcServerBean;
import org.apache.directory.server.config.beans.LdapServerBean;
import org.apache.directory.server.config.beans.NtpServerBean;
import org.apache.directory.server.config.beans.TransportBean;
import org.apache.directory.studio.apacheds.configuration.ApacheDS2ConfigurationPluginConstants;
import org.apache.directory.studio.apacheds.configuration.editor.Configuration;
import org.apache.directory.studio.apacheds.configuration.editor.ServerConfigurationEditor;
import org.apache.directory.studio.apacheds.configuration.jobs.LoadConfigurationRunnable;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.common.ui.filesystem.PathEditorInput;
import org.apache.directory.studio.ldapservers.LdapServersManager;
import org.apache.directory.studio.ldapservers.LdapServersUtils;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.model.LdapServerAdapter;
import org.apache.directory.studio.ldapservers.model.LdapServerStatus;
import org.apache.mina.util.AvailablePortFinder;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
/**
* This class implements an LDAP Server Adapter for ApacheDS version 2.0.0.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ApacheDS200LdapServerAdapter implements LdapServerAdapter
{
// Various strings constants used in paths
private static final String LOG4J_PROPERTIES = "log4j.properties"; //$NON-NLS-1$
private static final String RESOURCES = "resources"; //$NON-NLS-1$
private static final String LIBS = "libs"; //$NON-NLS-1$
private static final String CONF = "conf"; //$NON-NLS-1$
/** The array of libraries names */
private static final String[] libraries = new String[]
{ "apacheds-service.jar" }; //$NON-NLS-1$
private enum Action {
START, REPAIR, STOP;
}
/**
* {@inheritDoc}
*/
public void add( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Getting the bundle associated with the plugin
Bundle bundle = ApacheDS200Plugin.getDefault().getBundle();
// Verifying and copying ApacheDS 2.0.0 libraries
LdapServersUtils.verifyAndCopyLibraries( bundle, new Path( RESOURCES ).append( LIBS ),
getServerLibrariesFolder(), libraries, monitor,
Messages.getString( "ApacheDS200LdapServerAdapter.VerifyingAndCopyingLibraries" ) ); //$NON-NLS-1$
// Creating server folder structure
monitor.subTask( Messages.getString( "ApacheDS200LdapServerAdapter.CreatingServerFolderStructure" ) ); //$NON-NLS-1$
File serverFolder = LdapServersManager.getServerFolder( server ).toFile();
File confFolder = new File( serverFolder, CONF );
confFolder.mkdir();
File ldifFolder = new File( serverFolder, "ldif" ); //$NON-NLS-1$
ldifFolder.mkdir();
File logFolder = new File( serverFolder, "log" ); //$NON-NLS-1$
logFolder.mkdir();
File partitionFolder = new File( serverFolder, "partitions" ); //$NON-NLS-1$
partitionFolder.mkdir();
// Copying configuration files
monitor.subTask( Messages.getString( "ApacheDS200LdapServerAdapter.CopyingConfigurationFiles" ) ); //$NON-NLS-1$
IPath resourceConfFolderPath = new Path( RESOURCES ).append( CONF );
// call of getServerConfiguration() extracts the default configuration
getServerConfiguration( server );
LdapServersUtils.copyResource( bundle, resourceConfFolderPath.append( LOG4J_PROPERTIES ), new File( confFolder,
LOG4J_PROPERTIES ) );
// Creating an empty log file
new File( logFolder, "apacheds.log" ).createNewFile(); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void delete( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Nothing to do (nothing more than the default behavior of
// the delete action before this method is called)
}
/**
* {@inheritDoc}
*/
public void openConfiguration( final LdapServer server, final StudioProgressMonitor monitor ) throws Exception
{
// Opening the editor
Display.getDefault().syncExec( new Runnable()
{
public void run()
{
try
{
PathEditorInput input = new PathEditorInput( LdapServersManager.getServerFolder( server )
.append( CONF ).append( ApacheDS2ConfigurationPluginConstants.OU_CONFIG_LDIF ) );
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.openEditor( input, ServerConfigurationEditor.ID );
}
catch ( PartInitException e )
{
monitor.reportError( e );
}
}
} );
}
/**
* {@inheritDoc}
*/
public void start( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
ILaunch launch = startOrRepair( server, monitor, Action.START );
// Storing the launch configuration as a custom object in the LDAP Server for later use
server.putCustomObject( LdapServersUtils.LAUNCH_CONFIGURATION_CUSTOM_OBJECT, launch );
// Running the startup listener watchdog
LdapServersUtils.runStartupListenerWatchdog( server, getTestingPort( server ) );
}
/**
* Starts the ApacheDS in "repair" mode
*
* @param server
* the server
* @param monitor
* the progress monitor
* @throws Exception
* if an error occurs when starting the server
*/
public void repair( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// repair
startOrRepair( server, monitor, Action.REPAIR );
// Await termination of the repair action
long startTime = System.currentTimeMillis();
final long watchDog = startTime + ( 1000 * 60 * 3 ); // 3 minutes
do
{
Thread.sleep( 1000 );
}
while ( ( System.currentTimeMillis() < watchDog ) && ( LdapServerStatus.REPAIRING == server.getStatus() ) );
// stop the console printer thread
LdapServersUtils.stopConsolePrinterThread( server );
}
private ILaunch startOrRepair( LdapServer server, StudioProgressMonitor monitor, Action action ) throws Exception
{
// Getting the bundle associated with the plugin
Bundle bundle = ApacheDS200Plugin.getDefault().getBundle();
// Verifying and copying ApacheDS 2.0.0 libraries
LdapServersUtils.verifyAndCopyLibraries( bundle, new Path( RESOURCES ).append( LIBS ),
getServerLibrariesFolder(), libraries, monitor,
Messages.getString( "ApacheDS200LdapServerAdapter.VerifyingAndCopyingLibraries" ) ); //$NON-NLS-1$
// Starting the console printer thread
LdapServersUtils.startConsolePrinterThread( server, LdapServersManager.getServerFolder( server )
.append( "log" ) //$NON-NLS-1$
.append( "apacheds.log" ).toFile() );//$NON-NLS-1$
// Launching ApacheDS
ILaunch launch = launchApacheDS( server, action );
return launch;
}
/**
* Launches ApacheDS using a launch configuration.
*
* @param server
* the server
* @param repair
* true to launch ApacheDS in repair mode
* @return
* the associated launch
*/
private static ILaunch launchApacheDS( LdapServer server, Action action )
throws Exception
{
// Getting the default VM installation
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
// Creating a new editable launch configuration
ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurationType( IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION );
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance( null, server.getId() );
// Setting the JRE container path attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, vmInstall
.getInstallLocation().toString() );
// Setting the main type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
"org.apache.directory.server.UberjarMain" ); //$NON-NLS-1$
// Creating the classpath list
List<String> classpath = new ArrayList<String>();
for ( String library : libraries )
{
IRuntimeClasspathEntry libraryClasspathEntry = JavaRuntime
.newArchiveRuntimeClasspathEntry( getServerLibrariesFolder().append( library ) );
libraryClasspathEntry.setClasspathProperty( IRuntimeClasspathEntry.USER_CLASSES );
classpath.add( libraryClasspathEntry.getMemento() );
}
// Setting the classpath type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath );
// Setting the default classpath type attribute to false
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false );
// The server folder path
IPath serverFolderPath = LdapServersManager.getServerFolder( server );
// Creating the program arguments string
StringBuffer programArguments = new StringBuffer();
programArguments.append( "\"" + serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( action == Action.REPAIR )
{
programArguments.append( " " );
programArguments.append( "\"repair\"" );
}
else if ( action == Action.STOP )
{
programArguments.append( " " );
programArguments.append( "\"stop\"" );
}
// Setting the program arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
programArguments.toString() );
// Creating the VM arguments string
StringBuffer vmArguments = new StringBuffer();
vmArguments.append( "-Dlog4j.configuration=file:\"" //$NON-NLS-1$
+ serverFolderPath.append( CONF ).append( LOG4J_PROPERTIES ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.var.dir=\"" + serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.log.dir=\"" + serverFolderPath.append( "log" ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.instance=\"" + server.getName() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.controls=" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.extendedOperations=" ); // $NON-NLS-1$
// Setting the VM arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, vmArguments.toString() );
// Setting the launch configuration as private
workingCopy.setAttribute( IDebugUIConstants.ATTR_PRIVATE, true );
// Indicating that we don't want any console to show up
workingCopy.setAttribute( DebugPlugin.ATTR_CAPTURE_OUTPUT, false );
// Saving the launch configuration
ILaunchConfiguration configuration = workingCopy.doSave();
// Launching the launch configuration
ILaunch launch = configuration.launch( ILaunchManager.RUN_MODE, new NullProgressMonitor() );
// Starting the "terminate" listener thread
LdapServersUtils.startTerminateListenerThread( server, launch );
return launch;
}
/**
* {@inheritDoc}
*/
public void stop( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Graceful stop ApacheDS
launchApacheDS( server, Action.STOP );
// Await termination of the server
long startTime = System.currentTimeMillis();
final long watchDog = startTime + ( 1000 * 60 * 3 ); // 3 minutes
do
{
Thread.sleep( 1000 );
}
while ( ( System.currentTimeMillis() < watchDog ) && ( LdapServerStatus.STOPPING == server.getStatus() ) );
// Stopping the console printer thread
LdapServersUtils.stopConsolePrinterThread( server );
// Terminating the launch configuration
LdapServersUtils.terminateLaunchConfiguration( server );
}
/**
* Gets the path to the server libraries folder.
*
* @return
* the path to the server libraries folder
*/
private static IPath getServerLibrariesFolder()
{
return ApacheDS200Plugin.getDefault().getStateLocation().append( LIBS );
}
/**
* Gets the server configuration.
*
* @param server
* the server
* @return
* the associated server configuration
* @throws Exception
* @throws ServerXmlIOException
* @throws FileNotFoundException
*/
public static Configuration getServerConfiguration( LdapServer server ) throws Exception
{
File configFile = LdapServersManager.getServerFolder( server ).append( CONF )
.append( ApacheDS2ConfigurationPluginConstants.OU_CONFIG_LDIF ).toFile();
return LoadConfigurationRunnable.readConfiguration( configFile );
}
/**
* Gets the testing port.
*
* @param configuration
* the 1.5.6 server configuration
* @return
* the testing port
* @throws Exception
* @throws ServerXmlIOException
*/
private int getTestingPort( LdapServer server ) throws Exception
{
ConfigBean configuration = getServerConfiguration( server ).getConfigBean();
// LDAP
if ( isEnableLdap( configuration ) )
{
return getLdapPort( configuration );
}
// LDAPS
else if ( isEnableLdaps( configuration ) )
{
return getLdapsPort( configuration );
}
// Kerberos
else if ( isEnableKerberos( configuration ) )
{
return getKerberosPort( configuration );
}
// DNS
else if ( isEnableDns( configuration ) )
{
return getDnsPort( configuration );
}
// NTP
else if ( isEnableNtp( configuration ) )
{
return getNtpPort( configuration );
}
// ChangePassword
else if ( isEnableChangePassword( configuration ) )
{
return getChangePasswordPort( configuration );
}
else
{
return 0;
}
}
/**
* Indicates if the LDAP Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the LDAP Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableLdap( ConfigBean configuration )
{
TransportBean ldapServerTransportBean = getLdapServerTransportBean( configuration );
if ( ldapServerTransportBean != null )
{
return ldapServerTransportBean.isEnabled();
}
return false;
}
/**
* Indicates if the LDAPS Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the LDAPS Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableLdaps( ConfigBean configuration )
{
TransportBean ldapsServerTransportBean = getLdapsServerTransportBean( configuration );
if ( ldapsServerTransportBean != null )
{
return ldapsServerTransportBean.isEnabled();
}
return false;
}
/**
* Gets the LDAP Server transport bean.
*
* @param configuration the configuration
* @return the LDAP Server transport bean.
*/
private static TransportBean getLdapServerTransportBean( ConfigBean configuration )
{
return getLdapServerTransportBean( configuration, "ldap" ); //$NON-NLS-1$
}
/**
* Gets the LDAPS Server transport bean.
*
* @param configuration the configuration
* @return the LDAPS Server transport bean.
*/
private static TransportBean getLdapsServerTransportBean( ConfigBean configuration )
{
return getLdapServerTransportBean( configuration, "ldaps" ); //$NON-NLS-1$
}
/**
* Gets the corresponding LDAP Server transport bean.
*
* @param configuration the configuration
* @param id the id
* @return the corresponding LDAP Server transport bean.
*/
private static TransportBean getLdapServerTransportBean( ConfigBean configuration, String id )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
LdapServerBean ldapServerBean = directoryServiceBean.getLdapServerBean();
if ( ldapServerBean != null )
{
// Looking for the transport in the list
TransportBean[] ldapServerTransportBeans = ldapServerBean.getTransports();
if ( ldapServerTransportBeans != null )
{
for ( TransportBean ldapServerTransportBean : ldapServerTransportBeans )
{
if ( id.equals( ldapServerTransportBean.getTransportId() ) )
{
return ldapServerTransportBean;
}
}
}
}
}
return null;
}
/**
* Indicates if the Kerberos Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the Kerberos Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableKerberos( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
KdcServerBean kdcServerBean = directoryServiceBean.getKdcServerBean();
if ( kdcServerBean != null )
{
kdcServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the DNS Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the DNS Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableDns( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
DnsServerBean dnsServerBean = directoryServiceBean.getDnsServerBean();
if ( dnsServerBean != null )
{
dnsServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the NTP Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the NTP Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableNtp( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
NtpServerBean ntpServerBean = directoryServiceBean.getNtpServerBean();
if ( ntpServerBean != null )
{
ntpServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the Change Password Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the Change Password Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableChangePassword( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
ChangePasswordServerBean changePasswordServerBean = directoryServiceBean.getChangePasswordServerBean();
if ( changePasswordServerBean != null )
{
changePasswordServerBean.isEnabled();
}
}
return false;
}
/**
* Gets the LDAP port.
*
* @param configuration the configuration
* @return the LDAP port
*/
public static int getLdapPort( ConfigBean configuration )
{
TransportBean ldapServerTransportBean = getLdapServerTransportBean( configuration );
if ( ldapServerTransportBean != null )
{
return ldapServerTransportBean.getSystemPort();
}
return 0;
}
/**
* Gets the LDAPS port.
*
* @param configuration the configuration
* @return the LDAPS port
*/
public static int getLdapsPort( ConfigBean configuration )
{
TransportBean ldapsServerTransportBean = getLdapsServerTransportBean( configuration );
if ( ldapsServerTransportBean != null )
{
return ldapsServerTransportBean.getSystemPort();
}
return 0;
}
/**
* Gets the Kerberos port.
*
* @param configuration the configuration
* @return the Kerberos port
*/
public static int getKerberosPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
KdcServerBean kdcServerBean = directoryServiceBean.getKdcServerBean();
if ( kdcServerBean != null )
{
// Looking for the transport in the list
TransportBean[] kdcServerTransportBeans = kdcServerBean.getTransports();
if ( kdcServerTransportBeans != null )
{
for ( TransportBean kdcServerTransportBean : kdcServerTransportBeans )
{
if ( ( "tcp".equals( kdcServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( kdcServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return kdcServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the DNS port.
*
* @param configuration the configuration
* @return the DNS port
*/
public static int getDnsPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
DnsServerBean dnsServerBean = directoryServiceBean.getDnsServerBean();
if ( dnsServerBean != null )
{
// Looking for the transport in the list
TransportBean[] dnsServerTransportBeans = dnsServerBean.getTransports();
if ( dnsServerTransportBeans != null )
{
for ( TransportBean dnsServerTransportBean : dnsServerTransportBeans )
{
if ( ( "tcp".equals( dnsServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( dnsServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return dnsServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the NTP port.
*
* @param configuration the configuration
* @return the NTP port
*/
public static int getNtpPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
NtpServerBean ntpServerBean = directoryServiceBean.getNtpServerBean();
if ( ntpServerBean != null )
{
// Looking for the transport in the list
TransportBean[] ntpServerTransportBeans = ntpServerBean.getTransports();
if ( ntpServerTransportBeans != null )
{
for ( TransportBean ntpServerTransportBean : ntpServerTransportBeans )
{
if ( ( "tcp".equals( ntpServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( ntpServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return ntpServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the Change Password port.
*
* @param configuration the configuration
* @return the Change Password port
*/
public static int getChangePasswordPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
ChangePasswordServerBean changePasswordServerBean = directoryServiceBean.getChangePasswordServerBean();
if ( changePasswordServerBean != null )
{
// Looking for the transport in the list
TransportBean[] changePasswordServerTransportBeans = changePasswordServerBean.getTransports();
if ( changePasswordServerTransportBeans != null )
{
for ( TransportBean changePasswordServerTransportBean : changePasswordServerTransportBeans )
{
if ( ( "tcp".equals( changePasswordServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( changePasswordServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return changePasswordServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* {@inheritDoc}
*/
public String[] checkPortsBeforeServerStart( LdapServer server ) throws Exception
{
List<String> alreadyInUseProtocolPortsList = new ArrayList<String>();
ConfigBean configuration = getServerConfiguration( server ).getConfigBean();
// LDAP
if ( isEnableLdap( configuration ) )
{
if ( !AvailablePortFinder.available( getLdapPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.LDAPPort" ), new Object[] { getLdapPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// LDAPS
if ( isEnableLdaps( configuration ) )
{
if ( !AvailablePortFinder.available( getLdapsPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.LDAPSPort" ), new Object[] { getLdapsPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// Kerberos
if ( isEnableKerberos( configuration ) )
{
if ( !AvailablePortFinder.available( getKerberosPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS
.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.KerberosPort" ), new Object[] { getKerberosPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// DNS
if ( isEnableDns( configuration ) )
{
if ( !AvailablePortFinder.available( getDnsPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.DNSPort" ), new Object[] { getDnsPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// NTP
if ( isEnableNtp( configuration ) )
{
if ( !AvailablePortFinder.available( getNtpPort( configuration ) ) )
{
alreadyInUseProtocolPortsList.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.NTPPort" ), new Object[] //$NON-NLS-1$
{ getNtpPort( configuration ) } ) );
}
}
// Change Password
if ( isEnableChangePassword( configuration ) )
{
if ( !AvailablePortFinder.available( getChangePasswordPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS
.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.ChangePasswordPort" ), new Object[] { getChangePasswordPort( configuration ) } ) ); //$NON-NLS-1$
}
}
return alreadyInUseProtocolPortsList.toArray( new String[0] );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ApacheDS200Plugin.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ApacheDS200Plugin.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.ldapservers.apacheds;
import java.io.IOException;
import java.net.URL;
import java.util.PropertyResourceBundle;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class ApacheDS200Plugin extends AbstractUIPlugin
{
/** The shared plugin instance. */
private static ApacheDS200Plugin plugin;
/** The plugin properties */
private PropertyResourceBundle properties;
/**
* The constructor
*/
public ApacheDS200Plugin()
{
plugin = this;
}
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
}
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop( BundleContext context ) throws Exception
{
plugin = null;
super.stop( context );
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static ApacheDS200Plugin getDefault()
{
return plugin;
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* BrowserWidgetsConstants for the key.
*
* @param key
* The key (relative path to the image in filesystem)
* @return The image descriptor or null
*/
public ImageDescriptor getImageDescriptor( String key )
{
if ( key != null )
{
URL url = FileLocator.find( getBundle(), new Path( key ), null );
if ( url != null )
return ImageDescriptor.createFromURL( url );
else
return null;
}
else
{
return null;
}
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* BrowserWidgetsConstants for the key. A ImageRegistry is used to manage the
* the key->Image mapping.
* <p>
* Note: Don't dispose the returned SWT Image. It is disposed
* automatically when the plugin is stopped.
*
* @param key
* The key (relative path to the image in filesystem)
* @return The SWT Image or null
*/
public Image getImage( String key )
{
Image image = getImageRegistry().get( key );
if ( image == null )
{
ImageDescriptor id = getImageDescriptor( key );
if ( id != null )
{
image = id.createImage();
getImageRegistry().put( key, image );
}
}
return image;
}
/**
* Gets the plugin properties.
*
* @return
* the plugin properties
*/
public PropertyResourceBundle getPluginProperties()
{
if ( properties == null )
{
try
{
properties = new PropertyResourceBundle( FileLocator.openStream( this.getBundle(), new Path(
"plugin.properties" ), false ) ); //$NON-NLS-1$
}
catch ( IOException e )
{
// We can't use the PLUGIN_ID constant since loading the plugin.properties file has failed,
// So we're using a default plugin id.
getLog().log(
new Status( Status.ERROR, "org.apache.directory.studio.ldapservers.apacheds", Status.OK, //$NON-NLS-1$
Messages.getString( "ApacheDS200Plugin.UnableGetPluginProperties" ), e ) ); //$NON-NLS-1$
}
}
return properties;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ExtensionUtils.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/ExtensionUtils.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.ldapservers.apacheds;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.views.ServersView;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ExtensionUtils
{
private static final String EXTENSION_ID = "org.apache.directory.server.2.0.0"; //$NON-NLS-1$
public static boolean verifyApacheDs200OrPrintError( LdapServer server, ServersView view )
{
// Checking that the server is really an ApacheDS 2.0.0 server
if ( !EXTENSION_ID.equalsIgnoreCase( server.getLdapServerAdapterExtension().getId() ) )
{
String message = Messages.getString( "CreateConnectionAction.UnableReadServerConfiguration" ) //$NON-NLS-1$
+ "\n\n" //$NON-NLS-1$
+ Messages.getString( "CreateConnectionAction.NotA200Server" ); //$NON-NLS-1$
reportErrorReadingServerConfiguration( view, message );
return false;
}
else
{
return true;
}
}
/**
* Reports to the user an error message indicating the server
* configuration could not be read correctly.
*
* @param message
* the message
*/
private static void reportErrorReadingServerConfiguration( ServersView view, String message )
{
MessageDialog dialog = new MessageDialog( view.getSite().getShell(),
Messages.getString( "CreateConnectionAction.UnableReadServerConfiguration" ), //$NON-NLS-1$
null, message, MessageDialog.ERROR, new String[]
{ IDialogConstants.OK_LABEL }, MessageDialog.OK );
dialog.open();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/RepairRunnable.java | plugins/ldapservers.apacheds/src/main/java/org/apache/directory/studio/ldapservers/apacheds/RepairRunnable.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.ldapservers.apacheds;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.common.core.jobs.StudioRunnableWithProgress;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.model.LdapServerStatus;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
/**
* This class implements a {@link Job} that is used to repair the partitions.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RepairRunnable implements StudioRunnableWithProgress
{
/** The server */
private LdapServer server;
/**
* Creates a new instance of StartLdapServerRunnable.
*
* @param server
* the LDAP Server
*/
public RepairRunnable( LdapServer server )
{
this.server = server;
}
/**
* {@inheritDoc}
*/
public String getErrorMessage()
{
return NLS.bind( Messages.getString( "RepairRunnable.UnableToRepair" ), new String[] //$NON-NLS-1$
{ server.getName() } );
}
/**
* {@inheritDoc}
*/
public Object[] getLockedObjects()
{
return new Object[]
{ server };
}
/**
* {@inheritDoc}
*/
public String getName()
{
return NLS.bind( Messages.getString( "RepairRunnable.Repair" ), new String[] //$NON-NLS-1$
{ server.getName() } );
}
/**
* {@inheritDoc}
*/
public void run( StudioProgressMonitor monitor )
{
// Setting the status on the server to 'repairing'
server.setStatus( LdapServerStatus.REPAIRING );
try
{
ApacheDS200LdapServerAdapter adapter = new ApacheDS200LdapServerAdapter();
adapter.repair( server, monitor );
}
catch ( Exception e )
{
// Setting the server as stopped
server.setStatus( LdapServerStatus.STOPPED );
// Reporting the error to the monitor
monitor.reportError( 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/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioRunnableWithProgress.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioRunnableWithProgress.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.common.core.jobs;
/**
* A runnable with a progress monitor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface StudioRunnableWithProgress
{
/**
* Runs the runnable.
*
* @param monitor the monitor
*/
void run( StudioProgressMonitor monitor );
/**
* Gets the locked objects.
*
* @return the locked objects
*/
Object[] getLockedObjects();
/**
* Gets the error message.
*
* @return the error message
*/
String getErrorMessage();
/**
* Gets the name that is used when reporting progress.
*
* @return the name
*/
String getName();
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/CommonCorePlugin.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/CommonCorePlugin.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.common.core.jobs;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class CommonCorePlugin extends Plugin
{
/** The shared plugin instance. */
private static CommonCorePlugin plugin;
/** The watcher job */
private StudioProgressMonitorWatcherJob studioProgressMonitorWatcherJob;
/**
* The default constructor for this class
*/
public CommonCorePlugin()
{
super();
plugin = this;
}
/**
* @see Plugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start( BundleContext context ) throws Exception
{
super.start( context );
studioProgressMonitorWatcherJob = new StudioProgressMonitorWatcherJob();
studioProgressMonitorWatcherJob.setSystem( true );
studioProgressMonitorWatcherJob.schedule();
}
/**
* @see Plugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop( BundleContext context ) throws Exception
{
plugin = null;
studioProgressMonitorWatcherJob.stop();
studioProgressMonitorWatcherJob = null;
super.stop( context );
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static CommonCorePlugin getDefault()
{
return plugin;
}
/**
* @return The watcher job
*/
public StudioProgressMonitorWatcherJob getStudioProgressMonitorWatcherJob()
{
return studioProgressMonitorWatcherJob;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/Messages.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.common.core.jobs;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* This class get messages from the resources file.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class Messages
{
/** The resource name */
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle( Messages.class.getPackage().getName() + ".messages" );
/**
* private constructor
*/
private Messages()
{
}
/**
* Get back a message from the resource file given a key
*
* @param key The key associated with the message
* @return The found message
*/
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/CommonCoreConstants.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/CommonCoreConstants.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.common.core.jobs;
/**
* Constants used in the Apache Directory Studio Common Core plugin.
* Final reference -> class shouldn't be extended
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class CommonCoreConstants
{
/** The plug-in ID */
public static final String PLUGIN_ID = CommonCoreConstants.class.getPackage().getName();
/** The Job family ID */
public static final String JOB_FAMILY_ID = PLUGIN_ID + ".family"; //$NON-NLS-1$
/**
* Ensures no construction of this class, also ensures there is no need for final keyword above
* (Implicit super constructor is not visible for default constructor),
* but is still self documenting.
*/
private CommonCoreConstants()
{
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioRunnableWithProgressAdapter.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioRunnableWithProgressAdapter.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.common.core.jobs;
/**
* An adapter class for StudioRunnableWithProgress.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class StudioRunnableWithProgressAdapter implements StudioRunnableWithProgress
{
/** The locked objects */
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/**
* @return an empty array
*/
public Object[] getLockedObjects()
{
return EMPTY_OBJECT_ARRAY;
}
/**
* @return empty string
*/
public String getErrorMessage()
{
return ""; //$NON-NLS-1$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioJob.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioJob.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.common.core.jobs;
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 StudioJob<T extends StudioRunnableWithProgress> extends Job
{
/** The runnables. */
protected T[] runnables;
/**
* Creates a new instance of StudioJob.
*
* @param runnables the runnables to run
*/
public StudioJob( T... runnables )
{
super( runnables[0].getName() );
this.runnables = runnables;
}
/**
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
protected IStatus run( IProgressMonitor ipm )
{
StudioProgressMonitor monitor = new StudioProgressMonitor( ipm );
// Execute job
if ( !monitor.errorsReported() )
{
try
{
for ( StudioRunnableWithProgress runnable : runnables )
{
if ( runnable instanceof StudioBulkRunnableWithProgress )
{
StudioBulkRunnableWithProgress bulkRunnable = ( StudioBulkRunnableWithProgress ) 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()
{
// Default implementation does nothing.
}
/**
* Resumes event firing in current thread.
*/
protected void resumeEventFiringInCurrentThread()
{
// Default implementation does nothing.
}
/**
* Executes the job.
*/
public void execute()
{
setUser( true );
schedule();
}
/**
* {@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 ( T runnable : runnables )
{
Object[] myLockedObjects = runnable.getLockedObjects();
String[] myLockedObjectsIdentifiers = getLockIdentifiers( myLockedObjects );
Job[] jobs = getJobManager().find( null );
for ( Job job : jobs )
{
if ( job instanceof StudioJob )
{
@SuppressWarnings("unchecked")
StudioJob<StudioRunnableWithProgress> otherJob = ( StudioJob<StudioRunnableWithProgress> ) job;
for ( StudioRunnableWithProgress otherRunnable : otherJob.runnables )
{
if ( ( runnable.getClass() == otherRunnable.getClass() ) && ( runnable != otherRunnable ) )
{
Object[] otherLockedObjects = otherRunnable.getLockedObjects();
String[] otherLockedObjectIdentifiers = getLockIdentifiers( otherLockedObjects );
for ( String other : otherLockedObjectIdentifiers )
{
for ( String myLockedObjectIdentifier : myLockedObjectsIdentifiers )
{
if ( other.startsWith( myLockedObjectIdentifier ) || myLockedObjectIdentifier.startsWith( other ) )
{
return false;
}
}
}
}
}
}
}
}
return super.shouldSchedule();
}
/**
* Gets the string identifiers for the given objects.
*
* @param objects the objects
* @return the string identifiers associated with the objects
*/
protected String[] getLockIdentifiers( Object... objects )
{
String[] identifiers = new String[objects.length];
for ( int i = 0; i < identifiers.length; i++ )
{
identifiers[i] = getLockIdentifier( objects[i] );
}
return identifiers;
}
/**
* Gets the generic lock identifier for an object.
*
* @param object the object
* @return the lock identifier for the object
*/
private String getLockIdentifier( Object object )
{
if ( object == null )
{
return "null";
}
else
{
return object.toString();
}
}
/**
* {@inheritDoc}
*/
public boolean belongsTo( Object family )
{
return getFamily().equals( family );
}
/**
* Get the object corresponding to the family of the Job.
*
* @return the object corresponding to the family of the Job
*/
public Object getFamily()
{
return CommonCoreConstants.JOB_FAMILY_ID;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioProgressMonitorWatcherJob.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioProgressMonitorWatcherJob.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.common.core.jobs;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
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 that watches the {@link StudioProgressMonitor}s.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StudioProgressMonitorWatcherJob extends Job
{
/** The running flag */
private final AtomicBoolean running;
/** The list of active monitors being watched */
private final ConcurrentLinkedQueue<StudioProgressMonitor> monitors;
/**
* The constructor
*/
public StudioProgressMonitorWatcherJob()
{
super( Messages.getString( "StudioProgressMonitor.CheckCancellation" ) );
running = new AtomicBoolean( true );
monitors = new ConcurrentLinkedQueue<StudioProgressMonitor>();
}
/**
* Set the running flag to false
*/
public void stop()
{
running.set( false );
}
/**
* Add a new monitor to the list of monitors being watched
*
* @param monitor The monitor to add
*/
public void addMonitor( StudioProgressMonitor monitor )
{
monitors.add( monitor );
}
/**
* {@inheritDoc}
*/
@Override
protected IStatus run( IProgressMonitor monitor )
{
while ( running.get() )
{
for ( Iterator<StudioProgressMonitor> it = monitors.iterator(); it.hasNext(); )
{
StudioProgressMonitor next = it.next();
StudioProgressMonitor spm = next;
do
{
// reset allow message reporting
if ( !spm.isCanceled() && !spm.isDone )
{
spm.allowMessageReporting.set( true );
}
// check if canceled
if ( spm.isCanceled() )
{
spm.fireCancelRequested();
}
if ( spm.isCanceled() || spm.isDone )
{
it.remove();
break;
}
if ( spm.getWrappedProgressMonitor() instanceof StudioProgressMonitor )
{
spm = ( StudioProgressMonitor ) spm.getWrappedProgressMonitor();
}
else
{
spm = null;
}
}
while ( spm != null );
}
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException e )
{
}
}
return Status.OK_STATUS;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioBulkRunnableWithProgress.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioBulkRunnableWithProgress.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.common.core.jobs;
/**
* 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 StudioBulkRunnableWithProgress extends StudioRunnableWithProgress
{
/**
* 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/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioProgressMonitor.java | plugins/common.core/src/main/java/org/apache/directory/studio/common/core/jobs/StudioProgressMonitor.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.common.core.jobs;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.ProgressMonitorWrapper;
import org.eclipse.core.runtime.Status;
/**
* The StudioProgressMonitor extends the the Eclipse
* Progress Monitor with active cancellation capabilities.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StudioProgressMonitor extends ProgressMonitorWrapper
{
/** The plugin ID */
protected String pluginId;
/** The flag indicating if the work is done */
protected boolean isDone;
/** The list of error statuses */
protected List<Status> errorStatusList;
/** The list of cancel listeners */
protected List<CancelListener> cancelListenerList;
/** Flag to indicate if message reporting is allowed. Whenever reporting a mesasage
* this flag is set to false. The {@link StudioProgressMonitorWatcherJob} is resetting
* it to true once a second. This way too many updates are prevented. */
protected AtomicBoolean allowMessageReporting;
/**
* Creates a new instance of ExtendedProgressMonitor.
*
* @param monitor the progress monitor to forward to
*/
public StudioProgressMonitor( IProgressMonitor monitor )
{
this( CommonCoreConstants.PLUGIN_ID, monitor );
}
/**
* Creates a new instance of ExtendedProgressMonitor.
*
* @param pluginId the identifier of the plugin, used to report errors
* @param monitor the progress monitor to forward to
*/
public StudioProgressMonitor( String pluginId, IProgressMonitor monitor )
{
super( monitor );
this.pluginId = pluginId;
isDone = false;
CommonCorePlugin.getDefault().getStudioProgressMonitorWatcherJob().addMonitor(this);
allowMessageReporting = new AtomicBoolean( true );
}
/**
* @see org.eclipse.core.runtime.ProgressMonitorWrapper#setCanceled(boolean)
*/
public void setCanceled( boolean canceled )
{
super.setCanceled( canceled );
if ( canceled )
{
fireCancelRequested();
}
}
/**
* @see org.eclipse.core.runtime.ProgressMonitorWrapper#done()
*/
public void done()
{
synchronized ( this )
{
isDone = true;
super.done();
}
}
/**
* Adds the cancel listener.
*
* @param listener the listener
*/
public void addCancelListener( CancelListener listener )
{
if ( cancelListenerList == null )
{
cancelListenerList = new ArrayList<CancelListener>();
}
if ( !cancelListenerList.contains( listener ) )
{
cancelListenerList.add( listener );
}
}
/**
* Removes the cancel listener.
*
* @param listener the listener
*/
public void removeCancelListener( CancelListener listener )
{
if ( ( cancelListenerList != null ) && cancelListenerList.contains( listener ) )
{
cancelListenerList.remove( listener );
}
}
/* Package protected */void fireCancelRequested()
{
CancelEvent event = new CancelEvent( this );
if ( cancelListenerList != null )
{
for ( CancelListener cancelListener : cancelListenerList )
{
cancelListener.cancelRequested( event );
}
}
}
/**
* Report progress.
*
* @param message the message
*/
public void reportProgress( String message )
{
boolean doReport = allowMessageReporting.getAndSet( false );
if ( doReport )
{
subTask( message );
}
}
/**
* Report error.
*
* @param message the message
*/
public void reportError( String message )
{
reportError( message, null );
}
/**
* Report error.
*
* @param exception the exception
*/
public void reportError( Exception exception )
{
reportError( null, exception );
}
/**
* Report error.
*
* @param message the message
* @param exception the exception
*/
public void reportError( String message, Exception exception )
{
if ( errorStatusList == null )
{
errorStatusList = new ArrayList<Status>( 3 );
}
if ( message == null )
{
message = ""; //$NON-NLS-1$
}
Status errorStatus = new Status( IStatus.ERROR, pluginId, IStatus.ERROR, message, exception );
errorStatusList.add( errorStatus );
}
/**
* Errors reported.
*
* @return true, if errors reported
*/
public boolean errorsReported()
{
return errorStatusList != null;
}
/**
* Gets the error status.
*
* @param message the message
*
* @return the error status
*/
public IStatus getErrorStatus( String message )
{
if ( ( errorStatusList == null ) || errorStatusList.isEmpty() )
{
if ( isCanceled() )
{
return Status.CANCEL_STATUS;
}
else
{
return Status.OK_STATUS;
}
}
else
{
StringBuilder buffer = new StringBuilder();
buffer.append( message );
// append status messages to message
for ( Status status : errorStatusList )
{
String statusMessage = status.getMessage();
Throwable exception = status.getException();
String exceptionMessage = null;
if ( exception != null)
{
exceptionMessage = exception.getMessage();
}
// append explicit status message
if ( !StringUtils.isEmpty( statusMessage ) )
{
buffer.append( "\n - " ).append( statusMessage );
}
// append exception message if different to status message
if ( (exception != null ) && ( exceptionMessage != null ) && !exceptionMessage.equals( statusMessage ) )
{
// strip control characters
int indexOfAny = StringUtils.indexOfAny( exceptionMessage, "\n\r\t" ); //$NON-NLS-1$
if ( indexOfAny > -1 )
{
exceptionMessage = exceptionMessage.substring( 0, indexOfAny );
}
buffer.append( "\n - " ).append( exceptionMessage ); //$NON-NLS-1$
}
}
// create main status
MultiStatus multiStatus = new MultiStatus( pluginId, IStatus.ERROR, buffer.toString(), null );
// append child status
for ( Status status : errorStatusList )
{
String statusMessage = status.getMessage();
if ( status.getException() != null )
{
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter( stringWriter );
status.getException().printStackTrace( printWriter );
statusMessage = stringWriter.toString();
}
multiStatus.add( new Status( status.getSeverity(), status.getPlugin(), status.getCode(), statusMessage,
status.getException() ) );
}
return multiStatus;
}
}
/**
* Gets the exception.
*
* @return the exception
*/
public Exception getException()
{
if ( errorStatusList != null )
{
return ( Exception ) errorStatusList.get( 0 ).getException();
}
return null;
}
/**
* Resets this status.
*/
public void reset()
{
isDone = false;
errorStatusList = null;
}
/**
* CancelEvent.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public static class CancelEvent
{
/** The Monitor used by the Cancel Event */
private IProgressMonitor monitor;
/**
* Creates a new instance of CancelEvent.
*
* @param monitor the progress monitor
*/
public CancelEvent( IProgressMonitor monitor )
{
this.monitor = monitor;
}
/**
* Gets the monitor.
*
* @return the progress monitor
*/
public IProgressMonitor getMonitor()
{
return monitor;
}
}
/**
* CancelListener.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface CancelListener
{
/**
* Cancel requested.
*
* @param event the event
*/
void cancelRequested( CancelEvent event );
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ExceptionHandler.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ExceptionHandler.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.ui;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Display;
/**
* This class is used to handle exceptions thrown at runtime.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ExceptionHandler
{
/**
* Opens an error dialog to display the given error.
*
* @param status
* the error to show to the user
*/
public void handleException( IStatus status )
{
display( null, status );
}
/**
* Opens an error dialog to display the given error.
*
* @param message
* the message to show in this dialog, or null to indicate that the error's message should be shown as the primary message
* @param status
* the error to show to the user
*/
private void display( final String message, final IStatus status )
{
if ( Thread.currentThread() == Display.getDefault().getThread() )
{
ErrorDialog.openError( Display.getDefault().getActiveShell(),
Messages.getString( "ExceptionHandler.Error" ), message, status ); //$NON-NLS-1$
}
else
{
Runnable runnable = () ->
ErrorDialog.openError( Display.getDefault().getActiveShell(), Messages
.getString( "ExceptionHandler.Error" ), message, status ); //$NON-NLS-1$
Display.getDefault().asyncExec( runnable );
}
ConnectionCorePlugin.getDefault().getLog().log( status );
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIConstants.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIConstants.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.ui;
/**
* Constants used in the connection UI plugin.
* Final reference -> class shouldn't be extended
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class ConnectionUIConstants
{
/** The plug-in ID */
public static final String PLUGIN_ID = ConnectionUIConstants.class.getPackage().getName();
/** The dialog setting key used for the history of host names. */
public static final String DIALOGSETTING_KEY_HOST_HISTORY = "hostHistory"; //$NON-NLS-1$
/** The dialog setting key used for the history of ports. */
public static final String DIALOGSETTING_KEY_PORT_HISTORY = "portHistory"; //$NON-NLS-1$
/** The dialog setting key used for the history of principals (bind DNs). */
public static final String DIALOGSETTING_KEY_PRINCIPAL_HISTORY = "principalHistory"; //$NON-NLS-1$
/** The dialog setting key used for the history of SASL realms. */
public static final String DIALOGSETTING_KEY_REALM_HISTORY = "saslrealmHistory"; //$NON-NLS-1$
/** The certificate image */
public static final String IMG_CERTIFICATE = "resources/icons/certificate.gif"; //$NON-NLS-1$
/** The image to add a connection. */
public static final String IMG_CONNECTION_ADD = "resources/icons/connection_add.gif"; //$NON-NLS-1$
/** The image used to display the connected state of connections. */
public static final String IMG_CONNECTION_CONNECTED = "resources/icons/connection_connected.gif"; //$NON-NLS-1$
/** The image used to display the disconnected state of connections. */
public static final String IMG_CONNECTION_DISCONNECTED = "resources/icons/connection_disconnected.gif"; //$NON-NLS-1$
/** The image used to display the connected state of SSL connections. */
public static final String IMG_CONNECTION_SSL_CONNECTED = "resources/icons/connection_ssl_connected.gif"; //$NON-NLS-1$
/** The image used to display the disconnected state of SSL connections. */
public static final String IMG_CONNECTION_SSL_DISCONNECTED = "resources/icons/connection_ssl_disconnected.gif"; //$NON-NLS-1$
/** The image to connect connections. */
public static final String IMG_CONNECTION_CONNECT = "resources/icons/connection_connect.gif"; //$NON-NLS-1$
/** The image to disconnect connections. */
public static final String IMG_CONNECTION_DISCONNECT = "resources/icons/connection_disconnect.gif"; //$NON-NLS-1$
/** The new connection wizard image */
public static final String IMG_CONNECTION_WIZARD = "resources/icons/connection_wizard.gif"; //$NON-NLS-1$
/** The image used for connection folders. */
public static final String IMG_CONNECTION_FOLDER = "resources/icons/connection_folder.gif"; //$NON-NLS-1$
/** The image to add a connection folder. */
public static final String IMG_CONNECTION_FOLDER_ADD = "resources/icons/connection_folder_add.gif"; //$NON-NLS-1$
/** The expand all image */
public static final String IMG_EXPANDALL = "resources/icons/expandall.gif"; //$NON-NLS-1$
/** The collapse all image */
public static final String IMG_COLLAPSEALL = "resources/icons/collapseall.gif"; //$NON-NLS-1$
/** The export certificate wizard image */
public static final String IMG_CERTIFICATE_EXPORT_WIZARD = "resources/icons/certificate_export_wizard.gif"; //$NON-NLS-1$
/** The connection transfer typename */
public static final String TYPENAME = "org.apache.directory.studio.ldapbrowser.connection"; //$NON-NLS-1$
/** The COPY command */
public static final String CMD_COPY = "org.apache.directory.studio.ldapbrowser.action.copy"; //$NON-NLS-1$
/** The PASTE command */
public static final String CMD_PASTE = "org.apache.directory.studio.ldapbrowser.action.paste"; //$NON-NLS-1$
/** The DELETE command */
public static final String CMD_DELETE = "org.apache.directory.studio.ldapbrowser.action.delete"; //$NON-NLS-1$
/** The PROPERTIES command */
public static final String CMD_PROPERTIES = "org.apache.directory.studio.ldapbrowser.action.properties"; //$NON-NLS-1$
/** The new wizard/new connection connection */
public static final String NEW_WIZARD_NEW_CONNECTION = ConnectionUIPlugin.getDefault().getPluginProperties()
.getString( "NewWizards_NewConnectionWizard_id" ); //$NON-NLS-1$
/**
* Ensures no construction of this class, also ensures there is no need for final keyword above
* (Implicit super constructor is not visible for default constructor),
* but is still self documenting.
*/
private ConnectionUIConstants()
{
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIReferralHandler.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIReferralHandler.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.ui;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.directory.api.ldap.model.exception.LdapURLEncodingException;
import org.apache.directory.api.ldap.model.url.LdapUrl;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.IReferralHandler;
import org.apache.directory.studio.connection.core.Utils;
import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
import org.apache.directory.studio.connection.core.event.ConnectionUpdateAdapter;
import org.apache.directory.studio.connection.ui.dialogs.SelectReferralConnectionDialog;
import org.eclipse.ui.PlatformUI;
/**
* Default implementation of {@link IReferralHandler}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ConnectionUIReferralHandler extends ConnectionUpdateAdapter implements IReferralHandler
{
/** The referral URL to referral connection cache. */
private Map<String, Connection> referralUrlToReferralConnectionCache = new ConcurrentHashMap<>();
/**
* The constructor
*/
public ConnectionUIReferralHandler()
{
super();
ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionCorePlugin.getDefault().getEventRunner() );
}
/**
* {@inheritDoc}
*/
@Override
public void connectionClosed( Connection connection )
{
referralUrlToReferralConnectionCache.clear();
}
/**
* {@inheritDoc}
*/
public Connection getReferralConnection( final List<String> referralUrls )
{
final Connection[] referralConnections = new Connection[1];
try
{
// check cache
for ( String url : referralUrls )
{
String normalizedUrl = Utils.getSimpleNormalizedUrl( new LdapUrl( url ) );
if ( referralUrlToReferralConnectionCache.containsKey( normalizedUrl ) )
{
// check if referral connection exists in connection manager
Connection referralConnection = referralUrlToReferralConnectionCache.get( normalizedUrl );
Connection[] connections = ConnectionCorePlugin.getDefault().getConnectionManager()
.getConnections();
for ( Connection connection : connections )
{
if ( connection.equals( referralConnection ) )
{
return referralConnection;
}
}
// referral connection doesn't exist in connection manager, remove it from cache
referralUrlToReferralConnectionCache.remove( normalizedUrl );
}
}
// open dialog
PlatformUI.getWorkbench().getDisplay().syncExec( () ->
{
SelectReferralConnectionDialog dialog = new SelectReferralConnectionDialog( PlatformUI
.getWorkbench()
.getDisplay().getActiveShell(), referralUrls );
if ( dialog.open() == SelectReferralConnectionDialog.OK )
{
Connection connection = dialog.getReferralConnection();
referralConnections[0] = connection;
}
} );
// put to cache
if ( referralConnections[0] != null )
{
for ( String url : referralUrls )
{
String normalizedUrl = Utils.getSimpleNormalizedUrl( new LdapUrl( url ) );
referralUrlToReferralConnectionCache.put( normalizedUrl, referralConnections[0] );
}
}
}
catch ( LdapURLEncodingException luee )
{
// Will never occur
}
return referralConnections[0];
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/UiThreadEventRunner.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/UiThreadEventRunner.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.ui;
import org.apache.directory.studio.connection.core.event.EventRunnable;
import org.apache.directory.studio.connection.core.event.EventRunner;
import org.eclipse.swt.widgets.Display;
/**
* Implementation of {@link EventRunner} that executes an {@link EventRunnable}
* withing the SWT UI thread.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class UiThreadEventRunner implements EventRunner
{
/**
* {@inheritDoc}
*
* This implementation executes the given {@link EventRunnable} within
* the SWT UI thread.
*/
public void execute( EventRunnable runnable )
{
Display.getDefault().asyncExec( 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageManager.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.ui;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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.Platform;
import org.eclipse.core.runtime.Status;
/**
* The ConnectionParameterPageManager manages the {@link ConnectionParameterPage}s.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class ConnectionParameterPageManager
{
/**
* A private constructor to make this class an uitlity class
*/
private ConnectionParameterPageManager()
{
}
/**
* Gets the connection parameter pages by searching for connection parameter page
* extensions.
*
* @return the connection parameter pages
*/
public static ConnectionParameterPage[] getConnectionParameterPages()
{
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry.getExtensionPoint( "org.apache.directory.studio.connectionparameterpages" ); //$NON-NLS-1$
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
final Map<String, ConnectionParameterPage> pageMap = new ConcurrentHashMap<>();
// For each extension: instantiate the page
for ( IConfigurationElement member : members )
{
try
{
ConnectionParameterPage page = ( ConnectionParameterPage ) member.createExecutableExtension( "class" ); //$NON-NLS-1$
page.setPageId( member.getAttribute( "id" ) ); //$NON-NLS-1$
page.setPageName( member.getAttribute( "name" ) ); //$NON-NLS-1$
page.setPageDescription( member.getAttribute( "description" ) ); //$NON-NLS-1$
page.setPageDependsOnId( member.getAttribute( "dependsOnId" ) ); //$NON-NLS-1$
pageMap.put( page.getPageId(), page );
}
catch ( Exception e )
{
ConnectionUIPlugin
.getDefault()
.getLog()
.log(
new Status(
IStatus.ERROR,
ConnectionUIConstants.PLUGIN_ID,
1,
Messages.getString( "ConnectionParameterPageManager.UnableCreateConnectionParamPage" ) //$NON-NLS-1$
+ member.getAttribute( "class" ), //$NON-NLS-1$
e ) );
}
}
final ConnectionParameterPage[] pages = pageMap.values().toArray( new ConnectionParameterPage[0] );
Comparator<? super ConnectionParameterPage> pageComparator =
( ConnectionParameterPage page1, ConnectionParameterPage page2 ) ->
{
String dependsOnId1 = page1.getPageDependsOnId();
String dependsOnId2 = page2.getPageDependsOnId();
do
{
if ( ( dependsOnId1 == null ) && ( dependsOnId2 != null ) )
{
return -1;
}
else if ( ( dependsOnId2 == null ) && ( dependsOnId1 != null ) )
{
return 1;
}
else if ( ( dependsOnId1 != null ) && dependsOnId1.equals( page2.getPageId() ) )
{
return 1;
}
else if ( ( dependsOnId2 != null ) && dependsOnId2.equals( page1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId1 );
if ( ( page != null ) && !page.getPageDependsOnId().equals( dependsOnId1 ) )
{
dependsOnId1 = page.getPageDependsOnId();
}
else
{
dependsOnId1 = null;
}
}
while ( ( dependsOnId1 != null ) && !dependsOnId1.equals( page1.getPageId() ) );
dependsOnId1 = page1.getPageDependsOnId();
dependsOnId2 = page2.getPageDependsOnId();
do
{
if ( ( dependsOnId1 == null ) && ( dependsOnId2 != null ) )
{
return -1;
}
else if ( ( dependsOnId2 == null ) && ( dependsOnId1 != null ) )
{
return 1;
}
else if ( ( dependsOnId1 != null ) && dependsOnId1.equals( page2.getPageId() ) )
{
return 1;
}
else if ( ( dependsOnId2 != null ) && dependsOnId2.equals( page1.getPageId() ) )
{
return -1;
}
ConnectionParameterPage page = pageMap.get( dependsOnId2 );
if ( page == null )
{
dependsOnId2 = null;
}
else
{
dependsOnId2 = page.getPageDependsOnId();
}
}
while ( ( dependsOnId2 != null ) && !dependsOnId2.equals( page2.getPageId() ) );
return 0;
};
Arrays.sort( pages, pageComparator );
return pages;
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/Messages.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.connection.ui;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* This class get messages from the resources file.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class Messages
{
/** The resource name */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle( Messages.class.getPackage().getName() + ".messages" );
/**
* A private constructor : this is an utility class
*/
private Messages()
{
}
/**
* Get back a message from the resource file given a key
*
* @param key The key associated with the message
* @return The found message
*/
public static String getString( String key )
{
try
{
return RESOURCE_BUNDLE.getString( key );
}
catch ( MissingResourceException e )
{
return '!' + key + '!';
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/AbstractConnectionParameterPage.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/AbstractConnectionParameterPage.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.ui;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.swt.widgets.Composite;
/**
* Base implementation of ConnectionParameterPage.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractConnectionParameterPage implements ConnectionParameterPage
{
/** The page id. */
protected String pageId;
/** The page name. */
protected String pageName;
/** The page description. */
protected String pageDescription;
/** The page id this page depends on. */
protected String pageDependsOnId;
/** The runnable context. */
protected IRunnableContext runnableContext;
/** The connection parameter page modify listener. */
protected ConnectionParameterPageModifyListener connectionParameterPageModifyListener;
/** The message. */
protected String message;
/** The error message. */
protected String errorMessage;
/** The info message. */
protected String infoMessage;
/** The connection parameter. */
protected ConnectionParameter connectionParameter;
/**
* Sets the connection parameter page modify listener.
*
* @param listener the connection parameter page modify listener
*/
public void setConnectionParameterPageModifyListener( ConnectionParameterPageModifyListener listener )
{
this.connectionParameterPageModifyListener = listener;
}
/**
* Fires a connection page modified event when then page was modified.
*/
protected void fireConnectionPageModified()
{
connectionParameterPageModifyListener.connectionParameterPageModified();
}
/**
* Sets the runnable context.
*
* @param runnableContext the runnable context
*/
public void setRunnableContext( IRunnableContext runnableContext )
{
this.runnableContext = runnableContext;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getPageId()
*/
public String getPageId()
{
return pageId;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#setPageId(java.lang.String)
*/
public void setPageId( String pageId )
{
this.pageId = pageId;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getPageName()
*/
public String getPageName()
{
return pageName;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#setPageName(java.lang.String)
*/
public void setPageName( String pageName )
{
this.pageName = pageName;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getPageDescription()
*/
public String getPageDescription()
{
return pageDescription;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#setPageDescription(java.lang.String)
*/
public void setPageDescription( String pageDescription )
{
this.pageDescription = pageDescription;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getPageDependsOnId()
*/
public String getPageDependsOnId()
{
return pageDependsOnId;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#setPageDependsOnId(java.lang.String)
*/
public void setPageDependsOnId( String pageDependsOnId )
{
this.pageDependsOnId = pageDependsOnId;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getErrorMessage()
*/
public String getErrorMessage()
{
return errorMessage;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getMessage()
*/
public String getMessage()
{
return message;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#isValid()
*/
public boolean isValid()
{
return message == null && errorMessage == null;
}
/**
* @see org.apache.directory.studio.connection.ui.ConnectionParameterPage#getInfoMessage()
*/
public String getInfoMessage()
{
return infoMessage;
}
/**
* {@inheritDoc}
*/
public final void init( Composite parent, ConnectionParameterPageModifyListener listener,
ConnectionParameter parameter )
{
createComposite( parent );
if ( listener != null )
{
setConnectionParameterPageModifyListener( listener );
}
if ( parameter != null )
{
loadParameters( parameter );
}
initListeners();
connectionPageModified();
}
/**
* Called when an input field was modified.
*/
protected final void connectionPageModified()
{
validate();
fireConnectionPageModified();
}
/**
* Creates the composite.
*
* @param parent the parent
*/
protected abstract void createComposite( Composite parent );
/**
* Validates the input fields.
*/
protected abstract void validate();
/**
* Initializes the fields with the given parameters.
*
* @param parameter the connection parameter
*/
protected abstract void loadParameters( ConnectionParameter parameter );
/**
* Initializes the listeners.
*/
protected abstract void initListeners();
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUICertificateHandler.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUICertificateHandler.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.ui;
import java.security.cert.X509Certificate;
import java.util.Collection;
import org.apache.directory.api.ldap.model.exception.LdapTlsHandshakeFailCause;
import org.apache.directory.studio.connection.core.ICertificateHandler;
import org.apache.directory.studio.connection.ui.dialogs.CertificateTrustDialog;
import org.eclipse.ui.PlatformUI;
/**
* Default implementation of {@link ICertificateHandler}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ConnectionUICertificateHandler implements ICertificateHandler
{
/**
* {@inheritDoc}
*/
public TrustLevel verifyTrustLevel( final String host, final X509Certificate[] certChain,
final Collection<LdapTlsHandshakeFailCause> failCauses )
{
// open dialog
final TrustLevel[] trustLevel = new TrustLevel[1];
PlatformUI.getWorkbench().getDisplay().syncExec( () -> {
CertificateTrustDialog dialog = new CertificateTrustDialog( PlatformUI.getWorkbench().getDisplay()
.getActiveShell(), host, certChain, failCauses );
dialog.open();
trustLevel[0] = dialog.getTrustLevel();
} );
return trustLevel[0];
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/RunnableContextRunner.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/RunnableContextRunner.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.ui;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
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.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress;
import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.PlatformUI;
/**
* This class provides some convenience methods to execute a runnable within
* an {@link IRunnableContext}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RunnableContextRunner
{
private static List<Listener> listeners = new LinkedList<>();
private RunnableContextRunner()
{
// Nothing to do
}
/**
* Executes the given job within the given runnable context.
*
* @param runnable the runnable to execute
* @param runnableContext the runnable context or null to create a progress monitor dialog
* @param handleError true to handle errors
* @return the status
*/
public static IStatus execute( final StudioConnectionRunnableWithProgress runnable,
IRunnableContext runnableContext, boolean handleError )
{
if ( runnableContext == null )
{
runnableContext = PlatformUI.getWorkbench().getProgressService();
}
final StudioProgressMonitor[] spm = new StudioProgressMonitor[1];
IRunnableWithProgress runnableWithProgress = new IRunnableWithProgress()
{
public void run( IProgressMonitor monitor ) throws InterruptedException
{
spm[0] = new StudioProgressMonitor( monitor );
// ensure that connections are opened
Connection[] connections = runnable.getConnections();
if ( connections != null )
{
for ( Connection connection : connections )
{
if ( ( connection != null ) && !connection.getConnectionWrapper().isConnected() )
{
spm[0].setTaskName( Messages.bind( Messages.jobs__open_connections_task, new String[]
{ connection.getName() } ) );
spm[0].worked( 1 );
connection.getConnectionWrapper().connect( spm[0] );
if ( connection.getConnectionWrapper().isConnected() )
{
connection.getConnectionWrapper().bind( spm[0] );
}
if ( connection.getConnectionWrapper().isConnected() )
{
for ( IConnectionListener listener : ConnectionCorePlugin.getDefault()
.getConnectionListeners() )
{
listener.connectionOpened( connection, spm[0] );
}
ConnectionEventRegistry.fireConnectionOpened( connection, this );
}
}
}
}
if ( !spm[0].errorsReported() )
{
try
{
if ( runnable instanceof StudioConnectionBulkRunnableWithProgress )
{
StudioConnectionBulkRunnableWithProgress bulkRunnable = ( StudioConnectionBulkRunnableWithProgress ) runnable;
ConnectionEventRegistry.suspendEventFiringInCurrentThread();
try
{
bulkRunnable.run( spm[0] );
}
finally
{
ConnectionEventRegistry.resumeEventFiringInCurrentThread();
}
bulkRunnable.runNotification( spm[0] );
}
else
{
runnable.run( spm[0] );
}
}
catch ( Exception e )
{
spm[0].reportError( e );
}
finally
{
spm[0].done();
monitor.done();
}
}
}
};
try
{
runnableContext.run( true, true, runnableWithProgress );
}
catch ( Exception ex )
{
ConnectionUIPlugin
.getDefault()
.getExceptionHandler()
.handleException(
new Status( IStatus.ERROR, ConnectionUIConstants.PLUGIN_ID, IStatus.ERROR,
ex.getMessage() != null ? ex.getMessage() : StringUtils.EMPTY, ex ) ); //$NON-NLS-1$
}
IStatus status = spm[0].getErrorStatus( runnable.getErrorMessage() );
if ( ( handleError && !spm[0].isCanceled() ) && !status.isOK() )
{
ConnectionUIPlugin.getDefault().getExceptionHandler().handleException( status );
}
notifyDone( runnable, status );
return status;
}
public interface Listener
{
void done( StudioConnectionRunnableWithProgress runnable, IStatus status );
}
public synchronized static void addListener( Listener listener )
{
listeners.add( listener );
}
public synchronized static void removeListener( Listener listener )
{
listeners.remove( listener );
}
public synchronized static void notifyDone( StudioConnectionRunnableWithProgress runnable, IStatus status )
{
for ( Listener listener : listeners )
{
listener.done( runnable, status );
}
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/PasswordsKeyStoreManagerUtils.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/PasswordsKeyStoreManagerUtils.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.ui;
import java.security.KeyStoreException;
import org.apache.directory.studio.connection.core.ConnectionCoreConstants;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.ui.dialogs.PasswordDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
/**
* This class contains utility methods for the passwords keystore.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class PasswordsKeyStoreManagerUtils
{
/**
* A private constructor : this is an utility class
*/
private PasswordsKeyStoreManagerUtils()
{
}
/**
* Checks if the passwords keystore is enabled.
*
* @return <code>true</code> if the passwords keystore is enabled,
* <code>false</code> if not.
*/
public static boolean isPasswordsKeystoreEnabled()
{
return ConnectionCorePlugin.getDefault().getPluginPreferences()
.getInt(
ConnectionCoreConstants.PREFERENCE_CONNECTIONS_PASSWORDS_KEYSTORE ) == ConnectionCoreConstants.PREFERENCE_CONNECTIONS_PASSWORDS_KEYSTORE_ON;
}
/**
* Asks the user to load the keystore.
*
* @return <code>true</code> if the keystore was loaded,
* <code>false</code> if not.
*/
public static boolean askUserToLoadKeystore()
{
final boolean[] keystoreLoaded = new boolean[1];
keystoreLoaded[0] = false;
PlatformUI.getWorkbench().getDisplay().syncExec( () ->
{
while ( true )
{
// Getting the shell
Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
// We ask the user for the keystore password
PasswordDialog passwordDialog = new PasswordDialog( shell, Messages
.getString( "PasswordsKeyStoreManagerUtils.VerifyMasterPassword" ), //$NON-NLS-1$
Messages.getString( "PasswordsKeyStoreManagerUtils.PleaseEnterMasterPassword" ), null ); //$NON-NLS-1$
if ( passwordDialog.open() == PasswordDialog.CANCEL )
{
// The user cancelled the action
keystoreLoaded[0] = false;
return;
}
// Getting the password
String masterPassword = passwordDialog.getPassword();
// Checking the password
Exception checkPasswordException = null;
try
{
if ( ConnectionCorePlugin.getDefault().getPasswordsKeyStoreManager()
.checkMasterPassword( masterPassword ) )
{
keystoreLoaded[0] = true;
break;
}
}
catch ( KeyStoreException e )
{
checkPasswordException = e;
}
// Creating the message
String message = null;
if ( checkPasswordException == null )
{
message = Messages
.getString( "PasswordsKeyStoreManagerUtils.MasterPasswordVerificationFailed" ); //$NON-NLS-1$
}
else
{
message = Messages
.getString( "PasswordsKeyStoreManagerUtils.MasterPasswordVerificationFailedWithException" ) //$NON-NLS-1$
+ checkPasswordException.getMessage();
}
// We ask the user if he wants to retry to unlock the passwords keystore
MessageDialog errorDialog = new MessageDialog(
shell,
Messages.getString( "PasswordsKeyStoreManagerUtils.VerifyMasterPasswordFailed" ), null, message, //$NON-NLS-1$
MessageDialog.ERROR, new String[]
{
IDialogConstants.RETRY_LABEL,
IDialogConstants.CANCEL_LABEL },
0 );
if ( errorDialog.open() == MessageDialog.CANCEL )
{
// The user cancelled the action
keystoreLoaded[0] = false;
return;
}
}
} );
return keystoreLoaded[0];
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPage.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPage.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.ui;
import org.apache.directory.api.ldap.model.url.LdapUrl;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.swt.widgets.Composite;
/**
* An IConnectionParameterPage is used to add connection parameter pages
* to the connection wizard and the connection property page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface ConnectionParameterPage
{
/**
* Save the fields to the connection parameters.
*
* @param parameter the connection parameter
*/
void saveParameters( ConnectionParameter parameter );
/**
* Checks if is valid.
*
* @return true, if is valid
*/
boolean isValid();
/**
* Gets an error message that should be displayed
* to the user. Null means no error message so an
* existing error message should be cleared.
*
* @return the error message
*/
String getErrorMessage();
/**
* Gets a non-error message that should be displayed
* to the user. Null means no message so an existing
* message should be cleared.
*
* @return the message
*/
String getMessage();
/**
* Gets an info message that should be displayed
* to the user. Null means no info message so an
* existing info message should be cleared.
*
* @return the info message
*/
String getInfoMessage();
/**
* Initializes the connection parameter page.
*
* @param parent the parent
* @param listener the connection parameter page modify listener
* @param parameter the initial connection parameter
*/
void init( Composite parent, ConnectionParameterPageModifyListener listener, ConnectionParameter parameter );
/**
* Saves the dialog settings.
*/
void saveDialogSettings();
/**
* Sets the runnable context.
*
* @param runnableContext the runnable context
*/
void setRunnableContext( IRunnableContext runnableContext );
/**
* Sets the page id.
*
* @param pageId the page id
*/
void setPageId( String pageId );
/**
* Gets the page id.
*
* @return the page id
*/
String getPageId();
/**
* Sets the page name.
*
* @param pageName the page name
*/
void setPageName( String pageName );
/**
* Gets the page name.
*
* @return the page name
*/
String getPageName();
/**
* Sets the page description.
*
* @param pageDescription the page description
*/
void setPageDescription( String pageDescription );
/**
* Gets the page description.
*
* @return the page description
*/
String getPageDescription();
/**
* Sets the page id this page depends on.
*
* @param pageDependsOnId the page id this page depends on
*/
void setPageDependsOnId( String pageDependsOnId );
/**
* Gets the page id this page depends on.
*
* @return the page id this page depends on
*/
String getPageDependsOnId();
/**
* Sets the focus.
*/
void setFocus();
/**
* The implementing class must return true if important
* connection parameters were modified that require a
* reconnection to take effect.
*
* @return true if a reconnection if required
*/
boolean isReconnectionRequired();
/**
* The implementing class must return true if any
* parameter was modified.
*
* @return true, if parameters were modified
*/
boolean areParametersModifed();
/**
* Merges the connection parameters into the LDAP URL.
*
* @param parameter the source connection parameter
* @param ldapUrl the target LDAP URL
*/
void mergeParametersToLdapURL( ConnectionParameter parameter, LdapUrl ldapUrl );
/**
* Merges the LDAP URL into the connection parameters.
*
* @param ldapUrl the source LDAP URL
* @param parameter the target connection parameter
*/
void mergeLdapUrlToParameters( LdapUrl ldapUrl, ConnectionParameter parameter );
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/UIAuthHandler.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/UIAuthHandler.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.ui;
import org.apache.commons.lang3.StringUtils;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.apache.directory.studio.connection.core.Credentials;
import org.apache.directory.studio.connection.core.IAuthHandler;
import org.apache.directory.studio.connection.core.ICredentials;
import org.apache.directory.studio.connection.core.PasswordsKeyStoreManager;
import org.apache.directory.studio.connection.ui.dialogs.PasswordDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.PlatformUI;
/**
* Default authentication handler that ask for the password using
* a UI dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class UIAuthHandler implements IAuthHandler
{
/**
* {@inheritDoc}
*/
public ICredentials getCredentials( final ConnectionParameter connectionParameter )
{
// Checking if the bind principal is null or empty (no authentication)
if ( Strings.isEmpty( connectionParameter.getBindPrincipal() ) )
{
return new Credentials( StringUtils.EMPTY, StringUtils.EMPTY, connectionParameter );
}
else
{
// Checking of the connection passwords keystore is enabled
if ( PasswordsKeyStoreManagerUtils.isPasswordsKeystoreEnabled() )
{
// Getting the passwords keystore manager
PasswordsKeyStoreManager passwordsKeyStoreManager = ConnectionCorePlugin.getDefault()
.getPasswordsKeyStoreManager();
// Checking if the keystore is not loaded
// and asking the user to load the keystore
if ( !passwordsKeyStoreManager.isLoaded() && !PasswordsKeyStoreManagerUtils.askUserToLoadKeystore() )
{
// The user failed to load the keystore and cancelled
return null;
}
// Getting the password
String password = passwordsKeyStoreManager.getConnectionPassword( connectionParameter.getId() );
// Checking if the bind password is available (the user chose to store the password)
if ( !Strings.isEmpty( password ) )
{
return new Credentials( connectionParameter.getBindPrincipal(),
password, connectionParameter );
}
// The user chose NOT to store the password, we need to ask him
else
{
return askConnectionPassword( connectionParameter );
}
}
// Connection passwords keystore is NOT enabled
else
{
// Checking if the bind password is available (the user chose to store the password)
if ( !Strings.isEmpty( connectionParameter.getBindPassword() ) )
{
return new Credentials( connectionParameter.getBindPrincipal(),
connectionParameter.getBindPassword(), connectionParameter );
}
// The user chose NOT to store the password, we need to ask him
else
{
return askConnectionPassword( connectionParameter );
}
}
}
}
/**
* Asks the user for the connection password.
*
* @param connectionParameter the connection parameter
* @return the corresponding credentials
*/
private Credentials askConnectionPassword( final ConnectionParameter connectionParameter )
{
final String[] password = new String[1];
PlatformUI.getWorkbench().getDisplay().syncExec( () ->
{
PasswordDialog dialog = new PasswordDialog(
PlatformUI.getWorkbench().getDisplay().getActiveShell(),
NLS.bind(
Messages.getString( "UIAuthHandler.EnterPasswordFor" ), new String[] //$NON-NLS-1$
{ connectionParameter.getName() } ),
NLS.bind(
Messages.getString( "UIAuthHandler.PleaseEnterPasswordOfUser" ),
connectionParameter.getBindPrincipal() ),
StringUtils.EMPTY ); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
if ( dialog.open() == PasswordDialog.OK )
{
password[0] = dialog.getPassword();
}
} );
if ( password[0] != null )
{
return new Credentials( connectionParameter.getBindPrincipal(), password[0],
connectionParameter );
}
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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageModifyListener.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionParameterPageModifyListener.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.ui;
import org.apache.directory.studio.connection.core.ConnectionParameter;
/**
* A ConnectionPageModifyListener listens for modifications of the
* ConnectionPageWrapper.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface ConnectionParameterPageModifyListener
{
/**
* Indicates that the connection parameter page was modified.
*/
void connectionParameterPageModified();
/**
* Gets the test connection parameters.
*
* @return the test connection parameters
*/
ConnectionParameter getTestConnectionParameters();
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIPlugin.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/ConnectionUIPlugin.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.ui;
import java.io.IOException;
import java.net.URL;
import java.util.PropertyResourceBundle;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.event.EventRunner;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ConnectionUIPlugin extends AbstractUIPlugin
{
/** The shared plugin instance. */
private static ConnectionUIPlugin plugin;
/** The event dispatcher */
private ExceptionHandler exceptionHandler;
/** The event runner. */
private EventRunner eventRunner;
/** The plugin properties */
private PropertyResourceBundle properties;
/**
* The constructor
*/
public ConnectionUIPlugin()
{
super();
plugin = this;
}
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start( BundleContext context ) throws Exception
{
super.start( context );
if ( exceptionHandler == null )
{
exceptionHandler = new ExceptionHandler();
}
if ( eventRunner == null )
{
eventRunner = new UiThreadEventRunner();
}
ConnectionCorePlugin defaultPlugin = ConnectionCorePlugin.getDefault();
defaultPlugin.setAuthHandler( new UIAuthHandler() );
defaultPlugin.setReferralHandler( new ConnectionUIReferralHandler() );
defaultPlugin.setCertificateHandler( new ConnectionUICertificateHandler() );
}
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop( BundleContext context ) throws Exception
{
plugin = null;
super.stop( context );
if ( exceptionHandler != null )
{
exceptionHandler = null;
}
if ( eventRunner != null )
{
eventRunner = null;
}
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static ConnectionUIPlugin getDefault()
{
return plugin;
}
/**
* Gets the exception handler.
*
* @return the exception handler
*/
public ExceptionHandler getExceptionHandler()
{
return exceptionHandler;
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* BrowserWidgetsConstants for the key.
*
* @param key The key (relative path to the image in filesystem)
* @return The image descriptor or null
*/
public ImageDescriptor getImageDescriptor( String key )
{
if ( key != null )
{
URL url = FileLocator.find( getBundle(), new Path( key ), null );
if ( url != null )
{
return ImageDescriptor.createFromURL( url );
}
}
return null;
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* BrowserWidgetsConstants for the key. A ImageRegistry is used to manage the
* the key->Image mapping.
* <p>
* Note: Don't dispose the returned SWT Image. It is disposed
* automatically when the plugin is stopped.
*
* @param key he key (relative path to the image in filesystem)
* @return The SWT Image or null
*/
public Image getImage( String key )
{
Image image = getImageRegistry().get( key );
if ( image == null )
{
ImageDescriptor imageDescriptor = getImageDescriptor( key );
if ( imageDescriptor != null )
{
image = imageDescriptor.createImage();
getImageRegistry().put( key, image );
}
}
return image;
}
/**
* Gets the event runner.
*
* @return the event runner
*/
public EventRunner getEventRunner()
{
return eventRunner;
}
/**
* 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.ui", Status.OK, //$NON-NLS-1$
Messages.getString( "ConnectionUIPlugin.UnableGetPluginProperties" ), e ) ); //$NON-NLS-1$
}
}
return properties;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/DragConnectionListener.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/DragConnectionListener.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.ui.dnd;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.widgets.Tree;
/**
* This class implements a {@link DragSourceListener} that is used to
* drag and drop connections withing the connections view.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DragConnectionListener implements DragSourceListener
{
/** The associated viewer */
private TreeViewer treeViewer;
/** The selection (used for drag and drop) */
private StructuredSelection selection = null;
/**
* Creates a new instance of DragConnectionListener.
*/
public DragConnectionListener( TreeViewer viewer )
{
treeViewer = viewer;
}
/**
* {@inheritDoc}
*
* This implementation saves the selection.
*/
public void dragStart( DragSourceEvent event )
{
selection = ( StructuredSelection ) treeViewer.getSelection();
event.doit = !selection.isEmpty();
}
/**
* {@inheritDoc}
*
* This implementation adds the dragged connections and connection folders to the
* given event data.
*/
public void dragSetData( DragSourceEvent event )
{
if ( ConnectionTransfer.getInstance().isSupportedType( event.dataType ) &&
( event.widget instanceof DragSource ) )
{
DragSource dragSource = ( DragSource ) event.widget;
if ( dragSource.getControl() instanceof Tree )
{
List<Object> objectList = new ArrayList<>();
if ( selection != null )
{
for ( Iterator<?> iterator = selection.iterator(); iterator.hasNext(); )
{
Object item = iterator.next();
if ( ( item instanceof Connection ) || ( item instanceof ConnectionFolder ) )
{
objectList.add( item );
}
}
}
event.data = objectList.toArray();
}
}
}
/**
* {@inheritDoc}
*
* This implementation does nothing.
*/
public void dragFinished( DragSourceEvent event )
{
// Nothing to do
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/DropConnectionListener.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/DropConnectionListener.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.ui.dnd;
import java.util.Set;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.core.ConnectionFolderManager;
import org.apache.directory.studio.connection.core.ConnectionManager;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* This class implements a {@link DropTargetListener} that is used to
* drag and drop connections within the connections view.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DropConnectionListener implements DropTargetListener
{
/**
* {@inheritDoc}
*
* This implementation checks if the event's data type is
* supported. If not supported dropping is rejected.
*/
public void dragEnter( DropTargetEvent event )
{
if ( !ConnectionTransfer.getInstance().isSupportedType( event.currentDataType ) )
{
event.detail = DND.DROP_NONE;
}
}
/**
* {@inheritDoc}
*
* This implementation just calls {@link #dragOver(DropTargetEvent)}.
*/
public void dragOperationChanged( DropTargetEvent event )
{
dragOver( event );
}
/**
* {@inheritDoc}
*
* This implementation does nothing.
*/
public void dragLeave( DropTargetEvent event )
{
// Nothing to do
}
/**
* {@inheritDoc}
*
* This implementation checks if the event's data type is
* supported. If not supported dropping is rejected.
*/
public void dragOver( DropTargetEvent event )
{
try
{
// move connection folder: check that the new connection folder is not the same or a parent folder
boolean isMoveConnectionFolderForbidden = false;
if ( ( ( event.detail == DND.DROP_MOVE ) || ( event.detail == DND.DROP_NONE ) ) &&
( ConnectionTransfer.getInstance().isSupportedType( event.currentDataType ) ) &&
( ( event.item != null ) && ( event.item.getData() instanceof ConnectionFolder ) ) )
{
ConnectionFolderManager connectionFolderManager = ConnectionCorePlugin.getDefault()
.getConnectionFolderManager();
ConnectionFolder overFolder = ( ConnectionFolder ) event.item.getData();
Set<ConnectionFolder> allParentFolders = connectionFolderManager
.getAllParentFolders( overFolder );
if ( event.widget instanceof DropTarget )
{
DropTarget dropTarget = ( DropTarget ) event.widget;
if ( dropTarget.getControl() instanceof Tree )
{
Tree tree = ( Tree ) dropTarget.getControl();
for ( TreeItem treeItem : tree.getSelection() )
{
if ( treeItem.getData() instanceof ConnectionFolder )
{
ConnectionFolder folder = ( ConnectionFolder ) treeItem.getData();
if ( allParentFolders.contains( folder ) )
{
isMoveConnectionFolderForbidden = true;
break;
}
}
}
}
}
}
if ( !ConnectionTransfer.getInstance().isSupportedType( event.currentDataType ) )
{
event.detail = DND.DROP_NONE;
}
else if ( isMoveConnectionFolderForbidden )
{
event.detail = DND.DROP_NONE;
}
else if ( event.detail == DND.DROP_LINK )
{
event.detail = DND.DROP_NONE;
}
else if ( event.detail == DND.DROP_NONE )
{
event.detail = DND.DROP_DEFAULT;
}
}
catch ( Exception e )
{
event.detail = DND.DROP_NONE;
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*
* This implementation does nothing.
*/
public void dropAccept( DropTargetEvent event )
{
// Nothing to do
}
/**
* {@inheritDoc}
*
* This implementation drops the dragged connection to
* the selected position.
*/
public void drop( DropTargetEvent event )
{
ConnectionManager connectionManager = ConnectionCorePlugin.getDefault().getConnectionManager();
ConnectionFolderManager connectionFolderManager = ConnectionCorePlugin.getDefault()
.getConnectionFolderManager();
try
{
if ( ConnectionTransfer.getInstance().isSupportedType( event.currentDataType ) )
{
// get connection and folders to handle
Object[] objects = ( Object[] ) event.data;
Object target;
if ( event.item == null )
{
target = connectionFolderManager .getRootConnectionFolder();
}
else
{
target = event.item.getData();
}
ConnectionFolder targetFolder = null;
if ( target instanceof ConnectionFolder )
{
targetFolder = ( ConnectionFolder ) target;
}
else if ( target instanceof Connection )
{
Connection connection = ( Connection ) target;
targetFolder = connectionFolderManager.getParentConnectionFolder( connection );
}
for ( Object object : objects )
{
if ( object instanceof Connection )
{
Connection connection = ( Connection ) object;
if ( event.detail == DND.DROP_MOVE )
{
ConnectionFolder parentConnectionFolder = connectionFolderManager
.getParentConnectionFolder( connection );
parentConnectionFolder.removeConnectionId( connection.getId() );
targetFolder.addConnectionId( connection.getId() );
}
else if ( event.detail == DND.DROP_COPY )
{
Connection newConnection = ( Connection ) connection.clone();
connectionManager.addConnection( newConnection );
targetFolder.addConnectionId( newConnection.getId() );
}
}
else if ( object instanceof ConnectionFolder )
{
ConnectionFolder folder = ( ConnectionFolder ) object;
if ( event.detail == DND.DROP_MOVE )
{
ConnectionFolder parentConnectionFolder = connectionFolderManager
.getParentConnectionFolder( folder );
parentConnectionFolder.removeSubFolderId( folder.getId() );
targetFolder.addSubFolderId( folder.getId() );
// TODO: expand target folder
}
else if ( event.detail == DND.DROP_COPY )
{
ConnectionFolder newFolder = ( ConnectionFolder ) folder.clone();
connectionFolderManager.addConnectionFolder( newFolder );
targetFolder.addSubFolderId( newFolder.getId() );
// TODO: expand target folder
}
}
}
}
else
{
event.detail = DND.DROP_NONE;
}
}
catch ( Exception e )
{
event.detail = DND.DROP_NONE;
e.printStackTrace();
}
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/ConnectionTransfer.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/dnd/ConnectionTransfer.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.ui.dnd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.core.ConnectionFolderManager;
import org.apache.directory.studio.connection.core.ConnectionManager;
import org.apache.directory.studio.connection.ui.ConnectionUIConstants;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
/**
* A {@link Transfer} that could be used to transfer {@link Connection} objects.
* Note that only the connection id is converted to a platform specific
* representation, not the complete object. To convert it back to an {@link Connection}
* object the {@link ConnectionManager#getConnectionById(String)} method is invoked.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class ConnectionTransfer extends ByteArrayTransfer
{
/** The Constant TYPENAME. */
private static final String TYPENAME = ConnectionUIConstants.TYPENAME;
/** The Constant TYPEID. */
private static final int TYPEID = registerType( TYPENAME );
/** The instance. */
private static ConnectionTransfer instance = new ConnectionTransfer();
/**
* Creates a new instance of ConnectionTransfer.
*/
private ConnectionTransfer()
{
super();
}
/**
* Gets the instance.
*
* @return the instance
*/
public static ConnectionTransfer getInstance()
{
return instance;
}
/**
* {@inheritDoc}
*
* This implementation only accepts {@link Connection} and {@link ConnectionFolder} objects.
* It just converts the id of the connection or connection folder to the platform
* specific representation.
*/
@Override
public void javaToNative( Object object, TransferData transferData )
{
if ( !( object instanceof Object[] ) )
{
return;
}
if ( isSupportedType( transferData ) )
{
Object[] objects = ( Object[] ) object;
try ( ByteArrayOutputStream out = new ByteArrayOutputStream() )
{
try ( DataOutputStream writeOut = new DataOutputStream( out ) )
{
for ( int i = 0; i < objects.length; i++ )
{
if ( objects[i] instanceof Connection )
{
byte[] idBytes = ( ( Connection ) objects[i] ).getConnectionParameter().getId().getBytes();
writeOut.writeInt( idBytes.length );
writeOut.write( idBytes );
}
else if ( objects[i] instanceof ConnectionFolder )
{
byte[] idBytes = ( ( ConnectionFolder ) objects[i] ).getId().getBytes();
writeOut.writeInt( idBytes.length );
writeOut.write( idBytes );
}
}
byte[] buffer = out.toByteArray();
super.javaToNative( buffer, transferData );
}
}
catch ( IOException e )
{
}
}
}
/**
* {@inheritDoc}
*
* This implementation just converts the platform specific representation
* to the connection id or connection folder id and invokes
* {@link ConnectionManager#getConnectionById(String)} to get the
* {@link Connection} object or {@link ConnectionFolderManager#getConnectionFolderById(String)}
* to get the {@link ConnectionFolder} object.
*/
@Override
public Object nativeToJava( TransferData transferData )
{
if ( isSupportedType( transferData ) )
{
byte[] buffer = ( byte[] ) super.nativeToJava( transferData );
if ( buffer == null )
{
return null;
}
List<Object> objectList = new ArrayList<>();
try ( ByteArrayInputStream in = new ByteArrayInputStream( buffer ) )
{
try ( DataInputStream readIn = new DataInputStream( in ) )
{
do
{
if ( readIn.available() > 1 )
{
int size = readIn.readInt();
byte[] idBytes = new byte[size];
if ( readIn.read( idBytes ) != size )
{
// We werev'nt able to read the full data : there is something wrong...
return null;
}
Connection connection = ConnectionCorePlugin.getDefault().getConnectionManager()
.getConnectionById( new String( idBytes ) );
if ( connection == null )
{
ConnectionFolder folder = ConnectionCorePlugin.getDefault().getConnectionFolderManager()
.getConnectionFolderById( new String( idBytes ) );
if ( folder != null )
{
objectList.add( folder );
}
}
else
{
objectList.add( connection );
}
}
}
while ( readIn.available() > 1 );
}
}
catch ( IOException ex )
{
return null;
}
return objectList.toArray();
}
return null;
}
/**
* {@inheritDoc}
*/
protected String[] getTypeNames()
{
return new String[]
{ TYPENAME };
}
/**
* {@inheritDoc}
*/
protected int[] getTypeIds()
{
return new int[]
{ TYPEID };
}
} | 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/StudioActionProxy.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/StudioActionProxy.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.ui.actions;
import org.apache.directory.studio.common.ui.CommonUIUtils;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
import org.apache.directory.studio.connection.core.event.ConnectionUpdateListener;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
/**
* Proxy class for actions. The proxy class registers for modification events and
* updates the real actions on every modificaton.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class StudioActionProxy extends Action implements ISelectionChangedListener, ConnectionUpdateListener
{
/** The action handler manager, used to deactivate and activate the action handlers and key bindings. */
private ActionHandlerManager actionHandlerManager;
/** The real action. */
protected StudioAction action;
/** The selection provider. */
protected ISelectionProvider selectionProvider;
/**
* Creates a new instance of StudioActionProxy.
*
* @param selectionProvider the selection provider
* @param actionHandlerManager the action handler manager
* @param action the action
* @param style the style
*/
protected StudioActionProxy( ISelectionProvider selectionProvider, ActionHandlerManager actionHandlerManager,
StudioAction action, int style )
{
super( action.getText(), style );
this.selectionProvider = selectionProvider;
this.actionHandlerManager = actionHandlerManager;
this.action = action;
super.setImageDescriptor( action.getImageDescriptor() );
super.setActionDefinitionId( action.getCommandId() );
selectionProvider.addSelectionChangedListener( this );
ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionUIPlugin.getDefault().getEventRunner() );
updateAction();
}
/**
* Creates a new instance of StudioActionProxy.
*
* @param selectionProvider the selection provider
* @param actionHandlerManager the action handler manager
* @param action the action
*/
protected StudioActionProxy( ISelectionProvider selectionProvider, ActionHandlerManager actionHandlerManager,
StudioAction action )
{
this( selectionProvider, actionHandlerManager, action, Action.AS_PUSH_BUTTON );
}
/**
* Disposes this action proxy.
*/
public void dispose()
{
ConnectionEventRegistry.removeConnectionUpdateListener( this );
selectionProvider.removeSelectionChangedListener( this );
action.dispose();
action = null;
}
/**
* Checks if is disposed.
*
* @return true, if is disposed
*/
public boolean isDisposed()
{
return action == null;
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionUpdated(org.apache.directory.studio.connection.core.Connection)
*/
public final void connectionUpdated( Connection connection )
{
if ( !isDisposed() )
{
updateAction();
}
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionAdded(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionAdded( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionRemoved(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionRemoved( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionOpened(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionOpened( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionClosed(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionClosed( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionFolderModified(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderModified( ConnectionFolder connectionFolder )
{
connectionUpdated( null );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionFolderAdded(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderAdded( ConnectionFolder connectionFolder )
{
connectionUpdated( null );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#
* connectionFolderRemoved(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderRemoved( ConnectionFolder connectionFolder )
{
connectionUpdated( null );
}
/**
* Input changed.
*
* @param input the input
*/
public void inputChanged( Object input )
{
if ( !isDisposed() )
{
action.setInput( input );
selectionChanged( new SelectionChangedEvent( this.selectionProvider, new StructuredSelection() ) );
}
}
/**
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged( SelectionChangedEvent event )
{
if ( !isDisposed() )
{
ISelection selection = event.getSelection();
action.setSelectedConnections( SelectionUtils.getConnections( selection ) );
action.setSelectedConnectionFolders( SelectionUtils.getConnectionFolders( selection ) );
updateAction();
}
}
/**
* Updates the action.
*/
public void updateAction()
{
if ( !isDisposed() )
{
setText( CommonUIUtils.getTextValue( action.getText() ) );
setToolTipText( CommonUIUtils.getTextValue( action.getText() ) );
setEnabled( action.isEnabled() );
setImageDescriptor( action.getImageDescriptor() );
setChecked( action.isChecked() );
}
}
/**
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run()
{
if ( !isDisposed() )
{
// deactivate global actions
if ( actionHandlerManager != null )
{
actionHandlerManager.deactivateGlobalActionHandlers();
}
action.run();
// activate global actions
if ( actionHandlerManager != null )
{
actionHandlerManager.activateGlobalActionHandlers();
}
}
}
/**
* Gets the real action.
*
* @return the real action
*/
public StudioAction getAction()
{
return action;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/ActionHandlerManager.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/ActionHandlerManager.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.ui.actions;
/**
* A ActionHandlerManager activates and deactives the action handlers.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface ActionHandlerManager
{
/**
* Deactivates global action handlers.
*/
void deactivateGlobalActionHandlers();
/**
* Activates global action handlers.
*/
void activateGlobalActionHandlers();
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/PasteAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/PasteAction.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.ui.actions;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.ClipboardUtils;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.core.ConnectionFolderManager;
import org.apache.directory.studio.connection.core.ConnectionManager;
import org.apache.directory.studio.connection.ui.dnd.ConnectionTransfer;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PlatformUI;
/**
* This class implements the Paste Action.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PasteAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public String getText()
{
List<Connection> connections = getConnectionsToPaste();
List<ConnectionFolder> connectionFolders = getConnectionFoldersToPaste();
if ( !connections.isEmpty() && connectionFolders.isEmpty() )
{
if ( connections.size() > 1 )
{
return Messages.getString( "PasteAction.PasteConnections" );
}
else
{
return Messages.getString( "PasteAction.PasteConnection" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else if ( !connectionFolders.isEmpty() && connections.isEmpty() )
{
if ( connectionFolders.size() > 1 )
{
return Messages.getString( "PasteAction.PasteConnectionFolders" );
}
else
{
return Messages.getString( "PasteAction.PasteConnectionFolder" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
return Messages.getString( "PasteAction.Paste" ); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_TOOL_PASTE );
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return IWorkbenchCommandConstants.EDIT_PASTE;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return ClipboardUtils.isAvailable( ConnectionTransfer.getInstance() );
}
/**
* {@inheritDoc}
*/
public void run()
{
ConnectionFolderManager connectionFolderManager = ConnectionCorePlugin.getDefault()
.getConnectionFolderManager();
ConnectionManager connectionManager = ConnectionCorePlugin.getDefault().getConnectionManager();
ConnectionFolder[] selectedFolders = getSelectedConnectionFolders();
Connection[] selectedConnections = getSelectedConnections();
ConnectionFolder targetFolder = null;
if ( selectedFolders.length > 0 )
{
targetFolder = selectedFolders[0];
}
else if ( selectedConnections.length > 0 )
{
targetFolder = connectionFolderManager.getParentConnectionFolder( selectedConnections[0] );
}
if ( targetFolder == null )
{
targetFolder = connectionFolderManager.getRootConnectionFolder();
}
// connections
List<Connection> connections = getConnectionsToPaste();
for ( Connection connection : connections )
{
Connection newConnection = ( Connection ) connection.clone();
connectionManager.addConnection( newConnection );
targetFolder.addConnectionId( newConnection.getId() );
}
// connection folders
List<ConnectionFolder> connectionFolders = getConnectionFoldersToPaste();
for ( ConnectionFolder connectionFolder : connectionFolders )
{
ConnectionFolder newConnectionFolder = ( ConnectionFolder ) connectionFolder.clone();
connectionFolderManager.addConnectionFolder( newConnectionFolder );
targetFolder.addSubFolderId( newConnectionFolder.getId() );
}
}
/**
* Condition: there are connections in clipboard
*
* @return the connections to paste
*/
private List<Connection> getConnectionsToPaste()
{
List<Connection> connections = new ArrayList<>();
Object content = ClipboardUtils.getFromClipboard( ConnectionTransfer.getInstance() );
if ( content instanceof Object[] )
{
for ( Object object : ( Object[] )content )
{
if ( object instanceof Connection )
{
connections.add( ( Connection ) object );
}
}
}
return connections;
}
/**
* Condition: there are connection folders in clipboard
*
* @return the connection folders to paste
*/
private List<ConnectionFolder> getConnectionFoldersToPaste()
{
List<ConnectionFolder> folders = new ArrayList<>();
Object content = ClipboardUtils.getFromClipboard( ConnectionTransfer.getInstance() );
if ( content instanceof Object[] )
{
for ( Object object : ( Object[] ) content )
{
if ( object instanceof ConnectionFolder )
{
folders.add( ( ConnectionFolder ) object );
}
}
}
return folders;
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/DeleteAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/DeleteAction.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.ui.actions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.apache.directory.studio.connection.core.jobs.CloseConnectionsRunnable;
import org.apache.directory.studio.connection.core.jobs.StudioConnectionJob;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PlatformUI;
/**
* This Action implements the Delete Action. It deletes Connections, Entries, Searches, Bookmarks, Attributes or Values.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DeleteAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public String getText()
{
Connection[] connections = getSelectedConnections();
ConnectionFolder[] connectionFolders = getSelectedConnectionFolders();
if ( ( connections.length > 0 ) && ( connectionFolders.length == 0 ) )
{
if ( connections.length > 1 )
{
return Messages.getString( "DeleteAction.DeleteConnections" );
}
else
{
return Messages.getString( "DeleteAction.DeleteConnection" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else if ( ( connectionFolders.length > 0 ) && ( connections.length == 0 ) )
{
if ( connectionFolders.length > 1 )
{
return Messages.getString( "DeleteAction.DeleteConnectionFolders" );
}
else
{
return Messages.getString( "DeleteAction.DeleteConnectionFolder" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
return Messages.getString( "DeleteAction.Delete" ); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_TOOL_DELETE );
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return IWorkbenchCommandConstants.EDIT_DELETE;
}
/**
* {@inheritDoc}
*/
public void run()
{
Connection[] connections = getSelectedConnections();
ConnectionFolder[] connectionFolders = getSelectedConnectionFolders();
StringBuilder message = new StringBuilder();
if ( connections.length > 0 )
{
if ( connections.length <= 5 )
{
if ( connections.length == 1 )
{
message.append( Messages.getString( "DeleteAction.SureDeleteFollowingConnection" ) ); //$NON-NLS-1$
}
else
{
message.append( Messages.getString( "DeleteAction.SureDeleteFollowingConnections" ) ); //$NON-NLS-1$
}
for ( Connection connection : connections )
{
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
message.append( " - " ); //$NON-NLS-1$
message.append( connection.getName() );
}
}
else
{
message.append( Messages.getString( "DeleteAction.SureDeleteSelectedConnections" ) ); //$NON-NLS-1$
}
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
}
if ( connectionFolders.length > 0 )
{
if ( connectionFolders.length <= 5 )
{
if ( connectionFolders.length == 1 )
{
message.append( Messages.getString( "DeleteAction.SureDeleteFollowingFolder" ) ); //$NON-NLS-1$
}
else
{
message.append( Messages.getString( "DeleteAction.SureDeleteFollowingFolders" ) ); //$NON-NLS-1$
}
for ( ConnectionFolder connectionFolder : connectionFolders )
{
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
message.append( " - " ); //$NON-NLS-1$
message.append( connectionFolder.getName() );
}
}
else
{
message.append( Messages.getString( "DeleteAction.SureDeleteSelectedConnectionFolders" ) ); //$NON-NLS-1$
}
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
message.append( ConnectionCoreConstants.LINE_SEPARATOR );
}
if ( ( message.length() == 0 ) || MessageDialog.openConfirm( getShell(), getText(), message.toString() ) )
{
List<Connection> connectionsToDelete = getConnectionsToDelete();
List<ConnectionFolder> connectionsFoldersToDelete = getConnectionsFoldersToDelete();
if ( !connectionsToDelete.isEmpty() )
{
deleteConnections( connectionsToDelete );
}
if ( !connectionsFoldersToDelete.isEmpty() )
{
deleteConnectionFolders( connectionsFoldersToDelete );
}
}
}
private List<ConnectionFolder> getConnectionsFoldersToDelete()
{
List<ConnectionFolder> selectedFolders = new ArrayList<>( Arrays
.asList( getSelectedConnectionFolders() ) );
List<ConnectionFolder> foldersToDelete = new ArrayList<>();
while ( !selectedFolders.isEmpty() )
{
ConnectionFolder folder = selectedFolders.get( 0 );
List<String> subFolderIds = folder.getSubFolderIds();
for ( String subFolderId : subFolderIds )
{
ConnectionFolder subFolder = ConnectionCorePlugin.getDefault().getConnectionFolderManager()
.getConnectionFolderById( subFolderId );
if ( subFolder != null )
{
selectedFolders.add( subFolder );
}
}
if ( !foldersToDelete.contains( folder ) )
{
foldersToDelete.add( folder );
}
selectedFolders.remove( folder );
}
return foldersToDelete;
}
private List<Connection> getConnectionsToDelete()
{
List<ConnectionFolder> selectedFolders = new ArrayList<>( Arrays
.asList( getSelectedConnectionFolders() ) );
List<Connection> selectedConnections = new ArrayList<>( Arrays.asList( getSelectedConnections() ) );
List<Connection> connectionsToDelete = new ArrayList<>( selectedConnections );
while ( !selectedFolders.isEmpty() )
{
ConnectionFolder folder = selectedFolders.get( 0 );
List<String> subFolderIds = folder.getSubFolderIds();
for ( String subFolderId : subFolderIds )
{
ConnectionFolder subFolder = ConnectionCorePlugin.getDefault().getConnectionFolderManager()
.getConnectionFolderById( subFolderId );
if ( subFolder != null )
{
selectedFolders.add( subFolder );
}
}
List<String> connectionIds = folder.getConnectionIds();
for ( String connectionId : connectionIds )
{
Connection connection = ConnectionCorePlugin.getDefault().getConnectionManager().getConnectionById(
connectionId );
if ( ( connection != null ) && !connectionsToDelete.contains( connection ) )
{
connectionsToDelete.add( connection );
}
}
selectedFolders.remove( folder );
}
return connectionsToDelete;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return getSelectedConnections().length + getSelectedConnectionFolders().length > 0;
}
/**
* Deletes Connections
*
* @param connectionsToDelete the Connections to delete
*/
private void deleteConnections( List<Connection> connectionsToDelete )
{
new StudioConnectionJob( new CloseConnectionsRunnable( connectionsToDelete ) ).execute();
for ( Connection connection : connectionsToDelete )
{
ConnectionCorePlugin.getDefault().getConnectionManager().removeConnection( connection );
}
}
/**
* Deletes Connection Folders
*
* @param connectionsFoldersToDelete the Connection Folders to delete
*/
private void deleteConnectionFolders( List<ConnectionFolder> connectionsFoldersToDelete )
{
for ( ConnectionFolder connectionFolder : connectionsFoldersToDelete )
{
ConnectionCorePlugin.getDefault().getConnectionFolderManager().removeConnectionFolder( 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/RenameAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/RenameAction.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.ui.actions;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IWorkbenchCommandConstants;
/**
* This Action renames Connections, Entries, Searches, or Bookmarks.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RenameAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public String getText()
{
Connection[] connections = getSelectedConnections();
ConnectionFolder[] connectionFolders = getSelectedConnectionFolders();
if ( ( connections.length == 1 ) && ( connectionFolders.length == 0 ) )
{
return Messages.getString( "RenameAction.Connection" ); //$NON-NLS-1$
}
else if ( ( connectionFolders.length == 1) && ( connections.length == 0 ) )
{
return Messages.getString( "RenameAction.ConnectionFolder" ); //$NON-NLS-1$
}
else
{
return Messages.getString( "RenameAction.Rename" ); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return null;
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return IWorkbenchCommandConstants.FILE_RENAME;
}
/**
* {@inheritDoc}
*/
public void run()
{
Connection[] connections = getSelectedConnections();
ConnectionFolder[] connectionFolders = getSelectedConnectionFolders();
if ( connections.length == 1 )
{
renameConnection( connections[0] );
}
else if ( connectionFolders.length == 1 )
{
renameConnectionFolder( connectionFolders[0] );
}
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return getSelectedConnections().length + getSelectedConnectionFolders().length == 1;
}
/**
* Renames a Connection.
*
* @param connection
* the Connection to rename
*/
private void renameConnection( final Connection connection )
{
IInputValidator validator = newName ->
{
if ( connection.getName().equals( newName ) )
{
return null;
}
else if ( ConnectionCorePlugin.getDefault().getConnectionManager().getConnectionByName( newName ) == null )
{
return null;
}
else
{
return Messages.getString( "RenameAction.ConnectionAlreadyExists" ); //$NON-NLS-1$
}
};
InputDialog dialog = new InputDialog(
getShell(),
Messages.getString( "RenameAction.RenameConnection" ), Messages.getString( "RenameAction.NewNameConnection" ), connection.getName(), //$NON-NLS-1$ //$NON-NLS-2$
validator );
dialog.open();
String newName = dialog.getValue();
if ( newName != null )
{
connection.setName( newName );
}
}
/**
* Renames a ConnectionFolder.
*
* @param connectionFolder the ConnectionFolder to rename
*/
private void renameConnectionFolder( final ConnectionFolder connectionFolder )
{
IInputValidator validator = newName ->
{
if ( connectionFolder.getName().equals( newName ) )
{
return null;
}
else if ( ConnectionCorePlugin.getDefault().getConnectionFolderManager().getConnectionFolderByName(
newName ) == null )
{
return null;
}
else
{
return Messages.getString( "RenameAction.ConnectionFolderAlreadyExists" ); //$NON-NLS-1$
}
};
InputDialog dialog = new InputDialog(
getShell(),
Messages.getString( "RenameAction.RenameConnectionFolder" ), Messages.getString( "RenameAction.NewNameConnectionFolder" ), connectionFolder.getName(), //$NON-NLS-1$ //$NON-NLS-2$
validator );
dialog.open();
String newName = dialog.getValue();
if ( newName != null )
{
connectionFolder.setName( newName );
}
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/CloseConnectionAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/CloseConnectionAction.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.ui.actions;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.jobs.CloseConnectionsRunnable;
import org.apache.directory.studio.connection.core.jobs.StudioConnectionJob;
import org.apache.directory.studio.connection.ui.ConnectionUIConstants;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.eclipse.jface.resource.ImageDescriptor;
/**
* This action closes the selected Connection(s).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class CloseConnectionAction extends StudioAction
{
/**
* @see org.apache.directory.studio.connection.ui.actions.StudioAction#run()
*/
public void run()
{
new StudioConnectionJob( new CloseConnectionsRunnable( getSelectedConnections() ) ).execute();
}
/**
* @see org.apache.directory.studio.connection.ui.actions.StudioAction#getText()
*/
public String getText()
{
if ( getSelectedConnections().length > 1 )
{
return Messages.getString( "CloseConnectionAction.CloseConnections" );
}
else
{
return Messages.getString( "CloseConnectionAction.CloseConnection" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* @see org.apache.directory.studio.connection.ui.actions.StudioAction#getImageDescriptor()
*/
public ImageDescriptor getImageDescriptor()
{
return ConnectionUIPlugin.getDefault().getImageDescriptor( ConnectionUIConstants.IMG_CONNECTION_DISCONNECT );
}
/**
* @see org.apache.directory.studio.connection.ui.actions.StudioAction#getCommandId()
*/
public String getCommandId()
{
return null;
}
/**
* @see org.apache.directory.studio.connection.ui.actions.StudioAction#isEnabled()
*/
public boolean isEnabled()
{
boolean canClose = false;
for ( Connection connection : getSelectedConnections() )
{
if ( connection.getConnectionWrapper().isConnected() )
{
canClose = true;
break;
}
}
return getSelectedConnections().length > 0 && canClose;
}
}
| 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.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/PropertiesAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/PropertiesAction.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.ui.actions;
import org.apache.directory.studio.connection.core.Utils;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.dialogs.PreferencesUtil;
/**
* This Action opens the Property Dialog for a given object.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class PropertiesAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public String getText()
{
return Messages.getString( "PropertiesAction.Properties" ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return null;
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return IWorkbenchCommandConstants.FILE_PROPERTIES;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return getSelectedConnections().length == 1;
}
/**
* {@inheritDoc}
*/
public void run()
{
IAdaptable element = null;
String pageId = null;
String title = null;
if ( getSelectedConnections().length == 1 )
{
element = getSelectedConnections()[0];
pageId = ConnectionUIPlugin.getDefault().getPluginProperties()
.getString( "Prop_ConnectionPropertyPage_id" ); //$NON-NLS-1$
title = getSelectedConnections()[0].getName();
}
if ( element != null )
{
PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn( getShell(), element, pageId, null, null );
if ( dialog != null )
{
title = Utils.shorten( title, 30 );
}
dialog.getShell().setText(
NLS.bind( Messages.getString( "PropertiesAction.PropertiesFor" ), new String[] //$NON-NLS-1$
{ title } ) );
dialog.open();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/NewConnectionAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/NewConnectionAction.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.ui.actions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.connection.ui.ConnectionUIConstants;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.apache.directory.studio.connection.ui.wizards.NewConnectionWizard;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.PlatformUI;
/**
* This Action launches the New Connection Wizard.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewConnectionAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public void run()
{
List<Object> selectedObjects = new ArrayList<>();
selectedObjects.addAll( Arrays.asList( getSelectedConnectionFolders() ) );
selectedObjects.addAll( Arrays.asList( getSelectedConnections() ) );
NewConnectionWizard wizard = new NewConnectionWizard();
wizard.init( PlatformUI.getWorkbench(), new StructuredSelection( selectedObjects ) );
WizardDialog dialog = new WizardDialog( getShell(), wizard );
dialog.setBlockOnOpen( true );
dialog.create();
dialog.open();
}
/**
* {@inheritDoc}
*/
public String getText()
{
return Messages.getString( "NewConnectionAction.NewConnection" ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return ConnectionUIPlugin.getDefault().getImageDescriptor( ConnectionUIConstants.IMG_CONNECTION_ADD );
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return null;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return true;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/NewConnectionFolderAction.java | plugins/connection.ui/src/main/java/org/apache/directory/studio/connection/ui/actions/NewConnectionFolderAction.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.ui.actions;
import org.apache.commons.lang3.StringUtils;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.ui.ConnectionUIConstants;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.apache.directory.studio.connection.ui.dialogs.ConnectionFolderDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
/**
* This Action launches the New Connection Folder Dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewConnectionFolderAction extends StudioAction
{
/**
* {@inheritDoc}
*/
public void run()
{
ConnectionFolderDialog dialog = new ConnectionFolderDialog(
PlatformUI.getWorkbench().getDisplay().getActiveShell(),
Messages.getString( "NewConnectionFolderAction.NewConnectionFolder" ),
Messages.getString( "NewConnectionFolderAction.NeterNameNewFolder" ), StringUtils.EMPTY, null ); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
if ( dialog.open() == ConnectionFolderDialog.OK )
{
String name = dialog.getValue();
ConnectionFolder folder = new ConnectionFolder( name );
ConnectionCorePlugin.getDefault().getConnectionFolderManager().addConnectionFolder( folder );
ConnectionFolder[] folders = getSelectedConnectionFolders();
if ( ( folders != null ) && ( folders.length > 0 ) )
{
folders[0].addSubFolderId( folder.getId() );
}
else
{
ConnectionCorePlugin.getDefault().getConnectionFolderManager().getRootConnectionFolder()
.addSubFolderId( folder.getId() );
}
}
}
/**
* {@inheritDoc}
*/
public String getText()
{
return Messages.getString( "NewConnectionFolderAction.NewConnectionFolderDots" ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getImageDescriptor()
{
return ConnectionUIPlugin.getDefault().getImageDescriptor( ConnectionUIConstants.IMG_CONNECTION_FOLDER_ADD );
}
/**
* {@inheritDoc}
*/
public String getCommandId()
{
return null;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled()
{
return true;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.