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/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ImportTemplatesWizard.java
plugins/templateeditor/src/main/java/org/apache/directory/studio/templateeditor/view/wizards/ImportTemplatesWizard.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.templateeditor.view.wizards; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils; import org.apache.directory.studio.templateeditor.view.preferences.PreferencesTemplatesManager; /** * This class implements the wizard for importing new templates from the disk. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ImportTemplatesWizard extends Wizard implements IImportWizard { /** The wizard page */ private ImportTemplatesWizardPage page; /** The templates manager */ private PreferencesTemplatesManager manager; /** * Creates a new instance of ImportTemplatesWizard. * */ public ImportTemplatesWizard( PreferencesTemplatesManager manager ) { this.manager = manager; } /** * {@inheritDoc} */ public void addPages() { page = new ImportTemplatesWizardPage(); addPage( page ); } /** * {@inheritDoc} */ public boolean performFinish() { // Saving the dialog settings page.saveDialogSettings(); // Getting the templates to be imported final File[] selectedTemplateFiles = page.getSelectedTemplateFiles(); // Creating a list where all the template files that could not be // imported will be stored final List<File> failedTemplates = new ArrayList<File>(); // Running the code to add the templates in a separate container // with progress monitor try { getContainer().run( false, false, new IRunnableWithProgress() { public void run( IProgressMonitor monitor ) { for ( File selectedTemplateFile : selectedTemplateFiles ) { if ( !manager.addTemplate( selectedTemplateFile ) ) { failedTemplates.add( selectedTemplateFile ); } } } } ); } catch ( InvocationTargetException e ) { // Nothing to do (it will never occur) } catch ( InterruptedException e ) { // Nothing to do. } // Handling the templates that could not be added if ( failedTemplates.size() > 0 ) { String title = null; String message = null; // Only one template could not be imported if ( failedTemplates.size() == 1 ) { title = Messages.getString( "ImportTemplatesWizard.ATemplateCouldNotBeImported" ); //$NON-NLS-1$ message = MessageFormat.format( Messages .getString( "ImportTemplatesWizard.TheTemplateCouldNotBeImported" ), failedTemplates.get( 0 ) //$NON-NLS-1$ .getAbsolutePath() ); } // Several templates could not be imported else { title = Messages.getString( "ImportTemplatesWizard.SeveralTemplatesCouldNotBeImported" ); //$NON-NLS-1$ message = Messages.getString( "ImportTemplatesWizard.TheFollowingTemplatesCouldNotBeImported" ); //$NON-NLS-1$ for ( File failedTemplate : failedTemplates ) { message += EntryTemplatePluginUtils.LINE_SEPARATOR + " - " + failedTemplate.getAbsolutePath(); //$NON-NLS-1$ } } // Common ending message message += EntryTemplatePluginUtils.LINE_SEPARATOR + EntryTemplatePluginUtils.LINE_SEPARATOR + Messages.getString( "ImportTemplatesWizard.SeeTheLogsFileForMoreInformation" ); //$NON-NLS-1$ // Creating and opening the dialog MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, null, message, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, MessageDialog.OK ); dialog.open(); } return true; } /** * {@inheritDoc} */ public void init( IWorkbench workbench, IStructuredSelection selection ) { // Nothing to do. } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/Messages.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/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.combinededitor; 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.combinededitor.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); private Messages() { } public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/CombinedEditorPlugin.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/CombinedEditorPlugin.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.combinededitor; import java.io.IOException; import java.net.URL; import java.util.PropertyResourceBundle; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * */ public class CombinedEditorPlugin extends AbstractUIPlugin { /** The shared instance */ private static CombinedEditorPlugin plugin; /** The plugin properties */ private PropertyResourceBundle properties; /** * The constructor */ public CombinedEditorPlugin() { } /** * {@inheritDoc} */ public void start( BundleContext context ) throws Exception { super.start( context ); plugin = this; } /** * {@inheritDoc} */ public void stop( BundleContext context ) throws Exception { plugin = null; super.stop( context ); } /** * Returns the shared instance * * @return the shared instance */ public static CombinedEditorPlugin getDefault() { return plugin; } /** * Use this method to get SWT images. Use the IMG_ constants from * PluginConstants for the key. * * @param key * The key (relative path to the image in filesystem) * @return The image descriptor or null */ public ImageDescriptor getImageDescriptor( String key ) { if ( key != null ) { URL url = FileLocator.find( getBundle(), new Path( key ), null ); if ( url != null ) return ImageDescriptor.createFromURL( url ); else return null; } else { return null; } } /** * Use this method to get SWT images. Use the IMG_ constants from * PluginConstants for the key. A ImageRegistry is used to manage the * the key->Image mapping. * <p> * Note: Don't dispose the returned SWT Image. It is disposed * automatically when the plugin is stopped. * * @param key * The key (relative path to the image in filesystem) * @return The SWT Image or null */ public Image getImage( String key ) { Image image = getImageRegistry().get( key ); if ( image == null ) { ImageDescriptor id = getImageDescriptor( key ); if ( id != null ) { image = id.createImage(); getImageRegistry().put( key, image ); } } return image; } /** * Gets the plugin properties. * * @return * the plugin properties */ public PropertyResourceBundle getPluginProperties() { if ( properties == null ) { try { properties = new PropertyResourceBundle( FileLocator.openStream( this.getBundle(), new Path( "plugin.properties" ), false ) ); //$NON-NLS-1$ } catch ( IOException e ) { // We can't use the PLUGIN_ID constant since loading the plugin.properties file has failed, // So we're using a default plugin id. getLog().log( new Status( Status.ERROR, "org.apache.directory.studio.combinededitor", Status.OK, //$NON-NLS-1$ Messages.getString( "CombinedEditorPlugin.UnableToGetPluginProperties" ), e ) ); //$NON-NLS-1$ } } return properties; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/PreferenceInitializer.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/PreferenceInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.combinededitor; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * This class initializes the preferences of the plugin. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class PreferenceInitializer extends AbstractPreferenceInitializer { /** * {@inheritDoc} */ public void initializeDefaultPreferences() { IPreferenceStore store = CombinedEditorPlugin.getDefault().getPreferenceStore(); // Preferences store.setDefault( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE ); store.setDefault( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR, true ); store.setDefault( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR, CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_TABLE ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/CombinedEditorPluginConstants.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/CombinedEditorPluginConstants.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.combinededitor; /** * This interface contains all the Constants used in the Plugin. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface CombinedEditorPluginConstants { /** The plug-in ID */ String PLUGIN_ID = CombinedEditorPluginConstants.class.getPackage().getName(); // Preferences String PREF_DEFAULT_EDITOR = PLUGIN_ID + ".prefs.DefaultEditor"; //$NON-NLS-1$ int PREF_DEFAULT_EDITOR_TEMPLATE = 1; int PREF_DEFAULT_EDITOR_TABLE = 2; int PREF_DEFAULT_EDITOR_LDIF = 3; String PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR = PLUGIN_ID + ".prefs.AutoSwitchToAnotherEditor"; //$NON-NLS-1$ String PREF_AUTO_SWITCH_EDITOR = PLUGIN_ID + ".prefs.AutoSwitchEditor"; //$NON-NLS-1$ int PREF_AUTO_SWITCH_EDITOR_TABLE = 1; int PREF_AUTO_SWITCH_EDITOR_LDIF = 2; }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/LdifEditorPage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/LdifEditorPage.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.combinededitor.editor; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.studio.entryeditors.EntryEditorInput; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry; import org.apache.directory.studio.ldapbrowser.core.utils.CompoundModification; import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifeditor.LdifEditorActivator; import org.apache.directory.studio.ldifeditor.LdifEditorConstants; import org.apache.directory.studio.ldifeditor.widgets.LdifEditorWidget; import org.apache.directory.studio.ldifparser.model.LdifFile; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.container.LdifInvalidContainer; import org.apache.directory.studio.ldifparser.model.container.LdifRecord; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.apache.directory.studio.combinededitor.actions.FetchOperationalAttributesAction; import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent; import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener; import org.apache.directory.studio.templateeditor.actions.EditorPagePropertiesAction; import org.apache.directory.studio.templateeditor.actions.RefreshAction; import org.apache.directory.studio.templateeditor.actions.SimpleActionProxy; /** * This class implements an editor page for the LDIF Editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class LdifEditorPage extends AbstractCombinedEntryEditorPage { /** The LDIF editor widget */ private LdifEditorWidget ldifEditorWidget; /** A count to know if the editor page has updated the shared working copy */ private int hasUpdatedSharedWorkingCopyCount = 0; /** The modify listener for the widget */ private WidgetModifyListener listener = new WidgetModifyListener() { public void widgetModified( WidgetModifyEvent event ) { updateSharedWorkingCopy(); } }; /** The context menu */ private Menu contextMenu; /** * Creates a new instance of LdifEditorPage. * * @param editor * the associated editor */ public LdifEditorPage( CombinedEntryEditor editor ) { super( editor ); // Creating and assigning the tab item CTabItem tabItem = new CTabItem( editor.getTabFolder(), SWT.NONE ); tabItem.setText( Messages.getString( "LdifEditorPage.LDIFEditor" ) ); //$NON-NLS-1$ tabItem.setImage( LdifEditorActivator.getDefault().getImage( LdifEditorConstants.IMG_BROWSER_LDIFEDITOR ) ); setTabItem( tabItem ); } /** * {@inheritDoc} */ public void init() { super.init(); ldifEditorWidget = new LdifEditorWidget( null, "", true ); //$NON-NLS-1$ ldifEditorWidget.createWidget( getEditor().getTabFolder() ); // Creating a new menu manager Control sourceViewerControl = ldifEditorWidget.getSourceViewer().getControl(); MenuManager menuManager = new MenuManager(); contextMenu = menuManager.createContextMenu( sourceViewerControl ); sourceViewerControl.setMenu( contextMenu ); IEditorSite site = getEditor().getEditorSite(); IActionBars bars = site.getActionBars(); Action cutAction = new Action( "Cut" ) { public void run() { ldifEditorWidget.getSourceViewer().doOperation( SourceViewer.CUT ); } }; Action copyAction = new Action( "Copy" ) { public void run() { ldifEditorWidget.getSourceViewer().doOperation( SourceViewer.COPY ); } }; Action pasteAction = new Action( "Paste" ) { public void run() { ldifEditorWidget.getSourceViewer().doOperation( SourceViewer.PASTE ); } }; bars.setGlobalActionHandler( ActionFactory.CUT.getId(), cutAction ); bars.setGlobalActionHandler( ActionFactory.COPY.getId(), copyAction ); bars.setGlobalActionHandler( ActionFactory.PASTE.getId(), pasteAction ); // TODO remove this menuManager.add( ActionFactory.CUT.create( PlatformUI.getWorkbench().getActiveWorkbenchWindow() ) ); menuManager.add( ActionFactory.COPY.create( PlatformUI.getWorkbench().getActiveWorkbenchWindow() ) ); menuManager.add( ActionFactory.PASTE.create( PlatformUI.getWorkbench().getActiveWorkbenchWindow() ) ); menuManager.add( new Separator() ); menuManager.add( new RefreshAction( getEditor() ) ); menuManager.add( new FetchOperationalAttributesAction( getEditor() ) ); menuManager.add( new Separator() ); menuManager.add( new SimpleActionProxy( new EditorPagePropertiesAction( getEditor() ) ) ); setInput(); getTabItem().setControl( ldifEditorWidget.getControl() ); } /** * Adds the listener. */ private void addListener() { ldifEditorWidget.addWidgetModifyListener( listener ); } /** * Removes the listener. */ private void removeListener() { ldifEditorWidget.removeWidgetModifyListener( listener ); } /** * Updates the shared working copy entry. */ private void updateSharedWorkingCopy() { LdifFile ldifModel = ldifEditorWidget.getLdifModel(); // only continue if the LDIF model is valid LdifRecord[] records = ldifModel.getRecords(); if ( records.length != 1 || !( records[0] instanceof LdifContentRecord ) || !records[0].isValid() || !records[0].getDnLine().isValid() ) { return; } for ( LdifContainer ldifContainer : ldifModel.getContainers() ) { if ( ldifContainer instanceof LdifInvalidContainer ) { return; } } // update shared working copy try { LdifContentRecord modifiedRecord = ( LdifContentRecord ) records[0]; EntryEditorInput input = getEditor().getEntryEditorInput(); IEntry sharedWorkingCopyEntry = input.getSharedWorkingCopy( getEditor() ); IBrowserConnection browserConnection = input.getSharedWorkingCopy( getEditor() ).getBrowserConnection(); DummyEntry modifiedEntry = ModelConverter.ldifContentRecordToEntry( modifiedRecord, browserConnection ); ( ( DummyEntry ) sharedWorkingCopyEntry ).setDn( modifiedEntry.getDn() ); new CompoundModification().replaceAttributes( modifiedEntry, sharedWorkingCopyEntry, this ); // Increasing the update count hasUpdatedSharedWorkingCopyCount++; } catch ( LdapInvalidDnException e ) { throw new RuntimeException( e ); } } /** * Sets the input to the LDIF Editor widget. */ private void setInput() { removeListener(); if ( ldifEditorWidget != null ) { SourceViewer sourceViewer = ldifEditorWidget.getSourceViewer(); IEntry entry = getEditor().getEntryEditorInput().getSharedWorkingCopy( getEditor() ); if ( entry != null ) { // Making the source viewer editable sourceViewer.setEditable( true ); // Showing the context menu sourceViewer.getControl().setMenu( contextMenu ); // Assigning the content to the source viewer sourceViewer.getDocument().set( ModelConverter.entryToLdifContentRecord( entry ) .toFormattedString( Utils.getLdifFormatParameters() ) ); } else { // Making the source viewer non editable sourceViewer.setEditable( false ); // Hiding the context menu sourceViewer.getControl().setMenu( null ); // Assigning a blank content to the source viewer sourceViewer.getDocument().set( "" ); //$NON-NLS-1$ } } addListener(); } /** * {@inheritDoc} */ public void update() { // Checking if the editor page is the source of this update if ( hasUpdatedSharedWorkingCopyCount != 0 ) { // Decreasing the number of updates to be discarded hasUpdatedSharedWorkingCopyCount--; } else { // Reseting the input setInput(); } } /** * {@inheritDoc} */ public void setFocus() { // Nothing to do. } /** * {@inheritDoc} */ public void editorInputChanged() { if ( isInitialized() ) { setInput(); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/CombinedEntryEditorNavigationLocation.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/CombinedEntryEditorNavigationLocation.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.combinededitor.editor; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.entryeditors.EntryEditorExtension; import org.apache.directory.studio.entryeditors.EntryEditorInput; import org.apache.directory.studio.entryeditors.EntryEditorManager; import org.apache.directory.studio.entryeditors.EntryEditorUtils; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBookmark; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIPlugin; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.INavigationLocation; import org.eclipse.ui.NavigationLocation; /** * This class is used to mark the entry editor input to the navigation history. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CombinedEntryEditorNavigationLocation extends NavigationLocation { private static final String BOOKMARK_TAG = "BOOKMARK"; //$NON-NLS-1$ private static final String CONNECTION_TAG = "CONNECTION"; //$NON-NLS-1$ private static final String DN_TAG = "DN"; //$NON-NLS-1$ private static final String EXTENSION_TAG = "EXTENSION"; //$NON-NLS-1$ private static final String SEARCH_TAG = "SEARCH"; //$NON-NLS-1$ private static final String TYPE_BOOKMARK_VALUE = "IBookmark"; //$NON-NLS-1$ private static final String TYPE_SEARCHRESULT_VALUE = "ISearchResult"; //$NON-NLS-1$ private static final String TYPE_TAG = "TYPE"; //$NON-NLS-1$ private static final String TYPE_ENTRY_VALUE = "IEntry"; //$NON-NLS-1$ /** * Creates a new instance of EntryEditorNavigationLocation. * * @param editor the entry editor */ protected CombinedEntryEditorNavigationLocation( IEditorPart editor ) { super( editor ); } /** * {@inheritDoc} */ public String getText() { String text = EntryEditorUtils.getHistoryNavigationText( getEntryEditorInput() ); return text != null ? text : super.getText(); } /** * {@inheritDoc} */ public void saveState( IMemento memento ) { EntryEditorInput eei = getEntryEditorInput(); if ( eei != null ) { memento.putString( EXTENSION_TAG, eei.getExtension().getId() ); if ( eei.getEntryInput() != null ) { IEntry entry = eei.getEntryInput(); memento.putString( TYPE_TAG, TYPE_ENTRY_VALUE ); memento.putString( DN_TAG, entry.getDn().getName() ); memento.putString( CONNECTION_TAG, entry.getBrowserConnection().getConnection().getId() ); } else if ( eei.getSearchResultInput() != null ) { ISearchResult searchResult = eei.getSearchResultInput(); memento.putString( TYPE_TAG, TYPE_SEARCHRESULT_VALUE ); memento.putString( DN_TAG, searchResult.getDn().getName() ); memento.putString( SEARCH_TAG, searchResult.getSearch().getName() ); memento.putString( CONNECTION_TAG, searchResult.getSearch().getBrowserConnection().getConnection() .getId() ); } else if ( eei.getBookmarkInput() != null ) { IBookmark bookmark = eei.getBookmarkInput(); memento.putString( TYPE_TAG, TYPE_BOOKMARK_VALUE ); memento.putString( BOOKMARK_TAG, bookmark.getName() ); memento.putString( CONNECTION_TAG, bookmark.getBrowserConnection().getConnection().getId() ); } } } /** * {@inheritDoc} */ public void restoreState( IMemento memento ) { try { String type = memento.getString( TYPE_TAG ); String extensionId = memento.getString( EXTENSION_TAG ); EntryEditorManager entryEditorManager = BrowserUIPlugin.getDefault().getEntryEditorManager(); EntryEditorExtension entryEditorExtension = entryEditorManager.getEntryEditorExtension( extensionId ); if ( TYPE_ENTRY_VALUE.equals( type ) ) { IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnectionById( memento.getString( CONNECTION_TAG ) ); Dn dn = new Dn( memento.getString( DN_TAG ) ); IEntry entry = connection.getEntryFromCache( dn ); super.setInput( new EntryEditorInput( entry, entryEditorExtension ) ); } else if ( TYPE_SEARCHRESULT_VALUE.equals( type ) ) { IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnectionById( memento.getString( CONNECTION_TAG ) ); ISearch search = connection.getSearchManager().getSearch( memento.getString( SEARCH_TAG ) ); ISearchResult[] searchResults = search.getSearchResults(); Dn dn = new Dn( memento.getString( DN_TAG ) ); for ( int i = 0; i < searchResults.length; i++ ) { if ( dn.equals( searchResults[i].getDn() ) ) { super.setInput( new EntryEditorInput( searchResults[i], entryEditorExtension ) ); break; } } } else if ( TYPE_BOOKMARK_VALUE.equals( type ) ) { IBrowserConnection connection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnectionById( memento.getString( CONNECTION_TAG ) ); IBookmark bookmark = connection.getBookmarkManager().getBookmark( memento.getString( BOOKMARK_TAG ) ); super.setInput( new EntryEditorInput( bookmark, entryEditorExtension ) ); } } catch ( LdapInvalidDnException e ) { e.printStackTrace(); } } /** * {@inheritDoc} */ public void restoreLocation() { } /** * {@inheritDoc} */ public boolean mergeInto( INavigationLocation currentLocation ) { if ( currentLocation == null ) { return false; } if ( getClass() != currentLocation.getClass() ) { return false; } CombinedEntryEditorNavigationLocation location = ( CombinedEntryEditorNavigationLocation ) currentLocation; Object other = location.getEntryEditorInput().getInput(); Object entry = getEntryEditorInput().getInput(); if ( other == null && entry == null ) { return true; } else if ( other == null || entry == null ) { return false; } else { return entry.equals( other ); } } /** * {@inheritDoc} */ public void update() { } /** * Gets the input. * * @return the input */ private EntryEditorInput getEntryEditorInput() { Object editorInput = getInput(); if ( editorInput instanceof EntryEditorInput ) { EntryEditorInput entryEditorInput = ( EntryEditorInput ) editorInput; return entryEditorInput; } return null; } /** * {@inheritDoc} */ public String toString() { return "" + getEntryEditorInput().getInput(); //$NON-NLS-1$ } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/SingleTabCombinedEntryEditor.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/SingleTabCombinedEntryEditor.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.combinededitor.editor; /** * An entry editor the opens all entries in one single editor tab. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SingleTabCombinedEntryEditor extends CombinedEntryEditor { /** * {@inheritDoc} */ public boolean isAutoSave() { return false; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TemplateEditorPage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TemplateEditorPage.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.combinededitor.editor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabItem; import org.apache.directory.studio.templateeditor.EntryTemplatePlugin; import org.apache.directory.studio.templateeditor.EntryTemplatePluginConstants; import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget; import org.apache.directory.studio.templateeditor.model.Template; /** * This class implements an editor page for the Template Editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class TemplateEditorPage extends AbstractCombinedEntryEditorPage { /** The template editor widget */ private TemplateEditorWidget templateEditorWidget; /** * Creates a new instance of TemplateEditorPage. * * @param editor * the associated editor */ public TemplateEditorPage( CombinedEntryEditor editor ) { super( editor ); // Creating and assigning the tab item CTabItem tabItem = new CTabItem( editor.getTabFolder(), SWT.NONE ); tabItem.setText( Messages.getString( "TemplateEditorPage.TemplateEditor" ) ); //$NON-NLS-1$ tabItem.setImage( EntryTemplatePlugin.getDefault().getImage( EntryTemplatePluginConstants.IMG_TEMPLATE ) ); setTabItem( tabItem ); // Creating the template editor widget templateEditorWidget = new TemplateEditorWidget( editor ); } /** * {@inheritDoc} */ public void init() { if ( templateEditorWidget != null ) { // Initializing the template editor widget templateEditorWidget.init( getEditor().getTabFolder() ); // Updating the editor's tab folder to force the attachment of the new form getTabItem().setControl( templateEditorWidget.getForm() ); getEditor().getTabFolder().update(); } } /** * {@inheritDoc} */ public void dispose() { if ( templateEditorWidget != null ) { // Disposing the template editor widget templateEditorWidget.dispose(); } } /** * {@inheritDoc} */ public void update() { if ( templateEditorWidget != null ) { // Updating the template editor widget templateEditorWidget.update(); // Updating the editor's tab folder to force the attachment of the new form getTabItem().setControl( templateEditorWidget.getForm() ); getEditor().getTabFolder().update(); } } /** * {@inheritDoc} */ public void setFocus() { if ( templateEditorWidget != null ) { // Setting focus on the template editor widget templateEditorWidget.setFocus(); } } /** * {@inheritDoc} */ public void editorInputChanged() { if ( templateEditorWidget != null ) { // Changing the editor input on the template editor widget templateEditorWidget.editorInputChanged(); // Updating the editor's tab folder to force the attachment of the new form getTabItem().setControl( templateEditorWidget.getForm() ); getEditor().getTabFolder().update(); } } /** * This method is called by the editor when a 'Switch Template' event occurs. * * @param templateEditorWidget * the template editor widget * @param template * the template */ public void templateSwitched( TemplateEditorWidget templateEditorWidget, Template template ) { // Updating the editor's tab folder to force the attachment of the new form getTabItem().setControl( templateEditorWidget.getForm() ); getEditor().getTabFolder().update(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TableEditorPageActionGroup.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TableEditorPageActionGroup.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.combinededitor.editor; import org.apache.directory.studio.connection.ui.actions.CollapseAllAction; import org.apache.directory.studio.connection.ui.actions.ExpandAllAction; import org.apache.directory.studio.entryeditors.IEntryEditor; import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator; import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants; import org.apache.directory.studio.ldapbrowser.common.actions.DeleteAllValuesAction; import org.apache.directory.studio.ldapbrowser.common.actions.FetchOperationalAttributesAction; import org.apache.directory.studio.ldapbrowser.common.actions.NewAttributeAction; import org.apache.directory.studio.ldapbrowser.common.actions.RefreshAction; import org.apache.directory.studio.ldapbrowser.common.actions.proxy.EntryEditorActionProxy; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EditAttributeDescriptionAction; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidget; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidgetActionGroup; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidgetConfiguration; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.OpenDefaultEditorAction; import org.apache.directory.studio.ldapbrowser.ui.actions.CopyAttributeDescriptionAction; import org.apache.directory.studio.ldapbrowser.ui.actions.CopyDnAction; import org.apache.directory.studio.ldapbrowser.ui.actions.CopySearchFilterAction; import org.apache.directory.studio.ldapbrowser.ui.actions.CopyUrlAction; import org.apache.directory.studio.ldapbrowser.ui.actions.CopyValueAction; import org.apache.directory.studio.ldapbrowser.ui.actions.LocateDnInDitAction; import org.apache.directory.studio.ldapbrowser.ui.actions.NewBatchOperationAction; import org.apache.directory.studio.ldapbrowser.ui.actions.NewSearchAction; import org.apache.directory.studio.ldapbrowser.ui.actions.OpenSchemaBrowserAction; import org.apache.directory.studio.ldapbrowser.ui.editors.entry.OpenEntryEditorAction; import org.apache.directory.studio.ldapbrowser.ui.editors.entry.OpenEntryEditorPreferencePageAction; import org.apache.directory.studio.utils.ActionUtils; import org.apache.directory.studio.valueeditors.ValueEditorManager; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ContributionItemFactory; import org.apache.directory.studio.templateeditor.actions.EditorPagePropertiesAction; /** * The EntryEditorWidgetActionGroup manages all actions of the entry editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class TableEditorPageActionGroup extends EntryEditorWidgetActionGroup { /** The open entry value editor action. */ private EntryEditorActionProxy openEntryValueEditorActionProxy; /** The open entry editor preference page. */ private OpenEntryEditorPreferencePageAction openEntryEditorPreferencePage; /** The collapse all action. */ private CollapseAllAction collapseAllAction; /** The expand all action. */ private ExpandAllAction expandAllAction; /** The Constant editAttributeDescriptionAction. */ private static final String editAttributeDescriptionAction = "editAttributeDescriptionAction"; //$NON-NLS-1$ /** The Constant refreshAttributesAction. */ private static final String refreshAttributesAction = "refreshAttributesAction"; //$NON-NLS-1$ /** The Constant newAttributeAction. */ private static final String newAttributeAction = "newAttributeAction"; //$NON-NLS-1$ /** The Constant newSearchAction. */ private static final String newSearchAction = "newSearchDialogAction"; //$NON-NLS-1$ /** The Constant newBatchOperationAction. */ private static final String newBatchOperationAction = "newBatchOperationAction"; //$NON-NLS-1$ /** The Constant copyDnAction. */ private static final String copyDnAction = "copyDnAction"; //$NON-NLS-1$ /** The Constant copyUrlAction. */ private static final String copyUrlAction = "copyUrlAction"; //$NON-NLS-1$ /** The Constant copyAttriuteDescriptionAction. */ private static final String copyAttriuteDescriptionAction = "copyAttriuteDescriptionAction"; //$NON-NLS-1$ /** The Constant copyDisplayValueAction. */ private static final String copyDisplayValueAction = "copyDisplayValueAction"; //$NON-NLS-1$ /** The Constant copyValueUtf8Action. */ private static final String copyValueUtf8Action = "copyValueUtf8Action"; //$NON-NLS-1$ /** The Constant copyValueBase64Action. */ private static final String copyValueBase64Action = "copyValueBase64Action"; //$NON-NLS-1$ /** The Constant copyValueHexAction. */ private static final String copyValueHexAction = "copyValueHexAction"; //$NON-NLS-1$ /** The Constant copyValueAsLdifAction. */ private static final String copyValueAsLdifAction = "copyValueAsLdifAction"; //$NON-NLS-1$ /** The Constant copySearchFilterAction. */ private static final String copySearchFilterAction = "copySearchFilterAction"; //$NON-NLS-1$ /** The Constant copyNotSearchFilterAction. */ private static final String copyNotSearchFilterAction = "copyNotSearchFilterAction"; //$NON-NLS-1$ /** The Constant copyAndSearchFilterAction. */ private static final String copyAndSearchFilterAction = "copyAndSearchFilterAction"; //$NON-NLS-1$ /** The Constant copyOrSearchFilterAction. */ private static final String copyOrSearchFilterAction = "copyOrSearchFilterAction"; //$NON-NLS-1$ /** The Constant deleteAllValuesAction. */ private static final String deleteAllValuesAction = "deleteAllValuesAction"; //$NON-NLS-1$ /** The Constant locateDnInDitAction. */ private static final String locateDnInDitAction = "locateDnInDitAction"; //$NON-NLS-1$ /** The Constant showOcdAction. */ private static final String showOcdAction = "showOcdAction"; //$NON-NLS-1$ /** The Constant showAtdAction. */ private static final String showAtdAction = "showAtdAction"; //$NON-NLS-1$ /** The Constant showEqualityMrdAction. */ private static final String showEqualityMrdAction = "showEqualityMrdAction"; //$NON-NLS-1$ /** The Constant showSubstringMrdAction. */ private static final String showSubstringMrdAction = "showSubstringMrdAction"; //$NON-NLS-1$ /** The Constant showOrderingMrdAction. */ private static final String showOrderingMrdAction = "showOrderingMrdAction"; //$NON-NLS-1$ /** The Constant showLsdAction. */ private static final String showLsdAction = "showLsdAction"; //$NON-NLS-1$ /** The Constant fetchOperationalAttributesAction. */ private static final String fetchOperationalAttributesAction = "fetchOperationalAttributesAction"; //$NON-NLS-1$ /** * Creates a new instance of TableEditorPageActionGroup. * @param editor * * @param entryEditor the entry editor * @param configuration the configuration */ public TableEditorPageActionGroup( IEntryEditor entryEditor, EntryEditorWidget mainWidget, EntryEditorWidgetConfiguration configuration ) { super( mainWidget, configuration ); TreeViewer viewer = mainWidget.getViewer(); ValueEditorManager valueEditorManager = configuration.getValueEditorManager( viewer ); // create OpenDefaultEditorAction with enabled rename action flag openDefaultValueEditorActionProxy.dispose(); openDefaultValueEditorActionProxy = new EntryEditorActionProxy( viewer, new OpenDefaultEditorAction( viewer, openBestValueEditorActionProxy ) ); openEntryValueEditorActionProxy = new EntryEditorActionProxy( viewer, new OpenEntryEditorAction( viewer, valueEditorManager, valueEditorManager.getEntryValueEditor(), this ) ); openEntryEditorPreferencePage = new OpenEntryEditorPreferencePageAction(); collapseAllAction = new CollapseAllAction( viewer ); expandAllAction = new ExpandAllAction( viewer ); entryEditorActionMap.put( editAttributeDescriptionAction, new EntryEditorActionProxy( viewer, new EditAttributeDescriptionAction( viewer ) ) ); entryEditorActionMap.put( refreshAttributesAction, new EntryEditorActionProxy( viewer, new RefreshAction() ) ); entryEditorActionMap.put( newAttributeAction, new EntryEditorActionProxy( viewer, new NewAttributeAction() ) ); entryEditorActionMap.put( newSearchAction, new EntryEditorActionProxy( viewer, new NewSearchAction() ) ); entryEditorActionMap.put( newBatchOperationAction, new EntryEditorActionProxy( viewer, new NewBatchOperationAction() ) ); entryEditorActionMap.put( locateDnInDitAction, new EntryEditorActionProxy( viewer, new LocateDnInDitAction() ) ); entryEditorActionMap.put( showOcdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_OBJECTCLASS ) ) ); entryEditorActionMap.put( showAtdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_ATTRIBUTETYPE ) ) ); entryEditorActionMap.put( showEqualityMrdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_EQUALITYMATCHINGRULE ) ) ); entryEditorActionMap.put( showSubstringMrdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_SUBSTRINGMATCHINGRULE ) ) ); entryEditorActionMap.put( showOrderingMrdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_ORDERINGMATCHINGRULE ) ) ); entryEditorActionMap.put( showLsdAction, new EntryEditorActionProxy( viewer, new OpenSchemaBrowserAction( OpenSchemaBrowserAction.MODE_SYNTAX ) ) ); entryEditorActionMap.put( copyDnAction, new EntryEditorActionProxy( viewer, new CopyDnAction() ) ); entryEditorActionMap.put( copyUrlAction, new EntryEditorActionProxy( viewer, new CopyUrlAction() ) ); entryEditorActionMap.put( copyAttriuteDescriptionAction, new EntryEditorActionProxy( viewer, new CopyAttributeDescriptionAction() ) ); entryEditorActionMap.put( copyDisplayValueAction, new EntryEditorActionProxy( viewer, new CopyValueAction( CopyValueAction.Mode.DISPLAY, valueEditorManager ) ) ); entryEditorActionMap.put( copyValueUtf8Action, new EntryEditorActionProxy( viewer, new CopyValueAction( CopyValueAction.Mode.UTF8, valueEditorManager ) ) ); entryEditorActionMap.put( copyValueBase64Action, new EntryEditorActionProxy( viewer, new CopyValueAction( CopyValueAction.Mode.BASE64, valueEditorManager ) ) ); entryEditorActionMap.put( copyValueHexAction, new EntryEditorActionProxy( viewer, new CopyValueAction( CopyValueAction.Mode.HEX, valueEditorManager ) ) ); entryEditorActionMap.put( copyValueAsLdifAction, new EntryEditorActionProxy( viewer, new CopyValueAction( CopyValueAction.Mode.LDIF, valueEditorManager ) ) ); entryEditorActionMap.put( copySearchFilterAction, new EntryEditorActionProxy( viewer, new CopySearchFilterAction( CopySearchFilterAction.MODE_EQUALS ) ) ); entryEditorActionMap.put( copyNotSearchFilterAction, new EntryEditorActionProxy( viewer, new CopySearchFilterAction( CopySearchFilterAction.MODE_NOT ) ) ); entryEditorActionMap.put( copyAndSearchFilterAction, new EntryEditorActionProxy( viewer, new CopySearchFilterAction( CopySearchFilterAction.MODE_AND ) ) ); entryEditorActionMap.put( copyOrSearchFilterAction, new EntryEditorActionProxy( viewer, new CopySearchFilterAction( CopySearchFilterAction.MODE_OR ) ) ); entryEditorActionMap.put( deleteAllValuesAction, new EntryEditorActionProxy( viewer, new DeleteAllValuesAction() ) ); entryEditorActionMap.put( fetchOperationalAttributesAction, new EntryEditorActionProxy( viewer, new FetchOperationalAttributesAction() ) ); entryEditorActionMap.put( PROPERTY_DIALOG_ACTION, new EntryEditorActionProxy( viewer, new EditorPagePropertiesAction( entryEditor ) ) ); } /** * {@inheritDoc} */ public void dispose() { if ( expandAllAction != null ) { deactivateGlobalActionHandlers(); openEntryValueEditorActionProxy.dispose(); openEntryValueEditorActionProxy = null; openEntryEditorPreferencePage = null; expandAllAction.dispose(); expandAllAction = null; collapseAllAction.dispose(); collapseAllAction = null; } super.dispose(); } /** * {@inheritDoc} */ public void fillToolBar( IToolBarManager toolBarManager ) { toolBarManager.add( new Separator() ); toolBarManager.add( entryEditorActionMap.get( NEW_VALUE_ACTION ) ); toolBarManager.add( entryEditorActionMap.get( newAttributeAction ) ); toolBarManager.add( new Separator() ); toolBarManager.add( entryEditorActionMap.get( DELETE_ACTION ) ); toolBarManager.add( entryEditorActionMap.get( deleteAllValuesAction ) ); toolBarManager.add( new Separator() ); toolBarManager.add( entryEditorActionMap.get( refreshAttributesAction ) ); toolBarManager.add( new Separator() ); toolBarManager.add( expandAllAction ); toolBarManager.add( collapseAllAction ); toolBarManager.add( new Separator() ); toolBarManager.add( showQuickFilterAction ); toolBarManager.update( true ); } /** * {@inheritDoc} */ public void fillMenu( IMenuManager menuManager ) { menuManager.add( openSortDialogAction ); menuManager.add( new Separator() ); menuManager.add( showDecoratedValuesAction ); menuManager.add( new Separator() ); menuManager.add( openEntryEditorPreferencePage ); menuManager.addMenuListener( new IMenuListener() { public void menuAboutToShow( IMenuManager manager ) { showDecoratedValuesAction.setChecked( !BrowserCommonActivator.getDefault().getPreferenceStore() .getBoolean( BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES ) ); } } ); menuManager.update( true ); } /** * {@inheritDoc} */ protected void contextMenuAboutToShow( IMenuManager menuManager ) { // new menuManager.add( entryEditorActionMap.get( newAttributeAction ) ); menuManager.add( entryEditorActionMap.get( NEW_VALUE_ACTION ) ); menuManager.add( entryEditorActionMap.get( newSearchAction ) ); menuManager.add( entryEditorActionMap.get( newBatchOperationAction ) ); menuManager.add( new Separator() ); // navigation menuManager.add( entryEditorActionMap.get( locateDnInDitAction ) ); MenuManager schemaMenuManager = new MenuManager( Messages .getString( "TableEditorPageActionGroup.OpenSchemaBrowser" ) ); //$NON-NLS-1$ schemaMenuManager.add( entryEditorActionMap.get( showOcdAction ) ); schemaMenuManager.add( entryEditorActionMap.get( showAtdAction ) ); schemaMenuManager.add( entryEditorActionMap.get( showEqualityMrdAction ) ); schemaMenuManager.add( entryEditorActionMap.get( showSubstringMrdAction ) ); schemaMenuManager.add( entryEditorActionMap.get( showOrderingMrdAction ) ); schemaMenuManager.add( entryEditorActionMap.get( showLsdAction ) ); menuManager.add( schemaMenuManager ); MenuManager showInSubMenu = new MenuManager( Messages.getString( "TableEditorPageActionGroup.ShowIn" ) ); //$NON-NLS-1$ showInSubMenu.add( ContributionItemFactory.VIEWS_SHOW_IN.create( PlatformUI.getWorkbench() .getActiveWorkbenchWindow() ) ); menuManager.add( showInSubMenu ); menuManager.add( new Separator() ); // copy, paste, delete menuManager.add( entryEditorActionMap.get( COPY_ACTION ) ); menuManager.add( entryEditorActionMap.get( PASTE_ACTION ) ); menuManager.add( entryEditorActionMap.get( DELETE_ACTION ) ); menuManager.add( entryEditorActionMap.get( SELECT_ALL_ACTION ) ); MenuManager advancedMenuManager = new MenuManager( Messages.getString( "TableEditorPageActionGroup.Advanced" ) ); //$NON-NLS-1$ advancedMenuManager.add( entryEditorActionMap.get( copyDnAction ) ); advancedMenuManager.add( entryEditorActionMap.get( copyUrlAction ) ); advancedMenuManager.add( new Separator() ); advancedMenuManager.add( entryEditorActionMap.get( copyAttriuteDescriptionAction ) ); advancedMenuManager.add( new Separator() ); advancedMenuManager.add( entryEditorActionMap.get( copyDisplayValueAction ) ); advancedMenuManager.add( entryEditorActionMap.get( copyValueUtf8Action ) ); advancedMenuManager.add( entryEditorActionMap.get( copyValueBase64Action ) ); advancedMenuManager.add( entryEditorActionMap.get( copyValueHexAction ) ); advancedMenuManager.add( new Separator() ); advancedMenuManager.add( entryEditorActionMap.get( copyValueAsLdifAction ) ); advancedMenuManager.add( new Separator() ); advancedMenuManager.add( entryEditorActionMap.get( copySearchFilterAction ) ); advancedMenuManager.add( entryEditorActionMap.get( copyNotSearchFilterAction ) ); advancedMenuManager.add( entryEditorActionMap.get( copyAndSearchFilterAction ) ); advancedMenuManager.add( entryEditorActionMap.get( copyOrSearchFilterAction ) ); advancedMenuManager.add( new Separator() ); advancedMenuManager.add( entryEditorActionMap.get( deleteAllValuesAction ) ); menuManager.add( advancedMenuManager ); menuManager.add( new Separator() ); // edit menuManager.add( entryEditorActionMap.get( editAttributeDescriptionAction ) ); super.addEditMenu( menuManager ); menuManager.add( openEntryValueEditorActionProxy ); menuManager.add( new Separator() ); // refresh menuManager.add( entryEditorActionMap.get( refreshAttributesAction ) ); if ( entryEditorActionMap.get( fetchOperationalAttributesAction ).isEnabled() ) { menuManager.add( entryEditorActionMap.get( fetchOperationalAttributesAction ) ); } menuManager.add( new Separator() ); // additions menuManager.add( new Separator( IWorkbenchActionConstants.MB_ADDITIONS ) ); // properties menuManager.add( entryEditorActionMap.get( PROPERTY_DIALOG_ACTION ) ); } /** * {@inheritDoc} */ public void activateGlobalActionHandlers() { if ( actionBars != null ) { actionBars.setGlobalActionHandler( ActionFactory.REFRESH.getId(), entryEditorActionMap .get( refreshAttributesAction ) ); } super.activateGlobalActionHandlers(); IAction naa = entryEditorActionMap.get( newAttributeAction ); ActionUtils.activateActionHandler( naa ); IAction lid = entryEditorActionMap.get( locateDnInDitAction ); ActionUtils.activateActionHandler( lid ); IAction eada = entryEditorActionMap.get( editAttributeDescriptionAction ); ActionUtils.activateActionHandler( eada ); ActionUtils.activateActionHandler( openEntryValueEditorActionProxy ); } /** * {@inheritDoc} */ public void deactivateGlobalActionHandlers() { if ( actionBars != null ) { actionBars.setGlobalActionHandler( ActionFactory.REFRESH.getId(), null ); } super.deactivateGlobalActionHandlers(); IAction naa = entryEditorActionMap.get( newAttributeAction ); ActionUtils.deactivateActionHandler( naa ); IAction lid = entryEditorActionMap.get( locateDnInDitAction ); ActionUtils.deactivateActionHandler( lid ); IAction eada = entryEditorActionMap.get( editAttributeDescriptionAction ); ActionUtils.deactivateActionHandler( eada ); ActionUtils.deactivateActionHandler( openEntryValueEditorActionProxy ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/ICombinedEntryEditorPage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/ICombinedEntryEditorPage.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.combinededitor.editor; import org.eclipse.swt.custom.CTabItem; /** * This interface defines a page for the editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ICombinedEntryEditorPage { /** * Disposes any allocated resource. */ void dispose(); /** * This method is called when editor input has changed. */ void editorInputChanged(); /** * Gets the associated editor. * * @return * the associated editor */ CombinedEntryEditor getEditor(); /** * Gets the {@link CTabItem} associated with the editor page. * * @return * the {@link CTabItem} associated with the editor page */ CTabItem getTabItem(); /** * Initializes the control of the page. */ void init(); /** * Returns whether or not the editor page has been initialized. * * @return * <code>true</code> if the editor page has been initialized, * <code>false</code> if not. */ boolean isInitialized(); /** * Asks this part to take focus within the workbench. Parts must * assign focus to one of the controls contained in the part's * parent composite. */ void setFocus(); /** * This method is called when then editor page needs to be updated. */ void update(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/MultiTabCombinedEntryEditor.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/MultiTabCombinedEntryEditor.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.combinededitor.editor; /** * An entry editor the opens entries in a single editor for each entry. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class MultiTabCombinedEntryEditor extends CombinedEntryEditor { /** * {@inheritDoc} */ public boolean isAutoSave() { return false; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/Messages.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/Messages.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.combinededitor.editor; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class Messages { private static final String BUNDLE_NAME = "org.apache.directory.studio.combinededitor.editor.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); private Messages() { } public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/CombinedEntryEditor.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/CombinedEntryEditor.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.combinededitor.editor; import org.apache.directory.studio.entryeditors.EntryEditorInput; import org.apache.directory.studio.entryeditors.EntryEditorUtils; import org.apache.directory.studio.entryeditors.IEntryEditor; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIConstants; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.INavigationLocation; import org.eclipse.ui.INavigationLocationProvider; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.IShowEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.apache.directory.studio.combinededitor.CombinedEditorPlugin; import org.apache.directory.studio.combinededitor.CombinedEditorPluginConstants; import org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils; import org.apache.directory.studio.templateeditor.actions.SwitchTemplateListener; import org.apache.directory.studio.templateeditor.editor.TemplateEditorWidget; import org.apache.directory.studio.templateeditor.model.Template; /** * This class implements the Template Entry Editor. * <p> * This editor is composed of a three tabs TabFolder object: * <ul> * <li>the Template Editor itself</li> * <li>the Table Editor</li> * <li>the LDIF Editor</li> * </ul> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class CombinedEntryEditor extends EditorPart implements INavigationLocationProvider, IEntryEditor, IReusableEditor, IShowEditorInput, SwitchTemplateListener { /** The Template Editor page */ private TemplateEditorPage templateEditorPage; /** The Table Editor page */ private TableEditorPage tableEditorPage; /** The LDIF Editor page */ private LdifEditorPage ldifEditorPage; /** The Tab Folder */ private CTabFolder tabFolder; /** The tab associated with the Template Editor */ private CTabItem templateEditorTab; /** The tab associated with the Table Editor */ private CTabItem tableEditorTab; /** The tab associated with the LDIF Editor */ private CTabItem ldifEditorTab; /** * {@inheritDoc} */ public void init( IEditorSite site, IEditorInput input ) throws PartInitException { setSite( site ); setInput( input ); } /** * {@inheritDoc} */ public void createPartControl( Composite parent ) { // Creating the TabFolder tabFolder = new CTabFolder( parent, SWT.BOTTOM ); // Creating the editor pages and tab items // The Template editor item templateEditorPage = new TemplateEditorPage( this ); templateEditorTab = templateEditorPage.getTabItem(); // The Table editor item tableEditorPage = new TableEditorPage( this ); tableEditorTab = tableEditorPage.getTabItem(); // The LDIF editor item ldifEditorPage = new LdifEditorPage( this ); ldifEditorTab = ldifEditorPage.getTabItem(); // Getting the preference store IPreferenceStore store = CombinedEditorPlugin.getDefault().getPreferenceStore(); // Getting the default editor int defaultEditor = store.getInt( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR ); switch ( defaultEditor ) { case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE : // Getting the boolean indicating if the user wants to auto-switch the template editor boolean autoSwitchToAnotherEditor = store .getBoolean( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR ); if ( autoSwitchToAnotherEditor && !canBeHandledWithATemplate() ) { switch ( store.getInt( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR ) ) { case CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_TABLE : // Selecting the Table Editor tabFolder.setSelection( tableEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically tableEditorPage.init(); break; case CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_LDIF : // Selecting the LDIF Editor tabFolder.setSelection( ldifEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically ldifEditorPage.init(); } } else { // Selecting the Template Editor tabFolder.setSelection( templateEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically templateEditorPage.init(); } break; case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TABLE : // Selecting the Table Editor tabFolder.setSelection( tableEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically tableEditorPage.init(); break; case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_LDIF : // Selecting the LDIF Editor tabFolder.setSelection( ldifEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically ldifEditorPage.init(); } } /** * {@inheritDoc} */ public void workingCopyModified( Object source ) { update(); if ( !isAutoSave() ) { // mark as dirty firePropertyChange( PROP_DIRTY ); } } /** * {@inheritDoc} */ public void dispose() { // // Disposing the TabFolder, its tabs and Editor Pages // // Tab Folder if ( ( tabFolder != null ) && ( !tabFolder.isDisposed() ) ) { tabFolder.dispose(); } // Template Editor Tab if ( ( templateEditorTab != null ) && ( !templateEditorTab.isDisposed() ) ) { templateEditorTab.dispose(); } // Table Editor Tab if ( ( tableEditorTab != null ) && ( !tableEditorTab.isDisposed() ) ) { tableEditorTab.dispose(); } // LDIF Editor Tab if ( ( ldifEditorTab != null ) && ( !ldifEditorTab.isDisposed() ) ) { ldifEditorTab.dispose(); } // Template Editor Page if ( templateEditorPage != null ) { templateEditorPage.dispose(); } // Table Editor Page if ( tableEditorPage != null ) { tableEditorPage.dispose(); } // LDIF Editor Page if ( ldifEditorPage != null ) { ldifEditorPage.dispose(); } super.dispose(); } /** * {@inheritDoc} */ public boolean canHandle( IEntry entry ) { return true; } /** * Indicates whether or not the entry can be handled with a (at least) template. * * @param entry the entry * @return <code>true</code> if the entry can be handled with a template, * <code>false</code> if not. */ private boolean canBeHandledWithATemplate( IEntry entry ) { return ( EntryTemplatePluginUtils.getMatchingTemplates( entry ).size() > 0 ); } /** * Indicates whether or not the input entry can be handled with a (at least) template. * * @return <code>true</code> if the input entry can be handled with a template, * <code>false</code> if not. */ private boolean canBeHandledWithATemplate() { IEditorInput editorInput = getEditorInput(); if ( editorInput instanceof EntryEditorInput ) { IEntry entry = ( ( EntryEditorInput ) editorInput ).getResolvedEntry(); if ( entry != null ) { return canBeHandledWithATemplate( entry ); } } return false; } /** * {@inheritDoc} */ public void doSave( IProgressMonitor monitor ) { if ( !isAutoSave() ) { EntryEditorInput eei = getEntryEditorInput(); eei.saveSharedWorkingCopy( true, this ); } } /** * {@inheritDoc} */ public boolean isDirty() { return getEntryEditorInput().isSharedWorkingCopyDirty( this ); } /** * {@inheritDoc} */ public boolean isSaveAsAllowed() { return false; } /** * {@inheritDoc} */ public void doSaveAs() { // Nothing to do, will never occur as "Save As..." is not allowed } /** * {@inheritDoc} */ public void setFocus() { if ( ( tabFolder != null ) && ( !tabFolder.isDisposed() ) ) { tabFolder.setFocus(); } } /** * {@inheritDoc} */ public EntryEditorInput getEntryEditorInput() { Object editorInput = getEditorInput(); if ( editorInput instanceof EntryEditorInput ) { return ( EntryEditorInput ) editorInput; } return null; } /** * Updates the selected AbstractTemplateEntryEditorPage. */ private void update() { ICombinedEntryEditorPage selectedPage = getEditorPageFromSelectedTab(); if ( selectedPage != null ) { selectedPage.update(); } } /** * {@inheritDoc} */ public void setInput( IEditorInput input ) { super.setInput( input ); setPartName( input.getName() ); } /** * {@inheritDoc} */ public INavigationLocation createEmptyNavigationLocation() { return null; } /** * {@inheritDoc} */ public INavigationLocation createNavigationLocation() { return new CombinedEntryEditorNavigationLocation( this ); } /** * {@inheritDoc} */ public void showEditorInput( IEditorInput input ) { if ( input instanceof EntryEditorInput ) { /* * Optimization: no need to set the input again if the same input is already set */ if ( getEntryEditorInput() != null && getEntryEditorInput().getResolvedEntry() == ( ( EntryEditorInput ) input ).getResolvedEntry() ) { return; } // If the editor is dirty, let's ask for a save before changing the input if ( isDirty() ) { if ( !EntryEditorUtils.askSaveSharedWorkingCopyBeforeInputChange( this ) ) { return; } } // now set the real input and mark history location setInput( input ); getSite().getPage().getNavigationHistory().markLocation( this ); firePropertyChange( BrowserUIConstants.INPUT_CHANGED ); // Getting the preference store IPreferenceStore store = CombinedEditorPlugin.getDefault().getPreferenceStore(); // Getting the default editor switch ( store.getInt( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR ) ) { case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE : // Getting the boolean indicating if the user wants to auto-switch the template editor boolean autoSwitchToAnotherEditor = store .getBoolean( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR ); if ( autoSwitchToAnotherEditor && !canBeHandledWithATemplate() ) { switch ( store.getInt( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR ) ) { case CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_TABLE : // Selecting the Table Editor tabFolder.setSelection( tableEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically tableEditorPage.init(); break; case CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_LDIF : // Selecting the LDIF Editor tabFolder.setSelection( ldifEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically ldifEditorPage.init(); } } else { // Selecting the Template Editor tabFolder.setSelection( templateEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically templateEditorPage.init(); } break; case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TABLE : // Selecting the Table Editor tabFolder.setSelection( tableEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically tableEditorPage.init(); break; case CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_LDIF : // Selecting the LDIF Editor tabFolder.setSelection( ldifEditorTab ); // Forcing the initialization of the first tab item, // because the listener is not triggered when selecting a tab item programmatically ldifEditorPage.init(); break; } // Noticing all pages that the editor input has changed templateEditorPage.editorInputChanged(); tableEditorPage.editorInputChanged(); ldifEditorPage.editorInputChanged(); } } /** * Gets the {@link ICombinedEntryEditorPage} associated with the selected tab. * * @return the {@link ICombinedEntryEditorPage} associated with the selected tab */ private ICombinedEntryEditorPage getEditorPageFromSelectedTab() { CTabItem selectedTabItem = getSelectedTabItem(); if ( selectedTabItem != null ) { // Template Editor Tab if ( selectedTabItem.equals( templateEditorTab ) ) { return templateEditorPage; } // Table Editor Tab else if ( selectedTabItem.equals( tableEditorTab ) ) { return tableEditorPage; } // LDIF Editor Tab else if ( selectedTabItem.equals( ldifEditorTab ) ) { return ldifEditorPage; } } return null; } /** * {@inheritDoc} */ public void templateSwitched( TemplateEditorWidget templateEditorWidget, Template template ) { if ( templateEditorPage != null ) { templateEditorPage.templateSwitched( templateEditorWidget, template ); } } /** * Returns the {@link CTabFolder} associated with the editor. * * @return the {@link CTabFolder} associated with the editor */ public CTabFolder getTabFolder() { return tabFolder; } /** * Returns the currently selected {@link CTabItem}. * * @return the currently selected {@link CTabItem} */ public CTabItem getSelectedTabItem() { return tabFolder.getSelection(); } /** * Get the {@link TemplateEditorPage} page. * * @return the {@link TemplateEditorPage} page * public TemplateEditorPage getTemplateEditorPage() { return templateEditorPage; } /** * Get the {@link TableEditorPage} page. * * @return the {@link TableEditorPage} page * public TableEditorPage getTableEditorPage() { return tableEditorPage; } /** * Get the {@link LdifEditorPage} page. * * @return the {@link LdifEditorPage} page * public LdifEditorPage getLdifEditorPage() { return ldifEditorPage; }*/ }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/AbstractCombinedEntryEditorPage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/AbstractCombinedEntryEditorPage.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.combinededitor.editor; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; /** * This interface defines a page for the editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class AbstractCombinedEntryEditorPage implements ICombinedEntryEditorPage { /** The associated editor */ private CombinedEntryEditor editor; /** The flag to know whether or not the editor page has been initialized */ private boolean initialized = false; /** The {@link CTabItem} associated with the editor page */ private CTabItem tabItem; /** * Creates a new instance of AbstractTemplateEntryEditorPage. * * @param editor the associated editor */ public AbstractCombinedEntryEditorPage( CombinedEntryEditor editor ) { this.editor = editor; } /** * {@inheritDoc} */ public void dispose() { // Default implementation does nothing } /** * {@inheritDoc} */ public void editorInputChanged() { // Default implementation does nothing } /** * {@inheritDoc} */ public CombinedEntryEditor getEditor() { return editor; } /** * {@inheritDoc} */ public CTabItem getTabItem() { return tabItem; } /** * {@inheritDoc} */ public void init() { setInitialized( true ); } /** * {@inheritDoc} */ public boolean isInitialized() { return initialized; } /** * {@inheritDoc} */ public void setFocus() { // Default implementation does nothing } /** * Sets the flag to know whether or not the editor page has been initialized. * * @param initialized * the value */ protected void setInitialized( boolean initialized ) { this.initialized = initialized; } /** * {@inheritDoc} */ public void update() { // Default implementation does nothing } /** * Sets the {@link CTabItem} associated with the editor page. * * @param tabItem * the {@link CTabItem} associated with the editor page */ protected void setTabItem( CTabItem tabItem ) { this.tabItem = tabItem; // Registering a listener on the editor's tab folder if ( ( getEditor() != null ) && ( getEditor().getTabFolder() != null ) && ( !getEditor().getTabFolder().isDisposed() ) ) { getEditor().getTabFolder().addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { tabFolderSelectionChanged(); } } ); } } /** * This method is called when the TabFolder selection is changed. */ private void tabFolderSelectionChanged() { if ( ( getEditor() != null ) && ( getEditor().getTabFolder() != null ) && ( !getEditor().getTabFolder().isDisposed() ) ) { // Getting the selected tab CTabItem selectedTab = getEditor().getTabFolder().getSelection(); // Verifying if the selected tab is this page's tab if ( ( selectedTab != null ) && ( selectedTab.equals( tabItem ) ) ) { // Checking if the page needs to be initialized or updated if ( !isInitialized() ) { // Initializing the page init(); } else { // Updating the page update(); } // Setting the correct focus setFocus(); } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TableEditorPage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/editor/TableEditorPage.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.combinededitor.editor; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidget; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidgetConfiguration; import org.apache.directory.studio.ldapbrowser.common.widgets.entryeditor.EntryEditorWidgetUniversalListener; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIConstants; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIPlugin; import org.apache.directory.studio.valueeditors.ValueEditorManager; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabItem; /** * This class implements an editor page for the Table Editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class TableEditorPage extends AbstractCombinedEntryEditorPage { /** The entry editor widget */ private EntryEditorWidget entryEditorWidget; /** The listener associated with the entry editor widget */ private EntryEditorWidgetUniversalListener listener; /** * Creates a new instance of TableEditorPage. * * @param editor the associated editor */ public TableEditorPage( CombinedEntryEditor editor ) { super( editor ); // Creating and assigning the tab item CTabItem tabItem = new CTabItem( editor.getTabFolder(), SWT.NONE ); tabItem.setText( Messages.getString( "TableEditorPage.TableEditor" ) ); //$NON-NLS-1$ tabItem .setImage( BrowserUIPlugin.getDefault().getImage( BrowserUIConstants.IMG_BROWSER_SINGLETAB_ENTRYEDITOR ) ); setTabItem( tabItem ); } /** * {@inheritDoc} */ public void init() { super.init(); EditorConfiguration configuration = new EditorConfiguration(); entryEditorWidget = new EntryEditorWidget( configuration ); entryEditorWidget.createWidget( getEditor().getTabFolder() ); TableEditorPageActionGroup entryEditorActionGroup = new TableEditorPageActionGroup( getEditor(), entryEditorWidget, configuration ); entryEditorActionGroup.fillToolBar( entryEditorWidget.getToolBarManager() ); entryEditorActionGroup.fillMenu( entryEditorWidget.getMenuManager() ); entryEditorActionGroup.fillContextMenu( entryEditorWidget.getContextMenuManager() ); setInput(); getEditor().getSite().setSelectionProvider( entryEditorWidget.getViewer() ); listener = new EntryEditorWidgetUniversalListener( entryEditorWidget.getViewer(), configuration, entryEditorActionGroup, entryEditorActionGroup.getOpenDefaultEditorAction() ); entryEditorActionGroup.setInput( getEditor().getEntryEditorInput().getSharedWorkingCopy( getEditor() ) ); getEditor().getSite().setSelectionProvider( entryEditorWidget.getViewer() ); getTabItem().setControl( entryEditorWidget.getControl() ); } /** * Sets the input to the Entry Editor Widget. */ private void setInput() { if ( entryEditorWidget != null ) { entryEditorWidget.getViewer().setInput( getEditor().getEntryEditorInput().getSharedWorkingCopy( getEditor() ) ); } } /** * {@inheritDoc} */ public void update() { if ( entryEditorWidget != null ) { entryEditorWidget.getViewer().refresh(); } } /** * {@inheritDoc} */ public void setFocus() { if ( entryEditorWidget != null ) { entryEditorWidget.setFocus(); } } /** * {@inheritDoc} */ public void dispose() { if ( entryEditorWidget != null ) { entryEditorWidget.dispose(); } if ( listener != null ) { listener.dispose(); } } /** * {@inheritDoc} */ public void editorInputChanged() { if ( isInitialized() ) { setInput(); } } /** * A special configuration for the {@link TableEditorPage}. */ class EditorConfiguration extends EntryEditorWidgetConfiguration { /** * {@inheritDoc} */ public ValueEditorManager getValueEditorManager( TreeViewer viewer ) { if ( valueEditorManager == null ) { valueEditorManager = new ValueEditorManager( viewer.getTree(), true, false ); } return valueEditorManager; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/actions/Messages.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/actions/Messages.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.combinededitor.actions; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class Messages { private static final String BUNDLE_NAME = "org.apache.directory.studio.combinededitor.actions.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); private Messages() { } public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/actions/FetchOperationalAttributesAction.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/actions/FetchOperationalAttributesAction.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.combinededitor.actions; import org.apache.directory.studio.entryeditors.IEntryEditor; import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeAttributesRunnable; import org.apache.directory.studio.ldapbrowser.core.jobs.StudioBrowserJob; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.eclipse.jface.action.Action; /** * This action fetches the operational attributes of the entry in the given editor. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class FetchOperationalAttributesAction extends Action { /** The associated editor */ private IEntryEditor editor; /** * Creates a new instance of FetchOperationalAttributesAction. * * @param editor * The associated editor */ public FetchOperationalAttributesAction( IEntryEditor editor ) { this.editor = editor; } @Override public int getStyle() { return Action.AS_CHECK_BOX; } /** * {@inheritDoc} */ public String getText() { return org.apache.directory.studio.ldapbrowser.common.actions.Messages .getString( "FetchOperationalAttributesAction.FetchOperationalAttributes" ); //$NON-NLS-1$ } /** * {@inheritDoc} */ public boolean isEnabled() { if ( editor != null ) { IEntry entry = editor.getEntryEditorInput().getResolvedEntry(); if ( entry != null ) { entry = entry.getBrowserConnection().getEntryFromCache( entry.getDn() ); return !entry.getBrowserConnection().isFetchOperationalAttributes(); } } return false; } /** * {@inheritDoc} */ public void run() { if ( editor != null ) { IEntry entry = editor.getEntryEditorInput().getResolvedEntry(); entry = entry.getBrowserConnection().getEntryFromCache( entry.getDn() ); boolean init = !entry.isInitOperationalAttributes(); entry.setInitOperationalAttributes( init ); new StudioBrowserJob( new InitializeAttributesRunnable( entry ) ).execute(); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/preferences/Messages.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/preferences/Messages.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.combinededitor.preferences; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class Messages { private static final String BUNDLE_NAME = "org.apache.directory.studio.combinededitor.preferences.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); private Messages() { } public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/preferences/CombinedEntryEditorPreferencePage.java
plugins/combinededitor/src/main/java/org/apache/directory/studio/combinededitor/preferences/CombinedEntryEditorPreferencePage.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.combinededitor.preferences; import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.apache.directory.studio.combinededitor.CombinedEditorPlugin; import org.apache.directory.studio.combinededitor.CombinedEditorPluginConstants; import org.apache.directory.studio.templateeditor.EntryTemplatePlugin; /** * This class implements the Combined Entry Editor preference page. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CombinedEntryEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** The preferences store */ private IPreferenceStore store; // UI Fields private Button defaultEditorTemplateRadioButton; private Button autoSwitchToOtherEditorCheckbox; private Button autoSwitchToTableEditorRadioButton; private Button autoSwitchToLDIFEditorRadioButton; private Label autoSwitchLabel; private Button defaultEditorTableRadioButton; private Button defaultEditorLDIFRadioButton; /** * Creates a new instance of CombinedEntryEditorPreferencePage. */ public CombinedEntryEditorPreferencePage() { super(); super.setPreferenceStore( EntryTemplatePlugin.getDefault().getPreferenceStore() ); super.setDescription( Messages.getString( "CombinedEntryEditorPreferencePage.PrefPageDescription" ) ); //$NON-NLS-1$ store = CombinedEditorPlugin.getDefault().getPreferenceStore(); } /** * {@inheritDoc} */ public void init( IWorkbench workbench ) { // Nothing to do } /** * {@inheritDoc} */ protected Control createContents( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout() ); composite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) ); createUI( composite ); initListeners(); initUI(); return composite; } /** * Creates the user interface. * * @param parent * the parent composite */ private void createUI( Composite parent ) { // Main Composite Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); // Default Editor Group Group defaultEditorGroup = BaseWidgetUtils.createGroup( composite, Messages .getString( "CombinedEntryEditorPreferencePage.UseAsDefaultEditor" ), 1 ); //$NON-NLS-1$ defaultEditorGroup.setLayout( new GridLayout( 4, false ) ); // Template Editor Radio Button defaultEditorTemplateRadioButton = BaseWidgetUtils.createRadiobutton( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.TemplateEditor" ), 1 ); //$NON-NLS-1$ defaultEditorTemplateRadioButton.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 4, 1 ) ); // Indent BaseWidgetUtils.createRadioIndent( defaultEditorGroup, 1 ); // Auto Switch Checkbox autoSwitchToOtherEditorCheckbox = BaseWidgetUtils.createCheckbox( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.AutoSwitchToFollowingTabNoTemplateAvailable" ), 1 ); //$NON-NLS-1$ autoSwitchToOtherEditorCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 3, 1 ) ); // Indent BaseWidgetUtils.createRadioIndent( defaultEditorGroup, 1 ); // Indent BaseWidgetUtils.createRadioIndent( defaultEditorGroup, 1 ); // Table Editor Radio Button autoSwitchToTableEditorRadioButton = BaseWidgetUtils.createRadiobutton( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.TableEditor" ), 1 ); //$NON-NLS-1$ // Table Editor Radio Button autoSwitchToLDIFEditorRadioButton = BaseWidgetUtils.createRadiobutton( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.LDIFEditor" ), 1 ); //$NON-NLS-1$ // Indent BaseWidgetUtils.createRadioIndent( defaultEditorGroup, 1 ); // Auto Switch Label autoSwitchLabel = BaseWidgetUtils.createLabel( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.AutoSwitchNote" ), //$NON-NLS-1$ 1 ); autoSwitchLabel.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 3, 1 ) ); // Table Editor Radio Button defaultEditorTableRadioButton = BaseWidgetUtils.createRadiobutton( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.TableEditor" ), 1 ); //$NON-NLS-1$ defaultEditorTableRadioButton.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 4, 1 ) ); // LDIF Editor Radio Button defaultEditorLDIFRadioButton = BaseWidgetUtils.createRadiobutton( defaultEditorGroup, Messages .getString( "CombinedEntryEditorPreferencePage.LDIFEditor" ), 1 ); //$NON-NLS-1$ defaultEditorLDIFRadioButton.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 4, 1 ) ); } /** * Initializes the listeners */ private void initListeners() { defaultEditorTemplateRadioButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { defaultEditorTemplateAction(); } } ); autoSwitchToOtherEditorCheckbox.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { autoSwitchToOtherEditorAction(); } } ); autoSwitchToTableEditorRadioButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { autoSwitchToTableEditorAction(); } } ); autoSwitchToLDIFEditorRadioButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { autoSwitchToLDIFEditorAction(); } } ); defaultEditorTableRadioButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { defaultEditorTableAction(); } } ); defaultEditorLDIFRadioButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { defaultEditorLDIFAction(); } } ); } /** * This method is called when the 'Default Editor Template Radio Button' is clicked. */ private void defaultEditorTemplateAction() { defaultEditorTemplateRadioButton.setSelection( true ); defaultEditorTableRadioButton.setSelection( false ); defaultEditorLDIFRadioButton.setSelection( false ); autoSwitchToOtherEditorCheckbox.setEnabled( true ); autoSwitchToTableEditorRadioButton.setEnabled( autoSwitchToOtherEditorCheckbox.getSelection() ); autoSwitchToLDIFEditorRadioButton.setEnabled( autoSwitchToOtherEditorCheckbox.getSelection() ); autoSwitchLabel.setEnabled( true ); } /** * This method is called when the 'Auto Switch To Other Editor Checkbox' is clicked. */ private void autoSwitchToOtherEditorAction() { autoSwitchToTableEditorRadioButton.setEnabled( autoSwitchToOtherEditorCheckbox.getSelection() ); autoSwitchToLDIFEditorRadioButton.setEnabled( autoSwitchToOtherEditorCheckbox.getSelection() ); autoSwitchLabel.setEnabled( autoSwitchToOtherEditorCheckbox.getSelection() ); } /** * This method is called when the 'Auto Switch To Table Editor Radio Button' is clicked. */ private void autoSwitchToTableEditorAction() { autoSwitchToTableEditorRadioButton.setSelection( true ); autoSwitchToLDIFEditorRadioButton.setSelection( false ); } /** * This method is called when the 'Auto Switch To LDIF Editor Radio Button' is clicked. */ private void autoSwitchToLDIFEditorAction() { autoSwitchToTableEditorRadioButton.setSelection( false ); autoSwitchToLDIFEditorRadioButton.setSelection( true ); } /** * This method is called when the 'Default Editor Table Radio Button' is clicked. */ private void defaultEditorTableAction() { defaultEditorTemplateRadioButton.setSelection( false ); defaultEditorTableRadioButton.setSelection( true ); defaultEditorLDIFRadioButton.setSelection( false ); autoSwitchToOtherEditorCheckbox.setEnabled( false ); autoSwitchToTableEditorRadioButton.setEnabled( false ); autoSwitchToLDIFEditorRadioButton.setEnabled( false ); autoSwitchLabel.setEnabled( false ); } /** * This method is called when the 'Default Editor LDIF Radio Button' is clicked. */ private void defaultEditorLDIFAction() { defaultEditorTemplateRadioButton.setSelection( false ); defaultEditorTableRadioButton.setSelection( false ); defaultEditorLDIFRadioButton.setSelection( true ); autoSwitchToOtherEditorCheckbox.setEnabled( false ); autoSwitchToTableEditorRadioButton.setEnabled( false ); autoSwitchToLDIFEditorRadioButton.setEnabled( false ); autoSwitchLabel.setEnabled( false ); } /** * Initializes the User Interface. */ private void initUI() { initUI( store.getInt( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR ), store .getBoolean( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR ), store .getInt( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR ) ); } /** * {@inheritDoc} */ protected void performDefaults() { initUI( store.getDefaultInt( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR ), store .getDefaultBoolean( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR ), store .getDefaultInt( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR ) ); super.performDefaults(); } /** * Initializes the UI. * * @param defaultEditor * the default editor * @param autoSwitchToOtherEditor * the auto switch to other editor * @param autoSwitchEditor * the auto switch editor */ private void initUI( int defaultEditor, boolean autoSwitchToOtherEditor, int autoSwitchEditor ) { // Default Editor if ( defaultEditor == CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE ) { defaultEditorTemplateRadioButton.setSelection( true ); defaultEditorTableRadioButton.setSelection( false ); defaultEditorLDIFRadioButton.setSelection( false ); } else if ( defaultEditor == CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TABLE ) { defaultEditorTemplateRadioButton.setSelection( false ); defaultEditorTableRadioButton.setSelection( true ); defaultEditorLDIFRadioButton.setSelection( false ); } else if ( defaultEditor == CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_LDIF ) { defaultEditorTemplateRadioButton.setSelection( false ); defaultEditorTableRadioButton.setSelection( false ); defaultEditorLDIFRadioButton.setSelection( true ); } // Auto Switch autoSwitchToOtherEditorCheckbox.setEnabled( defaultEditorTemplateRadioButton.getSelection() ); autoSwitchToOtherEditorCheckbox.setSelection( autoSwitchToOtherEditor ); // Auto Switch Editor autoSwitchToTableEditorRadioButton.setEnabled( defaultEditorTemplateRadioButton.getSelection() && autoSwitchToOtherEditorCheckbox.getSelection() ); autoSwitchToLDIFEditorRadioButton.setEnabled( defaultEditorTemplateRadioButton.getSelection() && autoSwitchToOtherEditorCheckbox.getSelection() ); if ( autoSwitchEditor == CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_TABLE ) { autoSwitchToTableEditorRadioButton.setSelection( true ); autoSwitchToLDIFEditorRadioButton.setSelection( false ); } else if ( autoSwitchEditor == CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR_LDIF ) { autoSwitchToTableEditorRadioButton.setSelection( false ); autoSwitchToLDIFEditorRadioButton.setSelection( true ); } autoSwitchLabel.setEnabled( defaultEditorTemplateRadioButton.getSelection() ); } /** * {@inheritDoc} */ public boolean performOk() { // Default Editor if ( defaultEditorTemplateRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE ); } else if ( defaultEditorTableRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TABLE ); } else if ( defaultEditorLDIFRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_LDIF ); } if ( defaultEditorTemplateRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE ); } // Auto Switch store.setValue( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_TO_ANOTHER_EDITOR, autoSwitchToOtherEditorCheckbox.getSelection() ); // Auto Switch Editor if ( autoSwitchToTableEditorRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TEMPLATE ); } else if ( autoSwitchToLDIFEditorRadioButton.getSelection() ) { store.setValue( CombinedEditorPluginConstants.PREF_AUTO_SWITCH_EDITOR, CombinedEditorPluginConstants.PREF_DEFAULT_EDITOR_TABLE ); } 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/TableDecorator.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/TableDecorator.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.ui; import java.util.Comparator; import org.eclipse.jface.viewers.LabelProvider; /** * A Class used to store the comparator and labelProvider used by the TableWidget. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @param <E>The element being handled bu the decorator */ public abstract class TableDecorator<E> extends LabelProvider implements Comparator<E> { /** The Dialog instance */ private AddEditDialog<E> dialog; /** * Create a new instance of a TableDecorator */ public TableDecorator() { } /** * @return the dialog */ public AddEditDialog<E> getDialog() { return dialog; } /** * @param dialog the dialog to set */ public void setDialog( AddEditDialog<E> dialog ) { this.dialog = dialog; } /** * Compare two elements. * @param e1 The first element * @param e2 The second element * @return A negative value when e1 < e2, positive when e1 > e2, and 0 when e1 = e2 */ public abstract int compare( E e1, E 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIPreferencesInitializer.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIPreferencesInitializer.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.ui; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * This class is used to set default preference values. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CommonUIPreferencesInitializer extends AbstractPreferenceInitializer { /** * {@inheritDoc} */ public void initializeDefaultPreferences() { IPreferenceStore store = CommonUIPlugin.getDefault().getPreferenceStore(); // Actual colors are defined in default.css and dark.css String dflt = IPreferenceStore.STRING_DEFAULT_DEFAULT; store.setDefault( CommonUIConstants.DEFAULT_COLOR, dflt ); store.setDefault( CommonUIConstants.DISABLED_COLOR, dflt ); store.setDefault( CommonUIConstants.ERROR_COLOR, dflt ); store.setDefault( CommonUIConstants.COMMENT_COLOR, dflt ); store.setDefault( CommonUIConstants.KEYWORD_1_COLOR, dflt ); store.setDefault( CommonUIConstants.KEYWORD_2_COLOR, dflt ); store.setDefault( CommonUIConstants.OBJECT_CLASS_COLOR, dflt ); store.setDefault( CommonUIConstants.ATTRIBUTE_TYPE_COLOR, dflt ); store.setDefault( CommonUIConstants.VALUE_COLOR, dflt ); store.setDefault( CommonUIConstants.OID_COLOR, dflt ); store.setDefault( CommonUIConstants.SEPARATOR_COLOR, dflt ); store.setDefault( CommonUIConstants.ADD_COLOR, dflt ); store.setDefault( CommonUIConstants.DELETE_COLOR, dflt ); store.setDefault( CommonUIConstants.MODIFY_COLOR, dflt ); store.setDefault( CommonUIConstants.RENAME_COLOR, dflt ); } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIConstants.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIConstants.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.ui; /** * Constants used in the connection UI plugin. * Final reference -&gt; class shouldn't be extended * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public final class CommonUIConstants { /** * 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 CommonUIConstants() { } /** The plug-in ID */ public static final String PLUGIN_ID = CommonUIConstants.class.getPackage().getName(); /** The pull-down image */ public static final String IMG_PULLDOWN = "resources/icons/pulldown.gif"; //$NON-NLS-1$ /* * Names of semantic colors. Actual color values are theme specific and defined in default.css and dark.css. */ public static final String DEFAULT_COLOR = "defaultColor"; public static final String DISABLED_COLOR = "disabledColor"; public static final String ERROR_COLOR = "errorColor"; public static final String COMMENT_COLOR = "commentColor"; public static final String KEYWORD_1_COLOR = "keyword1Color"; public static final String KEYWORD_2_COLOR = "keyword2Color"; public static final String OBJECT_CLASS_COLOR = "objectClassColor"; public static final String ATTRIBUTE_TYPE_COLOR = "attributeTypeColor"; public static final String VALUE_COLOR = "valueColor"; public static final String OID_COLOR = "oidColor"; public static final String SEPARATOR_COLOR = "separatorColor"; public static final String ADD_COLOR = "addColor"; public static final String DELETE_COLOR = "deleteColor"; public static final String MODIFY_COLOR = "modifyColor"; public static final String RENAME_COLOR = "renameColor"; public static final String IMG_INFORMATION = "resources/icons/information.gif"; //$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.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIUtils.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIUtils.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.ui; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.FormToolkit; import org.osgi.framework.Bundle; /** * This class contains helpful methods. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CommonUIUtils { /** * Opens an Error {@link MessageDialog} with the given message. * * @param message the message */ public static void openErrorDialog( String message ) { openErrorDialog( Messages.getString( "CommonUIUtils.Error" ), message ); //$NON-NLS-1$ } /** * Opens an Error {@link MessageDialog} with the given title and message. * * @param title the title * @param message the message */ public static void openErrorDialog( String title, String message ) { MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, null, message, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, MessageDialog.OK ); dialog.open(); } /** * Opens an Information {@link MessageDialog} with the given message. * * @param message the message */ public static void openInformationDialog( String message ) { openInformationDialog( Messages.getString( "CommonUIUtils.Information" ), message ); //$NON-NLS-1$ } /** * Opens an Information {@link MessageDialog} with the given title and message. * * @param title the title * @param message the message */ public static void openInformationDialog( String title, String message ) { MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, null, message, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, MessageDialog.OK ); dialog.open(); } /** * Opens an Warning {@link MessageDialog} with the given message. * * @param message the message */ public static void openWarningDialog( String message ) { openWarningDialog( Messages.getString( "CommonUIUtils.Warning" ), message ); //$NON-NLS-1$ } /** * Opens an Warning {@link MessageDialog} with the given title and message. * * @param title the title * @param message the message */ public static void openWarningDialog( String title, String message ) { MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, null, message, MessageDialog.WARNING, new String[] { IDialogConstants.OK_LABEL }, MessageDialog.OK ); dialog.open(); } /** * Checks, if this plugins runs in the Eclipse IDE or in RCP environment. * This is done by looking if "org.apache.directory.studio.rcp" bundle is installed. * * @return true if this plugin runs in IDE environment */ public static boolean isIDEEnvironment() { Bundle bundle = Platform.getBundle( "org.apache.directory.studio.rcp" ); return bundle == null; } /** * Create a default Text input, with a label and a ModifyListener. * * @param toolkit the toolkit * @param composite the Composite * @param label the Text label * @param value the default value. Default to "" if null * @param limit the size limit. Ignored if < 0 * @param listener the ModifyListener * @return An instance of a Text */ public static Text createText( FormToolkit toolkit, Composite composite, String label, String defaultValue, int limit, ModifyListener listener ) { toolkit.createLabel( composite, label ); String value = ""; if ( defaultValue != null ) { value = defaultValue; } Text text = toolkit.createText( composite, value ); text.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); if ( limit >= 0 ) { text.setTextLimit( limit ); } // Attach a listener to check the value if ( listener != null ) { text.addModifyListener( listener ); } return text; } /** * Create a default Text input, with a label and a ModifyListener. * * @param toolkit the toolkit * @param composite the Composite * @param label the Text label * @param value the default value. Default to "" if null * @param limit the size limit. Ignored if < 0 * @param gridData the GridData * @param listener the ModifyListener * @return An instance of a Text */ public static Text createText( FormToolkit toolkit, Composite composite, String label, String defaultValue, int limit, GridData gridData, ModifyListener listener ) { toolkit.createLabel( composite, label ); String value = ""; if ( defaultValue != null ) { value = defaultValue; } Text text = toolkit.createText( composite, value ); text.setLayoutData( gridData ); if ( limit >= 0 ) { text.setTextLimit( limit ); } // Attach a listener to check the value if ( listener != null ) { text.addModifyListener( listener ); } return text; } /** * An utility method that return a String which is never null. * * @param value The incoming value, which can be null * @return The String if it's not null, "" otherwise */ public static String getTextValue( String value ) { if ( value == null ) { return ""; } else { return value; } } /** * An utility method that return a String which is never 0. * * @param value The incoming value, which can be 0 * @return The Int value if it's not 0, "" otherwise */ public static String getTextValue( int value ) { if ( value == 0 ) { return ""; } 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/ClipboardUtils.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/ClipboardUtils.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.ui; import java.util.function.Function; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Display; /** * Clipboard utilities. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ClipboardUtils { /** * Retrieve the data of the specified type currently available on the system clipboard. * * @param transfer the transfer agent for the type of data being requested * @return the data obtained from the clipboard or null if no data of this type is available */ public static Object getFromClipboard( Transfer transfer ) { return getFromClipboard( transfer, Object.class ); } public static <T> T getFromClipboard( Transfer transfer, Class<T> type ) { return withClipboard( clipboard -> { if ( isAvailable( transfer, clipboard ) ) { Object contents = clipboard.getContents( transfer ); if ( contents != null && type.isAssignableFrom( contents.getClass() ) ) { return type.cast( contents ); } } return null; } ); } public static boolean isAvailable( Transfer transfer ) { return withClipboard( clipboard -> { return isAvailable( transfer, clipboard ); } ); } private static Boolean isAvailable( Transfer transfer, Clipboard clipboard ) { for ( org.eclipse.swt.dnd.TransferData transferData : clipboard.getAvailableTypes() ) { if ( transfer.isSupportedType( transferData ) ) { return true; } } return false; } private static <T> T withClipboard( Function<Clipboard, T> fn ) { Clipboard clipboard = null; try { clipboard = new Clipboard( Display.getCurrent() ); return fn.apply( clipboard ); } finally { if ( clipboard != null ) { clipboard.dispose(); } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/Messages.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/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.common.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 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIPlugin.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/CommonUIPlugin.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.ui; 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.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class CommonUIPlugin extends AbstractUIPlugin { /** The shared plugin instance. */ private static CommonUIPlugin plugin; /** The plugin properties */ private PropertyResourceBundle properties; /** The color registry */ private ColorRegistry colorRegistry; /** * The constructor */ public CommonUIPlugin() { plugin = this; } /** * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start( BundleContext context ) throws Exception { super.start( context ); if ( colorRegistry == null ) { colorRegistry = new ColorRegistry( PlatformUI.getWorkbench().getDisplay() ); } } /** * @see AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop( BundleContext context ) throws Exception { plugin = null; if ( colorRegistry != null ) { colorRegistry = null; } super.stop( context ); } /** * Returns the shared instance * * @return the shared instance */ public static CommonUIPlugin 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-&gt;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.common.ui", Status.OK, //$NON-NLS-1$ Messages.getString( "CommonUIPlugin.UnableGetPluginProperties" ), e ) ); //$NON-NLS-1$ } } return properties; } /** * Use this method to get SWT colors. A ColorRegistry is used to manage * the RGB->Color mapping. * <p> * Note: Don't dispose the returned color. It is disposed automatically * when the plugin is stopped. * * @param rgb the rgb color data * @return The SWT Color */ public Color getColor( RGB rgb ) { if ( !colorRegistry.hasValueFor( rgb.toString() ) ) { colorRegistry.put( rgb.toString(), rgb ); } return colorRegistry.get( rgb.toString() ); } /** * Returns the current value of the color-valued preference with the * given name in the preference store. * Return <code>null</code> if it's the default, This is important * to not override the system color when a high-contrast theme is used. */ public Color getColor( String name ) { IPreferenceStore store = getPreferenceStore(); if ( store.isDefault( name ) ) { return null; } RGB rgb = PreferenceConverter.getColor( store, name ); Color color = getColor( rgb ); return color; } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/AddEditDialog.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/AddEditDialog.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.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; /** * An abstract class used as a base class for Dialog asscoiated with the Add or Edit * action of a TableWidget * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * * @param <E> The Element type */ public abstract class AddEditDialog<E> extends Dialog { /** The edited Element, if any */ private E editedElement; /** The table's elements */ private List<E> elements; /** The position of the selected element, if we have any */ private int selectedPosition; /** A flag set to true when the dialog is opened using the Add button */ private boolean isAdd = false; /** A flag used to tell if the okButton must be disabled */ protected boolean okDisabled = false; /** * Create a new instance of the TableAddEditDialog * * @param parentShell The Parent shell */ protected AddEditDialog( Shell parentShell ) { super( parentShell ); } /** * Initialize the Dialog with the content of the edited element, if any */ protected abstract void initDialog(); /** * Override the createButtonBar method to be able to hide the OK button if needed */ protected Control createButtonBar( Composite parent ) { Control buttonBar = super.createButtonBar( parent ); if ( okDisabled ) { Button okButton = getButton( IDialogConstants.OK_ID ); okButton.setEnabled( false ); } return buttonBar; } /** * Add a new Element that will be edited */ public abstract void addNewElement(); /** * @return The edited element */ public E getEditedElement() { return editedElement; } /** * Store the Element that will be edited * @param editedElement The edited Element */ public final void setEditedElement( E editedElement ) { this.editedElement = editedElement; } /** * @return the selectedPosition */ public int getSelectedPosition() { return selectedPosition; } /** * @param selectedPosition the selectedPosition to set */ public void setSelectedPosition( int selectedPosition ) { this.selectedPosition = selectedPosition; } /** * Stores the TableWidget list of elements * @param elements The elements to store */ public void setElements( List<E> elements ) { this.elements = new ArrayList<E>(); this.elements.addAll( elements ); } /** * @return The list of elements stored in the TableWidget */ protected List<E> getElements() { return elements; } /** * Set the isAdd flag to true */ public void setAdd() { isAdd = true; } /** * Set the isAdd flag to false */ public void setEdit() { isAdd = false; } /** * @return True if the Dialog has been opened using the Add button. */ public boolean isAdd() { return isAdd; } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/HistoryUtils.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/HistoryUtils.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.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.dialogs.IDialogSettings; /** * The HistoryUtils are used to save and load the history of input fields. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class HistoryUtils { /** * Saves the the given value under the given key in the dialog settings. * * @param dialogSettings the dialog settings * @param key the key * @param value the value */ public static void save( IDialogSettings dialogSettings, String key, String value ) { if ( dialogSettings != null ) { // get current history String[] history = load( dialogSettings, key ); List<String> list = new ArrayList<String>( Arrays.asList( history ) ); // add new value or move to first position if ( list.contains( value ) ) { list.remove( value ); } list.add( 0, value ); // check history size while ( list.size() > 20 ) { list.remove( list.size() - 1 ); } // save history = list.toArray( new String[list.size()] ); dialogSettings.put( key, history ); } } /** * Loads the value of the given key from the dialog settings * * @param dialogSettings the dialog settings * @param key the key * @return the value */ public static String[] load( IDialogSettings dialogSettings, String key ) { if ( dialogSettings != null ) { String[] history = dialogSettings.getArray( key ); if ( history == null ) { history = new String[0]; } return history; } return 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/StudioPreferencePage.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/StudioPreferencePage.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.ui; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * This class implements the "Apache Directory Studio" preference page. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** * Creates a new instance of StudioPreferencePage. */ public StudioPreferencePage() { super( Messages.getString( "StudioPreferencePage.Title" ) ); //$NON-NLS-1$ setDescription( Messages.getString( "StudioPreferencePage.Description" ) ); //$NON-NLS-1$ // Removing Default and Apply buttons noDefaultAndApplyButton(); } /** * {@inheritDoc} */ protected Control createContents( Composite parent ) { // Nothing to do return parent; } /** * {@inheritDoc} */ public void init( IWorkbench workbench ) { // 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/filesystem/PathEditorInput.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/filesystem/PathEditorInput.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.ui.filesystem; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IPersistableElement; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.ILocationProvider; /** * This class defines an editor input based on the local file system path of a file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class PathEditorInput implements IPathEditorInput, ILocationProvider { /** The path */ private IPath path; /** * Creates a new instance of PathEditorInput. * * @param path the path */ public PathEditorInput( IPath path ) { this.path = path; } /** * {@inheritDoc} */ public boolean exists() { if ( path != null ) { return path.toFile().exists(); } return false; } /** * {@inheritDoc} */ public Object getAdapter( Class adapter ) { if ( ILocationProvider.class.equals( adapter ) ) { return this; } return Platform.getAdapterManager().getAdapter( this, adapter ); } /** * {@inheritDoc} */ public ImageDescriptor getImageDescriptor() { return PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor( path.toString() ); } /** * {@inheritDoc} */ public String getName() { if ( path != null ) { return path.toFile().getName(); } return ""; //$NON-NLS-1$ } /** * {@inheritDoc} */ public IPath getPath() { if ( path != null ) { return path; } return null; } /** * {@inheritDoc} */ public IPath getPath( Object element ) { if ( element instanceof PathEditorInput ) { return ( ( PathEditorInput ) element ).getPath(); } return null; } /** * {@inheritDoc} */ public IPersistableElement getPersistable() { return null; } /** * {@inheritDoc} */ public String getToolTipText() { if ( path != null ) { return path.makeRelative().toOSString(); } return ""; //$NON-NLS-1$ } /** * {@inheritDoc} */ public int hashCode() { if ( path != null ) { return path.hashCode(); } return super.hashCode(); } /** * {@inheritDoc} */ public boolean equals( Object o ) { if ( path != null ) { // Shortcut if ( this == o ) { return true; } if ( o instanceof PathEditorInput ) { PathEditorInput input = ( PathEditorInput ) o; return path.equals( input.path ); } } return super.equals( o ); } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/TableWidget.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/TableWidget.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.ui.widgets; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.apache.directory.studio.common.ui.AddEditDialog; import org.apache.directory.studio.common.ui.Messages; import org.apache.directory.studio.common.ui.TableDecorator; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.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.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.forms.widgets.FormToolkit; /** * The TableWidget provides a table viewer to add/edit/remove an element. * * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Edit...) * | | (Delete ) * +--------------------------------------+ * </pre> * * The elements are ordered. * * <pre> * Note : This class contain codes from the Apache PDF box project ('sort' method) * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class TableWidget<E> extends AbstractWidget { /** The element list */ private List<E> elements = new ArrayList<E>(); /** The current selection index, if any */ private int currentSelection; /** A flag set to tell if we have a Edit button */ private boolean hasEdit; /** A flag set when the table is ordered (ie, it has a Up and Down buttons) */ private boolean isOrdered; /** A flag that says if teh table is enabled or disabled */ private boolean isEnabled = true; /** The flag set when the table is ordered */ private static final boolean ORDERED = true; /** The flag set when the table is not ordered */ private static final boolean UNORDERED = false; // UI widgets private Composite composite; private Table elementTable; private TableViewer elementTableViewer; // The buttons private Button addButton; private Button editButton; private Button deleteButton; private Button upButton; private Button downButton; /** The decorator */ private TableDecorator<E> decorator; // A listener on the Elements table, that modifies the button when an Element is selected private ISelectionChangedListener tableViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { if ( isEnabled ) { int selectionLine = elementTableViewer.getTable().getSelectionIndex(); if ( selectionLine == currentSelection ) { // We have selected the line twice, deselect the line elementTableViewer.getTable().deselect( selectionLine ); currentSelection = -1; } else { currentSelection = selectionLine; StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); if ( hasEdit ) { editButton.setEnabled( !selection.isEmpty() ); } deleteButton.setEnabled( !selection.isEmpty() ); if ( isOrdered ) { // We can't enable the UP button when we don't have any element in the table, // or when we have only one, or when the selection is the first one in the table upButton.setEnabled( !selection.isEmpty() && ( elements.size() > 1 ) && ( selectionLine > 0 ) ); // We can't enable the DOWN button when we don't have any element in the table, // or when we have only one element, or when the selected element is the last one downButton.setEnabled( !selection.isEmpty() && ( elements.size() > 1 ) && ( selectionLine < elements.size() - 1 ) ); } } } } }; // A listener on the Element table, that reacts to a doubleClick : it's opening the Element editor private IDoubleClickListener tableViewerDoubleClickListener = new IDoubleClickListener() { public void doubleClick( DoubleClickEvent event ) { if ( isEnabled ) { editElement(); } } }; // A listener on the Add button, which opens the Element addition editor private SelectionListener addButtonListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { addElement(); } }; // A listener on the Edit button, that open the Element editor private SelectionListener editButtonListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { editElement(); } }; // A listener on the Delete button, which delete the selected Element private SelectionListener deleteButtonListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { deleteElement(); } }; // A listener on the Up button, that move the selected elemnt up one position private SelectionListener upButtonListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { upElement(); } }; // A listener on the Down button, that move the selected element down one position private SelectionListener downButtonListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { downElement(); } }; /** * Creates a new instance of TableWidget. * * @param decorator the decorator to use, containing the Dialog comparator and labelProvider */ public TableWidget( TableDecorator<E> decorator ) { this.decorator = decorator; currentSelection = -1; } /** * Creates the Table widget. It's a Table and three buttons : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Edit...) * | | (Delete ) * +--------------------------------------+ * </pre> * </pre> * * @param parent the parent * @param toolkit the toolkit */ public void createWidgetWithEdit( Composite parent, FormToolkit toolkit ) { createWidget( parent, toolkit, true, UNORDERED ); } /** * Creates the Table widget. It's a Table and two buttons : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Delete ) * | | * +--------------------------------------+ * </pre> * * @param parent the parent * @param toolkit the toolkit */ public void createWidgetNoEdit( Composite parent, FormToolkit toolkit ) { createWidget( parent, toolkit, false, UNORDERED ); } /** * Creates the ordered Table widget. It's a Table and five buttons : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Edit...) * | | (Delete ) * | | --------- * | | (Up... ) * | | (Down.. ) * +--------------------------------------+ * </pre> * The 'Up' and 'Down' buttons are used to order the elements. * * @param parent the parent * @param toolkit the toolkit */ public void createOrderedWidgetWithEdit( Composite parent, FormToolkit toolkit ) { createWidget( parent, toolkit, true, ORDERED ); } /** * Creates the Table widget. It's a Table and four buttons : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Delete ) * | | --------- * | | (Up... ) * | | (Down.. ) * +--------------------------------------+ * </pre> * The 'Up' and 'Down' buttons are used to order the elements. * * @param parent the parent * @param toolkit the toolkit */ public void createOrderedWidgetNoEdit( Composite parent, FormToolkit toolkit ) { createWidget( parent, toolkit, true, ORDERED ); } /** * Creates the Table widget. It's a Table and two or three button : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Edit...) * | | (Delete ) * +--------------------------------------+ * </pre> * or : * <pre> * +--------------------------------------+ * | Element 1 | (Add... ) * | Element 2 | (Delete ) * | | * +--------------------------------------+ * </pre> * * If the table is ordered, we have two additional buttons to re-organize * the elements at will : * <pre> * ... * | | --------- * | | (Up... ) * | | (Down.. ) * +--------------------------------------+ * </pre> * * @param parent the parent * @param toolkit the toolkit * @param hasEdit the flag set when the Edit button is present * @param isOrdered the flag set when we have the Up and Down buttons */ private void createWidget( Composite parent, FormToolkit toolkit, boolean hasEdit, boolean isOrdered ) { this.hasEdit = hasEdit; this.isOrdered = isOrdered; // Composite if ( toolkit != null ) { composite = toolkit.createComposite( parent ); } else { composite = new Composite( parent, SWT.NONE ); } // First, define a grid of 3 columns (two for the table, one for the buttons) GridLayout compositeGridLayout = new GridLayout( 2, false ); compositeGridLayout.marginHeight = compositeGridLayout.marginWidth = 0; composite.setLayout( compositeGridLayout ); // Create the Element Table and Table Viewer if ( toolkit != null ) { elementTable = toolkit.createTable( composite, SWT.NULL ); } else { elementTable = new Table( composite, SWT.NULL ); } // Define the table size and height. It will span on 3 to 5 lines, // depending on the number of buttons int nbLinesSpan = 3; if ( isOrdered ) { // If it's an ordered table, we add 3 line s: one for Up, one for Down and one for the separator nbLinesSpan += 3; } GridData gd = new GridData( SWT.FILL, SWT.FILL, true, true, 1, nbLinesSpan ); elementTable.setLayoutData( gd ); // Create the index TableViewer elementTableViewer = new TableViewer( elementTable ); elementTableViewer.setContentProvider( new ArrayContentProvider() ); // The LabelProvider elementTableViewer.setLabelProvider( decorator ); elementTableViewer.addSelectionChangedListener( tableViewerSelectionChangedListener ); // Listeners : we want to catch changes and double clicks (if we have an edit button) if ( hasEdit ) { elementTableViewer.addDoubleClickListener( tableViewerDoubleClickListener ); } // Inject the existing elements elementTableViewer.setInput( elements ); GridData buttonGd = new GridData( SWT.FILL, SWT.FILL, false, false, 1, 1 ); buttonGd.widthHint = 60; // Create the Add Button and its listener if ( toolkit != null ) { addButton = toolkit.createButton( composite, Messages.getString( "CommonUIWidgets.AddButton" ), SWT.PUSH ); addButton.setLayoutData( buttonGd ); } else { addButton = BaseWidgetUtils.createButton( composite, Messages.getString( "CommonUIWidgets.AddButton" ), 1 ); addButton.setLayoutData( buttonGd ); } addButton.setLayoutData( buttonGd ); addButton.addSelectionListener( addButtonListener ); // Create the Edit Button and its listener, if requested if ( hasEdit ) { if ( toolkit != null ) { editButton = toolkit.createButton( composite, Messages.getString( "CommonUIWidgets.EditButton" ), SWT.PUSH ); } else { editButton = BaseWidgetUtils.createButton( composite, Messages.getString( "CommonUIWidgets.EditButton" ), SWT.PUSH ); } // It's not enabled unless we have selected an element editButton.setEnabled( false ); editButton.setLayoutData( buttonGd ); editButton.addSelectionListener( editButtonListener ); } // Create the Delete Button and its listener if ( toolkit != null ) { deleteButton = toolkit.createButton( composite, Messages.getString( "CommonUIWidgets.DeleteButton" ), SWT.PUSH ); } else { deleteButton = BaseWidgetUtils.createButton( composite, Messages.getString( "CommonUIWidgets.DeleteButton" ), SWT.PUSH ); } // It's not selected unless we have selected an index deleteButton.setEnabled( false ); deleteButton.setLayoutData( buttonGd ); deleteButton.addSelectionListener( deleteButtonListener ); // Create the Up and Down button, if requested if ( isOrdered ) { Label separator = BaseWidgetUtils.createSeparator( composite, 1 ); separator.setLayoutData( new GridData( SWT.NONE, SWT.BEGINNING, false, false ) ); // Create the Up Button and its listener if ( toolkit != null ) { upButton = toolkit.createButton( composite, Messages.getString( "CommonUIWidgets.UpButton" ), SWT.PUSH ); } else { upButton = BaseWidgetUtils.createButton( composite, Messages.getString( "CommonUIWidgets.UpButton" ), SWT.PUSH ); } // It's not selected unless we have selected an index upButton.setEnabled( false ); upButton.setLayoutData( buttonGd ); //upButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) ); upButton.addSelectionListener( upButtonListener ); // Create the Down Button and its listener if ( toolkit != null ) { downButton = toolkit.createButton( composite, Messages.getString( "CommonUIWidgets.DownButton" ), SWT.PUSH ); } else { downButton = BaseWidgetUtils.createButton( composite, Messages.getString( "CommonUIWidgets.DownButton" ), SWT.PUSH ); } // It's not selected unless we have selected an index downButton.setEnabled( false ); downButton.setLayoutData( buttonGd ); //downButton.setLayoutData( new GridData( SWT.FILL, SWT.BEGINNING, false, false ) ); downButton.addSelectionListener( downButtonListener ); } } /** * Enable the table (Buttons will be active, except the Edit and Delete ones, actions on the table will be active) */ public void enable() { if ( addButton != null ) { addButton.setEnabled( true ); } if ( upButton != null ) { upButton.setEnabled( true ); } if ( downButton != null ) { downButton.setEnabled( true ); } isEnabled = true; } /** * Disable the table (Buttons will be inactive, actions on the table will be inactive) */ public void disable() { if ( addButton != null ) { addButton.setEnabled( false ); } if ( deleteButton != null ) { deleteButton.setEnabled( false ); } if ( editButton != null ) { editButton.setEnabled( false ); } if ( upButton != null ) { upButton.setEnabled( false ); } if ( downButton != null ) { downButton.setEnabled( false ); } isEnabled = false; } /** * Returns the primary control associated with this widget. * * @return the primary control associated with this widget. */ public Control getControl() { return composite; } /* --------------------------------------------------------------------------------------------------------------- */ /* Taken from the Apache PdfBox project, */ /* @author UWe Pachler */ /* --------------------------------------------------------------------------------------------------------------- */ /** * Sorts the given list using the given comparator. * * @param list list to be sorted * @param cmp comparator used to compare the object swithin the list */ public static <T> void sort( List<T> list, Comparator<T> cmp ) { int size = list.size(); if ( size < 2 ) { return; } quicksort( list, cmp, 0, size - 1 ); } private static <T> void quicksort( List<T> list, Comparator<T> cmp, int left, int right ) { if ( left < right ) { int splitter = split( list, cmp, left, right ); quicksort( list, cmp, left, splitter - 1 ); quicksort( list, cmp, splitter + 1, right ); } } private static <T> void swap( List<T> list, int i, int j ) { T tmp = list.get( i ); list.set( i, list.get( j ) ); list.set( j, tmp ); } private static <T> int split( List<T> list, Comparator<T> cmp, int left, int right ) { int i = left; int j = right - 1; T pivot = list.get( right ); do { while ( ( cmp.compare( list.get( i ), pivot ) <= 0 ) && ( i < right ) ) { ++i; } while ( ( cmp.compare( pivot, list.get( j ) ) <= 0 ) && ( j > left ) ) { --j; } if ( i < j ) { swap( list, i, j ); } } while ( i < j ); if ( cmp.compare( pivot, list.get( i ) ) < 0 ) { swap( list, i, right ); } return i; } /* --------------------------------------------------------------------------------------------------------------- */ /* End of the QuickSort implementation taken from the Apache PdfBox project, */ /* --------------------------------------------------------------------------------------------------------------- */ /** * Sets the Elements. * * @param elements the elements */ public void setElements( List<E> elements ) { this.elements.clear(); if ( ( elements != null ) && ( elements.size() > 0 ) ) { sort( elements, decorator ); this.elements.addAll( elements ); } elementTableViewer.refresh(); } /** * Gets the elements. * * @return the elements */ public List<E> getElements() { if ( elements != null ) { List<E> copy = new ArrayList<E>( elements.size() ); copy.addAll( elements ); return copy; } return null; } /** * This method is called when the 'Add...' button is clicked. */ private void addElement() { AddEditDialog<E> dialog = decorator.getDialog(); dialog.setAdd(); dialog.addNewElement(); dialog.setElements( elements ); // Inject the position if we have a selected value StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); int insertionPos = elements.size(); if ( !selection.isEmpty() ) { insertionPos = elementTableViewer.getTable().getSelectionIndex(); } // Open the Dialog, and process the addition if it went fine if ( decorator.getDialog().open() == Dialog.OK ) { E newElement = decorator.getDialog().getEditedElement(); if ( !elements.contains( newElement ) ) { String elementStr = newElement.toString(); int pos = 0; if ( isOrdered ) { // The table is ordered, insert the element at the right position ((OrderedElement)newElement).setPrefix( insertionPos ); elements.add( insertionPos, newElement ); // Move up the following elements for ( int i = insertionPos + 1; i < elements.size(); i++ ) { E element = elements.get( i ); ((OrderedElement)element).incrementPrefix(); } } else { if ( selection.isEmpty() ) { // no selected element, add at the end pos = elements.size(); } else { pos = elementTableViewer.getTable().getSelectionIndex() + 1; } elements.add( pos, newElement ); } elementTableViewer.refresh(); elementTableViewer.setSelection( new StructuredSelection( elementStr ) ); } notifyListeners(); } } /** * This method is called when the 'Edit...' button is clicked * or the table viewer is double-clicked. */ private void editElement() { StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); if ( !selection.isEmpty() ) { AddEditDialog<E> dialog = decorator.getDialog(); dialog.setEdit(); E selectedElement = (E)selection.getFirstElement(); int editPosition = elementTableViewer.getTable().getSelectionIndex(); dialog.setEditedElement( selectedElement ); dialog.setSelectedPosition( editPosition ); // Open the element dialog, with the selected index if ( decorator.getDialog().open() == Dialog.OK ) { E newElement = dialog.getEditedElement(); if ( !isOrdered ) { // Check to see if the modified element does not already exist if ( elements.contains( newElement ) ) { // Remove the original element elements.remove( selectedElement ); // Replace the existing element with the new one elements.remove( newElement ); int pos = 0; for ( E element : elements ) { if ( decorator.compare( element, newElement ) > 0 ) { break; } else { pos++; } } elements.add( pos, newElement ); } else { // We will remove the modified element, and replace it with the new element // Replace the old element by the new one elements.remove( editPosition ); elements.add( editPosition, newElement ); } } else { // Remove the original element elements.remove( selectedElement ); elements.add( editPosition, newElement ); } elementTableViewer.refresh(); elementTableViewer.setSelection( new StructuredSelection( newElement.toString() ) ); notifyListeners(); } } } /** * This method is called when the 'Delete' button is clicked. */ private void deleteElement() { StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); if ( !selection.isEmpty() ) { // If the table is ordered, we need to decrement the prefix of all the following elements if ( isOrdered ) { int selectedPosition = elementTableViewer.getTable().getSelectionIndex(); for ( int i = selectedPosition + 1; i < elements.size(); i++ ) { E nextElement = elements.get( i ); ((OrderedElement)nextElement).decrementPrefix(); elements.set( i - 1, nextElement ); } elements.remove( elements.size() - 1 ); } else { int selectedPosition = elementTableViewer.getTable().getSelectionIndex(); elements.remove( selectedPosition ); } elementTableViewer.refresh(); notifyListeners(); } } /** * This method is called when the 'Up...' button is clicked */ private void upElement() { StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); if ( !selection.isEmpty() ) { // Get the line the selected element is in. We will move it up int selectionLine = elementTableViewer.getTable().getSelectionIndex(); // The selected element E selectedElement = (E)selection.getFirstElement(); // Decrease the prefix ((OrderedElement)selectedElement).decrementPrefix(); // Just swap the elements which is just before with the selected one E previousElement = getElements().get( selectionLine - 1 ); // Increase the prefix ((OrderedElement)previousElement).incrementPrefix(); elements.remove( selectionLine - 1 ); elements.add( selectionLine, previousElement ); // Refresh the table now elementTableViewer.refresh(); elementTableViewer.setSelection( new StructuredSelection( selectedElement ) ); notifyListeners(); } } /** * This method is called when the 'Down...' button is clicked * or the table viewer is double-clicked. */ private void downElement() { StructuredSelection selection = ( StructuredSelection ) elementTableViewer.getSelection(); if ( !selection.isEmpty() ) { // Get the line the selected element is in. We will move it down int selectionLine = elementTableViewer.getTable().getSelectionIndex(); // The selected element E selectedElement = (E)selection.getFirstElement(); // Increase the prefix ((OrderedElement)selectedElement).incrementPrefix(); // Just swap the elements which is just after with the selected one E previousElement = getElements().get( selectionLine + 1 ); // Decrease the prefix ((OrderedElement)previousElement).decrementPrefix(); elements.remove( selectionLine + 1 ); elements.add( selectionLine, previousElement ); // refresh the table now elementTableViewer.refresh(); elementTableViewer.setSelection( new StructuredSelection( selectedElement ) ); notifyListeners(); } } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/ViewFormWidget.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/ViewFormWidget.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.ui.widgets; import org.apache.directory.studio.common.ui.CommonUIConstants; import org.apache.directory.studio.common.ui.CommonUIPlugin; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; 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.Menu; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; /** * The ViewFormWidget is a widget that provides an info text, * a tool bar, a menu and a main content composite including * a context menu. * It looks like this: * <pre> * ----------------------------------- * | info text | tool bar | menu | * ----------------------------------- * | | * | main content | * | | * ----------------------------------- * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class ViewFormWidget { /** The view form control */ protected ViewForm control; /** The info text, positioned at the top left */ protected Text infoText; /** The action tool bar */ protected ToolBar actionToolBar; /** The action tool bar manager */ protected IToolBarManager actionToolBarManager; /** The menu tool bar. */ protected ToolBar menuToolBar; /** The menu manager. */ protected MenuManager menuManager; /** The context menu manager. */ protected MenuManager contextMenuManager; /** * Creates the widget. * * @param parent the parent composite */ public void createWidget( Composite parent ) { control = new ViewForm( parent, SWT.NONE ); // control.marginWidth = 0; // control.marginHeight = 0; // control.horizontalSpacing = 0; // control.verticalSpacing = 0; control.setLayoutData( new GridData( GridData.FILL_BOTH ) ); // infoText = BaseWidgetUtils.createLabeledText(control, "", 1); Composite infoTextControl = BaseWidgetUtils.createColumnContainer( control, 1, 1 ); infoTextControl.setLayoutData( new GridData( GridData.FILL_BOTH ) ); infoText = BaseWidgetUtils.createLabeledText( infoTextControl, "", 1 ); //$NON-NLS-1$ infoText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, true ) ); control.setTopLeft( infoTextControl ); // tool bar actionToolBar = new ToolBar( control, SWT.FLAT | SWT.RIGHT ); actionToolBar.setLayoutData( new GridData( SWT.END, SWT.NONE, true, false ) ); actionToolBarManager = new ToolBarManager( actionToolBar ); control.setTopCenter( actionToolBar ); // local menu this.menuManager = new MenuManager(); menuToolBar = new ToolBar( control, SWT.FLAT | SWT.RIGHT ); ToolItem ti = new ToolItem( menuToolBar, SWT.PUSH, 0 ); ti.setImage( CommonUIPlugin.getDefault().getImage( CommonUIConstants.IMG_PULLDOWN ) ); ti.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { showViewMenu(); } } ); control.setTopRight( menuToolBar ); // content Composite composite = BaseWidgetUtils.createColumnContainer( control, 1, 1 ); GridLayout gl = new GridLayout(); gl.horizontalSpacing = 0; gl.verticalSpacing = 0; gl.marginHeight = 0; gl.marginWidth = 0; composite.setLayout( gl ); Control childControl = this.createContent( composite ); control.setContent( composite ); // context menu this.contextMenuManager = new MenuManager(); Menu menu = this.contextMenuManager.createContextMenu( childControl ); childControl.setMenu( menu ); } /** * Creates the content. * * @param control the control * * @return the control */ protected abstract Control createContent( Composite control ); /** * Shows the local view menu. */ private void showViewMenu() { Menu aMenu = menuManager.createContextMenu( control ); Point topLeft = new Point( 0, 0 ); topLeft.y += menuToolBar.getBounds().height; topLeft = menuToolBar.toDisplay( topLeft ); aMenu.setLocation( topLeft.x, topLeft.y ); aMenu.setVisible( true ); } /** * Disposes this widget. */ public void dispose() { if ( control != null ) { if ( contextMenuManager != null ) { contextMenuManager.removeAll(); contextMenuManager.dispose(); contextMenuManager = null; } if ( menuToolBar != null ) { menuToolBar.dispose(); menuToolBar = null; menuManager.dispose(); menuManager = null; } if ( actionToolBar != null ) { actionToolBar.dispose(); actionToolBar = null; actionToolBarManager.removeAll(); actionToolBarManager = null; } if ( infoText != null ) { infoText.dispose(); infoText = null; } control.dispose(); control = null; } } /** * Gets the info text. * * @return the info text */ public Text getInfoText() { return infoText; } /** * Gets the tool bar manager. * * @return the tool bar manager */ public IToolBarManager getToolBarManager() { return this.actionToolBarManager; } /** * Gets the menu manager. * * @return the menu manager */ public IMenuManager getMenuManager() { return menuManager; } /** * Gets the context menu manager. * * @return the context menu manager */ public IMenuManager getContextMenuManager() { return this.contextMenuManager; } /** * Returns the primary control associated with this view form. * * @return the SWT control which displays this view form's content */ public Control getControl() { return control; } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/OrderedElement.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/OrderedElement.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.ui.widgets; /** * An interface to be implemented by objects stored into an Ordered table * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface OrderedElement { /** * Move an element up in the list of elements, decreasing its prefix */ void incrementPrefix(); /** * Move an element down in the list of elements, increasing its prefix */ void decrementPrefix(); /** * Set the prefix to a given value * * @param prefix The value to set * @param prefix */ void setPrefix( int prefix ); }
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.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/WidgetModifyEvent.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/WidgetModifyEvent.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.ui.widgets; import java.util.EventObject; /** * A WidgetModifyEvent indicates that a {@link AbstractWidget} has * been modified. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class WidgetModifyEvent extends EventObject { /** The serialVersionUID */ private static final long serialVersionUID = 2421335730580648878L; /** * Creates a new instance of WidgetModifyEvent. * * @param source the event source */ public WidgetModifyEvent( Object source ) { super( source ); } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/WidgetModifyListener.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/WidgetModifyListener.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.ui.widgets; /** * A WidgetModifyListener listens for modifications of a * {@link AbstractWidget}. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface WidgetModifyListener { /** * Notified about the modification of a {@link AbstractWidget}. * * @param event the event */ void widgetModified( WidgetModifyEvent 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/AbstractWidget.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/AbstractWidget.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.ui.widgets; import java.util.ArrayList; import java.util.List; /** * Base class that provides support for {@link WidgetModifyListener} * registration and notification. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class AbstractWidget { /** The listener list */ protected List<WidgetModifyListener> modifyListenerList; /** * Creates a new instance of AbstractWidget. */ protected AbstractWidget() { modifyListenerList = new ArrayList<WidgetModifyListener>( 3 ); } /** * Adds the widget modify listener. * * @param listener the listener */ public void addWidgetModifyListener( WidgetModifyListener listener ) { if ( !modifyListenerList.contains( listener ) ) { modifyListenerList.add( listener ); } } /** * Removes the widget modify listener. * * @param listener the listener */ public void removeWidgetModifyListener( WidgetModifyListener listener ) { if ( modifyListenerList.contains( listener ) ) { modifyListenerList.remove( listener ); } } /** * Notifies the listeners. */ protected void notifyListeners() { WidgetModifyEvent event = new WidgetModifyEvent( this ); for ( WidgetModifyListener listener : modifyListenerList ) { listener.widgetModified( 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/BaseWidgetUtils.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/widgets/BaseWidgetUtils.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.ui.widgets; import org.apache.directory.studio.common.ui.CommonUIConstants; import org.apache.directory.studio.common.ui.CommonUIPlugin; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; /** * This class provides utility methods to create SWT widgets. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BaseWidgetUtils { /** * Creates a SWT {@link Group} under the given parent. * * @param parent the parent * @param label the label of the group * @param span the horizontal span * @return the created group */ public static Group createGroup( Composite parent, String label, int span ) { Group group = new Group( parent, SWT.NONE ); GridData gridData = new GridData( GridData.FILL_BOTH ); gridData.horizontalSpan = span; group.setLayoutData( gridData ); if ( label != null ) { group.setText( label ); } group.setLayout( new GridLayout() ); return group; } /** * Creates a SWT {@link Composite} under the given parent. * A GridLayout with the given number of columns is used. * * @param parent the parent * @param columnCount the number of columns * @param span the horizontal span * @return the created composite */ public static Composite createColumnContainer( Composite parent, int columnCount, int span ) { return createColumnContainer( parent, columnCount, false, span ); } /** * Creates a SWT {@link Composite} under the given parent. * A GridLayout with the given number of columns is used. * * @param parent the parent * @param columnCount the number of columns * @param makeColumnsEqualWidth if the columns width should be equal * @param span the horizontal span * @return the created composite */ public static Composite createColumnContainer( Composite parent, int columnCount, boolean makeColumnsEqualWidth, int span ) { Composite container = new Composite( parent, SWT.NONE ); GridLayout gridLayout = new GridLayout( columnCount, makeColumnsEqualWidth ); gridLayout.marginHeight = gridLayout.marginWidth = 0; container.setLayout( gridLayout ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; container.setLayoutData( gridData ); return container; } /** * Creates a SWT {@link Label} under the given parent. * * @param parent the parent * @param text the label's text * @param span the horizontal span * @return the created label */ public static Label createLabel( Composite parent, String text, int span ) { Label label = new Label( parent, SWT.NONE ); GridData gridData = new GridData(); gridData.horizontalSpan = span; label.setLayoutData( gridData ); label.setText( text ); return label; } /** * Creates a SWT {@link Label} under the given parent. * The label is created with the SWT.WRAP style to enable line wrapping. * * @param parent the parent * @param text the label's text * @param span the horizontal span * @return the created label */ public static Label createWrappedLabel( Composite parent, String text, int span ) { Label label = new Label( parent, SWT.WRAP ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; gridData.widthHint = 100; label.setLayoutData( gridData ); label.setText( text ); return label; } /** * Creates a SWT {@link Text} under the given parent. * The created text control is modifiable. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.NONE | SWT.BORDER ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; textWidget.setLayoutData( gridData ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control is modifiable. * * @param parent the parent * @param text the initial text * @param textWidth the width of the text control * @param span the horizontal span * @return the created text */ public static Text createText( Composite parent, String text, int textWidth, int span ) { Text textWidget = new Text( parent, SWT.NONE | SWT.BORDER ); GridData gridData = new GridData(); gridData.horizontalSpan = span; gridData.widthHint = 9 * textWidth; textWidget.setLayoutData( gridData ); textWidget.setText( text ); textWidget.setTextLimit( textWidth ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control is created with the SWT.PASSWORD style. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createPasswordText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.NONE | SWT.BORDER | SWT.PASSWORD ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; textWidget.setLayoutData( gridData ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control is created with the SWT.PASSWORD and * SWT.READ_ONLY style. So the created controls is not modifiable. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createReadonlyPasswordText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.NONE | SWT.BORDER | SWT.PASSWORD | SWT.READ_ONLY ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control behaves like a label: it has no border, * a grayed background and is not modifiable. * But the text is selectable and could be copied. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createLabeledText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.NONE ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control behaves like a label: it has no border, * a grayed background and is not modifiable. * But the text is selectable and could be copied. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @param widthHint the width hint * @return the created text */ public static Text createLabeledText( Composite parent, String text, int span, int widthHint ) { Text textWidget = new Text( parent, SWT.NONE ); GridData gridData = new GridData( SWT.FILL, SWT.NONE, true, false ); gridData.horizontalSpan = span; gridData.widthHint = widthHint; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control behaves like a label: it has no border, * a grayed background and is not modifiable. * But the text is selectable and could be copied. * The label is created with the SWT.WRAP style to enable line wrapping. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createWrappedLabeledText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.WRAP ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; gridData.widthHint = 10; gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The created text control behaves like a label: it has no border, * a grayed background and is not modifiable. * But the text is selectable and could be copied. * The label is created with the SWT.WRAP style to enable line wrapping. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @param widthHint the width hint * @return the created text */ public static Text createWrappedLabeledText( Composite parent, String text, int span, int widthHint ) { Text textWidget = new Text( parent, SWT.WRAP ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; gridData.widthHint = widthHint; gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Text} under the given parent. * The text is not modifiable, but the text is selectable * and could be copied. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Text createReadonlyText( Composite parent, String text, int span ) { Text textWidget = new Text( parent, SWT.NONE | SWT.BORDER | SWT.READ_ONLY ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; textWidget.setLayoutData( gridData ); textWidget.setEditable( false ); textWidget.setBackground( parent.getBackground() ); textWidget.setText( text ); return textWidget; } /** * Creates a SWT {@link Combo} under the given parent. * Beside the selection of an item it is also possible to type * free text into the combo. * * @param parent the parent * @param items the initial visible items * @param selectedIndex the initial selected item, zero-based * @param span the horizontal span * @return the created combo */ public static Combo createCombo( Composite parent, String[] items, int selectedIndex, int span ) { Combo combo = new Combo( parent, SWT.DROP_DOWN | SWT.BORDER ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; combo.setLayoutData( gridData ); combo.setItems( items ); combo.select( selectedIndex ); combo.setVisibleItemCount( 20 ); return combo; } /** * Creates a SWT {@link Combo} under the given parent. * It is not possible to type free text into the combo, only * selection of predefined items is possible. * * @param parent the parent * @param items the initial visible items * @param selectedIndex the initial selected item, zero-based * @param span the horizontal span * @return the created combo */ public static Combo createReadonlyCombo( Composite parent, String[] items, int selectedIndex, int span ) { Combo combo = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; combo.setLayoutData( gridData ); combo.setItems( items ); combo.select( selectedIndex ); combo.setVisibleItemCount( 20 ); return combo; } /** * Creates a checkbox under the given parent. * * @param parent the parent * @param text the label of the checkbox * @param span the horizontal span * @return the created checkbox */ public static Button createCheckbox( Composite parent, String text, int span ) { Button checkbox = new Button( parent, SWT.CHECK ); checkbox.setText( text ); GridData gridData = new GridData(); gridData.horizontalSpan = span; checkbox.setLayoutData( gridData ); return checkbox; } /** * Creates a radio button under the given parent. * * @param parent the parent * @param text the label of the radio button * @param span the horizontal span * @return the created radio button */ public static Button createRadiobutton( Composite parent, String text, int span ) { Button radio = new Button( parent, SWT.RADIO ); radio.setText( text ); GridData gridData = new GridData(); gridData.horizontalSpan = span; radio.setLayoutData( gridData ); return radio; } /** * Creates a button under the given parent. * The button width is set to the default width. * * @param parent the parent * @param text the label of the button * @param span the horizontal span * @return the created button */ public static Button createButton( Composite parent, String text, int span ) { GC gc = new GC( parent ); try { gc.setFont( JFaceResources.getDialogFont() ); FontMetrics fontMetrics = gc.getFontMetrics(); Button button = new Button( parent, SWT.PUSH ); GridData gridData = new GridData(); gridData.widthHint = Dialog.convertHorizontalDLUsToPixels( fontMetrics, IDialogConstants.BUTTON_WIDTH ); gridData.horizontalSpan = span; button.setLayoutData( gridData ); button.setText( text ); return button; } finally { gc.dispose(); } } /** * Adds some space to . * * @param parent the parent * @param span the horizontal span * @return the create label representing the radio buttons indent */ public static Label createRadioIndent( Composite parent, int span ) { Label label = new Label( parent, SWT.NONE ); GridData gridData = new GridData(); gridData.horizontalSpan = span; gridData.horizontalIndent = 22; label.setLayoutData( gridData ); return label; } /** * Creates a spacer. * * @param parent the parent * @param span the horizontal span * @return the create label representing the spacer */ public static Label createSpacer( Composite parent, int span ) { Label label = new Label( parent, SWT.NONE ); GridData gridData = new GridData(); gridData.horizontalSpan = span; gridData.heightHint = 1; label.setLayoutData( gridData ); return label; } /** * Creates a separator. * * @param parent the parent * @param span the horizontal span * @return the create label representing the separator */ public static Label createSeparator( Composite parent, int span ) { Label label = new Label( parent, SWT.SEPARATOR | SWT.HORIZONTAL ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = span; label.setLayoutData( gridData ); return label; } /** * Creates a SWT {@link Link} under the given parent. * * @param parent the parent * @param text the initial text * @param span the horizontal span * @return the created text */ public static Link createLink( Composite parent, String text, int span ) { Link link = new Link( parent, SWT.NONE ); link.setText( text ); GridData gridData = new GridData( SWT.FILL, SWT.BEGINNING, true, false ); gridData.horizontalSpan = span; gridData.widthHint = 150; link.setLayoutData( gridData ); return link; } /** * Creates a Text that can be used to enter an integer. * * @param toolkit the toolkit * @param parent the parent * @return a Text that is a valid integer */ public static Text createIntegerText( FormToolkit toolkit, Composite parent ) { return createIntegerText( toolkit, parent, null, -1 ); } /** * Creates a Text that can be used to enter an integer. * * @param toolkit the toolkit * @param parent the parent * @param width the size of the input text to use * @return a Text that is a valid integer */ public static Text createIntegerText( FormToolkit toolkit, Composite parent, int width ) { return createIntegerText( toolkit, parent, null, width ); } /** * Creates a Text that can be used to enter an integer. * * @param toolkit the toolkit * @param parent the parent * @param description the description that has to be added after the inmput text * @return a Text that is a valid integer */ public static Text createIntegerText( FormToolkit toolkit, Composite parent, String description ) { return createIntegerText( toolkit, parent, description, -1 ); } /** * Creates a Text that can be used to enter an integer. * * @param toolkit the toolkit * @param parent the parent * @param description the description that has to be added after the inmput text * @param width the size of the input text to use * @return a Text that is a valid integer */ public static Text createIntegerText( FormToolkit toolkit, Composite parent, String description, int width ) { Text integerText = toolkit.createText( parent, "" ); //$NON-NLS-1$ integerText.addVerifyListener( new VerifyListener() { public void verifyText( VerifyEvent e ) { for ( int i = 0; i < e.text.length(); i++ ) { if ( !Character.isDigit( e.text.charAt( i ) ) ) { e.doit = false; break; } } } } ); // Add the description, if needed if ( ( description != null ) && ( description.length() > 0 ) ) { ControlDecoration monitoringCheckboxDecoration = new ControlDecoration( integerText, SWT.CENTER | SWT.RIGHT ); monitoringCheckboxDecoration.setImage( CommonUIPlugin.getDefault().getImageDescriptor( CommonUIConstants.IMG_INFORMATION ).createImage() ); monitoringCheckboxDecoration.setMarginWidth( 4 ); monitoringCheckboxDecoration.setDescriptionText( description ); } if ( width >= 0 ) { GridData gridData = new GridData(); gridData.widthHint = width; integerText.setLayoutData( gridData ); } return integerText; } /** * Set a value in a Button, if it's not null * * @param value The Value to set * @param checkBox The Button which will be checked if the value is not null and set to True */ public static void setValue( Boolean value, Button checkBox ) { if ( value != null ) { checkBox.setSelection( value ); } else { checkBox.setSelection( false ); } } /** * Set a value in a Text, if it's not null * * @param value The Value to set * @param inputText The Text which will be set if the value is not null */ public static void setValue( Integer value, Text inputText ) { if ( value != null ) { inputText.setText( value.toString() ); } else { inputText.setText( "" ); } } /** * Set a value in a Text, if it's not null * * @param value The Value to set * @param checkBox The Text which will be set if the value is not null */ public static void setValue( String value, Text inputText ) { if ( value != null ) { inputText.setText( value ); } else { inputText.setText( "" ); } } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/wrappers/StringValueWrapper.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/wrappers/StringValueWrapper.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.ui.wrappers; /** * A wrapper for a String value. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StringValueWrapper implements Cloneable, Comparable<StringValueWrapper> { /** The value */ private String value; /** A flag to tell if the compare should be case sensitive or not */ private boolean caseSensitive = true; /** * Creates a new instance of StringValueWrapper. * * @param value the value */ public StringValueWrapper( String value, boolean caseSensitive ) { this.value = value; this.caseSensitive = caseSensitive; } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue( String value ) { this.value = value; } /** * Clone the current object */ public StringValueWrapper clone() { try { return (StringValueWrapper)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 StringValueWrapper ) { StringValueWrapper thatInstance = (StringValueWrapper)that; 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; if ( value != null ) { h += h*17 + value.hashCode(); } return h; } /** * @see Comparable#compareTo() */ public int compareTo( StringValueWrapper that ) { if ( that == null ) { return 1; } // Check the value if ( ( value == null ) || ( value.length() == 0 ) ) { return -1; } else { return value.compareToIgnoreCase( that.value ); } } /** * @see Object#toString() */ public String toString() { return 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/AttributeDialog.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/AttributeDialog.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.ui.dialogs; import org.apache.directory.studio.common.ui.AddEditDialog; import org.apache.directory.studio.common.ui.Messages; 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.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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; /** * The AttributeDialog is used to enter/select an attribute type. Here is what it looks like : * <pre> * .---------------------------------------------------------. * |X| Select Attribute Type or OID | * +---------------------------------------------------------| * | Attribute Type or OID : [ |v] | * | | * | (CANCEL) ( OK ) | * '---------------------------------------------------------' * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class AttributeDialog extends AddEditDialog<StringValueWrapper> { /** The possible attribute types and OIDs. */ private String[] attributeTypesAndOids; /** The combo containing the list of attributes. */ private Combo typeOrOidCombo; /** * Creates a new instance of AttributeDialog. * * @param parentShell the parent shell */ public AttributeDialog( Shell parentShell ) { super( parentShell ); } /** * Set the list of possible attributes and OIDs * * @param attributeNamesAndOids The list of possible attribuytes and OID */ public void setAttributeNamesAndOids( String[] attributeNamesAndOids ) { this.attributeTypesAndOids = attributeNamesAndOids; } /** * {@inheritDoc} */ protected void configureShell( Shell newShell ) { super.configureShell( newShell ); newShell.setText( Messages.getString( "AttributeDialog.SelectAttributeTypeOrOID" ) ); //$NON-NLS-1$ } /** * {@inheritDoc} */ protected void okPressed() { setEditedElement( new StringValueWrapper( typeOrOidCombo.getText(), false ) ); super.okPressed(); } /** * Overriding the createButton method. The OK button is not enabled until we have a selected attribute * * {@inheritDoc} */ protected Button createButton(Composite parent, int id, String label, boolean defaultButton) { Button button = super.createButton(parent, id, label, defaultButton); if ( id == IDialogConstants.OK_ID ) { String attribute = ((StringValueWrapper)getEditedElement() ).getValue(); if ( ( attribute == null ) || ( attribute.length() == 0 ) ) { button.setEnabled( false ); } } return button; } /** * Create the Attribute dialog : * * <pre> * .---------------------------------------------------------. * |X| Select Attribute Type or OID | * +---------------------------------------------------------| * | Attribute Type or OID : [ |v] | * | | * | (CANCEL) ( OK ) | * '---------------------------------------------------------' * </pre> * * {@inheritDoc} */ protected Control createDialogArea( Composite parent ) { Composite composite = ( Composite ) super.createDialogArea( parent ); Composite c = BaseWidgetUtils.createColumnContainer( composite, 2, 1 ); BaseWidgetUtils.createLabel( c, Messages.getString( "AttributeDialog.AttributeTypeOrOID" ), 1 ); //$NON-NLS-1$ typeOrOidCombo = BaseWidgetUtils.createCombo( c, attributeTypesAndOids, -1, 1 ); if ( getEditedElement() != null ) { typeOrOidCombo.setText( getEditedElement().getValue() ); } typeOrOidCombo.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { validate(); } } ); initDialog(); return composite; } /** * {@inheritDoc} */ protected void initDialog() { // Nothing to do } /** * Check that we have selected an attribute */ private void validate() { Button okButton = getButton( IDialogConstants.OK_ID ); // This button might be null when the dialog is called. if ( okButton == null ) { return; } okButton.setEnabled( !"".equals( typeOrOidCombo.getText() ) ); //$NON-NLS-1$ } /** * {@inheritDoc} */ @Override public void addNewElement() { // Default to none setEditedElement( new StringValueWrapper( "", 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/common.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/MessageDialogWithTextarea.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/MessageDialogWithTextarea.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.ui.dialogs; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.JFaceResources; 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; /** * Message dialog with an text area. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class MessageDialogWithTextarea extends MessageDialog { private String detailMessage; private Text textArea; /** * Instantiates a dialog. * * @param parentShell the parent shell * @param title the title * @param message the message * @param detailMessage the detail message */ public MessageDialogWithTextarea( Shell parentShell, String title, String message, String detailMessage ) { super( parentShell, title, null, message, INFORMATION, new String[] { IDialogConstants.OK_LABEL }, OK ); setShellStyle( SWT.RESIZE ); this.detailMessage = detailMessage; } @Override protected Control createCustomArea( Composite parent ) { textArea = new Text( parent, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY ); textArea.setFont( JFaceResources.getFont( JFaceResources.TEXT_FONT ) ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = convertHorizontalDLUsToPixels( ( int ) ( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH / 2 ) ); gd.heightHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH / 4 ); textArea.setLayoutData( gd ); //textArea.setBackground( parent.getBackground() ); textArea.setText( detailMessage ); return textArea; } }
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.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/ObjectClassDialog.java
plugins/common.ui/src/main/java/org/apache/directory/studio/common/ui/dialogs/ObjectClassDialog.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.ui.dialogs; import org.apache.directory.studio.common.ui.AddEditDialog; import org.apache.directory.studio.common.ui.Messages; 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.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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; /** * The ObjectClassDialog is used to enter/select an ObjectClass. Here is what it looks like : * <pre> * .---------------------------------------------------------. * |X| Select ObjectClass or OID | * +---------------------------------------------------------| * | ObjectClass or OID : [ |v] | * | | * | (CANCEL) ( OK ) | * '---------------------------------------------------------' * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ObjectClassDialog extends AddEditDialog<StringValueWrapper> { /** The possible objectClasses and OIDs. */ private String[] objectClassesAndOids; /** The combo containing the list of objectClasses. */ private Combo objectClassOrOidCombo; /** * Creates a new instance of ObjectClassDialog. * * @param parentShell the parent shell */ public ObjectClassDialog( Shell parentShell ) { super( parentShell ); } /** * Set the list of possible objectClasses and OIDs * * @param objectClassesAndOids The list of possible objectClasses and OID */ public void setAttributeNamesAndOids( String[] objectClassesAndOids ) { this.objectClassesAndOids = objectClassesAndOids; } /** * {@inheritDoc} */ protected void configureShell( Shell newShell ) { super.configureShell( newShell ); newShell.setText( Messages.getString( "ObjectClassDialog.SelectObjectClassOrOID" ) ); //$NON-NLS-1$ } /** * {@inheritDoc} */ protected void okPressed() { setEditedElement( new StringValueWrapper( objectClassOrOidCombo.getText(), false ) ); super.okPressed(); } /** * Overriding the createButton method. The OK button is not enabled until we have a selected ObjectClass * * {@inheritDoc} */ protected Button createButton( Composite parent, int id, String label, boolean defaultButton ) { Button button = super.createButton(parent, id, label, defaultButton); if ( id == IDialogConstants.OK_ID ) { String objectClass = ((StringValueWrapper)getEditedElement() ).getValue(); if ( ( objectClass == null ) || ( objectClass.length() == 0 ) ) { button.setEnabled( false ); } } return button; } /** * Create the ObjectClass dialog : * * <pre> * .---------------------------------------------------------. * |X| Select ObjectClass or OID | * +---------------------------------------------------------| * | ObjectClass or OID : [ |v] | * | | * | (CANCEL) ( OK ) | * '---------------------------------------------------------' * </pre> * * {@inheritDoc} */ protected Control createDialogArea( Composite parent ) { Composite composite = ( Composite ) super.createDialogArea( parent ); Composite c = BaseWidgetUtils.createColumnContainer( composite, 2, 1 ); BaseWidgetUtils.createLabel( c, Messages.getString( "ObjectClassDialog.ObjectClassOrOID" ), 1 ); //$NON-NLS-1$ objectClassOrOidCombo = BaseWidgetUtils.createCombo( c, objectClassesAndOids, -1, 1 ); if ( getEditedElement() != null ) { objectClassOrOidCombo.setText( getEditedElement().getValue() ); } objectClassOrOidCombo.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { validate(); } } ); initDialog(); return composite; } /** * {@inheritDoc} */ protected void initDialog() { // Nothing to do } /** * Check that we have selected an ObjectClass */ private void validate() { Button okButton = getButton( IDialogConstants.OK_ID ); // This button might be null when the dialog is called. if ( okButton == null ) { return; } okButton.setEnabled( !"".equals( objectClassOrOidCombo.getText() ) ); //$NON-NLS-1$ } /** * {@inheritDoc} */ @Override public void addNewElement() { // Default to none setEditedElement( new StringValueWrapper( "", 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/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/LdapFilterParserTest.java
plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/LdapFilterParserTest.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.ldapbrowser.core.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser; import org.junit.jupiter.api.Test; /** * Tests the filter parser. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class LdapFilterParserTest { private LdapFilterParser parser = new LdapFilterParser(); /** * Tests an equals filter */ @Test public void testEqualsFilter() { parser.parse( "(cn=test)" ); //$NON-NLS-1$ assertEquals( "(cn=test)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn=test)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an greater equals filter */ @Test public void testGreaterEqualsFilter() { parser.parse( "(cn>=test)" ); //$NON-NLS-1$ assertEquals( "(cn>=test)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn>=test)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an less equals filter */ @Test public void testLessEqualsFilter() { parser.parse( "(cn<=test)" ); //$NON-NLS-1$ assertEquals( "(cn<=test)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn<=test)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an aprox filter */ @Test public void testAproxFilter() { parser.parse( "(cn~=test)" ); //$NON-NLS-1$ assertEquals( "(cn~=test)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn~=test)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an substring filter */ @Test public void testSubstringFilter() { parser.parse( "(cn=te*st)" ); //$NON-NLS-1$ assertEquals( "(cn=te*st)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn=te*st)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an present filter */ @Test public void testPresentFilter() { parser.parse( "(cn=*)" ); //$NON-NLS-1$ assertEquals( "(cn=*)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn=*)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an simple filter */ @Test public void testRFC4515_1() { parser.parse( "(cn=Babs Jensen)" ); //$NON-NLS-1$ assertEquals( "(cn=Babs Jensen)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn=Babs Jensen)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an not filter */ @Test public void testRFC4515_2() { parser.parse( "(!(cn=Tim Howes))" ); //$NON-NLS-1$ assertEquals( "(!(cn=Tim Howes))", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(!(cn=Tim Howes))", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an and/or filter */ @Test public void testRFC4515_3() { parser.parse( "(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J*)))" ); //$NON-NLS-1$ assertEquals( "(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J*)))", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J*)))", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an substring filter */ @Test public void testRFC4515_4() { parser.parse( "(o=univ*of*mich*)" ); //$NON-NLS-1$ assertEquals( "(o=univ*of*mich*)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(o=univ*of*mich*)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an empty assertion value */ @Test public void testRFC4515_5() { parser.parse( "(seeAlso=)" ); //$NON-NLS-1$ assertEquals( "(seeAlso=)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(seeAlso=)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The first example shows the use of the escaping mechanism to * represent parenthesis characters. */ @Test public void testEscapeRFC4515_1() { parser.parse( "(o=Parens R Us \\28for all your parenthetical needs\\29)" ); //$NON-NLS-1$ assertEquals( "(o=Parens R Us \\28for all your parenthetical needs\\29)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(o=Parens R Us \\28for all your parenthetical needs\\29)", parser.getModel() //$NON-NLS-1$ .toUserProvidedString() ); assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The second shows how to represent * a "*" in an assertion value, preventing it from being interpreted as * a substring indicator. */ @Test public void testEscapeRFC4515_2() { parser.parse( "(cn=*\\2A*)" ); //$NON-NLS-1$ assertEquals( "(cn=*\\2A*)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn=*\\2A*)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The third illustrates the escaping of the backslash character. */ @Test public void testEscapeRFC4515_3() { parser.parse( "(filename=C:\\5cMyFile)" ); //$NON-NLS-1$ assertEquals( "(filename=C:\\5cMyFile)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(filename=C:\\5cMyFile)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The fourth example shows a filter searching for the four-octet value * 00 00 00 04 (hex), illustrating the use of the escaping mechanism to * represent arbitrary data, including NUL characters. */ @Test public void testEscapeRFC4515_4() { parser.parse( "(bin=\\00\\00\\00\\04)" ); //$NON-NLS-1$ assertEquals( "(bin=\\00\\00\\00\\04)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(bin=\\00\\00\\00\\04)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The fifth example illustrates the use of the escaping mechanism to * represent various non-ASCII UTF-8 characters. Specifically, there * are 5 characters in the &lt;assertionvalue> portion of this example: * LATIN CAPITAL LETTER L (U+004C), LATIN SMALL LETTER U (U+0075), LATIN * SMALL LETTER C WITH CARON (U+010D), LATIN SMALL LETTER I (U+0069), * and LATIN SMALL LETTER C WITH ACUTE (U+0107). */ @Test public void testEscapeRFC4515_5() { parser.parse( "(sn=Lu\\c4\\8di\\c4\\87)" ); //$NON-NLS-1$ assertEquals( "(sn=Lu\\c4\\8di\\c4\\87)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(sn=Lu\\c4\\8di\\c4\\87)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an filter with escaped assertion value. * * From RFC4515: * The sixth and final example demonstrates assertion of a BER-encoded * value. */ @Test public void testEscapeRFC4515_6() { parser.parse( "(1.3.6.1.4.1.1466.0=\\04\\02\\48\\69)" ); //$NON-NLS-1$ assertEquals( "(1.3.6.1.4.1.1466.0=\\04\\02\\48\\69)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(1.3.6.1.4.1.1466.0=\\04\\02\\48\\69)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The first example shows use of the matching rule "caseExactMatch." */ @Test public void testExtensibleFilterRFC4515_1() { parser.parse( "(cn:caseExactMatch:=Fred Flintstone)" ); //$NON-NLS-1$ assertEquals( "(cn:caseExactMatch:=Fred Flintstone)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn:caseExactMatch:=Fred Flintstone)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The second example demonstrates use of a MatchingRuleAssertion form * without a matchingRule. */ @Test public void testExtensibleFilterRFC4515_2() { parser.parse( "(cn:=Betty Rubble)" ); //$NON-NLS-1$ assertEquals( "(cn:=Betty Rubble)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(cn:=Betty Rubble)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The third example illustrates the use of the ":oid" notation to * indicate that the matching rule identified by the OID "2.4.6.8.10" * should be used when making comparisons, and that the attributes of an * entry's distinguished name should be considered part of the entry * when evaluating the match (indicated by the use of ":dn"). */ @Test public void testExtensibleFilterRFC4515_3() { parser.parse( "(sn:dn:2.4.6.8.10:=Barney Rubble)" ); //$NON-NLS-1$ assertEquals( "(sn:dn:2.4.6.8.10:=Barney Rubble)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(sn:dn:2.4.6.8.10:=Barney Rubble)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The fourth example denotes an equality match, except that Dn * components should be considered part of the entry when doing the * match. */ @Test public void testExtensibleFilterRFC4515_4() { parser.parse( "(o:dn:=Ace Industry)" ); //$NON-NLS-1$ assertEquals( "(o:dn:=Ace Industry)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(o:dn:=Ace Industry)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The fifth example is a filter that should be applied to any attribute * supporting the matching rule given (since the &lt;attr> has been * omitted). */ @Test public void testExtensibleFilterRFC4515_5() { parser.parse( "(:1.2.3:=Wilma Flintstone)" ); //$NON-NLS-1$ assertEquals( "(:1.2.3:=Wilma Flintstone)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(:1.2.3:=Wilma Flintstone)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Tests an extensible filter. * * From RFC4515: * The sixth and final example is also a filter that should be applied * to any attribute supporting the matching rule given. Attributes * supporting the matching rule contained in the Dn should also be * considered. */ @Test public void testExtensibleFilterRFC4515_6() { parser.parse( "(:Dn:2.4.6.8.10:=Dino)" ); //$NON-NLS-1$ assertEquals( "(:Dn:2.4.6.8.10:=Dino)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(:Dn:2.4.6.8.10:=Dino)", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } /** * Test for DIRSTUIO-210. */ @Test public void testDIRSTUDIO210() { parser.parse( "(objectClass>=z*) " ); //$NON-NLS-1$ assertEquals( "(objectClass>=)", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( "(objectClass>=z*) ", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertFalse( parser.getModel().isValid() ); } /** * Test for DIRSTUIO-279. */ @Test public void testDIRSTUDIO279() { parser.parse( " (&\n (objectClass=person)\n (cn=a*)\n) " ); //$NON-NLS-1$ assertEquals( "(&(objectClass=person)(cn=a*))", parser.getModel().toString() ); //$NON-NLS-1$ assertEquals( " (&\n (objectClass=person)\n (cn=a*)\n) ", parser.getModel().toUserProvidedString() ); //$NON-NLS-1$ assertFalse( parser.getModel().isValid() ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/LdapFilterParserErrorTolerantTest.java
plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/LdapFilterParserErrorTolerantTest.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.ldapbrowser.core.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterItemComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser; import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterToken; import org.junit.jupiter.api.Test; /** * Tests the filter parser for error tolerance. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class LdapFilterParserErrorTolerantTest { private LdapFilterParser parser = new LdapFilterParser(); @Test public void testLpar() { parser.parse( "(" ); //$NON-NLS-1$ LdapFilter model = parser.getModel(); assertNotNull( model.getStartToken() ); assertEquals( 0, model.getStartToken().getOffset() ); assertEquals( 1, model.getStartToken().getLength() ); assertEquals( LdapFilterToken.LPAR, model.getStartToken().getType() ); assertEquals( "(", model.getStartToken().getValue() ); //$NON-NLS-1$ assertNull( model.getFilterComponent() ); assertNull( model.getStopToken() ); assertEquals( "(", model.toString() ); //$NON-NLS-1$ assertEquals( "(", model.toUserProvidedString() ); //$NON-NLS-1$ assertFalse( parser.getModel().isValid() ); } @Test public void testLparAttr() { parser.parse( "(objectClass" ); //$NON-NLS-1$ LdapFilter model = parser.getModel(); assertNotNull( model.getStartToken() ); assertEquals( 0, model.getStartToken().getOffset() ); assertEquals( 1, model.getStartToken().getLength() ); assertEquals( LdapFilterToken.LPAR, model.getStartToken().getType() ); assertEquals( "(", model.getStartToken().getValue() ); //$NON-NLS-1$ LdapFilterComponent filterComponent = model.getFilterComponent(); assertNotNull( filterComponent ); assertTrue( filterComponent instanceof LdapFilterItemComponent ); LdapFilterItemComponent filterItemComponent = ( LdapFilterItemComponent ) filterComponent; assertNotNull( filterItemComponent.getAttributeToken() ); assertEquals( 1, filterItemComponent.getAttributeToken().getOffset() ); assertEquals( 11, filterItemComponent.getAttributeToken().getLength() ); assertEquals( LdapFilterToken.ATTRIBUTE, filterItemComponent.getAttributeToken().getType() ); assertEquals( "objectClass", filterItemComponent.getAttributeToken().getValue() ); //$NON-NLS-1$ assertNull( filterItemComponent.getFilterToken() ); assertNull( filterItemComponent.getValueToken() ); assertNull( model.getStopToken() ); assertEquals( "(objectClass", model.toString() ); //$NON-NLS-1$ assertEquals( "(objectClass", model.toUserProvidedString() ); //$NON-NLS-1$ assertFalse( parser.getModel().isValid() ); } @Test public void testLparAttrEquals() { parser.parse( "(objectClass=" ); //$NON-NLS-1$ LdapFilter model = parser.getModel(); assertNotNull( model.getStartToken() ); assertEquals( 0, model.getStartToken().getOffset() ); assertEquals( 1, model.getStartToken().getLength() ); assertEquals( LdapFilterToken.LPAR, model.getStartToken().getType() ); assertEquals( "(", model.getStartToken().getValue() ); //$NON-NLS-1$ LdapFilterComponent filterComponent = model.getFilterComponent(); assertNotNull( filterComponent ); assertTrue( filterComponent instanceof LdapFilterItemComponent ); LdapFilterItemComponent filterItemComponent = ( LdapFilterItemComponent ) filterComponent; assertNotNull( filterItemComponent.getAttributeToken() ); assertEquals( 1, filterItemComponent.getAttributeToken().getOffset() ); assertEquals( 11, filterItemComponent.getAttributeToken().getLength() ); assertEquals( LdapFilterToken.ATTRIBUTE, filterItemComponent.getAttributeToken().getType() ); assertEquals( "objectClass", filterItemComponent.getAttributeToken().getValue() ); //$NON-NLS-1$ assertNotNull( filterItemComponent.getFilterToken() ); assertEquals( 12, filterItemComponent.getFilterToken().getOffset() ); assertEquals( 1, filterItemComponent.getFilterToken().getLength() ); assertEquals( LdapFilterToken.EQUAL, filterItemComponent.getFilterToken().getType() ); assertEquals( "=", filterItemComponent.getFilterToken().getValue() ); //$NON-NLS-1$ assertNull( filterItemComponent.getValueToken() ); assertNull( model.getStopToken() ); assertEquals( "(objectClass=", model.toString() ); //$NON-NLS-1$ assertEquals( "(objectClass=", model.toUserProvidedString() ); //$NON-NLS-1$ assertFalse( parser.getModel().isValid() ); } @Test public void testLparAttrEqualsRpar() { parser.parse( "(objectClass=)" ); //$NON-NLS-1$ LdapFilter model = parser.getModel(); assertNotNull( model.getStartToken() ); assertEquals( 0, model.getStartToken().getOffset() ); assertEquals( 1, model.getStartToken().getLength() ); assertEquals( LdapFilterToken.LPAR, model.getStartToken().getType() ); assertEquals( "(", model.getStartToken().getValue() ); //$NON-NLS-1$ LdapFilterComponent filterComponent = model.getFilterComponent(); assertNotNull( filterComponent ); assertTrue( filterComponent instanceof LdapFilterItemComponent ); LdapFilterItemComponent filterItemComponent = ( LdapFilterItemComponent ) filterComponent; assertNotNull( filterItemComponent.getAttributeToken() ); assertEquals( 1, filterItemComponent.getAttributeToken().getOffset() ); assertEquals( 11, filterItemComponent.getAttributeToken().getLength() ); assertEquals( LdapFilterToken.ATTRIBUTE, filterItemComponent.getAttributeToken().getType() ); assertEquals( "objectClass", filterItemComponent.getAttributeToken().getValue() ); //$NON-NLS-1$ assertNotNull( filterItemComponent.getFilterToken() ); assertEquals( 12, filterItemComponent.getFilterToken().getOffset() ); assertEquals( 1, filterItemComponent.getFilterToken().getLength() ); assertEquals( LdapFilterToken.EQUAL, filterItemComponent.getFilterToken().getType() ); assertEquals( "=", filterItemComponent.getFilterToken().getValue() ); //$NON-NLS-1$ assertNotNull( filterItemComponent.getValueToken() ); assertNotNull( model.getStopToken() ); assertEquals( "(objectClass=)", model.toString() ); //$NON-NLS-1$ assertEquals( "(objectClass=)", model.toUserProvidedString() ); //$NON-NLS-1$ assertTrue( parser.getModel().isValid() ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/PasswordTest.java
plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/model/PasswordTest.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.ldapbrowser.core.model; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Test; /** * Test all the encryption algorithmes * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class PasswordTest { /** * Null Password should not be accepted */ @Test public void testNullPassword() { try { new Password( ( String ) null ); fail(); } catch ( IllegalArgumentException iae ) { assertTrue( true ); } } /** * */ @Test public void testPasswordSHAEncrypted() { Password password = new Password( "{SHA}5en6G6MezRroT3XKqkdPOmY/BfQ=" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordSHAEncryptedLowercase() { Password password = new Password( "{sha}5en6G6MezRroT3XKqkdPOmY/BfQ=" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordSSHAEncrypted() { Password password = new Password( "{SSHA}mjVVxasFkk59wMW4L1Ldt+YCblfhULHs03WW7g==" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordSSHAEncryptedLowercase() { Password password = new Password( "{ssha}mjVVxasFkk59wMW4L1Ldt+YCblfhULHs03WW7g==" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordMD5Encrypted() { Password password = new Password( "{MD5}Xr4ilOzQ4PCOq3aQ0qbuaQ==" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordMD5EncryptedLowercase() { Password password = new Password( "{md5}Xr4ilOzQ4PCOq3aQ0qbuaQ==" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordSMD5Encrypted() { Password password = new Password( "{SMD5}tQ9wo/VBuKsqBtylMMCcORbnYOJFMyDJ" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordSMD5EncryptedLowercase() { Password password = new Password( "{smd5}tQ9wo/VBuKsqBtylMMCcORbnYOJFMyDJ" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordCRYPTEncrypted() { Password password = new Password( "{CRYPT}qFkH8Z1woBlXw" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordCRYPTEncryptedLowercase() { Password password = new Password( "{crypt}qFkH8Z1woBlXw" ); //$NON-NLS-1$ assertTrue( password.verify( "secret" ) ); //$NON-NLS-1$ } /** * */ @Test public void testPasswordBadAlgorithm() { Password password = new Password( "{CRYPTE}qFkH8Z1woBlXw" ); //$NON-NLS-1$ assertFalse( password.verify( "secret" ) ); //$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/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/utils/AttributeComparatorTest.java
plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/utils/AttributeComparatorTest.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.ldapbrowser.core.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IValue; import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute; import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyConnection; import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Value; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class AttributeComparatorTest { private IBrowserConnection connection; private IEntry entry; private Attribute objectClass; private Value objectClassTop; private Value objectClassPerson; private Attribute cn; private Value cn_foo_1; private Value cn_foo_2; private Value cn_bar; private Value cn_empty_1; private Value cn_empty_2; private Attribute sn; private Value sn_foo; private AttributeComparator comparator; @BeforeEach public void setup() throws Exception { ConnectionEventRegistry.suspendEventFiringInCurrentThread(); connection = new DummyConnection( Schema.DEFAULT_SCHEMA ); entry = new DummyEntry( new Dn( "cn=foo" ), connection ); objectClass = new Attribute( entry, "objectClass" ); entry.addAttribute( objectClass ); objectClassTop = new Value( objectClass, "top" ); objectClass.addValue( objectClassTop ); objectClassPerson = new Value( objectClass, "person" ); objectClass.addValue( objectClassPerson ); cn = new Attribute( entry, "cn" ); entry.addAttribute( cn ); cn_foo_1 = new Value( cn, "foo" ); cn.addValue( cn_foo_1 ); cn_foo_2 = new Value( cn, "foo" ); cn.addValue( cn_foo_2 ); cn_bar = new Value( cn, "bar" ); cn.addValue( cn_bar ); cn_empty_1 = new Value( cn, "" ); cn.addValue( cn_empty_1 ); cn_empty_2 = new Value( cn, "" ); cn.addValue( cn_empty_2 ); sn = new Attribute( entry, "sn" ); entry.addAttribute( sn ); sn_foo = new Value( sn, "foo" ); sn.addValue( sn_foo ); comparator = new AttributeComparator(); } @Test public void testAttributesEqual() { assertEquals( 0, comparator.compare( objectClass, objectClass ) ); assertEquals( 0, comparator.compare( cn, cn ) ); assertEquals( 0, comparator.compare( cn, new Attribute( entry, "cn" ) ) ); } @Test public void testValuesEqual() { assertEquals( 0, comparator.compare( cn_foo_1, cn_foo_1 ) ); assertEquals( 0, comparator.compare( cn_foo_1, cn_foo_2 ) ); assertEquals( 0, comparator.compare( cn_foo_2, cn_foo_1 ) ); } @Test public void testMustAttributresDiffer() { int less = comparator.compare( cn, sn ); assertTrue( less < 0 ); int greater = comparator.compare( sn, cn ); assertTrue( greater > 0 ); assertEquals( 0, less + greater ); } @Test public void testObjectClassMustAttributesDiffer() { int less = comparator.compare( objectClass, cn ); assertTrue( less < 0 ); int greater = comparator.compare( cn, objectClass ); assertTrue( greater > 0 ); assertEquals( 0, less + greater ); } // TODO: objectclass, may, operational // TODO: objectclass < must < may < operational @Test public void testValuesDiffer() { int less = comparator.compare( cn_bar, cn_foo_1 ); assertTrue( less < 0 ); int greater = comparator.compare( cn_foo_1, cn_bar ); assertTrue( greater > 0 ); assertEquals( 0, less + greater ); } @Test public void testEmptyValuesEqual() { assertEquals( 0, comparator.compare( cn_empty_1, cn_empty_1 ) ); assertEquals( 0, comparator.compare( cn_empty_1, cn_empty_2 ) ); assertEquals( 0, comparator.compare( cn_empty_2, cn_empty_1 ) ); } @Test public void testEmptyValuesDiffer() { int less = comparator.compare( cn_empty_1, cn_bar ); assertTrue( less < 0 ); int greater = comparator.compare( cn_bar, cn_empty_1 ); assertTrue( greater > 0 ); assertEquals( 0, less + greater ); } @Test public void test_DIRSTUDIO_1200() throws Exception { Schema schema = Schema.DEFAULT_SCHEMA; DummyConnection connection = new DummyConnection( schema ); LdifContentRecord record = new LdifContentRecord( LdifDnLine.create( "cn=foo" ) ); record.addAttrVal( LdifAttrValLine.create( "objectClass", "inetOrgPerson" ) ); for ( int i = 0; i < 28; i++ ) { record.addAttrVal( LdifAttrValLine.create( "uid", "" + i ) ); } record.addAttrVal( LdifAttrValLine.create( "objectClass", "top" ) ); record.addAttrVal( LdifAttrValLine.create( "cn", "foo" ) ); record.addAttrVal( LdifAttrValLine.create( "cn", "bar" ) ); DummyEntry entry = ModelConverter.ldifContentRecordToEntry( record, connection ); List<IValue> sortedValues = AttributeComparator.toSortedValues( entry ); assertEquals( 32, sortedValues.size() ); assertEquals( "objectClass", sortedValues.get( 0 ).getAttribute().getDescription() ); assertEquals( "inetOrgPerson", sortedValues.get( 0 ).getStringValue() ); assertEquals( "uid", sortedValues.get( 31 ).getAttribute().getDescription() ); assertEquals( "9", sortedValues.get( 31 ).getStringValue() ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/utils/UtilsTest.java
plugins/ldapbrowser.core/src/test/java/org/apache/directory/studio/ldapbrowser/core/utils/UtilsTest.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.ldapbrowser.core.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.text.translate.CharSequenceTranslator; import org.junit.jupiter.api.Test; public class UtilsTest { @Test public void testPostalAddressTrivial() { assertEquals( "abc", Utils.createPostalAddressDecoder( "!" ).translate( "abc" ) ); assertEquals( "abc", Utils.createPostalAddressEncoder( "!" ).translate( "abc" ) ); } @Test public void testPostalAddressEscaped() { CharSequenceTranslator decoder = Utils.createPostalAddressDecoder( "!" ); assertEquals( "!", decoder.translate( "$" ) ); assertEquals( "$", decoder.translate( "\\24" ) ); assertEquals( "\\", decoder.translate( "\\5C" ) ); assertEquals( "\\", decoder.translate( "\\5c" ) ); assertEquals( "\\5C", decoder.translate( "\\5c5C" ) ); assertEquals( "\\5c", decoder.translate( "\\5C5c" ) ); CharSequenceTranslator encoder = Utils.createPostalAddressEncoder( "!" ); assertEquals( "$", encoder.translate( "!" ) ); assertEquals( "\\24", encoder.translate( "$" ) ); assertEquals( "\\5C", encoder.translate( "\\" ) ); } @Test public void testPostalAddressRfcExamples() { CharSequenceTranslator decoder = Utils.createPostalAddressDecoder( "\n" ); assertEquals( "1234 Main St.\nAnytown, CA 12345\nUSA", decoder.translate( "1234 Main St.$Anytown, CA 12345$USA" ) ); assertEquals( "$1,000,000 Sweepstakes\nPO Box 1000000\nAnytown, CA 12345\nUSA", decoder.translate( "\\241,000,000 Sweepstakes$PO Box 1000000$Anytown, CA 12345$USA" ) ); CharSequenceTranslator encoder = Utils.createPostalAddressEncoder( "\n" ); assertEquals( "1234 Main St.$Anytown, CA 12345$USA", encoder.translate( "1234 Main St.\nAnytown, CA 12345\nUSA" ) ); assertEquals( "\\241,000,000 Sweepstakes$PO Box 1000000$Anytown, CA 12345$USA", encoder.translate( "$1,000,000 Sweepstakes\nPO Box 1000000\nAnytown, CA 12345\nUSA" ) ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePreferences.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePreferences.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.ldapbrowser.core; import java.util.HashSet; import java.util.Set; import org.apache.directory.studio.ldapbrowser.core.model.schema.BinaryAttribute; import org.apache.directory.studio.ldapbrowser.core.model.schema.BinarySyntax; import org.apache.directory.studio.ldapbrowser.core.model.schema.ObjectClassIconPair; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.eclipse.core.runtime.Preferences; /** * This class is used to manage and access the preferences of the Browser Core Plugin * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserCorePreferences { private Set<String> binaryAttributeCache; private Set<String> binarySyntaxCache; /** * Gets the OIDs and names of the binary attributes * * @return * the OIDs and names of the binary attributes */ public Set<String> getUpperCasedBinaryAttributeOidsAndNames() { if ( binaryAttributeCache == null ) { binaryAttributeCache = new HashSet<String>(); BinaryAttribute[] binaryAttributes = getBinaryAttributes(); for ( BinaryAttribute binaryAttribute : binaryAttributes ) { if ( binaryAttribute.getAttributeNumericOidOrName() != null ) { binaryAttributeCache.add( binaryAttribute.getAttributeNumericOidOrName().toUpperCase() ); } } } return binaryAttributeCache; } /** * Gets an array containing the binary attributes * * @return * an array containing the binary attributes */ public BinaryAttribute[] getBinaryAttributes() { BinaryAttribute[] binaryAttributes = ( BinaryAttribute[] ) load( BrowserCoreConstants.PREFERENCE_BINARY_ATTRIBUTES ); return binaryAttributes; } /** * Sets the binary attributes * * @param binaryAttributes * the binary attributes to set */ public void setBinaryAttributes( BinaryAttribute[] binaryAttributes ) { store( BrowserCoreConstants.PREFERENCE_BINARY_ATTRIBUTES, binaryAttributes ); binaryAttributeCache = null; } /** * Gets the default binary attributes * * @return * the default binary attributes */ public BinaryAttribute[] getDefaultBinaryAttributes() { BinaryAttribute[] binaryAttributes = ( BinaryAttribute[] ) loadDefault( BrowserCoreConstants.PREFERENCE_BINARY_ATTRIBUTES ); return binaryAttributes; } /** * Sets the default binary attributes * * @param defaultBinaryAttributes * the default binary attributes to set */ public void setDefaultBinaryAttributes( BinaryAttribute[] defaultBinaryAttributes ) { storeDefault( BrowserCoreConstants.PREFERENCE_BINARY_ATTRIBUTES, defaultBinaryAttributes ); } /** * Gets the binary syntax OIDs. * * @return the binary syntax OIDs */ public Set<String> getUpperCasedBinarySyntaxOids() { if ( binarySyntaxCache == null ) { binarySyntaxCache = new HashSet<String>(); BinarySyntax[] binarySyntaxes = getBinarySyntaxes(); for ( BinarySyntax binarySyntax : binarySyntaxes ) { if ( binarySyntax.getSyntaxNumericOid() != null ) { binarySyntaxCache.add( binarySyntax.getSyntaxNumericOid().toUpperCase() ); } } } return binarySyntaxCache; } /** * Gets the binary syntaxes * * @return * the binary syntaxes */ public BinarySyntax[] getBinarySyntaxes() { BinarySyntax[] binarySyntaxes = ( BinarySyntax[] ) load( BrowserCoreConstants.PREFERENCE_BINARY_SYNTAXES ); return binarySyntaxes; } /** * Sets the binary syntaxes * * @param binarySyntaxes * the binary syntaxes to set */ public void setBinarySyntaxes( BinarySyntax[] binarySyntaxes ) { store( BrowserCoreConstants.PREFERENCE_BINARY_SYNTAXES, binarySyntaxes ); binarySyntaxCache = null; } /** * Gets the default binary syntaxes * * @return * the default binary syntaxes */ public BinarySyntax[] getDefaultBinarySyntaxes() { BinarySyntax[] binarySyntaxes = ( BinarySyntax[] ) loadDefault( BrowserCoreConstants.PREFERENCE_BINARY_SYNTAXES ); return binarySyntaxes; } /** * Sets the default binary syntaxes * * @param defaultBinarySyntaxes * the default binary syntaxes to set */ public void setDefaultBinarySyntaxes( BinarySyntax[] defaultBinarySyntaxes ) { storeDefault( BrowserCoreConstants.PREFERENCE_BINARY_SYNTAXES, defaultBinarySyntaxes ); } /** * Gets the object class icons. * * @return the object class icons */ public ObjectClassIconPair[] getObjectClassIcons() { ObjectClassIconPair[] ocIcons = ( ObjectClassIconPair[] ) load( BrowserCoreConstants.PREFERENCE_OBJECT_CLASS_ICONS ); return ocIcons; } /** * Sets the object class icons. * * @param ocIcons the new object class icons */ public void setObjectClassIcons( ObjectClassIconPair[] ocIcons ) { store( BrowserCoreConstants.PREFERENCE_OBJECT_CLASS_ICONS, ocIcons ); } /** * Gets the default object class icon. * * @return the default object class icon */ public ObjectClassIconPair[] getDefaultObjectClassIcon() { ObjectClassIconPair[] ocIcons = ( ObjectClassIconPair[] ) loadDefault( BrowserCoreConstants.PREFERENCE_OBJECT_CLASS_ICONS ); return ocIcons; } /** * Sets the default object class icons. * * @param ocIcons the new default object class icons */ public void setDefaultObjectClassIcons( ObjectClassIconPair[] ocIcons ) { storeDefault( BrowserCoreConstants.PREFERENCE_OBJECT_CLASS_ICONS, ocIcons ); } /** * Loads the current value of the string-valued property with the given name. * * @param key * the name of the property * @return * the corresponding object */ private static Object load( String key ) { Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); String s = store.getString( key ); return Utils.deserialize( s ); } /** * Stores the current value of the string-valued property with the given name. * * @param key * the name of the property * @param o * the new current value of the property */ private static void store( String key, Object o ) { Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); String s = Utils.serialize( o ); store.setValue( key, s ); BrowserCorePlugin.getDefault().savePluginPreferences(); } /** * Loads the default value for the string-valued property with the given name. * * @param key * the name of the property * @return * the default value of the named property */ private static Object loadDefault( String key ) { Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); String s = store.getDefaultString( key ); return Utils.deserialize( s ); } /** * Stores the default value for the string-valued property with the given name. * * @param key * the name of the property * @param o * the new default value for the property */ private static void storeDefault( String key, Object o ) { Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); String s = Utils.serialize( o ); store.setDefault( key, s ); BrowserCorePlugin.getDefault().savePluginPreferences(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCoreConstants.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCoreConstants.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.ldapbrowser.core; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; /** * This class contains all the constants used by the Browser Core Plugin * Final reference -> class shouldn't be extended * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public final class BrowserCoreConstants { /** * 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 BrowserCoreConstants() { } /** The plug-in ID */ public static final String PLUGIN_ID = BrowserCoreConstants.class.getPackage().getName(); public static final String PREFERENCE_BINARY_SYNTAXES = "binarySyntaxes"; //$NON-NLS-1$ public static final String PREFERENCE_BINARY_ATTRIBUTES = "binaryAttributes"; //$NON-NLS-1$ public static final String PREFERENCE_OBJECT_CLASS_ICONS = "objectClassIcons"; //$NON-NLS-1$ public static final String BINARY = "BINARY"; //$NON-NLS-1$ public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); //$NON-NLS-1$ public static final String DEFAULT_ENCODING = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); public static final String PREFERENCE_CHECK_FOR_CHILDREN = "checkForChildren"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER = "formatCsvAttributeDelimiter"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_VALUEDELIMITER = "formatCsvValueDelimiter"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_QUOTECHARACTER = "formatCsvQuoteCharacter"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_LINESEPARATOR = "formatCsvLineSeparator"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_BINARYENCODING = "formatCsvBinaryEncoding"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_CSV_ENCODING = "formatCsvEncoding"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_XLS_VALUEDELIMITER = "formatXlsValueDelimiter"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_XLS_BINARYENCODING = "formatXlsBinaryEncoding"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_ODF_VALUEDELIMITER = "formatOdfValueDelimiter"; //$NON-NLS-1$ public static final String PREFERENCE_FORMAT_ODF_BINARYENCODING = "formatOdfBinaryEncoding"; //$NON-NLS-1$ public static final String PREFERENCE_LDIF_LINE_WIDTH = "ldifLineWidth"; //$NON-NLS-1$ public static final String PREFERENCE_LDIF_LINE_SEPARATOR = "ldifLineSeparator"; //$NON-NLS-1$ public static final String PREFERENCE_LDIF_SPACE_AFTER_COLON = "ldifSpaceAfterColon"; //$NON-NLS-1$ public static final String PREFERENCE_LDIF_INCLUDE_VERSION_LINE = "ldifIncludeVersionLine"; //$NON-NLS-1$ public static final int BINARYENCODING_IGNORE = 0; public static final int BINARYENCODING_BASE64 = 1; public static final int BINARYENCODING_HEX = 2; public static final int SORT_BY_NONE = 0; public static final int SORT_BY_RDN = 1; public static final int SORT_BY_RDN_VALUE = 2; public static final int SORT_BY_ATTRIBUTE_DESCRIPTION = 3; public static final int SORT_BY_VALUE = 4; public static final int SORT_ORDER_NONE = 0; public static final int SORT_ORDER_ASCENDING = 1; public static final int SORT_ORDER_DESCENDING = 2; public static final String LDAP_SEARCH_PAGE_ID = "org.apache.directory.studio.ldapbrowser.ui.search.SearchPage"; //$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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BookmarkManager.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BookmarkManager.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.ldapbrowser.core; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.directory.studio.ldapbrowser.core.events.BookmarkUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBookmark; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.eclipse.osgi.util.NLS; /** * This class is used to manage Bookmarks. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BookmarkManager implements Serializable { private static final long serialVersionUID = 7605293576518974531L; private List<IBookmark> bookmarkList; private IBrowserConnection connection; /** * Creates a new instance of BookmarkManager. * * @param connection * the attached Connection */ public BookmarkManager( IBrowserConnection connection ) { this.connection = connection; bookmarkList = new ArrayList<IBookmark>(); } /** * Gets the Connection * * @return * the Connection */ public IBrowserConnection getConnection() { return connection; } /** * Adds a Bookmark * * @param bookmark * the Bookmark to add */ public void addBookmark( IBookmark bookmark ) { addBookmark( bookmarkList.size(), bookmark ); } /** * Adds a Bookmark at a specified position. * * @param index * the index at which the specified element is to be inserted. * @param bookmark * the Bookmark to add */ public void addBookmark( int index, IBookmark bookmark ) { if ( getBookmark( bookmark.getName() ) != null ) { String newBookmarkName = NLS.bind( BrowserCoreMessages.copy_n_of_s, "", bookmark.getName() ); //$NON-NLS-1$ for ( int i = 2; this.getBookmark( newBookmarkName ) != null; i++ ) { newBookmarkName = NLS.bind( BrowserCoreMessages.copy_n_of_s, i + " ", bookmark.getName() ); //$NON-NLS-1$ } bookmark.setName( newBookmarkName ); } bookmarkList.add( index, bookmark ); EventRegistry.fireBookmarkUpdated( new BookmarkUpdateEvent( bookmark, BookmarkUpdateEvent.Detail.BOOKMARK_ADDED ), this ); } /** * Gets a Bookmark * * @param name * the name of the Bookmark * @return * the corresponding Bookmark */ public IBookmark getBookmark( String name ) { for ( IBookmark bookmark : bookmarkList ) { if ( bookmark.getName().equals( name ) ) { return bookmark; } } return null; } /** * Returns the index in the Bookmarks list of the first occurrence of the specified Bookmark * * @param bookmark * the bookmark to search for * @return * the index in the Bookmarks list of the first occurrence of the specified Bookmark */ public int indexOf( IBookmark bookmark ) { return bookmarkList.indexOf( bookmark ); } /** * Removes a Bookmark * * @param bookmark * the Bookmark to remove */ public void removeBookmark( IBookmark bookmark ) { bookmarkList.remove( bookmark ); EventRegistry.fireBookmarkUpdated( new BookmarkUpdateEvent( bookmark, BookmarkUpdateEvent.Detail.BOOKMARK_REMOVED ), this ); } /** * Removes a Bookmark * * @param name * the name of the Bookmark to remove */ public void removeBookmark( String name ) { this.removeBookmark( this.getBookmark( name ) ); } /** * Gets an array containing all Bookmarks * * @return * an array containing all Bookmarks */ public IBookmark[] getBookmarks() { return bookmarkList.toArray( new IBookmark[0] ); } /** * Gets the number of Bookmarks * * @return * the number of Bookmarjs */ public int getBookmarkCount() { return bookmarkList.size(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/SearchManager.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/SearchManager.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.ldapbrowser.core; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.eclipse.osgi.util.NLS; /** * This class is used to manages {@link ISearch}es of an {@link IBrowserConnection} * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SearchManager implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 8665227628274097691L; /** The list of searches. */ private List<ISearch> searchList; /** The connection. */ private IBrowserConnection connection; /** * Creates a new instance of SearchManager. */ protected SearchManager() { } /** * Creates a new instance of SearchManager. * * @param connection * the attached Connection */ public SearchManager( IBrowserConnection connection ) { this.connection = connection; this.searchList = new ArrayList<ISearch>(); } /** * Gets the Connection. * * @return * the Connection */ public IBrowserConnection getConnection() { return connection; } /** * Adds a Search. * * @param search * the Search to add */ public void addSearch( ISearch search ) { addSearch( searchList.size(), search ); } /** * Adds a Search at a specified position. * * @param index * index at which the specified Search is to be inserted. * @param search * the Search to be inserted */ public void addSearch( int index, ISearch search ) { if ( getSearch( search.getName() ) != null ) { String newSearchName = NLS.bind( BrowserCoreMessages.copy_n_of_s, "", search.getName() ); //$NON-NLS-1$ for ( int i = 2; this.getSearch( newSearchName ) != null; i++ ) { newSearchName = NLS.bind( BrowserCoreMessages.copy_n_of_s, i + " ", search.getName() ); //$NON-NLS-1$ } search.setName( newSearchName ); } searchList.add( index, search ); EventRegistry.fireSearchUpdated( new SearchUpdateEvent( search, SearchUpdateEvent.EventDetail.SEARCH_ADDED ), this ); } /** * Gets a Search. * * @param name * the name of the Search * @return * the corresponding Search */ public ISearch getSearch( String name ) { for ( ISearch search : searchList ) { if ( search.getName().equals( name ) ) { return search; } } return null; } /** * Returns the index in the Searches list of the first occurrence of the specified Search. * * @param search * the Search to search for * @return * the index in the Searches list of the first occurrence of the specified Search */ public int indexOf( ISearch search ) { return searchList.indexOf( search ); } /** * Removes a Search * * @param search * the Search to remove */ public void removeSearch( ISearch search ) { searchList.remove( search ); EventRegistry.fireSearchUpdated( new SearchUpdateEvent( search, SearchUpdateEvent.EventDetail.SEARCH_REMOVED ), this ); } /** * Removes a Search * * @param name * the name of the Search to remove */ public void removeSearch( String name ) { removeSearch( getSearch( name ) ); } /** * Gets a list containing all the Searches * * @return * a list containing all the Searches */ public List<ISearch> getSearches() { // clone the internal list return new ArrayList<ISearch>( searchList ); } /** * Gets the number of Searches * * @return * the number of Searches */ public int getSearchCount() { return searchList.size(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionIO.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionIO.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.ldapbrowser.core; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.StudioControl; import org.apache.directory.studio.connection.core.io.ConnectionIOException; import org.apache.directory.studio.ldapbrowser.core.model.BookmarkParameter; import org.apache.directory.studio.ldapbrowser.core.model.IBookmark; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.impl.Bookmark; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.eclipse.osgi.util.NLS; /** * This class is used to read/write the 'connections.xml' file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserConnectionIO { // XML tags private static final String BROWSER_CONNECTIONS_TAG = "browserConnections"; //$NON-NLS-1$ private static final String BROWSER_CONNECTION_TAG = "browserConnection"; //$NON-NLS-1$ private static final String ID_TAG = "id"; //$NON-NLS-1$ private static final String SEARCHES_TAG = "searches"; //$NON-NLS-1$ private static final String SEARCH_PARAMETER_TAG = "searchParameter"; //$NON-NLS-1$ private static final String NAME_TAG = "name"; //$NON-NLS-1$ private static final String SEARCH_BASE_TAG = "searchBase"; //$NON-NLS-1$ private static final String FILTER_TAG = "filer"; //$NON-NLS-1$ private static final String RETURNING_ATTRIBUTES_TAG = "returningAttributes"; //$NON-NLS-1$ private static final String RETURNING_ATTRIBUTE_TAG = "returningAttribute"; //$NON-NLS-1$ private static final String VALUE_TAG = "value"; //$NON-NLS-1$ private static final String SCOPE_TAG = "scope"; //$NON-NLS-1$ private static final String TIME_LIMIT_TAG = "timeLimit"; //$NON-NLS-1$ private static final String COUNT_LIMIT_TAG = "countLimit"; //$NON-NLS-1$ private static final String ALIASES_DEREFERENCING_METHOD_TAG = "aliasesDereferencingMethod"; //$NON-NLS-1$ private static final String REFERRALS_HANDLING_METHOD_TAG = "referralsHandlingMethod"; //$NON-NLS-1$ private static final String PAGED_SEARCH_SCROLL_MODE = "pagedSearchScrollMode"; //$NON-NLS-1$ private static final String CONTROLS_TAG = "controls"; //$NON-NLS-1$ private static final String CONTROL_TAG = "control"; //$NON-NLS-1$ private static final String OID_TAG = "oid"; //$NON-NLS-1$ private static final String IS_CRITICAL_TAG = "isCritical"; //$NON-NLS-1$ private static final String BOOKMARKS_TAG = "bookmarks"; //$NON-NLS-1$ private static final String BOOKMARK_PARAMETER_TAG = "bookmarkParameter"; //$NON-NLS-1$ private static final String DN_TAG = "dn"; //$NON-NLS-1$ // Scope values private static final String SCOPE_OBJECT = "OBJECT"; //$NON-NLS-1$ private static final String SCOPE_ONELEVEL = "ONELEVEL"; //$NON-NLS-1$ private static final String SCOPE_SUBTREE = "SUBTREE"; //$NON-NLS-1$ private static final String SCOPE_OBJECT_2 = "base"; //$NON-NLS-1$ private static final String SCOPE_ONELEVEL_2 = "one"; //$NON-NLS-1$ private static final String SCOPE_SUBTREE_2 = "sub"; //$NON-NLS-1$ /** * Loads the browser connections using the input stream. * * @param stream * the input stream * @param browserConnectionMap * the map of browser connections * @throws ConnectionIOException * if an error occurs when converting the document */ public static void load( InputStream stream, Map<String, IBrowserConnection> browserConnectionMap ) throws ConnectionIOException { SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read( stream ); } catch ( DocumentException e ) { throw new ConnectionIOException( e.getMessage() ); } Element rootElement = document.getRootElement(); if ( !rootElement.getName().equals( BROWSER_CONNECTIONS_TAG ) ) { throw new ConnectionIOException( BrowserCoreMessages.BrowserConnectionIO_TheFileDoesNotSeemToBeValid ); } for ( Iterator<?> i = rootElement.elementIterator( BROWSER_CONNECTION_TAG ); i.hasNext(); ) { Element browserConnectionElement = ( Element ) i.next(); readBrowserConnection( browserConnectionElement, browserConnectionMap ); } } /** * Reads a browser connection from the given Element. * * @param element * the element * @param browserConnectionMap * the map of browser connections * * @throws ConnectionIOException * if an error occurs when converting values */ private static void readBrowserConnection( Element element, Map<String, IBrowserConnection> browserConnectionMap ) throws ConnectionIOException { // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { String id = idAttribute.getValue(); IBrowserConnection browserConnection = browserConnectionMap.get( id ); if ( browserConnection != null ) { Element searchesElement = element.element( SEARCHES_TAG ); if ( searchesElement != null ) { for ( Iterator<?> i = searchesElement.elementIterator( SEARCH_PARAMETER_TAG ); i.hasNext(); ) { Element searchParameterElement = ( Element ) i.next(); SearchParameter searchParameter = readSearch( searchParameterElement, browserConnection ); ISearch search = new Search( browserConnection, searchParameter ); browserConnection.getSearchManager().addSearch( search ); } } Element bookmarksElement = element.element( BOOKMARKS_TAG ); if ( bookmarksElement != null ) { for ( Iterator<?> i = bookmarksElement.elementIterator( BOOKMARK_PARAMETER_TAG ); i.hasNext(); ) { Element bookmarkParameterElement = ( Element ) i.next(); BookmarkParameter bookmarkParameter = readBookmark( bookmarkParameterElement, browserConnection ); IBookmark bookmark = new Bookmark( browserConnection, bookmarkParameter ); browserConnection.getBookmarkManager().addBookmark( bookmark ); } } } } } private static SearchParameter readSearch( Element searchParameterElement, IBrowserConnection browserConnection ) throws ConnectionIOException { SearchParameter searchParameter = new SearchParameter(); // Name Attribute nameAttribute = searchParameterElement.attribute( NAME_TAG ); if ( nameAttribute != null ) { searchParameter.setName( nameAttribute.getValue() ); } // Search base Attribute searchBaseAttribute = searchParameterElement.attribute( SEARCH_BASE_TAG ); if ( searchBaseAttribute != null ) { try { searchParameter.setSearchBase( new Dn( searchBaseAttribute.getValue() ) ); } catch ( LdapInvalidDnException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseSearchBase, new String[] { searchParameter.getName(), searchBaseAttribute.getValue() } ) ); } } // Filter Attribute filterAttribute = searchParameterElement.attribute( FILTER_TAG ); if ( filterAttribute != null ) { searchParameter.setFilter( filterAttribute.getValue() ); } // Returning Attributes Element returningAttributesElement = searchParameterElement.element( RETURNING_ATTRIBUTES_TAG ); if ( returningAttributesElement != null ) { List<String> returningAttributes = new ArrayList<String>(); for ( Iterator<?> i = returningAttributesElement.elementIterator( RETURNING_ATTRIBUTE_TAG ); i.hasNext(); ) { Element returningAttributeElement = ( Element ) i.next(); Attribute valueAttribute = returningAttributeElement.attribute( VALUE_TAG ); if ( valueAttribute != null ) { returningAttributes.add( valueAttribute.getValue() ); } } searchParameter.setReturningAttributes( returningAttributes .toArray( new String[returningAttributes.size()] ) ); } // Scope Attribute scopeAttribute = searchParameterElement.attribute( SCOPE_TAG ); if ( scopeAttribute != null ) { try { searchParameter.setScope( convertSearchScope( scopeAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseScope, new String[] { searchParameter.getName(), scopeAttribute.getValue() } ) ); } } // Time limit Attribute timeLimitAttribute = searchParameterElement.attribute( TIME_LIMIT_TAG ); if ( timeLimitAttribute != null ) { try { searchParameter.setTimeLimit( Integer.parseInt( timeLimitAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseTimeLimit, new String[] { searchParameter.getName(), timeLimitAttribute.getValue() } ) ); } } // Count limit Attribute countLimitAttribute = searchParameterElement.attribute( COUNT_LIMIT_TAG ); if ( countLimitAttribute != null ) { try { searchParameter.setCountLimit( Integer.parseInt( countLimitAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseCountLimit, new String[] { searchParameter.getName(), countLimitAttribute.getValue() } ) ); } } // Alias dereferencing method Attribute aliasesDereferencingMethodAttribute = searchParameterElement .attribute( ALIASES_DEREFERENCING_METHOD_TAG ); if ( aliasesDereferencingMethodAttribute != null ) { try { searchParameter.setAliasesDereferencingMethod( Connection.AliasDereferencingMethod .valueOf( aliasesDereferencingMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseAliasesDereferencingMethod, new String[] { searchParameter.getName(), aliasesDereferencingMethodAttribute.getValue() } ) ); } } // Referrals handling method Attribute referralsHandlingMethodAttribute = searchParameterElement.attribute( REFERRALS_HANDLING_METHOD_TAG ); if ( referralsHandlingMethodAttribute != null ) { try { searchParameter.setReferralsHandlingMethod( Connection.ReferralHandlingMethod .valueOf( referralsHandlingMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseReferralsHandlingMethod, new String[] { searchParameter.getName(), referralsHandlingMethodAttribute.getValue() } ) ); } } // Paged search scroll mode Attribute pagedSearchScrollModeAttribute = searchParameterElement.attribute( PAGED_SEARCH_SCROLL_MODE ); if ( pagedSearchScrollModeAttribute != null ) { searchParameter.setPagedSearchScrollMode( Boolean.valueOf( pagedSearchScrollModeAttribute.getValue() ) ); } // Controls Element controlsElement = searchParameterElement.element( CONTROLS_TAG ); if ( controlsElement != null ) { for ( Iterator<?> i = controlsElement.elementIterator( CONTROL_TAG ); i.hasNext(); ) { Element controlElement = ( Element ) i.next(); Attribute oidAttribute = controlElement.attribute( OID_TAG ); Attribute isCriticalAttribute = controlElement.attribute( IS_CRITICAL_TAG ); Attribute valueAttribute = controlElement.attribute( VALUE_TAG ); try { if ( oidAttribute != null && isCriticalAttribute != null && valueAttribute != null ) { byte[] bytes = Base64.getDecoder().decode( valueAttribute.getValue() ); Control control = Controls.create( oidAttribute.getValue(), Boolean.valueOf( isCriticalAttribute.getValue() ), bytes ); searchParameter.getControls().add( control ); } else if ( valueAttribute != null ) { // Backward compatibility: read objects using Java serialization byte[] bytes = Base64.getDecoder().decode( valueAttribute.getValue() ); ByteArrayInputStream bais = null; ObjectInputStream ois = null; bais = new ByteArrayInputStream( bytes ); ois = new ObjectInputStream( bais ); StudioControl studioControl = ( StudioControl ) ois.readObject(); Control control = Controls.create( studioControl.getOid(), studioControl.isCritical(), studioControl.getControlValue() ); searchParameter.getControls().add( control ); ois.close(); } } catch ( Exception e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseControl, new String[] { searchParameter.getName(), valueAttribute.getValue() } ) ); } } } return searchParameter; } private static BookmarkParameter readBookmark( Element bookmarkParameterElement, IBrowserConnection browserConnection ) throws ConnectionIOException { BookmarkParameter bookmarkParameter = new BookmarkParameter(); // Name Attribute nameAttribute = bookmarkParameterElement.attribute( NAME_TAG ); if ( nameAttribute != null ) { bookmarkParameter.setName( nameAttribute.getValue() ); } // Dn Attribute dnAttribute = bookmarkParameterElement.attribute( DN_TAG ); if ( dnAttribute != null ) { try { bookmarkParameter.setDn( new Dn( dnAttribute.getValue() ) ); } catch ( LdapInvalidDnException e ) { throw new ConnectionIOException( NLS.bind( BrowserCoreMessages.BrowserConnectionIO_UnableToParseDn, new String[] { bookmarkParameter.getName(), dnAttribute.getValue() } ) ); } } return bookmarkParameter; } /** * Saves the browser connections using the output stream. * * @param stream * the OutputStream * @param browserConnectionMap * the map of browser connections * @throws IOException * if an I/O error occurs */ public static void save( OutputStream stream, Map<String, IBrowserConnection> browserConnectionMap ) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement( BROWSER_CONNECTIONS_TAG ); if ( browserConnectionMap != null ) { for ( IBrowserConnection browserConnection : browserConnectionMap.values() ) { writeBrowserConnection( root, browserConnection ); } } // Writing the file to disk OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding( "UTF-8" ); //$NON-NLS-1$ XMLWriter writer = new XMLWriter( stream, outformat ); writer.write( document ); writer.flush(); } /** * Writes the given browser connection to the given parent Element. * * @param parent * the parent Element * @param browserConnection * the browser connection * @throws IOException */ private static void writeBrowserConnection( Element parent, IBrowserConnection browserConnection ) throws IOException { Element browserConnectionElement = parent.addElement( BROWSER_CONNECTION_TAG ); // ID browserConnectionElement.addAttribute( ID_TAG, browserConnection.getConnection().getId() ); // Searches Element searchesElement = browserConnectionElement.addElement( SEARCHES_TAG ); List<ISearch> searches = browserConnection.getSearchManager().getSearches(); for ( ISearch search : searches ) { Element searchParameterElement = searchesElement.addElement( SEARCH_PARAMETER_TAG ); writeSearch( searchParameterElement, search.getSearchParameter() ); } // Bookmarks Element bookmarksElement = browserConnectionElement.addElement( BOOKMARKS_TAG ); IBookmark[] bookmarks = browserConnection.getBookmarkManager().getBookmarks(); for ( IBookmark bookmark : bookmarks ) { Element bookmarkParameterElement = bookmarksElement.addElement( BOOKMARK_PARAMETER_TAG ); writeBookmark( bookmarkParameterElement, bookmark.getBookmarkParameter() ); } } private static void writeSearch( Element searchParameterElement, SearchParameter searchParameter ) throws IOException { // Name searchParameterElement.addAttribute( NAME_TAG, searchParameter.getName() ); // Search base String searchBase = searchParameter.getSearchBase() != null ? searchParameter.getSearchBase().getName() : ""; //$NON-NLS-1$ searchParameterElement.addAttribute( SEARCH_BASE_TAG, searchBase ); // Filter searchParameterElement.addAttribute( FILTER_TAG, searchParameter.getFilter() ); // Returning Attributes Element returningAttributesElement = searchParameterElement.addElement( RETURNING_ATTRIBUTES_TAG ); for ( String ra : searchParameter.getReturningAttributes() ) { Element raElement = returningAttributesElement.addElement( RETURNING_ATTRIBUTE_TAG ); raElement.addAttribute( VALUE_TAG, ra ); } // Scope searchParameterElement.addAttribute( SCOPE_TAG, convertSearchScope( searchParameter.getScope() ) ); // Time limit searchParameterElement.addAttribute( TIME_LIMIT_TAG, "" + searchParameter.getTimeLimit() ); //$NON-NLS-1$ // Count limit searchParameterElement.addAttribute( COUNT_LIMIT_TAG, "" + searchParameter.getCountLimit() ); //$NON-NLS-1$ // Alias dereferencing method searchParameterElement.addAttribute( ALIASES_DEREFERENCING_METHOD_TAG, searchParameter .getAliasesDereferencingMethod().toString() ); // Referrals handling method searchParameterElement.addAttribute( REFERRALS_HANDLING_METHOD_TAG, searchParameter .getReferralsHandlingMethod().toString() ); // Paged search scroll mode searchParameterElement.addAttribute( PAGED_SEARCH_SCROLL_MODE, "" + searchParameter.isPagedSearchScrollMode() ); // Controls Element controlsElement = searchParameterElement.addElement( CONTROLS_TAG ); for ( Control control : searchParameter.getControls() ) { byte[] bytes = Controls.getEncodedValue( control ); String controlsValue = new String( Base64.getEncoder().encode( bytes ), StandardCharsets.UTF_8 ); Element controlElement = controlsElement.addElement( CONTROL_TAG ); controlElement.addAttribute( OID_TAG, control.getOid() ); controlElement.addAttribute( IS_CRITICAL_TAG, "" + control.isCritical() ); controlElement.addAttribute( VALUE_TAG, controlsValue ); } } private static void writeBookmark( Element bookmarkParameterElement, BookmarkParameter bookmarkParameter ) { // Name bookmarkParameterElement.addAttribute( NAME_TAG, bookmarkParameter.getName() ); // Dn String dn = bookmarkParameter.getDn() != null ? bookmarkParameter.getDn().getName() : ""; //$NON-NLS-1$ bookmarkParameterElement.addAttribute( DN_TAG, dn ); } /** * Converts the given search scope to a string. * * @param scope the search scope * @return the converted string for the search scope * @see https://issues.apache.org/jira/browse/DIRSTUDIO-771 */ private static String convertSearchScope( SearchScope scope ) { if ( scope != null ) { switch ( scope ) { case OBJECT: return SCOPE_OBJECT; case ONELEVEL: return SCOPE_ONELEVEL; case SUBTREE: return SCOPE_SUBTREE; } } return SCOPE_SUBTREE; } /** * Converts the given string to a search scope. * * @param scope the scope string * @return the corresponding search scope * @throws IllegalArgumentException if the string could not be converted * @see https://issues.apache.org/jira/browse/DIRSTUDIO-771 */ private static SearchScope convertSearchScope( String scope ) throws IllegalArgumentException { if ( ( SCOPE_OBJECT.equalsIgnoreCase( scope ) || SCOPE_OBJECT_2.equalsIgnoreCase( scope ) ) ) { return SearchScope.OBJECT; } else if ( ( SCOPE_ONELEVEL.equalsIgnoreCase( scope ) || SCOPE_ONELEVEL_2.equalsIgnoreCase( scope ) ) ) { return SearchScope.ONELEVEL; } else if ( ( SCOPE_SUBTREE.equalsIgnoreCase( scope ) || SCOPE_SUBTREE_2.equalsIgnoreCase( scope ) ) ) { return SearchScope.SUBTREE; } else { throw new IllegalArgumentException(); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePlugin.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePlugin.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.ldapbrowser.core; import java.io.IOException; import java.util.PropertyResourceBundle; import org.apache.directory.studio.connection.core.event.CoreEventRunner; 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.Plugin; import org.eclipse.core.runtime.Status; import org.osgi.framework.BundleContext; /** * The main plugin class to be used in the desktop. */ public class BrowserCorePlugin extends Plugin { /** The shared instance. */ private static BrowserCorePlugin plugin; /** The connection manager */ private BrowserConnectionManager connectionManager; /** The preferences */ private BrowserCorePreferences preferences; /** The event runner. */ private EventRunner eventRunner; /** The plugin properties */ private PropertyResourceBundle properties; /** * Creates a new instance of BrowserCorePlugin. */ public BrowserCorePlugin() { super(); plugin = this; this.preferences = new BrowserCorePreferences(); } /** * {@inheritDoc} */ public void start( BundleContext context ) throws Exception { super.start( context ); if ( eventRunner == null ) { eventRunner = new CoreEventRunner(); } if ( connectionManager == null ) { connectionManager = new BrowserConnectionManager(); } } /** * {@inheritDoc} */ public void stop( BundleContext context ) throws Exception { super.stop( context ); if ( eventRunner != null ) { eventRunner = null; } if ( connectionManager != null ) { // IConnection[] connections = connectionManager.getConnections(); // for ( int i = 0; i < connections.length; i++ ) // { // connections[i].close(); // } connectionManager = null; } } /** * Returns the BrowserPlugin instance. * * @return The BrowserPlugin instance */ public static BrowserCorePlugin getDefault() { return plugin; } /** * Gets the Connection Manager * * @return * the connection manager */ public BrowserConnectionManager getConnectionManager() { return connectionManager; } /** * * @return The preferences */ public BrowserCorePreferences getCorePreferences() { return preferences; } /** * 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.ldapbrowser.core", Status.OK, //$NON-NLS-1$ BrowserCoreMessages.activator_unable_get_plugin_properties, e ) ); } } 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionManager.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionManager.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.ldapbrowser.core; import java.beans.Encoder; import java.beans.Expression; import java.beans.PersistenceDelegate; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.apache.directory.api.util.FileUtils; 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.Utils; import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry; import org.apache.directory.studio.connection.core.event.ConnectionUpdateListener; import org.apache.directory.studio.connection.core.io.ConnectionIOException; import org.apache.directory.studio.ldapbrowser.core.events.BookmarkUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.BookmarkUpdateListener; import org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateListener; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateListener; import org.apache.directory.studio.ldapbrowser.core.model.BookmarkParameter; import org.apache.directory.studio.ldapbrowser.core.model.IBookmark; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.impl.Bookmark; import org.apache.directory.studio.ldapbrowser.core.model.impl.BrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; /** * This class is used to manage {@link IBrowserConnection}s. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserConnectionManager implements ConnectionUpdateListener, BrowserConnectionUpdateListener, SearchUpdateListener, BookmarkUpdateListener { /** The list of connections. */ private Map<String, IBrowserConnection> connectionMap; /** * Creates a new instance of ConnectionManager. */ public BrowserConnectionManager() { this.connectionMap = new HashMap<String, IBrowserConnection>(); // no need to fire events while loading connections EventRegistry.suspendEventFiringInCurrentThread(); loadBrowserConnections(); EventRegistry.resumeEventFiringInCurrentThread(); ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionCorePlugin.getDefault().getEventRunner() ); EventRegistry.addSearchUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() ); EventRegistry.addBookmarkUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() ); EventRegistry.addBrowserConnectionUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() ); } /** * Gets the Schema Cache filename for the corresponding browser connection. * * @param browserConnection * the browser connection * @return * the Schema Cache filename for the corresponding browser connection */ public static final String getSchemaCacheFileName( String id ) { return BrowserCorePlugin.getDefault().getStateLocation().append( "schema-" + Utils.getFilenameString( id ) + ".ldif" ).toOSString(); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Gets the filename of the Connection Store. * * @return * the filename of the Connection Store */ public static final String getBrowserConnectionStoreFileName() { String filename = BrowserCorePlugin.getDefault().getStateLocation() .append( "browserconnections.xml" ).toOSString(); //$NON-NLS-1$ File file = new File( filename ); if ( !file.exists() ) { // try to convert old connections.xml: // 1st search it in current workspace with the old ldapstudio plugin ID // 2nd search it in old .ldapstudio workspace with the old ldapstudio plugin ID String[] oldFilenames = new String[2]; oldFilenames[0] = filename.replace( "org.apache.directory.studio.ldapbrowser.core", //$NON-NLS-1$ "org.apache.directory.ldapstudio.browser.core" ); //$NON-NLS-1$ oldFilenames[1] = oldFilenames[0].replace( ".ApacheDirectoryStudio", ".ldapstudio" ); //$NON-NLS-1$ //$NON-NLS-2$ for ( int i = 0; i < oldFilenames.length; i++ ) { File oldFile = new File( oldFilenames[i] ); if ( oldFile.exists() ) { try { String oldContent = FileUtils.readFileToString( oldFile, "UTF-8" ); //$NON-NLS-1$ String newContent = oldContent.replace( "org.apache.directory.ldapstudio.browser.core", //$NON-NLS-1$ "org.apache.directory.studio.ldapbrowser.core" ); //$NON-NLS-1$ FileUtils.writeStringToFile( file, newContent, "UTF-8" ); //$NON-NLS-1$ break; } catch ( IOException e ) { e.printStackTrace(); } } } } return filename; } /** * Gets a browser connection from its id. * * @param id * the id of the Connection * @return * the corresponding IBrowserConnection */ public IBrowserConnection getBrowserConnectionById( String id ) { return connectionMap.get( id ); } /** * Gets a browser connection from its name. * * @param name * the name of the Connection * @return * the corresponding IBrowserConnection */ public IBrowserConnection getBrowserConnectionByName( String name ) { Connection connection = ConnectionCorePlugin.getDefault().getConnectionManager().getConnectionByName( name ); return getBrowserConnection( connection ); } /** * Gets a browser connection from its underlying connection. * * @param connection * the underlying connection * @return * the corresponding IBrowserConnection */ public IBrowserConnection getBrowserConnection( Connection connection ) { return connection != null ? getBrowserConnectionById( connection.getId() ) : null; } /** * Gets an array containing all the Connections. * * @return * an array containing all the Connections */ public IBrowserConnection[] getBrowserConnections() { return ( IBrowserConnection[] ) connectionMap.values().toArray( new IBrowserConnection[0] ); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionRemoved(org.apache.directory.studio.connection.core.Connection) */ public void connectionRemoved( Connection connection ) { // update connection list connectionMap.remove( connection.getId() ); // remove schema file File schemaFile = new File( getSchemaCacheFileName( connection.getId() ) ); if ( schemaFile.exists() ) { schemaFile.delete(); } // make persistent saveBrowserConnections(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionAdded(org.apache.directory.studio.connection.core.Connection) */ public void connectionAdded( Connection connection ) { // update connection list BrowserConnection browserConnection = new BrowserConnection( connection ); connectionMap.put( connection.getId(), browserConnection ); // make persistent saveBrowserConnections(); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionUpdated(org.apache.directory.studio.connection.core.Connection) */ public void connectionUpdated( Connection connection ) { saveBrowserConnections(); saveSchema( getBrowserConnection( connection ) ); } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionOpened(org.apache.directory.studio.connection.core.Connection) */ public void connectionOpened( Connection connection ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionClosed(org.apache.directory.studio.connection.core.Connection) */ public void connectionClosed( Connection connection ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderModified(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderModified( ConnectionFolder connectionFolder ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderAdded(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderAdded( ConnectionFolder connectionFolder ) { } /** * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderRemoved(org.apache.directory.studio.connection.core.ConnectionFolder) */ public void connectionFolderRemoved( ConnectionFolder connectionFolder ) { } /** * @see org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateListener#browserConnectionUpdated(org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateEvent) */ public void browserConnectionUpdated( BrowserConnectionUpdateEvent browserConnectionUpdateEvent ) { if ( browserConnectionUpdateEvent.getDetail() == BrowserConnectionUpdateEvent.Detail.SCHEMA_UPDATED ) { saveSchema( browserConnectionUpdateEvent.getBrowserConnection() ); } } /** * {@inheritDoc} */ public void searchUpdated( SearchUpdateEvent searchUpdateEvent ) { if ( searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_ADDED || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_REMOVED || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_RENAMED || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_PARAMETER_UPDATED ) { saveBrowserConnections(); } } /** * {@inheritDoc} */ public void bookmarkUpdated( BookmarkUpdateEvent bookmarkUpdateEvent ) { if ( bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_ADDED || bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_REMOVED || bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_UPDATED ) { saveBrowserConnections(); } } /** * Saves the browser Connections */ private void saveBrowserConnections() { // To avoid a corrupt file, save object to a temp file first try { BrowserConnectionIO.save( new FileOutputStream( getBrowserConnectionStoreFileName() + "-temp" ), //$NON-NLS-1$ connectionMap ); } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } // move temp file to good file File file = new File( getBrowserConnectionStoreFileName() ); File tempFile = new File( getBrowserConnectionStoreFileName() + "-temp" ); //$NON-NLS-1$ if ( file.exists() ) { file.delete(); } try { String content = FileUtils.readFileToString( tempFile, "UTF-8" ); //$NON-NLS-1$ FileUtils.writeStringToFile( file, content, "UTF-8" ); //$NON-NLS-1$ } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } // Object[][] object = new Object[connectionMap.size()][3]; // // Iterator<IBrowserConnection> connectionIterator = connectionMap.values().iterator(); // for ( int i = 0; connectionIterator.hasNext(); i++ ) // { // IBrowserConnection browserConnection = connectionIterator.next(); // // ISearch[] searches = browserConnection.getSearchManager().getSearches(); // SearchParameter[] searchParameters = new SearchParameter[searches.length]; // for ( int k = 0; k < searches.length; k++ ) // { // searchParameters[k] = searches[k].getSearchParameter(); // } // // IBookmark[] bookmarks = browserConnection.getBookmarkManager().getBookmarks(); // BookmarkParameter[] bookmarkParameters = new BookmarkParameter[bookmarks.length]; // for ( int k = 0; k < bookmarks.length; k++ ) // { // bookmarkParameters[k] = bookmarks[k].getBookmarkParameter(); // } // // object[i][0] = browserConnection.getConnection().getId(); // object[i][1] = searchParameters; // object[i][2] = bookmarkParameters; // } // // save( object, getBrowserConnectionStoreFileName() ); } /** * Saves the Schema of the Connection * * @param browserConnection * the Connection */ private void saveSchema( IBrowserConnection browserConnection ) { if ( browserConnection == null ) { return; } try { String filename = getSchemaCacheFileName( browserConnection.getConnection().getId() ); FileWriter writer = new FileWriter( filename ); browserConnection.getSchema().saveToLdif( writer ); writer.close(); } catch ( Exception e ) { e.printStackTrace(); } } /** * Loads the Connections */ private void loadBrowserConnections() { Connection[] connections = ConnectionCorePlugin.getDefault().getConnectionManager().getConnections(); for ( int i = 0; i < connections.length; i++ ) { Connection connection = connections[i]; BrowserConnection browserConnection = new BrowserConnection( connection ); connectionMap.put( connection.getId(), browserConnection ); try { String schemaFilename = getSchemaCacheFileName( connection.getId() ); FileReader reader = new FileReader( schemaFilename ); Schema schema = new Schema(); schema.loadFromLdif( reader ); browserConnection.setSchema( schema ); } catch ( Exception e ) { } } // java.beans.XMLDecoder try { String fileName = getBrowserConnectionStoreFileName(); File file = new File( fileName ); if ( file.exists() ) { String oldContent = FileUtils.readFileToString( file, "UTF-8" ); //$NON-NLS-1$ if ( !oldContent.contains( "java.beans.XMLDecoder" ) ) //$NON-NLS-1$ { // new file format try { BrowserConnectionIO.load( new FileInputStream( getBrowserConnectionStoreFileName() ), connectionMap ); } catch ( Exception e ) { // If loading failed, try with temp file try { BrowserConnectionIO.load( new FileInputStream( getBrowserConnectionStoreFileName() + "-temp" ), connectionMap ); //$NON-NLS-1$ } catch ( FileNotFoundException e1 ) { // TODO Auto-generated catch block return; } catch ( ConnectionIOException e1 ) { // TODO Auto-generated catch block return; } } } else { // old file format Object[][] object = ( Object[][] ) this.load( getBrowserConnectionStoreFileName() ); if ( object != null ) { try { for ( int i = 0; i < object.length; i++ ) { String connectionId = ( String ) object[i][0]; IBrowserConnection browserConnection = getBrowserConnectionById( connectionId ); if ( browserConnection != null ) { if ( object[i].length > 0 ) { SearchParameter[] searchParameters = ( SearchParameter[] ) object[i][1]; for ( int k = 0; k < searchParameters.length; k++ ) { ISearch search = new Search( browserConnection, searchParameters[k] ); browserConnection.getSearchManager().addSearch( search ); } } if ( object[i].length > 1 ) { BookmarkParameter[] bookmarkParameters = ( BookmarkParameter[] ) object[i][2]; for ( int k = 0; k < bookmarkParameters.length; k++ ) { IBookmark bookmark = new Bookmark( browserConnection, bookmarkParameters[k] ); browserConnection.getBookmarkManager().addBookmark( bookmark ); } } } } } catch ( ArrayIndexOutOfBoundsException e ) { // Thrown by decoder.readObject(), signals EOF } catch ( Exception e ) { e.printStackTrace(); } } } } } catch ( Exception e ) { } } /** * Loads an Object from an XML file * * @param filename * the filename of the XML file * @return * the deserialized Object */ private synchronized Object load( String filename ) { try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); XMLDecoder decoder = new XMLDecoder( new BufferedInputStream( ( new FileInputStream( filename ) ) ) ); Object object = decoder.readObject(); decoder.close(); return object; } catch ( IOException ioe ) { return null; } catch ( Exception e ) { // if loading failed, try with temp file String tempFilename = filename + "-temp"; //$NON-NLS-1$ try { XMLDecoder decoder = new XMLDecoder( new BufferedInputStream( ( new FileInputStream( tempFilename ) ) ) ); Object object = decoder.readObject(); decoder.close(); return object; } catch ( IOException ioe2 ) { return null; } catch ( Exception e2 ) { return null; } } } class TypeSafeEnumPersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo( Object oldInstance, Object newInstance ) { return oldInstance == newInstance; } protected Expression instantiate( Object oldInstance, Encoder out ) { Class<?> type = oldInstance.getClass(); if ( !Modifier.isPublic( type.getModifiers() ) ) { throw new IllegalArgumentException( "Could not instantiate instance of non-public class: " //$NON-NLS-1$ + oldInstance ); } for ( Field field : type.getFields() ) { int mod = field.getModifiers(); if ( Modifier.isPublic( mod ) && Modifier.isStatic( mod ) && Modifier.isFinal( mod ) && ( type == field.getDeclaringClass() ) ) { try { if ( oldInstance == field.get( null ) ) { return new Expression( oldInstance, field, "get", new Object[] //$NON-NLS-1$ { null } ); } } catch ( IllegalAccessException exception ) { throw new IllegalArgumentException( "Could not get value of the field: " + field, exception ); //$NON-NLS-1$ } } } throw new IllegalArgumentException( "Could not instantiate value: " + oldInstance ); //$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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePreferencesInitializer.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCorePreferencesInitializer.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.ldapbrowser.core; import org.apache.directory.studio.ldapbrowser.core.model.schema.BinaryAttribute; import org.apache.directory.studio.ldapbrowser.core.model.schema.BinarySyntax; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; /** * This class is used to set default preference values. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserCorePreferencesInitializer extends AbstractPreferenceInitializer { /** * {@inheritDoc} */ public void initializeDefaultPreferences() { Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); store.setDefault( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN, true ); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER, "," ); //$NON-NLS-1$ store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_VALUEDELIMITER, "|" ); //$NON-NLS-1$ store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_QUOTECHARACTER, "\"" ); //$NON-NLS-1$ store .setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_LINESEPARATOR, BrowserCoreConstants.LINE_SEPARATOR ); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_BINARYENCODING, BrowserCoreConstants.BINARYENCODING_IGNORE ); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING, BrowserCoreConstants.DEFAULT_ENCODING ); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER, "|" ); //$NON-NLS-1$ store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING, BrowserCoreConstants.BINARYENCODING_IGNORE ); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_VALUEDELIMITER, "|" ); //$NON-NLS-1$ store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_BINARYENCODING, BrowserCoreConstants.BINARYENCODING_IGNORE ); store.setDefault( BrowserCoreConstants.PREFERENCE_LDIF_LINE_WIDTH, 76 ); store.setDefault( BrowserCoreConstants.PREFERENCE_LDIF_LINE_SEPARATOR, BrowserCoreConstants.LINE_SEPARATOR ); store.setDefault( BrowserCoreConstants.PREFERENCE_LDIF_SPACE_AFTER_COLON, true ); store.setDefault( BrowserCoreConstants.PREFERENCE_LDIF_INCLUDE_VERSION_LINE, true ); // default binary attributes BinaryAttribute[] defaultBinaryAttributes = new BinaryAttribute[] { new BinaryAttribute( "0.9.2342.19200300.100.1.7" ), // photo //$NON-NLS-1$ new BinaryAttribute( "0.9.2342.19200300.100.1.53" ), // personalSignature //$NON-NLS-1$ new BinaryAttribute( "0.9.2342.19200300.100.1.55" ), // audio //$NON-NLS-1$ new BinaryAttribute( "0.9.2342.19200300.100.1.60" ), // jpegPhoto //$NON-NLS-1$ new BinaryAttribute( "1.3.6.1.4.1.42.2.27.4.1.8" ), // javaSerializedData //$NON-NLS-1$ new BinaryAttribute( "1.3.6.1.4.1.1466.101.120.35" ), // thumbnailPhoto //$NON-NLS-1$ new BinaryAttribute( "1.3.6.1.4.1.1466.101.120.36" ), // thumbnailLogo //$NON-NLS-1$ new BinaryAttribute( "2.5.4.35" ), // userPassword //$NON-NLS-1$ new BinaryAttribute( "2.5.4.36" ), // userCertificate //$NON-NLS-1$ new BinaryAttribute( "2.5.4.37" ), // cACertificate //$NON-NLS-1$ new BinaryAttribute( "2.5.4.38" ), // authorityRevocationList //$NON-NLS-1$ new BinaryAttribute( "2.5.4.39" ), // certificateRevocationList //$NON-NLS-1$ new BinaryAttribute( "2.5.4.40" ), // crossCertificatePair //$NON-NLS-1$ new BinaryAttribute( "2.5.4.45" ), // x500UniqueIdentifier //$NON-NLS-1$ new BinaryAttribute( "1.2.840.113556.1.4.2" ), // objectGUID //$NON-NLS-1$ new BinaryAttribute( "1.2.840.113556.1.4.146" ), // objectSid //$NON-NLS-1$ }; BrowserCorePlugin.getDefault().getCorePreferences().setDefaultBinaryAttributes( defaultBinaryAttributes ); // default binary syntaxes BinarySyntax[] defaultBinarySyntaxes = new BinarySyntax[] { new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.5" ), // Binary //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.8" ), // Certificate //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.9" ), // Certificate List //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.10" ), // Certificate Pair //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.23" ), // Fax //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.28" ), // JPEG //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.40" ), // Octet String //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.4.1.1466.115.121.1.49" ), // Supported Algorithm //$NON-NLS-1$ new BinarySyntax( "1.3.6.1.1.16.1" ), // UUID //$NON-NLS-1$ new BinarySyntax( "2.5.5.10" ), // MS-specific: Octet,Replica-Link //$NON-NLS-1$ }; BrowserCorePlugin.getDefault().getCorePreferences().setDefaultBinarySyntaxes( defaultBinarySyntaxes ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCoreMessages.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserCoreMessages.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.ldapbrowser.core; import org.eclipse.osgi.util.NLS; /** * This class contains most of the Strings used by the Plugin * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserCoreMessages extends NLS { private static final String BUNDLE_NAME = "org.apache.directory.studio.ldapbrowser.core.browsercoremessages"; //$NON-NLS-1$ /** * Creates a new instance of BrowserCoreMessages. */ private BrowserCoreMessages() { } static { // initialize resource bundle NLS.initializeMessages( BUNDLE_NAME, BrowserCoreMessages.class ); } public static String activator_unable_get_plugin_properties; public static String copy_n_of_s; public static String event__added_att_to_dn; public static String event__deleted_att_from_dn; public static String event__dn_attributes_initialized; public static String event__dn_children_initialized; public static String event__bulk_modification; public static String event__empty_value_added_to_att_at_dn; public static String event__empty_value_deleted_from_att_at_dn; public static String event__added_dn; public static String event__deleted_dn; public static String event__moved_oldrdn_from_oldparent_to_newparent; public static String event__renamed_olddn_to_newdn; public static String event__added_val_to_att_at_dn; public static String event__deleted_val_from_att_at_dn; public static String event__replaced_oldval_by_newval_at_att_at_dn; public static String event__renamed_oldval_by_newval_at_dn; public static String jobs__copy_entries_source_and_target_are_equal; public static String model__empty_connection; public static String model__empty_entry; public static String model__empty_attribute; public static String model__empty_value; public static String model__empty_url; public static String model__empty_dn; public static String model__empty_rdn; public static String model__empty_password; public static String model__invalid_url; public static String model__invalid_protocol; public static String model__attribute_does_not_exist; public static String model__attribute_already_exists; public static String model__attributes_entry_is_not_myself; public static String model__url_no_attributes; public static String model__url_no_dn; public static String model__url_no_extensions; public static String model__url_no_filter; public static String model__url_no_host; public static String model__url_no_port; public static String model__url_no_protocol; public static String model__url_no_scope; public static String model__values_attribute_is_not_myself; public static String model__move_between_different_connections_not_supported; public static String model__copied_n_entries; public static String model__deleted_n_entries; public static String model__retrieved_n_entries; public static String model__retrieved_1_entry; public static String model__no_connection_provider; public static String model__connecting; public static String model__binding; public static String model__loading_rootdse; public static String model__error_loading_rootdse; public static String model__setting_base_dn; public static String model__error_setting_base_dn; public static String model__error_setting_metadata; public static String model__loading_schema; public static String model__no_schema_information; public static String model__missing_schema_location; public static String model__error_loading_schema; public static String model__no_such_entry; public static String model__error_logging_modification; public static String model__no_hash; public static String model__unsupported_hash; public static String model__invalid_hash; public static String ldif__imported_n_entries_m_errors; public static String ldif__n_errors_see_logfile; public static String ldif__imported_into_host_port_on_date; public static String ldif__import_into_host_port_failed_on_date; public static String ldif__error_msg; public static String dsml__n_errors_see_responsefile; public static String dsml__kind_request_not_supported; public static String dsml__should_not_be_encountering_request; public static String model__no_connection; public static String model__no_auth_handler; public static String model__no_credentials; public static String model__no_referral_handler; public static String model__no_referral_connection; public static String model__invalid_record; public static String model__unknown_host; public static String jobs__check_bind_name; public static String jobs__check_bind_task; public static String jobs__check_bind_error; public static String jobs__check_network_name; public static String jobs__check_network_task; public static String jobs__check_network_error; public static String jobs__fetch_basedns_name; public static String jobs__fetch_basedns_task; public static String jobs__fetch_basedns_error; public static String jobs__copy_entries_name_1; public static String jobs__copy_entries_name_n; public static String jobs__copy_entries_task_1; public static String jobs__copy_entries_task_n; public static String jobs__copy_entries_error_1; public static String jobs__copy_entries_error_n; public static String jobs__create_entry_name_1; public static String jobs__create_entry_name_n; public static String jobs__create_entry_task_1; public static String jobs__create_entry_task_n; public static String jobs__create_entry_error_1; public static String jobs__create_entry_error_n; public static String jobs__create_values_name_1; public static String jobs__create_values_name_n; public static String jobs__create_values_task_1; public static String jobs__create_values_task_n; public static String jobs__create_values_error_1; public static String jobs__create_values_error_n; public static String jobs__delete_attributes_name_1; public static String jobs__delete_attributes_name_n; public static String jobs__delete_attributes_task_1; public static String jobs__delete_attributes_task_n; public static String jobs__delete_attributes_error_1; public static String jobs__delete_attributes_error_n; public static String jobs__delete_entries_name_1; public static String jobs__delete_entries_name_n; public static String jobs__delete_entries_task_1; public static String jobs__delete_entries_task_n; public static String jobs__delete_entries_error_1; public static String jobs__delete_entries_error_n; public static String jobs__execute_ldif_name; public static String jobs__execute_ldif_task; public static String jobs__execute_ldif_error; public static String jobs__export_cvs_error; public static String jobs__export_csv_name; public static String jobs__export_csv_task; public static String jobs__export_ldif_name; public static String jobs__export_ldif_task; public static String jobs__export_ldif_error; public static String jobs__export_dsml_name; public static String jobs__export_dsml_task; public static String jobs__export_dsml_error; public static String jobs__export_progress; public static String jobs__export_xls_name; public static String jobs__export_xls_task; public static String jobs__export_xls_error; public static String jobs__export_odf_name; public static String jobs__export_odf_task; public static String jobs__export_odf_error; public static String jobs__import_ldif_name; public static String jobs__import_ldif_task; public static String jobs__import_ldif_error; public static String jobs__import_dsml_name; public static String jobs__import_dsml_task; public static String jobs__import_dsml_error; public static String jobs__init_entries_title_attandsub; public static String jobs__init_entries_title_subonly; public static String jobs__init_entries_title_attonly; public static String jobs__init_entries_title; public static String jobs__init_entries_task; public static String jobs__init_entries_progress_att; public static String jobs__init_entries_progress_sub; public static String jobs__init_entries_progress_subcount; public static String jobs__init_entries_error_1; public static String jobs__init_entries_error_n; public static String jobs__modify_value_name; public static String jobs__modify_value_task; public static String jobs__modify_value_error; public static String jobs__open_connections_name_1; public static String jobs__open_connections_name_n; public static String jobs__open_connections_task; public static String jobs__open_connections_error_1; public static String jobs__open_connections_error_n; public static String jobs__read_entry_name; public static String jobs__read_entry_task; public static String jobs__read_entry_error; public static String jobs__reload_schemas_name_1; public static String jobs__reload_schemas_name_n; public static String jobs__reload_schemas_task; public static String jobs__reload_schemas_error_1; public static String jobs__reload_schemas_error_n; public static String jobs__move_entry_name_1; public static String jobs__move_entry_name_n; public static String jobs__move_entry_task_1; public static String jobs__move_entry_task_n; public static String jobs__move_entry_error_1; public static String jobs__move_entry_error_n; public static String jobs__rename_entry_name; public static String jobs__rename_entry_task; public static String jobs__rename_entry_error; public static String jobs__rename_value_name_1; public static String jobs__rename_value_name_n; public static String jobs__rename_value_task_1; public static String jobs__rename_value_task_n; public static String jobs__rename_value_error_1; public static String jobs__rename_value_error_n; public static String jobs__search_name; public static String jobs__search_task; public static String jobs__search_error_1; public static String jobs__search_error_n; public static String jobs__extended_operation_name; public static String jobs__extended_operation_error; public static String jobs__extended_operation_task; public static String model__empty_string_value; public static String model__empty_binary_value; public static String model__invalid_rdn; public static String model_filter_missing_closing_parenthesis; public static String model_filter_missing_filter_expression; public static String model__quick_search_name; public static String BrowserConnectionIO_TheFileDoesNotSeemToBeValid; public static String BrowserConnectionIO_UnableToParseAliasesDereferencingMethod; public static String BrowserConnectionIO_UnableToParseControl; public static String BrowserConnectionIO_UnableToParseCountLimit; public static String BrowserConnectionIO_UnableToParseDn; public static String BrowserConnectionIO_UnableToParseReferralsHandlingMethod; public static String BrowserConnectionIO_UnableToParseScope; public static String BrowserConnectionIO_UnableToParseSearchBase; public static String BrowserConnectionIO_UnableToParseTimeLimit; }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionListener.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/BrowserConnectionListener.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.ldapbrowser.core; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.IConnectionListener; import org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeAttributesRunnable; import org.apache.directory.studio.ldapbrowser.core.jobs.ReloadSchemaRunnable; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils; /** * The {@link BrowserConnectionListener} opens and closes the * {@link IBrowserConnection} if the underlying {@link Connection} * is opened and closed. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BrowserConnectionListener implements IConnectionListener { /** * This implementation opens the browser connection when the connection was opened. */ public void connectionOpened( Connection connection, StudioProgressMonitor monitor ) { IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); if ( browserConnection != null ) { try { EventRegistry.suspendEventFiringInCurrentThread(); openBrowserConnection( browserConnection, monitor ); setBinaryAttributes( browserConnection, monitor ); } finally { EventRegistry.resumeEventFiringInCurrentThread(); BrowserConnectionUpdateEvent browserConnectionUpdateEvent = new BrowserConnectionUpdateEvent( browserConnection, BrowserConnectionUpdateEvent.Detail.BROWSER_CONNECTION_OPENED ); EventRegistry.fireBrowserConnectionUpdated( browserConnectionUpdateEvent, this ); BrowserConnectionUpdateEvent schemaUpdateEvent = new BrowserConnectionUpdateEvent( browserConnection, BrowserConnectionUpdateEvent.Detail.SCHEMA_UPDATED ); EventRegistry.fireBrowserConnectionUpdated( schemaUpdateEvent, this ); } } } /** * This implementation closes the browser connection when the connection was closed. */ public void connectionClosed( Connection connection, StudioProgressMonitor monitor ) { IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); if ( browserConnection != null ) { try { EventRegistry.suspendEventFiringInCurrentThread(); browserConnection.clearCaches(); } finally { EventRegistry.resumeEventFiringInCurrentThread(); BrowserConnectionUpdateEvent browserConnectionUpdateEvent = new BrowserConnectionUpdateEvent( browserConnection, BrowserConnectionUpdateEvent.Detail.BROWSER_CONNECTION_CLOSED ); EventRegistry.fireBrowserConnectionUpdated( browserConnectionUpdateEvent, this ); } } } /** * Opens the browser connection. * * @param browserConnection the browser connection * @param monitor the progress monitor */ private static void openBrowserConnection( IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { ReloadSchemaRunnable.reloadSchema( false, browserConnection, monitor ); IRootDSE rootDSE = browserConnection.getRootDSE(); InitializeAttributesRunnable.initializeAttributes( rootDSE, monitor ); } /** * Extracts the binary attributes from the schema and * sets the binary attributes to the underlying connection. * * @param browserConnection the browser connection * @param monitor the progress monitor */ private static void setBinaryAttributes( IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { List<String> binaryAttributeNames = new ArrayList<String>(); Schema schema = browserConnection.getSchema(); Collection<AttributeType> attributeTypeDescriptions = schema.getAttributeTypeDescriptions(); for ( AttributeType atd : attributeTypeDescriptions ) { if ( SchemaUtils.isBinary( atd, schema ) ) { String name = atd.getNames().isEmpty() ? atd.getOid() : atd.getNames().get( 0 ); binaryAttributeNames.add( name ); } } if ( browserConnection.getConnection() != null ) { browserConnection.getConnection().getConnectionWrapper().setBinaryAttributes( binaryAttributeNames ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/FetchBaseDNsRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/FetchBaseDNsRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.List; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.DirectoryMetadataEntry; /** * Runnable to fetch the base DNs from a directory server. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class FetchBaseDNsRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection */ private IBrowserConnection connection; /** The base DNs*/ private List<String> baseDNs; /** * Creates a new instance of FetchBaseDNsRunnable. * * @param connection the connection */ public FetchBaseDNsRunnable( IBrowserConnection connection ) { this.connection = connection; this.baseDNs = new ArrayList<String>(); } /** * {@inheritDoc} */ public Connection[] getConnections() { return null; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__fetch_basedns_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Connection[] { connection.getConnection() }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__fetch_basedns_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__fetch_basedns_task, 5 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); InitializeRootDSERunnable.loadRootDSE( connection, monitor ); IEntry[] baseDNEntries = connection.getRootDSE().getChildren(); if ( baseDNEntries != null ) { for ( IEntry baseDNEntry : baseDNEntries ) { if ( !( baseDNEntry instanceof DirectoryMetadataEntry ) ) { baseDNs.add( baseDNEntry.getDn().getName() ); } } } monitor.worked( 1 ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { } /** * Gets the base DNs. * * @return the base DNs */ public List<String> getBaseDNs() { return baseDNs; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExecuteLdifRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExecuteLdifRunnable.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.ldapbrowser.core.jobs; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.parser.LdifParser; /** * Runnable to execute an LDIF. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExecuteLdifRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** The LDIF to execute. */ private String ldif; /** The update if entry exists flag. */ private boolean updateIfEntryExists; /** The continue on error flag. */ private boolean continueOnError; /** * Creates a new instance of ExecuteLdifJob. * * @param browserConnection the browser connection * @param ldif the LDIF to execute * @param continueOnError the continue on error flag */ public ExecuteLdifRunnable( IBrowserConnection browserConnection, String ldif, boolean updateIfEntryExists, boolean continueOnError ) { this.browserConnection = browserConnection; this.ldif = ldif; this.continueOnError = continueOnError; this.updateIfEntryExists = updateIfEntryExists; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__execute_ldif_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( ldif ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__execute_ldif_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { executeLdif( browserConnection, ldif, updateIfEntryExists, continueOnError, monitor ); } public static void executeLdif( IBrowserConnection browserConnection, String ldif, boolean updateIfEntryExists, boolean continueOnError, StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__execute_ldif_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { Reader ldifReader = new StringReader( ldif ); LdifParser parser = new LdifParser(); LdifEnumeration enumeration = parser.parse( ldifReader ); Writer logWriter = new Writer() { public void close() { } public void flush() { } public void write( char[] cbuf, int off, int len ) { } }; ImportLdifRunnable.importLdif( browserConnection, enumeration, logWriter, updateIfEntryExists, continueOnError, monitor ); logWriter.close(); ldifReader.close(); } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ReadEntryRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ReadEntryRunnable.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.ldapbrowser.core.jobs; import java.util.List; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; /** * Runnable to read a single entry from directory. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ReadEntryRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** The Dn of the entry. */ private Dn dn; /** The entry read from directory. */ private IEntry readEntry; /** * Creates a new instance of ReadEntryRunnable. * * @param browserConnection the browser connection * @param dn the Dn of the entry */ public ReadEntryRunnable( IBrowserConnection browserConnection, Dn dn ) { this.browserConnection = browserConnection; this.dn = dn; this.readEntry = null; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__read_entry_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { browserConnection }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__read_entry_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor pm ) { readEntry = browserConnection.getEntryFromCache( dn ); if ( readEntry == null ) { pm.beginTask( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__read_entry_task, new String[] { dn.toString() } ), 2 ); pm.reportProgress( " " ); //$NON-NLS-1$ pm.worked( 1 ); readEntry = getEntry( browserConnection, dn, null, pm ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { } /** * Gets the entry, either from the BrowserConnection's cache or from the directory. * * @param browserConnection the browser connection * @param dn the Dn of the entry * @param controls the LDAP controls * @param monitor the progress monitor * * @return the read entry */ static IEntry getEntry( IBrowserConnection browserConnection, Dn dn, List<Control> controls, StudioProgressMonitor monitor ) { try { // first check cache IEntry entry = browserConnection.getEntryFromCache( dn ); if ( entry != null ) { return entry; } // search in directory ISearch search = new Search( null, browserConnection, dn, null, ISearch.NO_ATTRIBUTES, SearchScope.OBJECT, 1, 0, AliasDereferencingMethod.NEVER, ReferralHandlingMethod.IGNORE, true, controls, false ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); ISearchResult[] srs = search.getSearchResults(); if ( srs.length > 0 ) { return srs[0].getEntry(); } else { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.model__no_such_entry, dn ) ); return null; } } catch ( Exception e ) { monitor.reportError( e ); return null; } } /** * Gets the read entry. * * @return the read entry */ public IEntry getReadEntry() { return readEntry; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportCsvRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportCsvRunnable.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.ldapbrowser.core.jobs; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.text.translate.CharSequenceTranslator; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.AttributeDescription; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifparser.LdifUtils; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.eclipse.core.runtime.Preferences; /** * Runnable to export directory content to an CSV file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExportCsvRunnable implements StudioConnectionRunnableWithProgress { /** The filename of the CSV file. */ private String exportCsvFilename; /** The browser connection. */ private IBrowserConnection browserConnection; /** The search parameter. */ private SearchParameter searchParameter; /** The export dn flag. */ private boolean exportDn; /** * Creates a new instance of ExportCsvRunnable. * * @param exportCsvFilename the filename of the csv file * @param browserConnection the browser connection * @param searchParameter the search parameter * @param exportDn true to export the Dn */ public ExportCsvRunnable( String exportCsvFilename, IBrowserConnection browserConnection, SearchParameter searchParameter, boolean exportDn ) { this.exportCsvFilename = exportCsvFilename; this.browserConnection = browserConnection; this.searchParameter = searchParameter; this.exportDn = exportDn; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__export_csv_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { browserConnection.getUrl() + "_" + DigestUtils.shaHex( exportCsvFilename ) }; //$NON-NLS-1$ } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__export_cvs_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__export_csv_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences(); String attributeDelimiter = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER ); String valueDelimiter = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_VALUEDELIMITER ); String quoteCharacter = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_QUOTECHARACTER ); String lineSeparator = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_LINESEPARATOR ); String encoding = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING ); int binaryEncoding = coreStore.getInt( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_BINARYENCODING ); String[] exportAttributes = this.searchParameter.getReturningAttributes(); try { // open file FileOutputStream fos = new FileOutputStream( exportCsvFilename ); OutputStreamWriter osw = new OutputStreamWriter( fos, encoding ); BufferedWriter bufferedWriter = new BufferedWriter( osw ); // header if ( this.exportDn ) { bufferedWriter.write( "dn" ); //$NON-NLS-1$ if ( exportAttributes == null || exportAttributes.length > 0 ) bufferedWriter.write( attributeDelimiter ); } for ( int i = 0; i < exportAttributes.length; i++ ) { bufferedWriter.write( exportAttributes[i] ); if ( i + 1 < exportAttributes.length ) bufferedWriter.write( attributeDelimiter ); } bufferedWriter.write( BrowserCoreConstants.LINE_SEPARATOR ); // export int count = 0; exportToCsv( browserConnection, searchParameter, bufferedWriter, count, monitor, exportAttributes, attributeDelimiter, valueDelimiter, quoteCharacter, lineSeparator, encoding, binaryEncoding, exportDn ); // close file bufferedWriter.close(); osw.close(); fos.close(); } catch ( Exception e ) { monitor.reportError( e ); } } /** * Exports to CSV. * * @param browserConnection the browser connection * @param searchParameter the search parameter * @param bufferedWriter the buffered writer * @param count the count * @param monitor the monitor * @param attributes the attributes * @param attributeDelimiter the attribute delimiter * @param valueDelimiter the value delimiter * @param quoteCharacter the quote character * @param lineSeparator the line separator * @param encoding the encoding * @param binaryEncoding the binary encoding * @param exportDn the export dn * * @throws IOException Signals that an I/O exception has occurred. */ private static void exportToCsv( IBrowserConnection browserConnection, SearchParameter searchParameter, BufferedWriter bufferedWriter, int count, StudioProgressMonitor monitor, String[] attributes, String attributeDelimiter, String valueDelimiter, String quoteCharacter, String lineSeparator, String encoding, int binaryEncoding, boolean exportDn ) throws IOException { try { LdifEnumeration enumeration = ExportLdifRunnable.search( browserConnection, searchParameter, monitor ); while ( !monitor.isCanceled() && !monitor.errorsReported() && enumeration.hasNext() ) { LdifContainer container = enumeration.next(); if ( container instanceof LdifContentRecord ) { LdifContentRecord record = ( LdifContentRecord ) container; bufferedWriter.write( recordToCsv( browserConnection, record, attributes, attributeDelimiter, valueDelimiter, quoteCharacter, lineSeparator, encoding, binaryEncoding, exportDn ) ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException ce ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( ce ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // nothing } else { monitor.reportError( ce ); } } } /** * Transforms an LDIF rRecord to CSV. * * @param browserConnection the browser connection * @param record the record * @param attributes the attributes * @param attributeDelimiter the attribute delimiter * @param valueDelimiter the value delimiter * @param quoteCharacter the quote character * @param lineSeparator the line separator * @param encoding the encoding * @param binaryEncoding the binary encoding * @param exportDn the export dn * * @return the string */ private static String recordToCsv( IBrowserConnection browserConnection, LdifContentRecord record, String[] attributes, String attributeDelimiter, String valueDelimiter, String quoteCharacter, String lineSeparator, String encoding, int binaryEncoding, boolean exportDn ) { CharSequenceTranslator decoder = Utils.createPostalAddressDecoder( lineSeparator ); // group multi-valued attributes Map<String, String> attributeMap = getAttributeMap( browserConnection, record, valueDelimiter, encoding, binaryEncoding ); // print attributes StringBuffer sb = new StringBuffer(); if ( exportDn ) { String value = record.getDnLine().getValueAsString(); appendValue( quoteCharacter, sb, value ); if ( attributes == null || attributes.length > 0 ) sb.append( attributeDelimiter ); } for ( int i = 0; i < attributes.length; i++ ) { String attributeName = attributes[i]; AttributeDescription ad = new AttributeDescription( attributeName ); String oidString = ad.toOidString( browserConnection.getSchema() ); if ( attributeMap.containsKey( oidString ) ) { String value = attributeMap.get( oidString ); AttributeType type = browserConnection.getSchema().getAttributeTypeDescription( attributeName ); if ( SchemaConstants.POSTAL_ADDRESS_SYNTAX.equals( type.getSyntaxOid() ) ) { value = decoder.translate( value ); } appendValue( quoteCharacter, sb, value ); } // delimiter if ( i + 1 < attributes.length ) { sb.append( attributeDelimiter ); } } sb.append( lineSeparator ); return sb.toString(); } private static void appendValue( String quoteCharacter, StringBuffer sb, String value ) { // escape quote character value = value.replaceAll( quoteCharacter, quoteCharacter + quoteCharacter ); // prefix values starting with '=' with a single quote to avoid interpretation as formula if ( value.startsWith( "=" ) ) { value = "'" + value; } // always quote sb.append( quoteCharacter ); sb.append( value ); sb.append( quoteCharacter ); } /** * Gets the attribute map. * * @param browserConnection the browser connection * @param record the record * @param valueDelimiter the value delimiter * @param encoding the encoding * @param binaryEncoding the binary encoding * * @return the attribute map */ static Map<String, String> getAttributeMap( IBrowserConnection browserConnection, LdifContentRecord record, String valueDelimiter, String encoding, int binaryEncoding ) { Map<String, String> attributeMap = new HashMap<String, String>(); LdifAttrValLine[] lines = record.getAttrVals(); for ( int i = 0; i < lines.length; i++ ) { String attributeName = lines[i].getUnfoldedAttributeDescription(); if ( browserConnection != null ) { // convert attributeName to oid AttributeDescription ad = new AttributeDescription( attributeName ); attributeName = ad.toOidString( browserConnection.getSchema() ); } String value = lines[i].getValueAsString(); if ( !Charset.forName( encoding ).newEncoder().canEncode( value ) ) { if ( binaryEncoding == BrowserCoreConstants.BINARYENCODING_BASE64 ) { value = LdifUtils.base64encode( lines[i].getValueAsBinary() ); } else if ( binaryEncoding == BrowserCoreConstants.BINARYENCODING_HEX ) { value = LdifUtils.hexEncode( lines[i].getValueAsBinary() ); } else { value = BrowserCoreConstants.BINARY; } if ( attributeMap.containsKey( attributeName ) ) { String oldValue = ( String ) attributeMap.get( attributeName ); attributeMap.put( attributeName, oldValue + valueDelimiter + value ); } else { attributeMap.put( attributeName, value ); } } else { if ( attributeMap.containsKey( attributeName ) ) { String oldValue = ( String ) attributeMap.get( attributeName ); attributeMap.put( attributeName, oldValue + valueDelimiter + value ); } else { attributeMap.put( attributeName, value ); } } } return attributeMap; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/CreateEntryRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/CreateEntryRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.List; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.EntryAddedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter; /** * Runnable to create an entry. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CreateEntryRunnable implements StudioConnectionBulkRunnableWithProgress { /** The entry to create. */ private IEntry entryToCreate; /** The browser connection. */ private IBrowserConnection browserConnection; /** The created entry. */ private IEntry createdEntry; /** * Creates a new instance of CreateEntryRunnable. * * @param entryToCreate the entry to create * @param browserConnection the browser connection */ public CreateEntryRunnable( IEntry entryToCreate, IBrowserConnection browserConnection ) { this.entryToCreate = entryToCreate; this.browserConnection = browserConnection; this.createdEntry = null; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__create_entry_name_1; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { browserConnection }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__create_entry_error_1; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__create_entry_task_1, new String[] { entryToCreate.getDn().getName() } ), 2 + 1 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { createEntry( browserConnection, entryToCreate, monitor ); } catch ( LdapException e ) { monitor.reportError( e ); } if ( !monitor.errorsReported() && !monitor.isCanceled() ) { List<org.apache.directory.api.ldap.model.message.Control> controls = new ArrayList<>(); if ( entryToCreate.isReferral() ) { controls.add( Controls.MANAGEDSAIT_CONTROL ); } // Here we try to read the created entry to be able to send the right event notification. // In some cases that doesn't work: // - if there was a referral and the entry was created on another (master) server and not yet sync'ed to the current server // So we use a dummy monitor to no bother the user with an error message. StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); createdEntry = ReadEntryRunnable .getEntry( browserConnection, entryToCreate.getDn(), controls, dummyMonitor ); dummyMonitor.done(); if ( createdEntry != null ) { createdEntry.setHasChildrenHint( false ); // set some flags at the parent if ( createdEntry.hasParententry() ) { if ( createdEntry.isAlias() ) { createdEntry.getParententry().setFetchAliases( true ); } if ( createdEntry.isReferral() ) { createdEntry.getParententry().setFetchReferrals( true ); } if ( createdEntry.isSubentry() ) { createdEntry.getParententry().setFetchSubentries( true ); } } } } monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { if ( createdEntry != null ) { EventRegistry.fireEntryUpdated( new EntryAddedEvent( browserConnection, createdEntry ), this ); } } /** * Creates the entry using the underlying connection wrapper. * * @param browserConnection the browser connection * @param entryToCreate the entry to create * @param monitor the monitor */ static void createEntry( IBrowserConnection browserConnection, IEntry entryToCreate, StudioProgressMonitor monitor ) throws LdapException { Entry entry = ModelConverter.toLdapApiEntry( entryToCreate ); // ManageDsaIT control Control[] controls = null; if ( entryToCreate.isReferral() ) { controls = new Control[] { Controls.MANAGEDSAIT_CONTROL }; } browserConnection.getConnection().getConnectionWrapper() .createEntry( entry, controls, monitor, 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/EntryExistsCopyStrategyDialog.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/EntryExistsCopyStrategyDialog.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.ldapbrowser.core.jobs; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; /** * A dialog to select the copy strategy if an entry already exists. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface EntryExistsCopyStrategyDialog { /** * Sets the existing entry. * * @param browserConnection the browser connection * @param newLdapDn the new Dn */ void setExistingEntry( IBrowserConnection browserConnection, Dn newLdapDn ); /** * Gets the copy strategy. * * @return the copy strategy */ EntryExistsCopyStrategy getStrategy(); /** * Gets the Rdn if {@link EntryExistsCopyStrategy.RENAME_AND_CONTINUE} was selected. * Returns null if another strategy was selected. * * @return the Rdn */ Rdn getRdn(); /** * Returns true to remember the selected copy strategy. * * @return true, to remember the selected copy strategy */ boolean isRememberSelection(); /** * Opens the dialog. * * @return the status code */ int open(); /** * Enum for the copy strategy. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum EntryExistsCopyStrategy { /** Break strategy, don't continue copy process. */ BREAK, /** Ignore the entry to copy and continue the copy process. */ IGNORE_AND_CONTINUE, /** Overwrite the entry to copy and continue the copy process. */ OVERWRITE_AND_CONTINUE, /** Rename the entry to copy and continue the copy process. */ RENAME_AND_CONTINUE; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/StudioBrowserJob.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/StudioBrowserJob.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.ldapbrowser.core.jobs; import org.apache.directory.studio.connection.core.jobs.StudioConnectionJob; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; /** * Job to run {@link StudioConnectionRunnableWithProgress} runnables. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StudioBrowserJob extends StudioConnectionJob { /** * Creates a new instance of StudioBrowserJob. * * @param runnables the runnables to run */ public StudioBrowserJob( StudioConnectionRunnableWithProgress... runnables ) { super( runnables ); } /** * {@inheritDoc} */ protected void suspendEventFiringInCurrentThread() { EventRegistry.suspendEventFiringInCurrentThread(); super.suspendEventFiringInCurrentThread(); } /** * {@inheritDoc} */ protected void resumeEventFiringInCurrentThread() { EventRegistry.resumeEventFiringInCurrentThread(); super.resumeEventFiringInCurrentThread(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeChildrenRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeChildrenRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.message.controls.PagedResults; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.ChildrenInitializedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.impl.ContinuedSearchResultEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; import org.apache.directory.studio.ldapbrowser.core.model.impl.SearchContinuation; /** * Runnable to initialize the child entries of an entry * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class InitializeChildrenRunnable implements StudioConnectionBulkRunnableWithProgress { /** The entries. */ private IEntry[] entries; /** The purge all caches flag. */ private boolean purgeAllCaches; /** The paged search control, only used internally. */ private PagedResults pagedSearchControl; /** * Creates a new instance of InitializeChildrenRunnable. * * @param entries the entries * @param purgeAllCaches true to purge all caches */ public InitializeChildrenRunnable( boolean purgeAllCaches, IEntry... entries ) { this.entries = entries; this.purgeAllCaches = purgeAllCaches; } /** * Creates a new instance of InitializeChildrenRunnable. * * @param entry the entry * @param pagedSearchControl the paged search control */ private InitializeChildrenRunnable( IEntry entry, PagedResults pagedSearchControl ) { this.entries = new IEntry[] { entry }; this.pagedSearchControl = pagedSearchControl; } /** * {@inheritDoc} */ public Connection[] getConnections() { Connection[] connections = new Connection[entries.length]; for ( int i = 0; i < connections.length; i++ ) { connections[i] = entries[i].getBrowserConnection().getConnection(); } return connections; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__init_entries_title_subonly; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.addAll( Arrays.asList( entries ) ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return entries.length == 1 ? BrowserCoreMessages.jobs__init_entries_error_1 : BrowserCoreMessages.jobs__init_entries_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", entries.length + 2 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( IEntry entry : entries ) { monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_task, new String[] { entry.getDn().getName() } ) ); monitor.worked( 1 ); IBrowserConnection browserConnection = entry.getBrowserConnection(); if ( browserConnection != null ) { if ( entry instanceof IRootDSE ) { // special handling for Root DSE InitializeRootDSERunnable.loadRootDSE( browserConnection, monitor ); continue; } if ( pagedSearchControl == null && browserConnection.isPagedSearch() ) { pagedSearchControl = Controls.newPagedResultsControl( browserConnection.getPagedSearchSize() ); } initializeChildren( entry, monitor, pagedSearchControl ); } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( IEntry entry : entries ) { if ( entry.getBrowserConnection() != null && entry.isChildrenInitialized() ) { EventRegistry.fireEntryUpdated( new ChildrenInitializedEvent( entry ), this ); } } } /** * Initializes the child entries. * * @param parent the parent * @param monitor the progress monitor * @param pagedSearchControl the paged search control */ private void initializeChildren( IEntry parent, StudioProgressMonitor monitor, PagedResults pagedSearchControl ) { monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_progress_sub, new String[] { parent.getDn().getName() } ) ); // clear old children clearCaches( parent, purgeAllCaches ); // create search ISearch search = createSearch( parent, pagedSearchControl, false, false, false ); // search executeSearch( parent, search, monitor ); ISearchResult[] srs = search.getSearchResults(); SearchContinuation[] scs = search.getSearchContinuations(); // fill children in search result if ( ( srs != null && srs.length > 0 ) || ( scs != null && scs.length > 0 ) ) { // clearing old children before filling new children is // necessary to handle aliases and referrals. clearCaches( parent, false ); do { if ( srs != null ) { for ( ISearchResult searchResult : srs ) { parent.addChild( searchResult.getEntry() ); } srs = null; } if ( scs != null ) { for ( SearchContinuation searchContinuation : scs ) { ContinuedSearchResultEntry entry = new ContinuedSearchResultEntry( parent .getBrowserConnection(), searchContinuation.getUrl().getDn() ); entry.setUnresolved( searchContinuation.getUrl() ); parent.addChild( entry ); } scs = null; } PagedResults prRequestControl = null; PagedResults prResponseControl = null; for ( Control responseControl : search.getResponseControls() ) { if ( responseControl instanceof PagedResults ) { prResponseControl = ( PagedResults ) responseControl; } } for ( Control requestControl : search.getControls() ) { if ( requestControl instanceof PagedResults ) { prRequestControl = ( PagedResults ) requestControl; } } if ( prRequestControl != null && prResponseControl != null ) { if ( search.isPagedSearchScrollMode() ) { if ( ArrayUtils.isNotEmpty( prRequestControl.getCookie() ) ) { // create top page search runnable, same as original search InitializeChildrenRunnable topPageChildrenRunnable = new InitializeChildrenRunnable( parent, null ); parent.setTopPageChildrenRunnable( topPageChildrenRunnable ); } if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) ) { PagedResults newPrc = Controls.newPagedResultsControl( prRequestControl.getSize(), prResponseControl.getCookie() ); InitializeChildrenRunnable nextPageChildrenRunnable = new InitializeChildrenRunnable( parent, newPrc ); parent.setNextPageChildrenRunnable( nextPageChildrenRunnable ); } } else { // transparently continue search, till count limit is reached if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) && ( search.getCountLimit() == 0 || search.getSearchResults().length < search .getCountLimit() ) ) { search.setSearchResults( new ISearchResult[0] ); search.getResponseControls().clear(); prRequestControl.setCookie( prResponseControl.getCookie() ); executeSearch( parent, search, monitor ); srs = search.getSearchResults(); scs = search.getSearchContinuations(); } } } } while ( srs != null && srs.length > 0 ); } else { parent.setHasChildrenHint( false ); } // get sub-entries ISearch subSearch = createSearch( parent, null, true, false, false ); if ( parent.getBrowserConnection().isFetchSubentries() || parent.isFetchSubentries() ) { executeSubSearch( parent, subSearch, monitor ); } // get aliases and referrals ISearch aliasOrReferralSearch = createSearch( parent, null, false, parent.isFetchAliases(), parent .isFetchReferrals() ); if ( parent.isFetchAliases() || parent.isFetchReferrals() ) { executeSubSearch( parent, aliasOrReferralSearch, monitor ); } // check exceeded limits / canceled parent.setHasMoreChildren( search.isCountLimitExceeded() || subSearch.isCountLimitExceeded() || aliasOrReferralSearch.isCountLimitExceeded() || monitor.isCanceled() ); // set initialized state parent.setChildrenInitialized( true ); } private void executeSubSearch( IEntry parent, ISearch subSearch, StudioProgressMonitor monitor ) { executeSearch( parent, subSearch, monitor ); ISearchResult[] subSrs = subSearch.getSearchResults(); SearchContinuation[] subScs = subSearch.getSearchContinuations(); // fill children in search result if ( subSrs != null && subSrs.length > 0 ) { for ( ISearchResult searchResult : subSrs ) { parent.addChild( searchResult.getEntry() ); } for ( SearchContinuation searchContinuation : subScs ) { ContinuedSearchResultEntry entry = new ContinuedSearchResultEntry( parent.getBrowserConnection(), searchContinuation.getUrl().getDn() ); entry.setUnresolved( searchContinuation.getUrl() ); parent.addChild( entry ); } } } private static void executeSearch( IEntry parent, ISearch search, StudioProgressMonitor monitor ) { SearchRunnable.searchAndUpdateModel( parent.getBrowserConnection(), search, monitor ); ISearchResult[] srs = search.getSearchResults(); monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_progress_subcount, new String[] { srs == null ? Integer.toString( 0 ) : Integer.toString( srs.length ), parent.getDn().getName() } ) ); } private static ISearch createSearch( IEntry parent, PagedResults pagedSearchControl, boolean isSubentriesSearch, boolean isAliasSearch, boolean isReferralsSearch ) { // scope SearchScope scope = SearchScope.ONELEVEL; // filter String filter = parent.getChildrenFilter(); if ( isSubentriesSearch ) { filter = ISearch.FILTER_SUBENTRY; } else if ( isAliasSearch && isReferralsSearch ) { filter = ISearch.FILTER_ALIAS_OR_REFERRAL; } else if ( isAliasSearch ) { filter = ISearch.FILTER_ALIAS; } else if ( isReferralsSearch ) { filter = ISearch.FILTER_REFERRAL; } // alias handling AliasDereferencingMethod aliasesDereferencingMethod = parent.getBrowserConnection() .getAliasesDereferencingMethod(); if ( parent.isAlias() || isAliasSearch ) { aliasesDereferencingMethod = AliasDereferencingMethod.NEVER; } // referral handling ReferralHandlingMethod referralsHandlingMethod = parent.getBrowserConnection().getReferralsHandlingMethod(); // create search ISearch search = new Search( null, parent.getBrowserConnection(), parent.getDn(), filter, ISearch.NO_ATTRIBUTES, scope, parent.getBrowserConnection().getCountLimit(), parent.getBrowserConnection().getTimeLimit(), aliasesDereferencingMethod, referralsHandlingMethod, BrowserCorePlugin.getDefault() .getPluginPreferences().getBoolean( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN ), null, parent.getBrowserConnection().isPagedSearchScrollMode() ); // controls if ( parent.isReferral() || isReferralsSearch || parent.getBrowserConnection().isManageDsaIT() ) { search.getSearchParameter().getControls().add( Controls.MANAGEDSAIT_CONTROL ); } if ( isSubentriesSearch ) { search.getSearchParameter().getControls().add( Controls.SUBENTRIES_CONTROL ); } if ( pagedSearchControl != null ) { search.getSearchParameter().getControls().add( pagedSearchControl ); } return search; } static void clearCaches( IEntry entry, boolean purgeAllCaches ) { // clear the parent-child relationship, recursively IEntry[] children = entry.getChildren(); if ( children != null ) { for ( IEntry child : children ) { if ( child != null ) { entry.deleteChild( child ); clearCaches( child, purgeAllCaches ); } } } entry.setChildrenInitialized( false ); // reset paging runnables entry.setTopPageChildrenRunnable( null ); entry.setNextPageChildrenRunnable( null ); // reset attributes and additional flags if ( purgeAllCaches ) { entry.setAttributesInitialized( false ); entry.setHasChildrenHint( true ); entry.setHasMoreChildren( 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportLdifRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportLdifRunnable.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.ldapbrowser.core.jobs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.directory.api.ldap.model.entry.DefaultAttribute; import org.apache.directory.api.ldap.model.entry.DefaultModification; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Modification; import org.apache.directory.api.ldap.model.entry.ModificationOperation; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.exception.LdapSchemaException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCoreConstants; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifparser.LdifFormatParameters; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifChangeAddRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeDeleteRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeModDnRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeModifyRecord; import org.apache.directory.studio.ldifparser.model.container.LdifChangeRecord; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.container.LdifModSpec; import org.apache.directory.studio.ldifparser.model.container.LdifRecord; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine; import org.apache.directory.studio.ldifparser.model.lines.LdifControlLine; import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecTypeLine; import org.apache.directory.studio.ldifparser.parser.LdifParser; /** * Runnable used to import an LDIF file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ImportLdifRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** The LDIF file. */ private File ldifFile; /** The log file. */ private File logFile; /** The update if entry exists flag. */ private boolean updateIfEntryExists; /** The continue on error flag. */ private boolean continueOnError; /** * Creates a new instance of ImportLdifRunnable. * * @param browserConnection the browser connection * @param ldifFile the LDIF file * @param logFile the log file * @param updateIfEntryExists the update if entry exists flag * @param continueOnError the continue on error flag */ public ImportLdifRunnable( IBrowserConnection browserConnection, File ldifFile, File logFile, boolean updateIfEntryExists, boolean continueOnError ) { this.browserConnection = browserConnection; this.ldifFile = ldifFile; this.logFile = logFile; this.continueOnError = continueOnError; this.updateIfEntryExists = updateIfEntryExists; } /** * Creates a new instance of ImportLdifRunnable. * * @param connection the connection * @param ldifFile the LDIF file * @param updateIfEntryExists the update if entry exists flag * @param continueOnError the continue on error flag */ public ImportLdifRunnable( IBrowserConnection connection, File ldifFile, boolean updateIfEntryExists, boolean continueOnError ) { this( connection, ldifFile, null, updateIfEntryExists, continueOnError ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_ldif_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( ldifFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_ldif_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_ldif_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { Reader ldifReader = new BufferedReader( new FileReader( this.ldifFile ) ); LdifParser parser = new LdifParser(); LdifEnumeration enumeration = parser.parse( ldifReader ); Writer logWriter; if ( this.logFile != null ) { logWriter = new BufferedWriter( new FileWriter( this.logFile ) ); } else { logWriter = new Writer() { public void close() throws IOException { } public void flush() throws IOException { } public void write( char[] cbuf, int off, int len ) throws IOException { } }; } importLdif( browserConnection, enumeration, logWriter, updateIfEntryExists, continueOnError, monitor ); logWriter.close(); ldifReader.close(); } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Imports the LDIF enumeration * * @param browserConnection the browser connection * @param enumeration the LDIF enumeration * @param logWriter the log writer * @param updateIfEntryExists the update if entry exists flag * @param continueOnError the continue on error flag * @param monitor the progress monitor */ static void importLdif( IBrowserConnection browserConnection, LdifEnumeration enumeration, Writer logWriter, boolean updateIfEntryExists, boolean continueOnError, StudioProgressMonitor monitor ) { if ( browserConnection == null ) { return; } StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); int importedCount = 0; int errorCount = 0; try { while ( !monitor.isCanceled() && enumeration.hasNext() ) { LdifContainer container = enumeration.next(); if ( container instanceof LdifRecord ) { LdifRecord record = ( LdifRecord ) container; try { dummyMonitor.reset(); importLdifRecord( browserConnection, record, updateIfEntryExists, dummyMonitor ); if ( dummyMonitor.errorsReported() ) { errorCount++; logModificationError( browserConnection, logWriter, record, dummyMonitor.getException(), monitor ); if ( !continueOnError ) { monitor.reportError( dummyMonitor.getException() ); return; } } else { importedCount++; logModification( browserConnection, logWriter, record, monitor ); // update cache and adjust attribute/children initialization flags Dn dn = new Dn( record.getDnLine().getValueAsString() ); IEntry entry = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = null; while ( parentEntry == null && parentDn != null ) { parentEntry = browserConnection.getEntryFromCache( parentDn ); parentDn = parentDn.getParent(); } if ( record instanceof LdifChangeDeleteRecord ) { if ( entry != null ) { entry.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( entry ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } else if ( record instanceof LdifChangeModDnRecord ) { if ( entry != null ) { entry.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( entry ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } LdifChangeModDnRecord modDnRecord = ( LdifChangeModDnRecord ) record; if ( modDnRecord.getNewsuperiorLine() != null ) { Dn newSuperiorDn = new Dn( modDnRecord.getNewsuperiorLine() .getValueAsString() ); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } else if ( record instanceof LdifChangeAddRecord || record instanceof LdifContentRecord ) { if ( entry != null ) { entry.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); parentEntry.setHasChildrenHint( true ); } } else { if ( entry != null ) { entry.setAttributesInitialized( false ); } } } } catch ( Exception e ) { logModificationError( browserConnection, logWriter, record, e, monitor ); errorCount++; if ( !continueOnError ) { monitor.reportError( e ); return; } } monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.ldif__imported_n_entries_m_errors, new String[] { "" + importedCount, "" + errorCount } ) ); //$NON-NLS-1$ //$NON-NLS-2$ } else { logWriter.write( container.toRawString() ); } } if ( errorCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.ldif__n_errors_see_logfile, new String[] { "" + errorCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * Imports the LDIF record. * * @param browserConnection the browser connection * @param record the LDIF record * @param updateIfEntryExists the update if entry exists flag * @param monitor the progress monitor * @throws LdapInvalidDnException */ static void importLdifRecord( IBrowserConnection browserConnection, LdifRecord record, boolean updateIfEntryExists, StudioProgressMonitor monitor ) throws LdapException { if ( !record.isValid() ) { throw new LdapSchemaException( BrowserCoreMessages.bind( BrowserCoreMessages.model__invalid_record, record.getInvalidString() ) ); } String dn = record.getDnLine().getValueAsString(); if ( record instanceof LdifContentRecord || record instanceof LdifChangeAddRecord ) { IEntry dummyEntry; if ( record instanceof LdifContentRecord ) { LdifContentRecord attrValRecord = ( LdifContentRecord ) record; try { dummyEntry = ModelConverter.ldifContentRecordToEntry( attrValRecord, browserConnection ); } catch ( LdapInvalidDnException e ) { monitor.reportError( e ); return; } } else { LdifChangeAddRecord changeAddRecord = ( LdifChangeAddRecord ) record; try { dummyEntry = ModelConverter.ldifChangeAddRecordToEntry( changeAddRecord, browserConnection ); } catch ( LdapInvalidDnException e ) { monitor.reportError( e ); return; } } Entry entry = ModelConverter.toLdapApiEntry( dummyEntry ); browserConnection.getConnection().getConnectionWrapper() .createEntry( entry, getControls( record ), monitor, null ); if ( monitor.errorsReported() && updateIfEntryExists && StudioLdapException.isEntryAlreadyExistsException( monitor.getException() ) ) { // creation failed with Error 68, now try to update the existing entry monitor.reset(); Collection<Modification> modifications = ModelConverter.toReplaceModifications( entry ); browserConnection.getConnection().getConnectionWrapper() .modifyEntry( new Dn( dn ), modifications, getControls( record ), monitor, null ); } } else if ( record instanceof LdifChangeDeleteRecord ) { LdifChangeDeleteRecord changeDeleteRecord = ( LdifChangeDeleteRecord ) record; browserConnection.getConnection().getConnectionWrapper() .deleteEntry( new Dn( dn ), getControls( changeDeleteRecord ), monitor, null ); } else if ( record instanceof LdifChangeModifyRecord ) { LdifChangeModifyRecord modifyRecord = ( LdifChangeModifyRecord ) record; LdifModSpec[] modSpecs = modifyRecord.getModSpecs(); Collection<Modification> modifications = new ArrayList<>(); for ( int ii = 0; ii < modSpecs.length; ii++ ) { LdifModSpecTypeLine modSpecType = modSpecs[ii].getModSpecType(); LdifAttrValLine[] attrVals = modSpecs[ii].getAttrVals(); DefaultAttribute attribute = new DefaultAttribute( modSpecType.getUnfoldedAttributeDescription() ); for ( int x = 0; x < attrVals.length; x++ ) { Object valueAsObject = attrVals[x].getValueAsObject(); if ( valueAsObject instanceof String ) { attribute.add( ( String ) valueAsObject ); } else if ( valueAsObject instanceof byte[] ) { attribute.add( ( byte[] ) valueAsObject ); } } if ( modSpecType.isAdd() ) { modifications.add( new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, attribute ) ); } else if ( modSpecType.isDelete() ) { modifications.add( new DefaultModification( ModificationOperation.REMOVE_ATTRIBUTE, attribute ) ); } else if ( modSpecType.isReplace() ) { modifications.add( new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, attribute ) ); } } browserConnection.getConnection().getConnectionWrapper() .modifyEntry( new Dn( dn ), modifications, getControls( modifyRecord ), monitor, null ); } else if ( record instanceof LdifChangeModDnRecord ) { LdifChangeModDnRecord modDnRecord = ( LdifChangeModDnRecord ) record; if ( modDnRecord.getNewrdnLine() != null && modDnRecord.getDeloldrdnLine() != null ) { String newRdn = modDnRecord.getNewrdnLine().getValueAsString(); boolean deleteOldRdn = modDnRecord.getDeloldrdnLine().isDeleteOldRdn(); Dn newDn; if ( modDnRecord.getNewsuperiorLine() != null ) { newDn = new Dn( newRdn, modDnRecord.getNewsuperiorLine().getValueAsString() ); } else { Dn dnObject = new Dn( dn ); Dn parent = dnObject.getParent(); newDn = new Dn( newRdn, parent.getName() ); } browserConnection.getConnection().getConnectionWrapper() .renameEntry( new Dn( dn ), newDn, deleteOldRdn, getControls( modDnRecord ), monitor, null ); } } } /** * Gets the controls. * * @param record the LDIF record * * @return the controls */ private static Control[] getControls( LdifRecord record ) { Control[] controls = null; if ( record instanceof LdifChangeRecord ) { LdifChangeRecord changeRecord = ( LdifChangeRecord ) record; LdifControlLine[] controlLines = changeRecord.getControls(); controls = new Control[controlLines.length]; for ( int i = 0; i < controlLines.length; i++ ) { LdifControlLine line = controlLines[i]; controls[i] = Controls.create( line.getUnfoldedOid(), line.isCritical(), line.getControlValueAsBinary() ); } } return controls; } /** * Log a modification error to the given writer. * * @param browserConnection the browser connection * @param logWriter the log writer * @param record the record * @param exception the exception * @param monitor the progress monitor */ private static void logModificationError( IBrowserConnection browserConnection, Writer logWriter, LdifRecord record, Throwable exception, StudioProgressMonitor monitor ) { try { LdifFormatParameters ldifFormatParameters = Utils.getLdifFormatParameters(); DateFormat df = new SimpleDateFormat( ConnectionCoreConstants.DATEFORMAT ); String errorComment = "#!ERROR " + exception.getMessage(); //$NON-NLS-1$ errorComment = errorComment.replaceAll( "\r", " " ); //$NON-NLS-1$ //$NON-NLS-2$ errorComment = errorComment.replaceAll( "\n", " " ); //$NON-NLS-1$ //$NON-NLS-2$ LdifCommentLine errorCommentLine = LdifCommentLine.create( errorComment ); logWriter.write( LdifCommentLine.create( "#!RESULT ERROR" ) //$NON-NLS-1$ .toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NL LdifFormatParameters.DEFAULTS-1$ logWriter .write( LdifCommentLine .create( "#!CONNECTION ldap://" + browserConnection.getConnection().getHost() + ":" + browserConnection.getConnection().getPort() ).toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NLS-1$ //$NON-NLS-2$ logWriter.write( LdifCommentLine .create( "#!DATE " + df.format( new Date() ) ).toFormattedString( LdifFormatParameters.DEFAULT ) ); //$NON-NLS-1$ logWriter.write( errorCommentLine.toFormattedString( LdifFormatParameters.DEFAULT ) ); logWriter.write( record.toFormattedString( ldifFormatParameters ) ); } catch ( IOException ioe ) { monitor.reportError( BrowserCoreMessages.model__error_logging_modification, ioe ); } } /** * Log a modification to the given writer. * * @param browserConnection the browser connection * @param logWriter the log writer * @param record the record * @param monitor the progress monitor */ private static void logModification( IBrowserConnection browserConnection, Writer logWriter, LdifRecord record, StudioProgressMonitor monitor ) { try { LdifFormatParameters ldifFormatParameters = Utils.getLdifFormatParameters(); DateFormat df = new SimpleDateFormat( ConnectionCoreConstants.DATEFORMAT ); logWriter.write( LdifCommentLine.create( "#!RESULT OK" ).toFormattedString( ldifFormatParameters ) ); //$NON-NLS-1$ logWriter .write( LdifCommentLine .create( "#!CONNECTION ldap://" + browserConnection.getConnection().getHost() + ":" + browserConnection.getConnection().getPort() ).toFormattedString( ldifFormatParameters ) ); //$NON-NLS-1$ //$NON-NLS-2$ logWriter.write( LdifCommentLine .create( "#!DATE " + df.format( new Date() ) ).toFormattedString( ldifFormatParameters ) ); //$NON-NLS-1$ logWriter.write( record.toFormattedString( ldifFormatParameters ) ); } catch ( IOException ioe ) { monitor.reportError( BrowserCoreMessages.model__error_logging_modification, ioe ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportXlsRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportXlsRunnable.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.ldapbrowser.core.jobs; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.text.translate.CharSequenceTranslator; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.eclipse.core.runtime.Preferences; /** * Runnable to export directory content to an XLS file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExportXlsRunnable implements StudioConnectionRunnableWithProgress { /** The maximum count limit */ public static final int MAX_COUNT_LIMIT = 65000; /** The postal address decoder. */ private static CharSequenceTranslator DECODER = Utils.createPostalAddressDecoder( "\n" ); //$NON-NLS-1$; /** The filename of the XLS file. */ private String exportXlsFilename; /** The browser connection. */ private IBrowserConnection browserConnection; /** The search parameter. */ private SearchParameter searchParameter; /** The export dn flag. */ private boolean exportDn; /** * Creates a new instance of ExportXlsRunnable. * * @param exportLdifFilename the export ldif filename * @param browserConnection the browser connection * @param searchParameter the search parameter * @param exportDn true to export the Dn */ public ExportXlsRunnable( String exportLdifFilename, IBrowserConnection browserConnection, SearchParameter searchParameter, boolean exportDn ) { this.exportXlsFilename = exportLdifFilename; this.browserConnection = browserConnection; this.searchParameter = searchParameter; this.exportDn = exportDn; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__export_xls_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { browserConnection.getUrl() + "_" + DigestUtils.shaHex( exportXlsFilename ) }; //$NON-NLS-1$ } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__export_xls_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__export_xls_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences(); String valueDelimiter = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER ); int binaryEncoding = coreStore.getInt( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING ); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet( "Export" ); //$NON-NLS-1$ // header HSSFRow headerRow = sheet.createRow( 0 ); LinkedHashMap<String, Integer> attributeNameMap = new LinkedHashMap<String, Integer>(); if ( this.exportDn ) { int cellNum = 0; attributeNameMap.put( "dn", cellNum ); //$NON-NLS-1$ createStringCell( headerRow, cellNum ).setCellValue( "dn" ); //$NON-NLS-1$ } // max export if ( searchParameter.getCountLimit() < 1 || searchParameter.getCountLimit() > MAX_COUNT_LIMIT ) { searchParameter.setCountLimit( MAX_COUNT_LIMIT ); } // export try { int count = 0; exportToXls( browserConnection, searchParameter, sheet, headerRow, count, monitor, attributeNameMap, valueDelimiter, binaryEncoding, this.exportDn ); } catch ( Exception e ) { monitor.reportError( e ); } // column width for ( int i = 0; i <= sheet.getLastRowNum(); i++ ) { HSSFRow row = sheet.getRow( i ); for ( short j = 0; row != null && j <= row.getLastCellNum(); j++ ) { HSSFCell cell = row.getCell( j ); if ( cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_STRING ) { String value = cell.getStringCellValue(); if ( ( short ) ( value.length() * 256 * 1.1 ) > sheet.getColumnWidth( j ) ) { sheet.setColumnWidth( j, ( short ) ( value.length() * 256 * 1.1 ) ); } } } } try { FileOutputStream fileOut = new FileOutputStream( exportXlsFilename ); wb.write( fileOut ); fileOut.close(); } catch ( Exception e ) { monitor.reportError( e ); } } /** * Exports to XLS. * * @param browserConnection the browser connection * @param searchParameter the search parameter * @param sheet the sheet * @param headerRow the header row * @param count the count * @param monitor the monitor * @param attributeNameMap the attribute name map * @param valueDelimiter the value delimiter * @param binaryEncoding the binary encoding * @param exportDn the export dn * * @throws IOException Signals that an I/O exception has occurred. */ private static void exportToXls( IBrowserConnection browserConnection, SearchParameter searchParameter, HSSFSheet sheet, HSSFRow headerRow, int count, StudioProgressMonitor monitor, LinkedHashMap<String, Integer> attributeNameMap, String valueDelimiter, int binaryEncoding, boolean exportDn ) throws IOException { try { LdifEnumeration enumeration = ExportLdifRunnable.search( browserConnection, searchParameter, monitor ); while ( !monitor.isCanceled() && !monitor.errorsReported() && enumeration.hasNext() ) { LdifContainer container = enumeration.next(); if ( container instanceof LdifContentRecord ) { LdifContentRecord record = ( LdifContentRecord ) container; recordToHSSFRow( browserConnection, record, sheet, headerRow, attributeNameMap, valueDelimiter, binaryEncoding, exportDn ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException ne ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( ne ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // nothing } else { monitor.reportError( ne ); } } } /** * Transforms an LDIF record to an HSSF row. * * @param browserConnection the browser connection * @param record the record * @param sheet the sheet * @param headerRow the header row * @param headerRowAttributeNameMap the header row attribute name map * @param valueDelimiter the value delimiter * @param binaryEncoding the binary encoding * @param exportDn the export dn */ private static void recordToHSSFRow( IBrowserConnection browserConnection, LdifContentRecord record, HSSFSheet sheet, HSSFRow headerRow, Map<String, Integer> headerRowAttributeNameMap, String valueDelimiter, int binaryEncoding, boolean exportDn ) { // group multi-valued attributes Map<String, String> attributeMap = ExportCsvRunnable.getAttributeMap( null, record, valueDelimiter, "UTF-16", //$NON-NLS-1$ binaryEncoding ); CellStyle wrapStyle = sheet.getWorkbook().createCellStyle(); wrapStyle.setWrapText( true ); // output attributes HSSFRow row = sheet.createRow( sheet.getLastRowNum() + 1 ); if ( exportDn ) { HSSFCell cell = createStringCell(row, 0 ); cell.setCellValue( record.getDnLine().getValueAsString() ); } for ( String attributeName : attributeMap.keySet() ) { String value = attributeMap.get( attributeName ); if ( !headerRowAttributeNameMap.containsKey( attributeName ) ) { int cellNum = headerRowAttributeNameMap.size(); headerRowAttributeNameMap.put( attributeName, new Integer( cellNum ) ); HSSFCell cell = createStringCell( headerRow, cellNum ); cell.setCellValue( attributeName ); } if ( headerRowAttributeNameMap.containsKey( attributeName ) ) { int cellNum = headerRowAttributeNameMap.get( attributeName ).shortValue(); HSSFCell cell = createStringCell( row, cellNum ); AttributeType type = browserConnection.getSchema().getAttributeTypeDescription( attributeName ); if ( SchemaConstants.POSTAL_ADDRESS_SYNTAX.equals( type.getSyntaxOid() ) ) { // https://poi.apache.org/components/spreadsheet/quick-guide.html#NewLinesInCells value = DECODER.translate( value ); cell.setCellStyle( wrapStyle ); } cell.setCellValue( value ); } } } private static HSSFCell createStringCell( HSSFRow row, int cellNum ) { HSSFCell cell = row.createCell( cellNum ); cell.setCellType( Cell.CELL_TYPE_STRING ); return cell; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportOdfRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportOdfRunnable.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.ldapbrowser.core.jobs; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.text.translate.CharSequenceTranslator; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.eclipse.core.runtime.Preferences; import org.odftoolkit.odfdom.type.ValueType; import org.odftoolkit.simple.SpreadsheetDocument; import org.odftoolkit.simple.table.Cell; import org.odftoolkit.simple.table.Row; import org.odftoolkit.simple.table.Table; /** * Runnable to export directory content to an ODF file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExportOdfRunnable implements StudioConnectionRunnableWithProgress { /** The maximum count limit */ public static final int MAX_COUNT_LIMIT = 65000; /** The postal address decoder. */ private static CharSequenceTranslator DECODER = Utils.createPostalAddressDecoder( "\n" ); //$NON-NLS-1$; /** The filename of the ODF file. */ private String exportOdfFilename; /** The browser connection. */ private IBrowserConnection browserConnection; /** The search parameter. */ private SearchParameter searchParameter; /** The export dn flag. */ private boolean exportDn; /** * Creates a new instance of ExportOdfRunnable. * * @param exportOdfFilename the ODF filename * @param browserConnection the browser connection * @param searchParameter the search parameter * @param exportDn true to export the Dn */ public ExportOdfRunnable( String exportOdfFilename, IBrowserConnection browserConnection, SearchParameter searchParameter, boolean exportDn ) { this.exportOdfFilename = exportOdfFilename; this.browserConnection = browserConnection; this.searchParameter = searchParameter; this.exportDn = exportDn; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__export_odf_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new Object[] { browserConnection.getUrl() + "_" + DigestUtils.shaHex( exportOdfFilename ) }; //$NON-NLS-1$ } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__export_odf_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__export_odf_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences(); String valueDelimiter = coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_VALUEDELIMITER ); int binaryEncoding = coreStore.getInt( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_BINARYENCODING ); // export try { SpreadsheetDocument doc = SpreadsheetDocument.newSpreadsheetDocument(); // Remove the default table added in construction doc.removeSheet( 0 ); // create the table Table table = doc.appendSheet( "Export" ); //$NON-NLS-1$ // header Row headerRow = table.appendRow(); LinkedHashMap<String, Short> attributeNameMap = new LinkedHashMap<String, Short>(); if ( this.exportDn ) { short cellNum = ( short ) 0; attributeNameMap.put( "dn", new Short( cellNum ) ); //$NON-NLS-1$ Cell cell = headerRow.getCellByIndex( cellNum ); cell.setValueType( ValueType.STRING.name() ); cell.setStringValue( "dn" ); //$NON-NLS-1$ } // max export if ( searchParameter.getCountLimit() < 1 || searchParameter.getCountLimit() > MAX_COUNT_LIMIT ) { searchParameter.setCountLimit( MAX_COUNT_LIMIT ); } int count = 0; exportToOdf( browserConnection, searchParameter, table, headerRow, count, monitor, attributeNameMap, valueDelimiter, binaryEncoding, this.exportDn ); // remove default rows table.removeRowsByIndex( 0, 2 ); doc.save( exportOdfFilename ); } catch ( Exception e ) { monitor.reportError( e ); } } /** * Exports to ODF. * * @param browserConnection the browser connection * @param searchParameter the search parameter * @param table the table * @param headerRow the header row * @param count the count * @param monitor the monitor * @param attributeNameMap the attribute name map * @param valueDelimiter the value delimiter * @param binaryEncoding the binary encoding * @param exportDn the export dn * * @throws IOException Signals that an I/O exception has occurred. */ private static void exportToOdf( IBrowserConnection browserConnection, SearchParameter searchParameter, Table table, Row headerRow, int count, StudioProgressMonitor monitor, LinkedHashMap<String, Short> attributeNameMap, String valueDelimiter, int binaryEncoding, boolean exportDn ) throws IOException { try { LdifEnumeration enumeration = ExportLdifRunnable.search( browserConnection, searchParameter, monitor ); while ( !monitor.isCanceled() && !monitor.errorsReported() && enumeration.hasNext() ) { LdifContainer container = enumeration.next(); if ( container instanceof LdifContentRecord ) { LdifContentRecord record = ( LdifContentRecord ) container; recordToOdfRow( browserConnection, record, table, headerRow, attributeNameMap, valueDelimiter, binaryEncoding, exportDn ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException ne ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( ne ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // nothing } else { monitor.reportError( ne ); } } } /** * Transforms an LDIF record to an OdfTableRow. * * @param browserConnection the browser connection * @param record the record * @param table the table * @param headerRow the header row * @param headerRowAttributeNameMap the header row attribute name map * @param valueDelimiter the value delimiter * @param binaryEncoding the binary encoding * @param exportDn the export dn */ private static void recordToOdfRow( IBrowserConnection browserConnection, LdifContentRecord record, Table table, Row headerRow, Map<String, Short> headerRowAttributeNameMap, String valueDelimiter, int binaryEncoding, boolean exportDn ) { // group multi-valued attributes Map<String, String> attributeMap = ExportCsvRunnable.getAttributeMap( null, record, valueDelimiter, "UTF-16", //$NON-NLS-1$ binaryEncoding ); // output attributes Row row = table.appendRow(); if ( exportDn ) { Cell cell = row.getCellByIndex( 0 ); cell.setValueType( ValueType.STRING.name() ); cell.setStringValue( record.getDnLine().getValueAsString() ); } for ( String attributeName : attributeMap.keySet() ) { String value = attributeMap.get( attributeName ); if ( value == null ) { value = ""; //$NON-NLS-1$ } if ( !headerRowAttributeNameMap.containsKey( attributeName ) ) { short cellNum = ( short ) headerRowAttributeNameMap.size(); headerRowAttributeNameMap.put( attributeName, new Short( cellNum ) ); Cell cell = headerRow.getCellByIndex( cellNum ); cell.setValueType( ValueType.STRING.name() ); cell.setStringValue( attributeName ); } if ( headerRowAttributeNameMap.containsKey( attributeName ) ) { short cellNum = headerRowAttributeNameMap.get( attributeName ).shortValue(); Cell cell = row.getCellByIndex( cellNum ); cell.setValueType( ValueType.STRING.name() ); AttributeType type = browserConnection.getSchema().getAttributeTypeDescription( attributeName ); if ( SchemaConstants.POSTAL_ADDRESS_SYNTAX.equals( type.getSyntaxOid() ) ) { // https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part4-formula/OpenDocument-v1.3-os-part4-formula.html#__RefHeading__1017970_715980110 value = DECODER.translate( value ); cell.setTextWrapped( true ); } cell.setStringValue( 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExtendedOperationRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExtendedOperationRunnable.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.ldapbrowser.core.jobs; import org.apache.directory.api.ldap.model.message.ExtendedRequest; import org.apache.directory.api.ldap.model.message.ExtendedResponse; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Utils; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; /** * Runnable to execute extended operations. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExtendedOperationRunnable implements StudioConnectionRunnableWithProgress { private IBrowserConnection connection; private ExtendedRequest request; private ExtendedResponse response; public ExtendedOperationRunnable( final IBrowserConnection connection, ExtendedRequest request ) { this.connection = connection; this.request = request; } public Connection[] getConnections() { return new Connection[] { connection.getConnection() }; } public String getName() { return BrowserCoreMessages.jobs__extended_operation_name; } public Object[] getLockedObjects() { return new Object[] { connection }; } public String getErrorMessage() { return BrowserCoreMessages.jobs__extended_operation_error; } public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__extended_operation_task, new String[] { Utils.getOidDescription( request.getRequestName() ) } ), 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { response = connection.getConnection().getConnectionWrapper().extended( request, monitor ); } catch ( Exception e ) { monitor.reportError( e ); } } public ExtendedResponse getResponse() { return response; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/SearchRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/SearchRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.naming.directory.SearchControls; import org.apache.commons.lang3.ArrayUtils; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.message.controls.PagedResults; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.StudioControl; import org.apache.directory.studio.connection.core.io.api.StudioSearchResult; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.model.AttributeHierarchy; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.impl.BaseDNEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.ContinuedSearchResultEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Entry; import org.apache.directory.studio.ldapbrowser.core.model.impl.SearchContinuation; import org.apache.directory.studio.ldapbrowser.core.model.impl.Value; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; /** * Runnable to perform search operations. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SearchRunnable implements StudioConnectionBulkRunnableWithProgress { /** The searches. */ protected ISearch[] searches; /** The searches to perform. */ protected ISearch[] searchesToPerform; /** * Creates a new instance of SearchRunnable. * * @param searches the searches */ public SearchRunnable( ISearch[] searches ) { this.searches = searches; this.searchesToPerform = searches; } /** * Creates a new instance of SearchRunnable. * * @param search the search * @param searchToPerform the search to perform */ private SearchRunnable( ISearch search, ISearch searchToPerform ) { this.searches = new ISearch[] { search }; this.searchesToPerform = new ISearch[] { searchToPerform }; } /** * {@inheritDoc} */ public Connection[] getConnections() { Connection[] connections = new Connection[searches.length]; for ( int i = 0; i < connections.length; i++ ) { connections[i] = searches[i].getBrowserConnection().getConnection(); } return connections; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__search_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.addAll( Arrays.asList( searches ) ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return searches.length == 1 ? BrowserCoreMessages.jobs__search_error_1 : BrowserCoreMessages.jobs__search_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", searches.length + 1 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( int pi = 0; pi < searches.length; pi++ ) { ISearch search = searches[pi]; ISearch searchToPerform = searchesToPerform[pi]; monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__search_task, new String[] { search.getName() } ) ); monitor.worked( 1 ); if ( search.getBrowserConnection() != null ) { // reset search results search.setSearchResults( new ISearchResult[0] ); search.getResponseControls().clear(); search.setNextPageSearchRunnable( null ); search.setTopPageSearchRunnable( null ); searchToPerform.setSearchResults( new ISearchResult[0] ); searchToPerform.setNextPageSearchRunnable( null ); searchToPerform.setTopPageSearchRunnable( null ); searchToPerform.getResponseControls().clear(); do { // perform search searchAndUpdateModel( searchToPerform.getBrowserConnection(), searchToPerform, monitor ); if ( search != searchToPerform ) { // merge search results ISearchResult[] sr1 = search.getSearchResults(); ISearchResult[] sr2 = searchToPerform.getSearchResults(); ISearchResult[] sr = new ISearchResult[sr1.length + sr2.length]; System.arraycopy( sr1, 0, sr, 0, sr1.length ); System.arraycopy( sr2, 0, sr, sr1.length, sr2.length ); search.setSearchResults( sr ); } else { // set search results search.setSearchResults( searchToPerform.getSearchResults() ); } // check response controls ISearch clonedSearch = ( ISearch ) searchToPerform.clone(); clonedSearch.getResponseControls().clear(); PagedResults prResponseControl = null; PagedResults prRequestControl = null; for ( org.apache.directory.api.ldap.model.message.Control responseControl : searchToPerform .getResponseControls() ) { if ( responseControl instanceof PagedResults ) { prResponseControl = ( PagedResults ) responseControl; } } for ( Iterator<Control> it = clonedSearch.getControls().iterator(); it.hasNext(); ) { Control requestControl = it.next(); if ( requestControl instanceof PagedResults ) { prRequestControl = ( PagedResults ) requestControl; it.remove(); } } searchToPerform = null; // paged search if ( prResponseControl != null && prRequestControl != null ) { PagedResults nextPrc = Controls.newPagedResultsControl( prRequestControl.getSize(), prResponseControl.getCookie() ); ISearch nextPageSearch = ( ISearch ) clonedSearch.clone(); nextPageSearch.getResponseControls().clear(); nextPageSearch.getControls().add( nextPrc ); if ( search.isPagedSearchScrollMode() ) { if ( ArrayUtils.isNotEmpty( prRequestControl.getCookie() ) ) { // create top page search runnable, same as original search ISearch topPageSearch = ( ISearch ) search.clone(); topPageSearch.getResponseControls().clear(); SearchRunnable topPageSearchRunnable = new SearchRunnable( search, topPageSearch ); search.setTopPageSearchRunnable( topPageSearchRunnable ); } if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) ) { // create next page search runnable SearchRunnable nextPageSearchRunnable = new SearchRunnable( search, nextPageSearch ); search.setNextPageSearchRunnable( nextPageSearchRunnable ); } } else { // transparently continue search, till count limit is reached if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) && ( search.getCountLimit() == 0 || search.getSearchResults().length < search .getCountLimit() ) ) { searchToPerform = nextPageSearch; } } } } while ( searchToPerform != null ); } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( int pi = 0; pi < searches.length; pi++ ) { EventRegistry.fireSearchUpdated( new SearchUpdateEvent( searches[pi], SearchUpdateEvent.EventDetail.SEARCH_PERFORMED ), this ); } } /** * Searches the directory and updates the browser model. * * @param browserConnection the browser connection * @param search the search * @param monitor the progress monitor */ public static void searchAndUpdateModel( IBrowserConnection browserConnection, ISearch search, StudioProgressMonitor monitor ) { if ( browserConnection.getConnection() == null ) { return; } try { if ( !monitor.isCanceled() ) { // add returning attributes for children and alias detection SearchParameter searchParameter = getSearchParameter( search ); ArrayList<ISearchResult> searchResultList = new ArrayList<ISearchResult>(); ArrayList<SearchContinuation> searchContinuationList = new ArrayList<SearchContinuation>(); StudioSearchResultEnumeration enumeration = null; // search try { enumeration = search( browserConnection, searchParameter, monitor ); // iterate through the search result while ( !monitor.isCanceled() && enumeration != null && enumeration.hasMore() ) { StudioSearchResult sr = enumeration.next(); boolean isContinuedSearchResult = sr.isContinuedSearchResult(); LdapUrl searchContinuationUrl = sr.getSearchContinuationUrl(); if ( searchContinuationUrl == null ) { Dn dn = sr.getDn(); IEntry entry = null; Connection resultConnection = sr.getConnection(); IBrowserConnection resultBrowserConnection = BrowserCorePlugin.getDefault() .getConnectionManager().getBrowserConnection( resultConnection ); if ( resultBrowserConnection == null ) { resultBrowserConnection = browserConnection; } // get entry from cache or create it entry = resultBrowserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = createAndCacheEntry( resultBrowserConnection, dn, monitor ); // If the entry is still null, we return // See https://issues.apache.org/jira/browse/DIRSTUDIO-865 if ( entry == null ) { return; } } // initialize special flags initFlags( entry, sr, searchParameter ); // fill the attributes fillAttributes( entry, sr, search.getSearchParameter() ); if ( isContinuedSearchResult ) { // the result is from a continued search // we create a special entry that displays the URL of the entry entry = new ContinuedSearchResultEntry( resultBrowserConnection, dn ); } searchResultList .add( new org.apache.directory.studio.ldapbrowser.core.model.impl.SearchResult( entry, search ) ); } else { //entry = new ContinuedSearchResultEntry( resultBrowserConnection, dn ); SearchContinuation searchContinuation = new SearchContinuation( search, searchContinuationUrl ); searchContinuationList.add( searchContinuation ); } monitor .reportProgress( searchResultList.size() == 1 ? BrowserCoreMessages.model__retrieved_1_entry : BrowserCoreMessages.bind( BrowserCoreMessages.model__retrieved_n_entries, new String[] { Integer.toString( searchResultList.size() ) } ) ); } } catch ( Exception e ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( e ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { search.setCountLimitExceeded( true ); } else { monitor.reportError( e ); } } // check for response controls try { if ( enumeration != null ) { for ( org.apache.directory.api.ldap.model.message.Control control : enumeration .getResponseControls() ) { search.getResponseControls().add( control ); if ( control instanceof PagedResults ) { search.setCountLimitExceeded( ArrayUtils.isNotEmpty( ( ( PagedResults ) control ).getCookie() ) ); } } } } catch ( Exception e ) { monitor.reportError( e ); } monitor.reportProgress( searchResultList.size() == 1 ? BrowserCoreMessages.model__retrieved_1_entry : BrowserCoreMessages.bind( BrowserCoreMessages.model__retrieved_n_entries, new String[] { Integer.toString( searchResultList.size() ) } ) ); monitor.worked( 1 ); search.setSearchResults( ( ISearchResult[] ) searchResultList .toArray( new ISearchResult[searchResultList.size()] ) ); search.setSearchContinuations( ( SearchContinuation[] ) searchContinuationList .toArray( new SearchContinuation[searchContinuationList.size()] ) ); } } catch ( Exception e ) { if ( search != null ) { search.setSearchResults( new ISearchResult[0] ); } monitor.reportError( e ); } } public static StudioSearchResultEnumeration search( IBrowserConnection browserConnection, SearchParameter parameter, StudioProgressMonitor monitor ) { if ( browserConnection == null ) { return null; } String searchBase = parameter.getSearchBase().getName(); SearchControls searchControls = new SearchControls(); SearchScope scope = parameter.getScope(); switch ( scope ) { case OBJECT: searchControls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } searchControls.setReturningAttributes( parameter.getReturningAttributes() ); searchControls.setCountLimit( parameter.getCountLimit() ); int timeLimit = parameter.getTimeLimit() * 1000; if ( timeLimit > 1 ) { timeLimit--; } searchControls.setTimeLimit( timeLimit ); String filter = parameter.getFilter(); AliasDereferencingMethod aliasesDereferencingMethod = parameter.getAliasesDereferencingMethod(); ReferralHandlingMethod referralsHandlingMethod = parameter.getReferralsHandlingMethod(); Control[] controls = null; if ( parameter.getControls() != null ) { controls = parameter.getControls().toArray( new Control[0] ); } StudioSearchResultEnumeration result = browserConnection .getConnection() .getConnectionWrapper() .search( searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, monitor, null ); return result; } private static SearchParameter getSearchParameter( ISearch search ) { SearchParameter searchParameter = ( SearchParameter ) search.getSearchParameter().clone(); // add children detetion attributes if ( search.isInitHasChildrenFlag() ) { if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.HAS_SUBORDINATES_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.HAS_SUBORDINATES_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.HAS_SUBORDINATES_AT; searchParameter.setReturningAttributes( returningAttributes ); } else if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.NUM_SUBORDINATES_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.NUM_SUBORDINATES_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.NUM_SUBORDINATES_AT; searchParameter.setReturningAttributes( returningAttributes ); } else if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.SUBORDINATE_COUNT_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.SUBORDINATE_COUNT_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.SUBORDINATE_COUNT_AT; searchParameter.setReturningAttributes( returningAttributes ); } } // always add the objectClass attribute, we need it // - to detect alias and referral entries // - to determine the entry's icon // - to determine must and may attributes if ( !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.OBJECT_CLASS_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.ALL_USER_ATTRIBUTES ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.OBJECT_CLASS_AT; searchParameter.setReturningAttributes( returningAttributes ); } // filter controls if not supported by server if ( searchParameter.getControls() != null ) { IBrowserConnection connection = search.getBrowserConnection(); Set<String> supportedConrolSet = new HashSet<String>(); if ( connection.getRootDSE() != null && connection.getRootDSE().getAttribute( SchemaConstants.SUPPORTED_CONTROL_AT ) != null ) { IAttribute scAttribute = connection.getRootDSE().getAttribute( SchemaConstants.SUPPORTED_CONTROL_AT ); String[] supportedControls = scAttribute.getStringValues(); for ( int i = 0; i < supportedControls.length; i++ ) { supportedConrolSet.add( Strings.toLowerCase( supportedControls[i] ) ); } } List<Control> controls = searchParameter.getControls(); for ( Iterator<Control> it = controls.iterator(); it.hasNext(); ) { Control control = it.next(); if ( !supportedConrolSet.contains( Strings.toLowerCase( control.getOid() ) ) ) { it.remove(); } } } return searchParameter; } /** * Creates the entry and puts it into the BrowserConnection's entry cache. * * @param browserConnection the browser connection * @param dn the Dn of the entry * @param monitor * * @return the created entry */ private static IEntry createAndCacheEntry( IBrowserConnection browserConnection, Dn dn, StudioProgressMonitor monitor ) { StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); IEntry entry = null; // build tree to parent LinkedList<Dn> parentDnList = new LinkedList<Dn>(); Dn parentDn = dn; while ( parentDn != null && browserConnection.getEntryFromCache( parentDn ) == null ) { parentDnList.addFirst( parentDn ); parentDn = parentDn.getParent(); } for ( Dn aDn : parentDnList ) { parentDn = aDn.getParent(); if ( parentDn == null ) { // only the root DSE has a null parent entry = browserConnection.getRootDSE(); } else if ( !parentDn.isEmpty() && browserConnection.getEntryFromCache( parentDn ) != null ) { // a normal entry has a parent but the parent isn't the rootDSE IEntry parentEntry = browserConnection.getEntryFromCache( parentDn ); entry = new Entry( parentEntry, aDn.getRdn() ); entry.setDirectoryEntry( true ); parentEntry.addChild( entry ); parentEntry.setChildrenInitialized( true ); parentEntry.setHasMoreChildren( true ); parentEntry.setHasChildrenHint( true ); browserConnection.cacheEntry( entry ); } else { // we have a base Dn, check if the entry really exists in LDAP // this is to avoid that a node "dc=com" is created for "dc=example,dc=com" context entry SearchParameter searchParameter = new SearchParameter(); searchParameter.setSearchBase( aDn ); searchParameter.setFilter( null ); searchParameter.setReturningAttributes( ISearch.NO_ATTRIBUTES ); searchParameter.setScope( SearchScope.OBJECT ); searchParameter.setCountLimit( 1 ); searchParameter.setTimeLimit( 0 ); searchParameter.setAliasesDereferencingMethod( browserConnection.getAliasesDereferencingMethod() ); searchParameter.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); searchParameter.setInitHasChildrenFlag( true ); dummyMonitor.reset(); StudioSearchResultEnumeration enumeration = search( browserConnection, searchParameter, dummyMonitor ); try { if ( enumeration != null && enumeration.hasMore() ) { // create base Dn entry entry = new BaseDNEntry( aDn, browserConnection ); browserConnection.getRootDSE().addChild( entry ); browserConnection.cacheEntry( entry ); enumeration.close(); } } catch ( LdapException e ) { } } } return entry; } /** * Initializes the following flags of the entry: * <ul> * <li>hasChildren</li> * <li>isAlias</li> * <li>isReferral</li> * <li>isSubentry</li> * </ul> * * @param entry the entry * @param sr the the JNDI search result * @param searchParameter the search parameters */ private static void initFlags( IEntry entry, StudioSearchResult sr, SearchParameter searchParameter ) { for ( Attribute attribute : sr.getEntry() ) { if ( attribute != null ) { String attributeDescription = attribute.getUpId(); if ( SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( attributeDescription ) ) { if ( entry.getAttribute( attributeDescription ) != null ) { entry.deleteAttribute( entry.getAttribute( attributeDescription ) ); } entry.addAttribute( new org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute( entry, attributeDescription ) ); } for ( org.apache.directory.api.ldap.model.entry.Value valueObject : attribute ) { if ( valueObject.isHumanReadable() ) { String value = valueObject.getString(); if ( searchParameter.isInitHasChildrenFlag() ) { // hasChildren flag if ( SchemaConstants.HAS_SUBORDINATES_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "FALSE".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } if ( SchemaConstants.NUM_SUBORDINATES_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "0".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } if ( SchemaConstants.SUBORDINATE_COUNT_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "0".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } } if ( SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( attributeDescription ) ) { if ( SchemaConstants.ALIAS_OC.equalsIgnoreCase( value ) ) { entry.setAlias( true ); entry.setHasChildrenHint( false ); } if ( SchemaConstants.REFERRAL_OC.equalsIgnoreCase( value ) ) { entry.setReferral( true ); entry.setHasChildrenHint( false ); } IAttribute ocAttribute = entry.getAttribute( attributeDescription ); Value ocValue = new Value( ocAttribute, value );
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
true
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeAttributesRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeAttributesRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.AttributesInitializedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils; /** * Runnable to initialize the attributes of an entry. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class InitializeAttributesRunnable implements StudioConnectionBulkRunnableWithProgress { /** The entries. */ private IEntry[] entries; /** * Creates a new instance of InitializeAttributesRunnable. * * @param entries the entries * @param initOperationalAttributes true if operational attributes should be initialized */ public InitializeAttributesRunnable( IEntry... entries ) { this.entries = entries; } /** * {@inheritDoc} */ public Connection[] getConnections() { List<Connection> connections = new ArrayList<Connection>(); for ( IEntry entry : entries ) { if ( entry != null ) { connections.add( entry.getBrowserConnection().getConnection() ); } } return connections.toArray( new Connection[0] ); } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__init_entries_title_attonly; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { Object[] lockedObjects = new Object[ entries.length ]; System.arraycopy( entries, 0, lockedObjects, 0, entries.length ); return lockedObjects; } /** * {@inheritDoc} */ public String getErrorMessage() { if ( entries.length == 1 ) { return BrowserCoreMessages.jobs__init_entries_error_1; } else { return BrowserCoreMessages.jobs__init_entries_error_n; } } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", entries.length + 2 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( IEntry entry : entries ) { if ( monitor.isCanceled() ) { break; } if ( entry != null ) { monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_task, new String[] { entry.getDn().getName() } ) ); monitor.worked( 1 ); if ( entry.getBrowserConnection() != null ) { initializeAttributes( entry, monitor ); } } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( IEntry entry : entries ) { if ( ( entry != null ) && ( entry.getBrowserConnection() != null ) && ( entry.isAttributesInitialized() ) ) { // lookup the entry from cache and fire event with real entry if ( entry.getBrowserConnection().getEntryFromCache( entry.getDn() ) != null ) { entry = entry.getBrowserConnection().getEntryFromCache( entry.getDn() ); } EventRegistry.fireEntryUpdated( new AttributesInitializedEvent( entry ), this ); } } } /** * Initializes the attributes. * * @param entry the entry * @param monitor the progress monitor */ public static synchronized void initializeAttributes( IEntry entry, StudioProgressMonitor monitor ) { // get user attributes or both user and operational attributes String[] returningAttributes = null; LinkedHashSet<String> raSet = new LinkedHashSet<String>(); raSet.add( SchemaConstants.ALL_USER_ATTRIBUTES ); boolean initOperationalAttributes = entry.getBrowserConnection().isFetchOperationalAttributes() || entry.isInitOperationalAttributes(); if ( initOperationalAttributes ) { if ( entry.getBrowserConnection().getRootDSE().isFeatureSupported( SchemaConstants.FEATURE_ALL_OPERATIONAL_ATTRIBUTES ) ) { raSet.add( SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES ); } else { Collection<AttributeType> opAtds = SchemaUtils.getOperationalAttributeDescriptions( entry .getBrowserConnection().getSchema() ); Collection<String> atdNames = SchemaUtils.getNames( opAtds ); raSet.addAll( atdNames ); } } if ( entry.isReferral() ) { raSet.add( SchemaConstants.REF_AT ); } returningAttributes = ( String[] ) raSet.toArray( new String[raSet.size()] ); initializeAttributes( entry, returningAttributes, true, monitor ); } /** * Initializes the attributes. * * @param entry the entry * @param attributes the returning attributes * @param clearAllAttributes true to clear all old attributes before searching * @param monitor the progress monitor */ public static synchronized void initializeAttributes( IEntry entry, String[] attributes, boolean clearAllAttributes, StudioProgressMonitor monitor ) { monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_progress_att, new String[] { entry.getDn().getName() } ) ); if ( entry instanceof IRootDSE ) { // special handling for Root DSE InitializeRootDSERunnable.loadRootDSE( entry.getBrowserConnection(), monitor ); } else { AliasDereferencingMethod aliasesDereferencingMethod = entry.getBrowserConnection() .getAliasesDereferencingMethod(); if ( entry.isAlias() ) { aliasesDereferencingMethod = AliasDereferencingMethod.NEVER; } ReferralHandlingMethod referralsHandlingMethod = entry.getBrowserConnection().getReferralsHandlingMethod(); if ( clearAllAttributes ) { // Clear all attributes (user and operational) // Must be done here because SearchRunnable.searchAndUpdateModel only clears // requested attributes. If the user switches the "Show operational attributes" // property then the operational attributes are not cleared. IAttribute[] oldAttributes = entry.getAttributes(); if ( oldAttributes != null ) { for ( IAttribute oldAttribute : oldAttributes ) { entry.deleteAttribute( oldAttribute ); } } } // create search ISearch search = new Search( null, entry.getBrowserConnection(), entry.getDn(), entry.isSubentry() ? ISearch.FILTER_SUBENTRY : ISearch.FILTER_TRUE, attributes, SearchScope.OBJECT, 0, 0, aliasesDereferencingMethod, referralsHandlingMethod, false, null, false ); // add controls if ( entry.isReferral() ) { search.getControls().add( Controls.MANAGEDSAIT_CONTROL ); } // search SearchRunnable.searchAndUpdateModel( entry.getBrowserConnection(), search, monitor ); // we requested all attributes, set initialized state entry.setAttributesInitialized( 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportDsmlRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportDsmlRunnable.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.ldapbrowser.core.jobs; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.directory.api.dsmlv2.DsmlDecorator; import org.apache.directory.api.dsmlv2.request.AddRequestDsml; import org.apache.directory.api.dsmlv2.request.BatchRequestDsml; import org.apache.directory.api.dsmlv2.response.BatchResponseDsml; import org.apache.directory.api.dsmlv2.response.SearchResponseDsml; import org.apache.directory.api.dsmlv2.response.SearchResultDoneDsml; import org.apache.directory.api.dsmlv2.response.SearchResultEntryDsml; import org.apache.directory.api.dsmlv2.response.SearchResultReferenceDsml; import org.apache.directory.api.ldap.codec.api.LdapApiService; import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapURLEncodingException; import org.apache.directory.api.ldap.model.message.LdapResult; import org.apache.directory.api.ldap.model.message.MessageTypeEnum; import org.apache.directory.api.ldap.model.message.Response; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; import org.apache.directory.api.ldap.model.message.SearchResultDone; import org.apache.directory.api.ldap.model.message.SearchResultDoneImpl; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; /** * Runnable for Exporting a part of a LDAP Server into a DSML File. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExportDsmlRunnable implements StudioConnectionRunnableWithProgress { private static final String OBJECTCLASS_OBJECTCLASS_OID = "objectClass"; //$NON-NLS-1$ private static final String OBJECTCLASS_OBJECTCLASS_NAME = "2.5.4.0"; //$NON-NLS-1$ private static final String REFERRAL_OBJECTCLASS_OID = "2.16.840.1.113730.3.2.6"; //$NON-NLS-1$ private static final String REFERRAL_OBJECTCLASS_NAME = "referral"; //$NON-NLS-1$ private static final String REF_ATTRIBUTETYPE_OID = "2.16.840.1.113730.3.1.34"; //$NON-NLS-1$ private static final String REF_ATTRIBUTETYPE_NAME = "ref"; //$NON-NLS-1$ /** The name of the DSML file to export to */ private String exportDsmlFilename; /** The connection to use */ private IBrowserConnection browserConnection; /** The Search Parameter of the export*/ private SearchParameter searchParameter; /** The type of the export */ private ExportDsmlJobType type = ExportDsmlJobType.RESPONSE; /** * The LDAP Codec - for now need by the DSML Parser * @TODO - this should be removed - no reason why the DSML parser needs it * @TODO - hate to make it static like this but methods are static */ private static LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * This enum contains the two possible export types. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum ExportDsmlJobType { RESPONSE, REQUEST } /** * Creates a new instance of ExportDsmlRunnable. * * @param exportDsmlFilename * the name of the DSML file to export to * @param connection * the connection to use * @param searchParameter * the Search Parameter of the export */ public ExportDsmlRunnable( String exportDsmlFilename, IBrowserConnection connection, SearchParameter searchParameter, ExportDsmlJobType type ) { this.exportDsmlFilename = exportDsmlFilename; this.browserConnection = connection; this.searchParameter = searchParameter; this.type = type; // Adding the name and OID of the 'ref' attribute to the list of returning attributes // for handling externals correctly List<String> returningAttributes = new ArrayList<>( Arrays.asList( searchParameter .getReturningAttributes() ) ); returningAttributes.add( REF_ATTRIBUTETYPE_NAME ); returningAttributes.add( REF_ATTRIBUTETYPE_OID ); searchParameter.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__export_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<String> l = new ArrayList<>(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( exportDsmlFilename ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__export_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__export_dsml_task, 4 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Searching for the requested entries StudioSearchResultEnumeration ne = SearchRunnable.search( browserConnection, searchParameter, dummyMonitor ); monitor.worked( 1 ); // Getting the DSML string associated to the search // and the type of answer the user is expecting String dsmlExportString = null; switch ( type ) { case RESPONSE: dsmlExportString = processAsDsmlResponse( ne, dummyMonitor ); break; case REQUEST: dsmlExportString = processAsDsmlRequest( ne, dummyMonitor ); break; } monitor.worked( 1 ); // Writing the DSML string to the final destination file. if ( dsmlExportString != null ) { try ( FileOutputStream fos = new FileOutputStream( exportDsmlFilename ) ) { try ( OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ) ) //$NON-NLS-1$ { try ( BufferedWriter bufferedWriter = new BufferedWriter( osw ) ) { bufferedWriter.write( dsmlExportString ); } } } } monitor.worked( 1 ); } catch ( Exception e ) { monitor.reportError( e ); } } /** * Processes the {@link StudioSearchResultEnumeration} as a DSML response. * * @param sre the search result enumeration * @param monitor the monitor * @return the associated DSML * @throws LdapException */ private String processAsDsmlResponse( StudioSearchResultEnumeration sre, StudioProgressMonitor monitor ) throws LdapException { // Creating the batch reponse BatchResponseDsml batchResponse = new BatchResponseDsml(); processAsDsmlResponse( sre, batchResponse, monitor, searchParameter ); // Returning the associated DSML return batchResponse.toDsml(); } /** * Processes the {@link StudioSearchResultEnumeration} as a DSML response. * * @param sre * the search result enumeration * @param monitor * the monitor * @param searchParameter * the search parameter * @throws LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ public static void processAsDsmlResponse( StudioSearchResultEnumeration sre, BatchResponseDsml batchResponse, StudioProgressMonitor monitor, SearchParameter searchParameter ) throws LdapException { // Creating and adding the search response SearchResponseDsml sr = new SearchResponseDsml( codec ); batchResponse.addResponse( sr ); try { int count = 0; if ( !monitor.errorsReported() ) { // Creating and adding a search result entry or reference for each result while ( sre.hasMore() ) { Entry entry = sre.next().getEntry(); sr.addResponse( convertSearchResultToDsml( entry ) ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException e ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( e ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // ignore } else { monitor.reportError( e ); } } // Creating and adding a search result done at the end of the results SearchResultDone srd = new SearchResultDoneImpl(); LdapResult ldapResult = srd.getLdapResult(); if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, MessageTypeEnum.SEARCH_REQUEST ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } sr.addResponse( new SearchResultDoneDsml( codec, srd ) ); } /** * Converts the given {@link SearchResult} to a {@link SearchResultEntryDsml}. * * @param entry2 the search result * @return the associated search result entry DSML * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private static DsmlDecorator<? extends Response> convertSearchResultToDsml( Entry entry ) throws LdapException { if ( isReferral( entry ) ) { // The search result is a referral SearchResultReferenceDsml srr = new SearchResultReferenceDsml( codec ); // Getting the 'ref' attribute Attribute refAttribute = entry.get( ExportDsmlRunnable.REF_ATTRIBUTETYPE_NAME ); if ( refAttribute == null ) { // If we did not get it by its name, let's get it by its OID refAttribute = entry.get( ExportDsmlRunnable.REF_ATTRIBUTETYPE_OID ); } // Adding references if ( refAttribute != null ) { for ( Value value : refAttribute ) { srr.addSearchResultReference( new LdapUrl( ( String ) value.getString() ) ); } } return srr; } else { // The search result is NOT a referral SearchResultEntryDsml sre = new SearchResultEntryDsml( codec ); sre.setEntry( entry ); return sre; } } /** * Indicates if the given entry is a referral. * * @param entry * the entry * @return * <code>true</code> if the given entry is a referral, <code>false</code> if not */ private static boolean isReferral( Entry entry ) { if ( entry != null ) { // Getting the 'objectClass' Attribute Attribute objectClassAttribute = entry.get( ExportDsmlRunnable.OBJECTCLASS_OBJECTCLASS_NAME ); if ( objectClassAttribute == null ) { objectClassAttribute = entry.get( ExportDsmlRunnable.OBJECTCLASS_OBJECTCLASS_OID ); } if ( objectClassAttribute != null ) { // Checking if the 'objectClass' attribute contains the // 'referral' object class as value return ( ( objectClassAttribute.contains( ExportDsmlRunnable.REFERRAL_OBJECTCLASS_NAME ) ) || ( objectClassAttribute .contains( ExportDsmlRunnable.REFERRAL_OBJECTCLASS_OID ) ) ); } } return false; } /** * Processes the {@link StudioSearchResultEnumeration} as a DSML request. * * @param sre * the search result enumeration * @param monitor * the monitor * @return * the associated DSML * @throws LdapException */ private String processAsDsmlRequest( StudioSearchResultEnumeration sre, StudioProgressMonitor monitor ) throws LdapException { // Creating the batch request BatchRequestDsml batchRequest = new BatchRequestDsml(); try { int count = 0; if ( !monitor.errorsReported() ) { // Creating and adding an add request for each result while ( sre.hasMore() ) { Entry entry = sre.next().getEntry(); AddRequestDsml arDsml = convertToAddRequestDsml( entry ); batchRequest.addRequest( arDsml ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException e ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( e ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // ignore } else { monitor.reportError( e ); } } // Returning the associated DSML return batchRequest.toDsml(); } /** * Converts the given {@link SearchResult} to an {@link AddRequestDsml}. * * @param entry2 * the {@link SearchResult} * @return * the associated {@link AddRequestDsml} * @throws LdapException */ private AddRequestDsml convertToAddRequestDsml( Entry entry ) throws LdapException { AddRequestDsml ar = new AddRequestDsml( codec ); ar.setEntry( entry ); return ar; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.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.ldapbrowser.core.jobs; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.naming.directory.SearchControls; import org.apache.commons.codec.digest.DigestUtils; import org.apache.directory.api.dsmlv2.DsmlDecorator; import org.apache.directory.api.dsmlv2.Dsmlv2Parser; import org.apache.directory.api.dsmlv2.request.BatchRequestDsml; import org.apache.directory.api.dsmlv2.request.Dsmlv2Grammar; import org.apache.directory.api.dsmlv2.response.AddResponseDsml; import org.apache.directory.api.dsmlv2.response.BatchResponseDsml; import org.apache.directory.api.dsmlv2.response.BindResponseDsml; import org.apache.directory.api.dsmlv2.response.CompareResponseDsml; import org.apache.directory.api.dsmlv2.response.DelResponseDsml; import org.apache.directory.api.dsmlv2.response.ExtendedResponseDsml; import org.apache.directory.api.dsmlv2.response.ModDNResponseDsml; import org.apache.directory.api.dsmlv2.response.ModifyResponseDsml; import org.apache.directory.api.ldap.codec.api.LdapApiService; import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.exception.LdapURLEncodingException; import org.apache.directory.api.ldap.model.message.AddRequest; import org.apache.directory.api.ldap.model.message.BindRequest; import org.apache.directory.api.ldap.model.message.CompareRequest; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.DeleteRequest; import org.apache.directory.api.ldap.model.message.ExtendedRequest; import org.apache.directory.api.ldap.model.message.LdapResult; import org.apache.directory.api.ldap.model.message.Message; import org.apache.directory.api.ldap.model.message.MessageTypeEnum; import org.apache.directory.api.ldap.model.message.ModifyDnRequest; import org.apache.directory.api.ldap.model.message.ModifyRequest; import org.apache.directory.api.ldap.model.message.Request; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; import org.apache.directory.api.ldap.model.message.SearchRequest; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.io.LdapRuntimeException; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; /** * Runnable to import a DSML File into a LDAP server * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List<DsmlDecorator<? extends Request>> requests = batchRequest.getRequests(); for ( DsmlDecorator<? extends Request> request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator<? extends Request> request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry, getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName(), request.getModifications(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { Dn newDn; try { if ( request.isMove() ) { newDn = new Dn( request.getNewRdn(), request.getNewSuperior() ); } else { newDn = new Dn( request.getNewRdn(), request.getName().getParent() ); } } catch ( LdapInvalidDnException e ) { throw new LdapRuntimeException( e ); } // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName(), newDn, request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioSearchResultEnumeration sre = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( sre, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List<String> returningAttributes = new ArrayList<String>(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection<Control> controls = request.getControls().values(); if ( controls != null ) { return controls.toArray( new Control[0] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ReloadSchemaRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ReloadSchemaRunnable.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.ldapbrowser.core.jobs; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BrowserConnectionUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; /** * Runnable to reload the schema. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ReloadSchemaRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** * Creates a new instance of ReloadSchemaRunnable. * * @param browserConnection the browser connection */ public ReloadSchemaRunnable( IBrowserConnection browserConnection ) { this.browserConnection = browserConnection; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__reload_schemas_name_1; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new IBrowserConnection[] { browserConnection }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__reload_schemas_error_1; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", 3 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__reload_schemas_task, new String[] { browserConnection.getConnection().getName() } ) ); monitor.worked( 1 ); // load schema monitor.reportProgress( BrowserCoreMessages.model__loading_schema ); reloadSchema( true, browserConnection, monitor ); monitor.worked( 1 ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { BrowserConnectionUpdateEvent browserConnectionUpdateEvent = new BrowserConnectionUpdateEvent( browserConnection, BrowserConnectionUpdateEvent.Detail.SCHEMA_UPDATED ); EventRegistry.fireBrowserConnectionUpdated( browserConnectionUpdateEvent, this ); } /** * Reloads the schema. * * @param forceReload true to force the reload of the schema, otherwise it would only be reloaded * if the server-side schema is newer than the cached schema. * @param browserConnection the browser connection * @param monitor the progress monitor */ public static void reloadSchema( boolean forceReload, IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { Dn schemaLocation = getSchemaLocation( browserConnection, monitor ); if ( schemaLocation == null ) { monitor.reportError( BrowserCoreMessages.model__missing_schema_location ); return; } Schema schema = browserConnection.getSchema(); boolean mustReload = forceReload || ( schema == Schema.DEFAULT_SCHEMA ) || mustReload( schemaLocation, browserConnection, monitor ); if ( mustReload ) { browserConnection.setSchema( Schema.DEFAULT_SCHEMA ); try { SearchParameter sp = new SearchParameter(); sp.setSearchBase( schemaLocation ); sp.setFilter( Schema.SCHEMA_FILTER ); sp.setScope( SearchScope.OBJECT ); sp.setReturningAttributes( new String[] { SchemaConstants.OBJECT_CLASSES_AT, SchemaConstants.ATTRIBUTE_TYPES_AT, SchemaConstants.LDAP_SYNTAXES_AT, SchemaConstants.MATCHING_RULES_AT, SchemaConstants.MATCHING_RULE_USE_AT, SchemaConstants.CREATE_TIMESTAMP_AT, SchemaConstants.MODIFY_TIMESTAMP_AT } ); LdifEnumeration le = ExportLdifRunnable.search( browserConnection, sp, monitor ); if ( le.hasNext() ) { LdifContentRecord schemaRecord = ( LdifContentRecord ) le.next(); schema = new Schema(); schema.loadFromRecord( schemaRecord ); browserConnection.setSchema( schema ); } else { monitor.reportError( BrowserCoreMessages.model__no_schema_information ); } } catch ( Exception e ) { monitor.reportError( BrowserCoreMessages.model__error_loading_schema, e ); e.printStackTrace(); } } } /** * Checks if the schema must be reloaded * * @param browserConnection the browser connection * @param monitor the progress monitor */ private static boolean mustReload( Dn schemaLocation, IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { Schema schema = browserConnection.getSchema(); try { SearchParameter sp = new SearchParameter(); sp.setSearchBase( schemaLocation ); sp.setFilter( Schema.SCHEMA_FILTER ); sp.setScope( SearchScope.OBJECT ); sp.setReturningAttributes( new String[] { SchemaConstants.CREATE_TIMESTAMP_AT, SchemaConstants.MODIFY_TIMESTAMP_AT } ); StudioSearchResultEnumeration enumeration = SearchRunnable.search( browserConnection, sp, monitor ); while ( enumeration != null && enumeration.hasMore() ) { String createTimestamp = null; String modifyTimestamp = null; Entry entry = enumeration.next().getEntry(); if ( entry.hasObjectClass( SchemaConstants.MODIFY_TIMESTAMP_AT ) ) { modifyTimestamp = entry.get( SchemaConstants.MODIFY_TIMESTAMP_AT ).getString(); } if ( entry.hasObjectClass( SchemaConstants.CREATE_TIMESTAMP_AT ) ) { createTimestamp = entry.get( SchemaConstants.CREATE_TIMESTAMP_AT ).getString(); } String schemaTimestamp = modifyTimestamp != null ? modifyTimestamp : createTimestamp; String cacheTimestamp = schema.getModifyTimestamp() != null ? schema.getModifyTimestamp() : schema .getCreateTimestamp(); if ( cacheTimestamp != null && schemaTimestamp != null && schemaTimestamp.compareTo( cacheTimestamp ) > 0 ) { return true; } } } catch ( Exception e ) { monitor.reportError( BrowserCoreMessages.model__error_loading_schema, e ); e.printStackTrace(); } return false; } private static Dn getSchemaLocation( IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { try { SearchParameter sp = new SearchParameter(); sp.setSearchBase( new Dn() ); sp.setScope( SearchScope.OBJECT ); sp.setReturningAttributes( new String[] { SchemaConstants.SUBSCHEMA_SUBENTRY_AT } ); StudioSearchResultEnumeration enumeration = SearchRunnable.search( browserConnection, sp, monitor ); while ( enumeration != null && enumeration.hasMore() ) { Entry entry = enumeration.next().getEntry(); if ( entry.containsAttribute( SchemaConstants.SUBSCHEMA_SUBENTRY_AT ) ) { String value = entry.get( SchemaConstants.SUBSCHEMA_SUBENTRY_AT ).getString(); if ( Dn.isValid( value ) ) { Dn dn = new Dn( value ); return dn; } } } } catch ( Exception e ) { monitor.reportError( BrowserCoreMessages.model__error_loading_schema, e ); 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/RenameEntryRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/RenameEntryRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.directory.SearchControls; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.EntryRenamedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; /** * Runnable to rename an entry. * * First it tries to rename an entry using an modrdn operation. If * that operation fails with an LDAP error 66 (ContextNotEmptyException) * the use is asked if s/he wants to simulate such a rename by recursively * searching/creating/deleting entries. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class RenameEntryRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** The old entry. */ private IEntry oldEntry; /** The new Rdn. */ private Rdn newRdn; /** The new entry. */ private IEntry newEntry; /** The updated searches. */ private Set<ISearch> searchesToUpdateSet = new HashSet<ISearch>(); /** The dialog to ask for simulated renaming */ private SimulateRenameDialog dialog; /** * Creates a new instance of RenameEntryRunnable. * * @param entry the entry to rename * @param newRdn the new Rdn * @param dialog the dialog */ public RenameEntryRunnable( IEntry entry, Rdn newRdn, SimulateRenameDialog dialog ) { this.browserConnection = entry.getBrowserConnection(); this.oldEntry = entry; this.newEntry = null; this.newRdn = newRdn; this.dialog = dialog; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__rename_entry_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.add( oldEntry.getParententry() ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__rename_entry_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__rename_entry_task, new String[] { oldEntry.getDn().getName() } ), 3 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); Dn oldDn = oldEntry.getDn(); Dn parentDn = oldDn.getParent(); Dn newDn = null; try { newDn = parentDn.add( newRdn ); } catch ( LdapInvalidDnException lide ) { newDn = Dn.EMPTY_DN; } // use a dummy monitor to be able to handle exceptions StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // try to rename entry renameEntry( browserConnection, oldEntry, newDn, dummyMonitor ); // do a simulated rename, if renaming of a non-leaf entry is not supported. if ( dummyMonitor.errorsReported() && !monitor.isCanceled() ) { if ( dialog != null && StudioLdapException.isContextNotEmptyException( dummyMonitor.getException() ) ) { // open dialog dialog.setEntryInfo( browserConnection, oldDn, newDn ); dialog.open(); boolean isSimulatedRename = dialog.isSimulateRename(); if ( isSimulatedRename ) { // do simulated rename operation dummyMonitor.reset(); CopyEntriesRunnable.copyEntry( oldEntry, oldEntry.getParententry(), newRdn, SearchControls.SUBTREE_SCOPE, 0, null, dummyMonitor, monitor ); if ( !dummyMonitor.errorsReported() ) { dummyMonitor.reset(); DeleteEntriesRunnable.optimisticDeleteEntryRecursive( browserConnection, oldDn, oldEntry.isReferral(), false, 0, dummyMonitor, monitor ); } } else { // no simulated rename operation // report the exception to the real monitor Exception exception = dummyMonitor.getException(); monitor.reportError( exception ); } } else { // we have another exception // report it to the real monitor Exception exception = dummyMonitor.getException(); monitor.reportError( exception ); } } // update model if ( !monitor.errorsReported() && !monitor.isCanceled() ) { // uncache old entry browserConnection.uncacheEntryRecursive( oldEntry ); // remove old entry and add new entry to parent IEntry parent = oldEntry.getParententry(); if ( parent != null ) { boolean hasMoreChildren = parent.hasMoreChildren(); parent.deleteChild( oldEntry ); List<Control> controls = new ArrayList<>(); if ( oldEntry.isReferral() ) { controls.add( Controls.MANAGEDSAIT_CONTROL ); } // Here we try to read the renamed entry to be able to send the right event notification. // In some cases this don't work: // - if there was a referral and the entry was created on another (master) server and not yet sync'ed to the current server // So we use a dummy monitor to no bother the user with an error message. dummyMonitor.reset(); newEntry = ReadEntryRunnable.getEntry( browserConnection, newDn, controls, dummyMonitor ); dummyMonitor.done(); if ( newEntry != null ) { parent.addChild( newEntry ); } parent.setHasMoreChildren( hasMoreChildren ); // reset searches, if the renamed entry is a result of a search List<ISearch> searches = browserConnection.getSearchManager().getSearches(); for ( ISearch search : searches ) { if ( search.getSearchResults() != null ) { ISearchResult[] searchResults = search.getSearchResults(); for ( ISearchResult result : searchResults ) { if ( oldEntry.equals( result.getEntry() ) ) { search.setSearchResults( null ); searchesToUpdateSet.add( search ); break; } } } } } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { if ( oldEntry != null && newEntry != null ) { EventRegistry.fireEntryUpdated( new EntryRenamedEvent( oldEntry, newEntry ), this ); for ( ISearch search : searchesToUpdateSet ) { EventRegistry.fireSearchUpdated( new SearchUpdateEvent( search, SearchUpdateEvent.EventDetail.SEARCH_PERFORMED ), this ); } } } /** * Moves/Renames an entry. * * @param browserConnection the browser connection * @param entry the entry to move/rename * @param newDn the new Dn * @param monitor the progress monitor */ static void renameEntry( IBrowserConnection browserConnection, IEntry entry, Dn newDn, StudioProgressMonitor monitor ) { // ManageDsaIT control Control[] controls = null; if ( entry.isReferral() ) { controls = new Control[] { Controls.MANAGEDSAIT_CONTROL }; } if ( browserConnection.getConnection() != null ) { browserConnection.getConnection().getConnectionWrapper() .renameEntry( entry.getDn(), newDn, true, controls, monitor, 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/SimulateRenameDialog.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/SimulateRenameDialog.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.ldapbrowser.core.jobs; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; /** * A dialog used to ask the user to simulate the rename operation by * recursively searching/adding/deleting. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface SimulateRenameDialog { /** * Sets the existing entry. * * @param browserConnection the browser connection * @param oldDn the old Dn * @param newDn the new Dn */ void setEntryInfo( IBrowserConnection browserConnection, Dn oldDn, Dn newDn ); /** * Opens the dialog. * * @return the status code */ int open(); /** * Returns true to simulate the rename operation. * * @return true, to simulate the rename operation */ boolean isSimulateRename(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportLdifRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ExportLdifRunnable.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.ldapbrowser.core.jobs; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.controls.PagedResults; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IValue; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry; import org.apache.directory.studio.ldapbrowser.core.utils.AttributeComparator; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.ldifparser.LdifFormatParameters; import org.apache.directory.studio.ldifparser.model.LdifEnumeration; import org.apache.directory.studio.ldifparser.model.container.LdifContainer; import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord; import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine; import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine; import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine; import org.apache.directory.studio.ldifparser.model.lines.LdifVersionLine; /** * Runnable to export directory content to an LDIF file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ExportLdifRunnable implements StudioConnectionRunnableWithProgress { /** The filename of the LDIF file. */ private String exportLdifFilename; /** The browser connection. */ private IBrowserConnection browserConnection; /** The search parameter. */ private SearchParameter searchParameter; /** * Creates a new instance of ExportLdifRunnable. * * @param exportLdifFilename the filename of the LDIF file * @param browserConnection the browser connection * @param searchParameter the search parameter */ public ExportLdifRunnable( String exportLdifFilename, IBrowserConnection browserConnection, SearchParameter searchParameter ) { this.exportLdifFilename = exportLdifFilename; this.browserConnection = browserConnection; this.searchParameter = searchParameter; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__export_ldif_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( exportLdifFilename ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__export_ldif_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__export_ldif_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // open file FileWriter fileWriter = new FileWriter( exportLdifFilename ); BufferedWriter bufferedWriter = new BufferedWriter( fileWriter ); // export int count = 0; export( browserConnection, searchParameter, bufferedWriter, count, monitor ); // close file bufferedWriter.close(); fileWriter.close(); } catch ( Exception e ) { monitor.reportError( e ); } } private static void export( IBrowserConnection browserConnection, SearchParameter searchParameter, BufferedWriter bufferedWriter, int count, StudioProgressMonitor monitor ) throws IOException { try { LdifEnumeration enumeration = search( browserConnection, searchParameter, monitor ); LdifFormatParameters ldifFormatParameters = Utils.getLdifFormatParameters(); // add version spec if ( BrowserCorePlugin.getDefault().getPluginPreferences() .getBoolean( BrowserCoreConstants.PREFERENCE_LDIF_INCLUDE_VERSION_LINE ) ) { LdifVersionLine ldifVersionLine = LdifVersionLine.create(); String ldifVersionLineString = ldifVersionLine.toFormattedString( ldifFormatParameters ); bufferedWriter.write( ldifVersionLineString ); LdifSepLine ldifSepLine = LdifSepLine.create(); String ldifSepLineString = ldifSepLine.toFormattedString( ldifFormatParameters ); bufferedWriter.write( ldifSepLineString ); } // add the records while ( !monitor.isCanceled() && !monitor.errorsReported() && enumeration.hasNext() ) { LdifContainer container = enumeration.next(); if ( container instanceof LdifContentRecord ) { LdifContentRecord record = ( LdifContentRecord ) container; LdifDnLine dnLine = record.getDnLine(); LdifSepLine sepLine = record.getSepLine(); // sort and format DummyEntry entry = ModelConverter.ldifContentRecordToEntry( record, browserConnection ); List<IValue> sortedValues = AttributeComparator.toSortedValues( entry ); LdifContentRecord newRecord = new LdifContentRecord( dnLine ); for ( IValue value : sortedValues ) { newRecord.addAttrVal( ModelConverter.valueToLdifAttrValLine( value ) ); } newRecord.finish( sepLine ); String s = newRecord.toFormattedString( ldifFormatParameters ); // String s = record.toFormattedString(); bufferedWriter.write( s ); count++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__export_progress, new String[] { Integer.toString( count ) } ) ); } } } catch ( LdapException loe ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( loe ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // ignore } else { monitor.reportError( loe ); } } } static LdifEnumeration search( IBrowserConnection browserConnection, SearchParameter parameter, StudioProgressMonitor monitor ) { StudioSearchResultEnumeration result = SearchRunnable.search( browserConnection, parameter, monitor ); return new DefaultLdifEnumeration( result, browserConnection, parameter, monitor ); } static class DefaultLdifEnumeration implements LdifEnumeration { private StudioSearchResultEnumeration enumeration; private IBrowserConnection browserConnection; private SearchParameter parameter; private StudioProgressMonitor monitor; public DefaultLdifEnumeration( StudioSearchResultEnumeration enumeration, IBrowserConnection browserConnection, SearchParameter parameter, StudioProgressMonitor monitor ) { this.enumeration = enumeration; this.browserConnection = browserConnection; this.parameter = parameter; this.monitor = monitor; } public boolean hasNext() throws LdapException { if ( enumeration != null ) { if ( enumeration.hasMore() ) { return true; } for ( Control responseControl : enumeration.getResponseControls() ) { if ( responseControl instanceof PagedResults ) { PagedResults prc = ( PagedResults ) responseControl; if ( ArrayUtils.isNotEmpty( prc.getCookie() ) ) { // search again: pass the response control cookie to the request control byte[] cookie = prc.getCookie(); for ( Control requestControl : parameter.getControls() ) { if ( requestControl instanceof PagedResults ) { ( ( PagedResults ) requestControl ).setCookie( cookie ); } } enumeration = SearchRunnable.search( browserConnection, parameter, monitor ); return enumeration != null && enumeration.hasMore(); } } } } return false; } public LdifContainer next() throws LdapException { Entry entry = enumeration.next().getEntry(); Dn dn = entry.getDn(); LdifContentRecord record = LdifContentRecord.create( dn.getName() ); for ( Attribute attribute : entry ) { String attributeName = attribute.getUpId(); for ( Value value : attribute ) { if ( value.isHumanReadable() ) { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getString() ) ); } else { record.addAttrVal( LdifAttrValLine.create( attributeName, value.getBytes() ) ); } } } record.finish( LdifSepLine.create() ); return record; } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/MoveEntriesRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/MoveEntriesRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.directory.SearchControls; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EntryMovedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; /** * Runnable to move entries. * * First it tries to move an entry using an moddn operation. If * that operation fails with an LDAP error 66 (ContextNotEmptyException) * the use is asked if s/he wants to simulate such a move by recursively * searching/creating/deleting entries. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class MoveEntriesRunnable implements StudioConnectionBulkRunnableWithProgress { /** The browser connection. */ private IBrowserConnection browserConnection; /** The entries to move. */ private IEntry[] oldEntries; /** The new parent. */ private IEntry newParent; /** The moved entries. */ private IEntry[] newEntries; /** The searches to update. */ private Set<ISearch> searchesToUpdateSet = new HashSet<ISearch>(); /** The dialog to ask for simulated renaming */ private SimulateRenameDialog dialog; /** * Creates a new instance of MoveEntriesRunnable. * * @param entries the entries to move * @param newParent the new parent * @param dialog the dialog */ public MoveEntriesRunnable( IEntry[] entries, IEntry newParent, SimulateRenameDialog dialog ) { this.browserConnection = newParent.getBrowserConnection(); this.oldEntries = entries; this.newParent = newParent; this.dialog = dialog; this.newEntries = new IEntry[oldEntries.length]; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return oldEntries.length == 1 ? BrowserCoreMessages.jobs__move_entry_name_1 : BrowserCoreMessages.jobs__move_entry_name_n; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<IEntry> l = new ArrayList<IEntry>(); l.add( newParent ); l.addAll( Arrays.asList( oldEntries ) ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return oldEntries.length == 1 ? BrowserCoreMessages.jobs__move_entry_error_1 : BrowserCoreMessages.jobs__move_entry_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.bind( oldEntries.length == 1 ? BrowserCoreMessages.jobs__move_entry_task_1 : BrowserCoreMessages.jobs__move_entry_task_n, new String[] {} ), 3 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); // use a dummy monitor to be able to handle exceptions StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); int numAdd = 0; int numDel = 0; boolean isSimulatedRename = false; Dn parentDn = newParent.getDn(); for ( int i = 0; i < oldEntries.length; i++ ) { dummyMonitor.reset(); IEntry oldEntry = oldEntries[i]; Dn oldDn = oldEntry.getDn(); Dn newDn = null; try { newDn = parentDn.add( oldDn.getRdn() ); } catch ( LdapInvalidDnException lide ) { newDn = Dn.EMPTY_DN; } // try to move entry RenameEntryRunnable.renameEntry( browserConnection, oldEntry, newDn, dummyMonitor ); // do a simulated rename, if renaming of a non-leaf entry is not supported. if ( dummyMonitor.errorsReported() ) { if ( dialog != null && StudioLdapException.isContextNotEmptyException( dummyMonitor.getException() ) ) { // open dialog if ( numAdd == 0 ) { dialog.setEntryInfo( browserConnection, oldDn, newDn ); dialog.open(); isSimulatedRename = dialog.isSimulateRename(); } if ( isSimulatedRename ) { // do simulated rename operation dummyMonitor.reset(); numAdd = CopyEntriesRunnable.copyEntry( oldEntry, newParent, null, SearchControls.SUBTREE_SCOPE, numAdd, null, dummyMonitor, monitor ); if ( !dummyMonitor.errorsReported() ) { dummyMonitor.reset(); numDel = DeleteEntriesRunnable.optimisticDeleteEntryRecursive( browserConnection, oldDn, oldEntry.isReferral(), false, numDel, dummyMonitor, monitor ); } } else { // no simulated rename operation // report the exception to the real monitor Exception exception = dummyMonitor.getException(); monitor.reportError( exception ); } } else { // we have another exception // report it to the real monitor Exception exception = dummyMonitor.getException(); monitor.reportError( exception ); } } // update model if ( !dummyMonitor.errorsReported() ) { // uncache old entry browserConnection.uncacheEntryRecursive( oldEntry ); // remove old entry from old parent oldEntry.getParententry().deleteChild( oldEntry ); // add new entry to new parent boolean hasMoreChildren = newParent.hasMoreChildren() || !newParent.isChildrenInitialized(); List<Control> controls = new ArrayList<>(); if ( oldEntry.isReferral() ) { controls.add( Controls.MANAGEDSAIT_CONTROL ); } IEntry newEntry = ReadEntryRunnable.getEntry( browserConnection, newDn, controls, monitor ); newEntries[i] = newEntry; newParent.addChild( newEntry ); newParent.setHasMoreChildren( hasMoreChildren ); // reset searches, if the moved entry is a result of a search List<ISearch> searches = browserConnection.getSearchManager().getSearches(); for ( ISearch search : searches ) { if ( search.getSearchResults() != null ) { ISearchResult[] searchResults = search.getSearchResults(); for ( ISearchResult result : searchResults ) { if ( oldEntry.equals( result.getEntry() ) ) { search.setSearchResults( null ); searchesToUpdateSet.add( search ); break; } } } } } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { // notify the entries and their parents if ( newEntries.length < 2 ) { // notify fore each moved entry for ( int i = 0; i < newEntries.length; i++ ) { if ( oldEntries[i] != null && newEntries[i] != null ) { EventRegistry.fireEntryUpdated( new EntryMovedEvent( oldEntries[i], newEntries[i] ), this ); } } } else { // reset the old and new parents and send only a bulk update event // notifying for each moved entry would cause lot of UI updates... for ( IEntry oldEntry : oldEntries ) { oldEntry.getParententry().setChildrenInitialized( false ); } newParent.setChildrenInitialized( false ); EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/CopyEntriesRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/CopyEntriesRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.naming.directory.SearchControls; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Modification; import org.apache.directory.api.ldap.model.exception.LdapEntryAlreadyExistsException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Ava; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.jobs.EntryExistsCopyStrategyDialog.EntryExistsCopyStrategy; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter; /** * Runnable to copy entries asynchronously. * * TODO: implement overwrite strategy * TODO: implement remember selection * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class CopyEntriesRunnable implements StudioConnectionBulkRunnableWithProgress { /** The parent entry. */ private IEntry parent; /** The entries to copy. */ private IEntry[] entriesToCopy; /** The copy scope */ private SearchScope scope; /** The dialog to ask for the strategy */ private EntryExistsCopyStrategyDialog dialog; /** * Creates a new instance of CopyEntriesRunnable. * * @param parent the parent entry * @param entriesToCopy the entries to copy * @param scope the copy scope * @param dialog the dialog */ public CopyEntriesRunnable( final IEntry parent, final IEntry[] entriesToCopy, SearchScope scope, EntryExistsCopyStrategyDialog dialog ) { this.parent = parent; this.entriesToCopy = entriesToCopy; this.scope = scope; this.dialog = dialog; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { parent.getBrowserConnection().getConnection() }; } /** * {@inheritDoc} */ public String getName() { return entriesToCopy.length == 1 ? BrowserCoreMessages.jobs__copy_entries_name_1 : BrowserCoreMessages.jobs__copy_entries_name_n; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<IEntry> l = new ArrayList<>(); l.add( parent ); l.addAll( Arrays.asList( entriesToCopy ) ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return entriesToCopy.length == 1 ? BrowserCoreMessages.jobs__copy_entries_error_1 : BrowserCoreMessages.jobs__copy_entries_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( entriesToCopy.length == 1 ? BrowserCoreMessages.bind( BrowserCoreMessages.jobs__copy_entries_task_1, new String[] { entriesToCopy[0].getDn().getName(), parent.getDn().getName() } ) : BrowserCoreMessages.bind( BrowserCoreMessages.jobs__copy_entries_task_n, new String[] { Integer.toString( entriesToCopy.length ), parent.getDn().getName() } ), 2 + entriesToCopy.length ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); if ( scope == SearchScope.OBJECT || scope == SearchScope.ONELEVEL || scope == SearchScope.SUBTREE ) { StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); int copyScope = scope == SearchScope.SUBTREE ? SearchControls.SUBTREE_SCOPE : scope == SearchScope.ONELEVEL ? SearchControls.ONELEVEL_SCOPE : SearchControls.OBJECT_SCOPE; int num = 0; for ( int i = 0; !monitor.isCanceled() && i < entriesToCopy.length; i++ ) { IEntry entryToCopy = entriesToCopy[i]; if ( scope == SearchScope.OBJECT || !parent.getDn().getNormName().endsWith( entryToCopy.getDn().getNormName() ) ) { dummyMonitor.reset(); num = copyEntry( entryToCopy, parent, null, copyScope, num, dialog, dummyMonitor, monitor ); } else { monitor.reportError( BrowserCoreMessages.jobs__copy_entries_source_and_target_are_equal ); } } parent.setChildrenInitialized( false ); parent.setHasChildrenHint( true ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { // don't fire an EntryCreatedEvent for each created entry // that would cause massive UI updates // instead we fire a BulkModificationEvent EventRegistry.fireEntryUpdated( new BulkModificationEvent( parent.getBrowserConnection() ), this ); } /** * Copy entry. If scope is SearchControls.SUBTREE_SCOPE the entry is copied * recursively. * * @param browserConnection the browser connection * @param dnToCopy the Dn to copy * @param parentDn the parent Dn * @param newRdn the new Rdn, if null the Rdn of dnToCopy is used * @param scope the copy scope * @param numberOfCopiedEntries the number of copied entries * @param dialog the dialog to ask for the copy strategy, if null the user won't be * asked instead the NameAlreadyBoundException it reported to the monitor * @param dummyMonitor the dummy monitor, used for I/O that causes exceptions that * should be handled * @param monitor the real monitor * * @return the number of copied entries */ static int copyEntry( IEntry entryToCopy, IEntry parent, Rdn newRdn, int scope, int numberOfCopiedEntries, EntryExistsCopyStrategyDialog dialog, StudioProgressMonitor dummyMonitor, StudioProgressMonitor monitor ) { SearchControls searchControls = new SearchControls(); searchControls.setCountLimit( 1 ); searchControls.setReturningAttributes( new String[] { SchemaConstants.ALL_USER_ATTRIBUTES } ); searchControls.setSearchScope( SearchControls.OBJECT_SCOPE ); // handle special entries org.apache.directory.api.ldap.model.message.Control[] controls = null; if ( entryToCopy.isReferral() ) { controls = new org.apache.directory.api.ldap.model.message.Control[] { Controls.MANAGEDSAIT_CONTROL }; searchControls.setReturningAttributes( new String[] { SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.REF_AT } ); } if ( entryToCopy.isSubentry() ) { searchControls.setReturningAttributes( new String[] { SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.SUBTREE_SPECIFICATION_AT } ); } StudioSearchResultEnumeration result = entryToCopy .getBrowserConnection() .getConnection() .getConnectionWrapper() .search( entryToCopy.getDn().getName(), ISearch.FILTER_TRUE, searchControls, AliasDereferencingMethod.NEVER, ReferralHandlingMethod.IGNORE, controls, monitor, null ); // In case the parent is the RootDSE: use the parent Dn of the old entry Dn parentDn = parent.getDn(); if ( parentDn.isEmpty() ) { parentDn = entryToCopy.getDn().getParent(); } numberOfCopiedEntries = copyEntryRecursive( entryToCopy.getBrowserConnection(), result, parent.getBrowserConnection(), parentDn, newRdn, scope, numberOfCopiedEntries, dialog, dummyMonitor, monitor ); return numberOfCopiedEntries; } /** * Copy the entries. If scope is SearchControls.SUBTREE_SCOPE the entries are copied * recursively. * * @param sourceBrowserConnection the source browser connection * @param entries the source entries to copy * @param targetBrowserConnection the target browser connection * @param parentDn the target parent Dn * @param newRdn the new Rdn, if null the original Rdn of each entry is used * @param scope the copy scope * @param numberOfCopiedEntries the number of copied entries * @param dialog the dialog to ask for the copy strategy, if null the user won't be * asked instead the NameAlreadyBoundException it reported to the monitor * @param dummyMonitor the dummy monitor, used for I/O that causes exceptions that * should be handled * @param monitor the real monitor * * @return the number of copied entries */ static int copyEntryRecursive( IBrowserConnection sourceBrowserConnection, StudioSearchResultEnumeration entries, IBrowserConnection targetBrowserConnection, Dn parentDn, Rdn forceNewRdn, int scope, int numberOfCopiedEntries, EntryExistsCopyStrategyDialog dialog, StudioProgressMonitor dummyMonitor, StudioProgressMonitor monitor ) { try { while ( !monitor.isCanceled() && entries.hasMore() ) { // get next entry to copy Entry entry = entries.next().getEntry(); Dn oldLdapDn = entry.getDn(); Rdn oldRdn = oldLdapDn.getRdn(); // compose new Dn Rdn newRdn = oldLdapDn.getRdn(); if ( forceNewRdn != null ) { newRdn = forceNewRdn; } Dn newLdapDn = parentDn.add( newRdn ); entry.setDn( newLdapDn ); // apply new Rdn to the attributes applyNewRdn( entry, oldRdn, newRdn ); // ManageDsaIT control Control[] controls = null; if ( entry.hasObjectClass( SchemaConstants.REFERRAL_OC ) ) { controls = new Control[] { Controls.MANAGEDSAIT_CONTROL }; } // create entry targetBrowserConnection.getConnection().getConnectionWrapper() .createEntry( entry, controls, dummyMonitor, null ); while ( dummyMonitor.errorsReported() ) { if ( dialog != null && StudioLdapException.isEntryAlreadyExistsException( dummyMonitor.getException() ) ) { // open dialog dialog.setExistingEntry( targetBrowserConnection, newLdapDn ); dialog.open(); EntryExistsCopyStrategy strategy = dialog.getStrategy(); if ( strategy != null ) { dummyMonitor.reset(); switch ( strategy ) { case BREAK: monitor.setCanceled( true ); break; case IGNORE_AND_CONTINUE: break; case OVERWRITE_AND_CONTINUE: // create modifications Collection<Modification> modifications = ModelConverter .toReplaceModifications( entry ); // modify entry targetBrowserConnection .getConnection() .getConnectionWrapper() .modifyEntry( newLdapDn, modifications, null, dummyMonitor, null ); // force reload of attributes IEntry newEntry = targetBrowserConnection.getEntryFromCache( newLdapDn ); if ( newEntry != null ) { newEntry.setAttributesInitialized( false ); } break; case RENAME_AND_CONTINUE: Rdn renamedRdn = dialog.getRdn(); // apply renamed Rdn to the attributes applyNewRdn( entry, newRdn, renamedRdn ); // compose new Dn newLdapDn = parentDn.add( renamedRdn ); entry.setDn( newLdapDn ); // create entry targetBrowserConnection.getConnection().getConnectionWrapper() .createEntry( entry, null, dummyMonitor, null ); break; } } else { monitor.reportError( dummyMonitor.getException() ); break; } } else { monitor.reportError( dummyMonitor.getException() ); break; } } if ( !monitor.isCanceled() && !monitor.errorsReported() ) { numberOfCopiedEntries++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.model__copied_n_entries, new String[] { Integer.toString( numberOfCopiedEntries ) } ) ); //$NON-NLS-1$ // copy recursively if ( scope == SearchControls.ONELEVEL_SCOPE || scope == SearchControls.SUBTREE_SCOPE ) { SearchControls searchControls = new SearchControls(); searchControls.setCountLimit( 0 ); searchControls.setReturningAttributes( new String[] { SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.REF_AT } ); searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); StudioSearchResultEnumeration childEntries = sourceBrowserConnection .getConnection() .getConnectionWrapper() .search( oldLdapDn.getName(), ISearch.FILTER_TRUE, searchControls, AliasDereferencingMethod.NEVER, ReferralHandlingMethod.IGNORE, null, monitor, null ); if ( scope == SearchControls.ONELEVEL_SCOPE ) { scope = SearchControls.OBJECT_SCOPE; } numberOfCopiedEntries = copyEntryRecursive( sourceBrowserConnection, childEntries, targetBrowserConnection, newLdapDn, null, scope, numberOfCopiedEntries, dialog, dummyMonitor, monitor ); } } } } catch ( Exception e ) { monitor.reportError( e ); } return numberOfCopiedEntries; } private static void applyNewRdn( Entry entry, Rdn oldRdn, Rdn newRdn ) throws LdapException { // remove old Rdn attributes and values for ( Ava atav : oldRdn ) { entry.remove( atav.getType(), atav.getValue() ); } // add new Rdn attributes and values for ( Ava atav : newRdn ) { entry.add( atav.getType(), atav.getValue() ); } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/InitializeRootDSERunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; 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.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.DetectedConnectionProperties; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.AttributesInitializedEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.impl.BaseDNEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.DirectoryMetadataEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Search; /** * Runnable to initialize the Root DSE. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class InitializeRootDSERunnable implements StudioConnectionBulkRunnableWithProgress { /** The requested attributes when reading the Root DSE. */ public static final String[] ROOT_DSE_ATTRIBUTES = { SchemaConstants.NAMING_CONTEXTS_AT, SchemaConstants.SUBSCHEMA_SUBENTRY_AT, SchemaConstants.SUPPORTED_LDAP_VERSION_AT, SchemaConstants.SUPPORTED_SASL_MECHANISMS_AT, SchemaConstants.SUPPORTED_EXTENSION_AT, SchemaConstants.SUPPORTED_CONTROL_AT, SchemaConstants.SUPPORTED_FEATURES_AT, SchemaConstants.VENDOR_NAME_AT, SchemaConstants.VENDOR_VERSION_AT, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES }; private IRootDSE rootDSE; /** * Creates a new instance of InitializeRootDSERunnable. * * @param rootDSE the root DSE */ private InitializeRootDSERunnable( IRootDSE rootDSE ) { this.rootDSE = rootDSE; } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { rootDSE.getBrowserConnection().getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__init_entries_title_attonly; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { return new IEntry[] { rootDSE }; } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__init_entries_error_1; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", 3 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_task, new String[] { rootDSE.getDn().getName() } ) ); monitor.worked( 1 ); monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__init_entries_progress_att, new String[] { rootDSE.getDn().getName() } ) ); loadRootDSE( rootDSE.getBrowserConnection(), monitor ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new AttributesInitializedEvent( rootDSE ), this ); } /** * Loads the Root DSE. * * @param browserConnection the browser connection * @param monitor the progress monitor * * @throws Exception the exception */ public static synchronized void loadRootDSE( IBrowserConnection browserConnection, StudioProgressMonitor monitor ) { // clear old children InitializeChildrenRunnable.clearCaches( browserConnection.getRootDSE(), true ); // delete old attributes IAttribute[] oldAttributes = browserConnection.getRootDSE().getAttributes(); if ( oldAttributes != null ) { for ( IAttribute oldAttribute : oldAttributes ) { browserConnection.getRootDSE().deleteAttribute( oldAttribute ); } } // load well-known Root DSE attributes and operational attributes ISearch search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, ROOT_DSE_ATTRIBUTES, SearchScope.OBJECT, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null, false ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); // Load all user attributes. This is done because the BEA "LDAP server" (so called) is stupid // enough not to accept searches where "+" and "*" are provided on the list of parameters. // We have to do two searches... search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, new String[] { SchemaConstants.ALL_USER_ATTRIBUTES }, SearchScope.OBJECT, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null, false ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); // the list of entries under the Root DSE Map<Dn, IEntry> rootDseEntries = new HashMap<Dn, IEntry>(); // 1st: add base DNs, either the specified or from the namingContexts attribute if ( !browserConnection.isFetchBaseDNs() && browserConnection.getBaseDN() != null && !"".equals( browserConnection.getBaseDN().toString() ) ) //$NON-NLS-1$ { // only add the specified base Dn Dn dn = browserConnection.getBaseDN(); IEntry entry = browserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = new BaseDNEntry( dn, browserConnection ); browserConnection.cacheEntry( entry ); } rootDseEntries.put( dn, entry ); } else { // get base DNs from namingContexts attribute Set<String> namingContextSet = new HashSet<String>(); IAttribute attribute = browserConnection.getRootDSE().getAttribute( SchemaConstants.NAMING_CONTEXTS_AT ); if ( attribute != null ) { String[] values = attribute.getStringValues(); for ( int i = 0; i < values.length; i++ ) { namingContextSet.add( values[i] ); } } if ( !namingContextSet.isEmpty() ) { for ( String namingContext : namingContextSet ) { if ( namingContext.length() > 0 && namingContext.charAt( namingContext.length() - 1 ) == '\u0000' ) { namingContext = namingContext.substring( 0, namingContext.length() - 1 ); } if ( !"".equals( namingContext ) ) //$NON-NLS-1$ { try { Dn dn = new Dn( namingContext ); IEntry entry = browserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = new BaseDNEntry( dn, browserConnection ); browserConnection.cacheEntry( entry ); } rootDseEntries.put( dn, entry ); } catch ( LdapInvalidDnException e ) { monitor.reportError( BrowserCoreMessages.model__error_setting_base_dn, e ); } } else { // special handling of empty namingContext (Novell eDirectory): // perform a one-level search and add all result DNs to the set searchRootDseEntries( browserConnection, rootDseEntries, monitor ); } } } else { // special handling of non-existing namingContexts attribute (Oracle Internet Directory) // perform a one-level search and add all result DNs to the set searchRootDseEntries( browserConnection, rootDseEntries, monitor ); } } // 2nd: add schema sub-entry IEntry[] schemaEntries = getDirectoryMetadataEntries( browserConnection, SchemaConstants.SUBSCHEMA_SUBENTRY_AT ); for ( IEntry entry : schemaEntries ) { if ( entry instanceof DirectoryMetadataEntry ) { ( ( DirectoryMetadataEntry ) entry ).setSchemaEntry( true ); } rootDseEntries.put( entry.getDn(), entry ); } // get other meta data entries IAttribute[] rootDseAttributes = browserConnection.getRootDSE().getAttributes(); if ( rootDseAttributes != null ) { for ( IAttribute attribute : rootDseAttributes ) { IEntry[] metadataEntries = getDirectoryMetadataEntries( browserConnection, attribute.getDescription() ); for ( IEntry entry : metadataEntries ) { rootDseEntries.put( entry.getDn(), entry ); } } } // try to init entries StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); for ( IEntry entry : rootDseEntries.values() ) { initBaseEntry( entry, dummyMonitor ); } // set flags browserConnection.getRootDSE().setHasMoreChildren( false ); browserConnection.getRootDSE().setAttributesInitialized( true ); browserConnection.getRootDSE().setInitOperationalAttributes( true ); browserConnection.getRootDSE().setChildrenInitialized( true ); browserConnection.getRootDSE().setHasChildrenHint( true ); browserConnection.getRootDSE().setDirectoryEntry( true ); // Set detected connection properties DetectedConnectionProperties detectedConnectionProperties = browserConnection.getConnection() .getDetectedConnectionProperties(); IAttribute vendorNameAttribute = browserConnection.getRootDSE().getAttribute( "vendorName" ); //$NON-NLS-1$ if ( ( vendorNameAttribute != null ) && ( vendorNameAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setVendorName( vendorNameAttribute.getStringValue() ); } IAttribute vendorVersionAttribute = browserConnection.getRootDSE().getAttribute( "vendorVersion" ); //$NON-NLS-1$ if ( ( vendorVersionAttribute != null ) && ( vendorVersionAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setVendorVersion( vendorVersionAttribute.getStringValue() ); } IAttribute supportedControlAttribute = browserConnection.getRootDSE().getAttribute( "supportedControl" ); //$NON-NLS-1$ if ( ( supportedControlAttribute != null ) && ( supportedControlAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedControls( Arrays.asList( supportedControlAttribute .getStringValues() ) ); } IAttribute supportedExtensionAttribute = browserConnection.getRootDSE().getAttribute( "supportedExtension" ); //$NON-NLS-1$ if ( ( supportedExtensionAttribute != null ) && ( supportedExtensionAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedExtensions( Arrays.asList( supportedExtensionAttribute .getStringValues() ) ); } IAttribute supportedFeaturesAttribute = browserConnection.getRootDSE().getAttribute( "supportedFeatures" ); //$NON-NLS-1$ if ( ( supportedFeaturesAttribute != null ) && ( supportedFeaturesAttribute.getValueSize() > 0 ) ) { detectedConnectionProperties.setSupportedFeatures( Arrays.asList( supportedFeaturesAttribute .getStringValues() ) ); } detectedConnectionProperties .setServerType( ServerTypeDetector.detectServerType( browserConnection.getRootDSE() ) ); ConnectionCorePlugin.getDefault().getConnectionManager() .connectionUpdated( browserConnection.getConnection() ); } private static void initBaseEntry( IEntry entry, StudioProgressMonitor monitor ) { IBrowserConnection browserConnection = entry.getBrowserConnection(); Dn dn = entry.getDn(); // search the entry AliasDereferencingMethod derefAliasMethod = browserConnection.getAliasesDereferencingMethod(); ReferralHandlingMethod handleReferralsMethod = browserConnection.getReferralsHandlingMethod(); ISearch search = new Search( null, browserConnection, dn, ISearch.FILTER_TRUE, ISearch.NO_ATTRIBUTES, SearchScope.OBJECT, 1, 0, derefAliasMethod, handleReferralsMethod, true, null, false ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); ISearchResult[] results = search.getSearchResults(); if ( results != null && results.length == 1 ) { // add entry to Root DSE ISearchResult result = results[0]; entry = result.getEntry(); browserConnection.getRootDSE().addChild( entry ); } else { // Dn exists in the Root DSE, but doesn't exist in directory browserConnection.uncacheEntryRecursive( entry ); } } private static IEntry[] getDirectoryMetadataEntries( IBrowserConnection browserConnection, String metadataAttributeName ) { List<Dn> metadataEntryDnList = new ArrayList<Dn>(); IAttribute attribute = browserConnection.getRootDSE().getAttribute( metadataAttributeName ); if ( attribute != null ) { String[] values = attribute.getStringValues(); for ( String dn : values ) { if ( dn != null && !"".equals( dn ) ) //$NON-NLS-1$ { try { metadataEntryDnList.add( new Dn( dn ) ); } catch ( LdapInvalidDnException e ) { } } } } IEntry[] metadataEntries = new IEntry[metadataEntryDnList.size()]; for ( int i = 0; i < metadataEntryDnList.size(); i++ ) { Dn dn = metadataEntryDnList.get( i ); metadataEntries[i] = browserConnection.getEntryFromCache( dn ); if ( metadataEntries[i] == null ) { metadataEntries[i] = new DirectoryMetadataEntry( dn, browserConnection ); metadataEntries[i].setDirectoryEntry( true ); browserConnection.cacheEntry( metadataEntries[i] ); } } return metadataEntries; } private static void searchRootDseEntries( IBrowserConnection browserConnection, Map<Dn, IEntry> rootDseEntries, StudioProgressMonitor monitor ) { ISearch search = new Search( null, browserConnection, Dn.EMPTY_DN, ISearch.FILTER_TRUE, ISearch.NO_ATTRIBUTES, SearchScope.ONELEVEL, 0, 0, Connection.AliasDereferencingMethod.NEVER, Connection.ReferralHandlingMethod.IGNORE, false, null, false ); SearchRunnable.searchAndUpdateModel( browserConnection, search, monitor ); ISearchResult[] results = search.getSearchResults(); if ( results != null ) { for ( ISearchResult searchResult : results ) { IEntry entry = searchResult.getEntry(); rootDseEntries.put( entry.getDn(), entry ); } } } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/UpdateEntryRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/UpdateEntryRunnable.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.ldapbrowser.core.jobs; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.ldapbrowser.core.events.EntryModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; /** * Runnable to update an entry using an LDIF fragment. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class UpdateEntryRunnable extends ExecuteLdifRunnable { /** The entry */ private IEntry entry; /** * Creates a new instance of UpdateEntryRunnable. * * @param entry the entry * @param ldif the LDIF to execute */ public UpdateEntryRunnable( IEntry entry, String ldif ) { super( entry.getBrowserConnection(), ldif, false, false ); this.entry = entry; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { super.run( monitor ); if ( monitor.isCanceled() ) { // update attributes in any case, because the attributes are not initialized monitor.setCanceled( false ); } InitializeAttributesRunnable.initializeAttributes( entry, monitor ); } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new EntryModificationEvent( entry.getBrowserConnection(), entry ), this ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ServerTypeDetector.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ServerTypeDetector.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.ldapbrowser.core.jobs; import org.apache.directory.studio.connection.core.ConnectionServerType; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; /** * Utility class for detecting the type of server based on its Root DSE. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ServerTypeDetector { /** * Detects the type of server we are talking to. We can detect the following servers : * <ul> * <li>ApacheDS</li> * <li>IBM IDS</li> * <li>Netscape</li> * <li>Novell</li> * <li>SUN DS</li> * <li>Microsoft Active Directory</li> * <li>OpenLDAP</li> * <li>Siemens</li> * <li>RedHat 389</li> * </ul> * * NOTE : We should add detectors for RedHAT i389 and Forgerock OpenDJ * * @param rootDSE the Root DSE * @return the corresponding server type or 'UNKNOWN' */ public static ConnectionServerType detectServerType( IRootDSE rootDSE ) { ConnectionServerType serverType; IAttribute vnAttribute = rootDSE.getAttribute( "vendorName" ); //$NON-NLS-1$ IAttribute vvAttribute = rootDSE.getAttribute( "vendorVersion" ); //$NON-NLS-1$ if ( vnAttribute != null && vnAttribute.getStringValues().length > 0 && vvAttribute != null && vvAttribute.getStringValues().length > 0 ) { String vendorName = vnAttribute.getStringValues()[0]; String vendorVersion = vvAttribute.getStringValues()[0]; // ApacheDS serverType = detectApacheDS( vendorName ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // IBM serverType = detectIbm( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // Netscape serverType = detectNetscape( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // Novell serverType = detectNovell( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // Sun serverType = detectSun( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // RedHat 389 serverType = detectRedHat389( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // FrgeRock OpenDJ serverType = detectOpenDJ( vendorName, vendorVersion ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } } // Microsoft serverType = detectMicrosoft( rootDSE ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // OpenLDAP serverType = detectOpenLdap( rootDSE ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } // Siemens serverType = detectSiemens( rootDSE ); if ( !ConnectionServerType.UNKNOWN.equals( serverType ) ) { return serverType; } return ConnectionServerType.UNKNOWN; } /** * Detects ApacheDS. * * @param vendorName the vendor name * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectApacheDS( String vendorName ) { if ( vendorName.indexOf( "Apache Software Foundation" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.APACHEDS; } return ConnectionServerType.UNKNOWN; } /** * Detects the following IBM directory servers: * <ul> * <li>IBM Directory Server</li> * <li>IBM Secureway Directory</li> * <li>IBM Tivoli Directory Server</li> * </ul> * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectIbm( String vendorName, String vendorVersion ) { // IBM if ( vendorName.indexOf( "International Business Machines" ) > -1 ) //$NON-NLS-1$ { // IBM SecureWay Directory String[] iswVersions = { "3.2", "3.2.1", "3.2.2" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for ( String version : iswVersions ) { if ( vendorVersion.indexOf( version ) > -1 ) { return ConnectionServerType.IBM_SECUREWAY_DIRECTORY; } } // IBM Directory Server String[] idsVersions = { "4.1", "5.1" }; //$NON-NLS-1$ //$NON-NLS-2$ for ( String version : idsVersions ) { if ( vendorVersion.indexOf( version ) > -1 ) { return ConnectionServerType.IBM_DIRECTORY_SERVER; } } // IBM Tivoli Directory Server String[] tdsVersions = { "5.2", "6.0", "6.1", "6.2" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ for ( String version : tdsVersions ) { if ( vendorVersion.indexOf( version ) > -1 ) { return ConnectionServerType.IBM_TIVOLI_DIRECTORY_SERVER; } } } return ConnectionServerType.UNKNOWN; } /** * Detects the following Microsoft directory servers: * <ul> * <li>Microsoft Active Directory 2000</li> * <li>Microsoft Active Directory 2003</li> * </ul> * * @param rootDSE the Root DSE * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectMicrosoft( IRootDSE rootDSE ) { if ( rootDSE.getAttribute( "rootDomainNamingContext" ) != null ) { if ( rootDSE.getAttribute( "forestFunctionality" ) != null ) { return ConnectionServerType.MICROSOFT_ACTIVE_DIRECTORY_2003; } else { return ConnectionServerType.MICROSOFT_ACTIVE_DIRECTORY_2000; } } return ConnectionServerType.UNKNOWN; } /** * Detects Netscape directory server. * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectNetscape( String vendorName, String vendorVersion ) { if ( vendorName.indexOf( "Netscape" ) > -1 //$NON-NLS-1$ || vendorVersion.indexOf( "Netscape" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.NETSCAPE; } return ConnectionServerType.UNKNOWN; } /** * Detects Novell directory server. * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectNovell( String vendorName, String vendorVersion ) { if ( vendorName.indexOf( "Novell" ) > -1 //$NON-NLS-1$ || vendorVersion.indexOf( "eDirectory" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.NOVELL; } return ConnectionServerType.UNKNOWN; } /** * Detects the following OpenLDAP directory servers: * <ul> * <li>OpenLDAP 2.4</li> * <li>OpenLDAP 2.3</li> * <li>OpenLDAP 2.2</li> * <li>OpenLDAP 2.1</li> * <li>OpenLDAP 2.0</li> * <li>OpenLDAP</li> * </ul> * * @param rootDSE the Root DSE * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectOpenLdap( IRootDSE rootDSE ) { IAttribute ocAttribute = rootDSE.getAttribute( "objectClass" ); //$NON-NLS-1$ if ( ocAttribute != null ) { for ( int i = 0; i < ocAttribute.getStringValues().length; i++ ) { if ( "OpenLDAProotDSE".equals( ocAttribute.getStringValues()[i] ) ) //$NON-NLS-1$ { IAttribute scAttribute = rootDSE.getAttribute( "supportedControl" ); //$NON-NLS-1$ // Check for the new "Don't Use Copy" Control (RFC 6171) that has been added in OpenLDAP 2.4 if ( scAttribute != null ) { for ( int sci = 0; sci < scAttribute.getStringValues().length; sci++ ) { if ( "1.3.6.1.1.22".equals( scAttribute.getStringValues()[sci] ) ) //$NON-NLS-1$ { return ConnectionServerType.OPENLDAP_2_4; } } } // ConfigContext has been added in OpenLDAP 2.3 if ( rootDSE.getAttribute( "configContext" ) != null ) { return ConnectionServerType.OPENLDAP_2_3; } // Proxy Auth control has been added in OpenLDAP 2.0 if ( scAttribute != null ) { for ( int sci = 0; sci < scAttribute.getStringValues().length; sci++ ) { if ( "2.16.840.1.113730.3.4.18".equals( scAttribute.getStringValues()[sci] ) ) //$NON-NLS-1$ { return ConnectionServerType.OPENLDAP_2_2; } } } // Check for the 'Who Am I' extended operation, added in OpenLDAP 2.1 IAttribute seAttribute = rootDSE.getAttribute( "supportedExtension" ); //$NON-NLS-1$ if ( seAttribute != null ) { for ( int sei = 0; sei < seAttribute.getStringValues().length; sei++ ) { if ( "1.3.6.1.4.1.4203.1.11.3".equals( seAttribute.getStringValues()[sei] ) ) //$NON-NLS-1$ { return ConnectionServerType.OPENLDAP_2_1; } } } // The 'Language Tag' feature has been added in OpenLDAP 2.0 IAttribute sfAttribute = rootDSE.getAttribute( "supportedFeatures" ); //$NON-NLS-1$ if ( sfAttribute != null ) { for ( int sfi = 0; sfi < sfAttribute.getStringValues().length; sfi++ ) { if ( "1.3.6.1.4.1.4203.1.5.4".equals( sfAttribute.getStringValues()[sfi] ) ) //$NON-NLS-1$ { return ConnectionServerType.OPENLDAP_2_0; } } } return ConnectionServerType.OPENLDAP; } } } return ConnectionServerType.UNKNOWN; } /** * Detects Siemens directory server. * * @param rootDSE the Root DSE * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectSiemens( IRootDSE rootDSE ) { IAttribute ssseAttribute = rootDSE.getAttribute( "subSchemaSubentry" ); //$NON-NLS-1$ if ( ssseAttribute != null ) { for ( int i = 0; i < ssseAttribute.getStringValues().length; i++ ) { if ( "cn=LDAPGlobalSchemaSubentry".equals( ssseAttribute.getStringValues()[i] ) ) //$NON-NLS-1$ { return ConnectionServerType.SIEMENS_DIRX; } } } return ConnectionServerType.UNKNOWN; } /** * Detects Sun directory server. * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectSun( String vendorName, String vendorVersion ) { if ( vendorName.indexOf( "Sun" ) > -1 //$NON-NLS-1$ || vendorVersion.indexOf( "Sun" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.SUN_DIRECTORY_SERVER; } return ConnectionServerType.UNKNOWN; } /** * Detects RedHat 389 directory server. * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectRedHat389( String vendorName, String vendorVersion ) { if ( vendorName.indexOf( "389 Project" ) > -1 //$NON-NLS-1$ || vendorVersion.indexOf( "389-Directory" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.RED_HAT_389; } return ConnectionServerType.UNKNOWN; } /** * Detects ForgeRock OpenDJ directory server. * * @param vendorName the vendor name * @param vendorVersion the vendor version * @return the corresponding server type or 'UNKNOWN' */ private static ConnectionServerType detectOpenDJ( String vendorName, String vendorVersion ) { if ( vendorName.indexOf( "ForgeRock" ) > -1 //$NON-NLS-1$ || vendorVersion.indexOf( "OpenDJ" ) > -1 ) //$NON-NLS-1$ { return ConnectionServerType.FORGEROCK_OPEN_DJ; } return ConnectionServerType.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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/DeleteEntriesRunnable.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/DeleteEntriesRunnable.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.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.naming.directory.SearchControls; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.StudioControl; import org.apache.directory.studio.connection.core.io.StudioLdapException; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.events.BulkModificationEvent; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; /** * Runnable to delete entries. * * Deletes the entry recursively in a optimistic way: * <ol> * <li>Delete the entry * <li>If that fails with error code 66 then perform a one-level search * and start from 1. for each entry. * </ol> * * TODO: delete subentries? * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class DeleteEntriesRunnable implements StudioConnectionBulkRunnableWithProgress { /** The entries to delete. */ private Collection<IEntry> entriesToDelete; /** The deleted entries. */ private Set<IEntry> deletedEntriesSet; /** The searches to update. */ private Set<ISearch> searchesToUpdateSet; /** The use tree delete control flag. */ private boolean useTreeDeleteControl; /** * Creates a new instance of DeleteEntriesRunnable. * * @param entriesToDelete the entries to delete */ public DeleteEntriesRunnable( final Collection<IEntry> entriesToDelete, boolean useTreeDeleteControl ) { this.entriesToDelete = entriesToDelete; this.useTreeDeleteControl = useTreeDeleteControl; this.deletedEntriesSet = new HashSet<IEntry>(); this.searchesToUpdateSet = new HashSet<ISearch>(); } /** * {@inheritDoc} */ public Connection[] getConnections() { Connection[] connections = new Connection[entriesToDelete.size()]; int i = 0; for ( IEntry entry : entriesToDelete ) { connections[i] = entry.getBrowserConnection().getConnection(); i++; } return connections; } /** * {@inheritDoc} */ public String getName() { return entriesToDelete.size() == 1 ? BrowserCoreMessages.jobs__delete_entries_name_1 : BrowserCoreMessages.jobs__delete_entries_name_n; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<IEntry> l = new ArrayList<IEntry>(); l.addAll( entriesToDelete ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return entriesToDelete.size() == 1 ? BrowserCoreMessages.jobs__delete_entries_error_1 : BrowserCoreMessages.jobs__delete_entries_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( entriesToDelete.size() == 1 ? BrowserCoreMessages.bind( BrowserCoreMessages.jobs__delete_entries_task_1, new String[] { entriesToDelete.iterator().next().getDn().getName() } ) : BrowserCoreMessages.bind( BrowserCoreMessages.jobs__delete_entries_task_n, new String[] { Integer.toString( entriesToDelete.size() ) } ), 2 + entriesToDelete.size() ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); int num = 0; StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); for ( Iterator<IEntry> iterator = entriesToDelete.iterator(); !monitor.isCanceled() && !monitor.errorsReported() && iterator.hasNext(); ) { IEntry entryToDelete = iterator.next(); IBrowserConnection browserConnection = entryToDelete.getBrowserConnection(); // delete from directory int errorStatusSize1 = monitor.getErrorStatus( "" ).getChildren().length; //$NON-NLS-1$ num = optimisticDeleteEntryRecursive( browserConnection, entryToDelete.getDn(), entryToDelete.isReferral(), useTreeDeleteControl, num, dummyMonitor, monitor ); int errorStatusSize2 = monitor.getErrorStatus( "" ).getChildren().length; //$NON-NLS-1$ if ( !monitor.isCanceled() ) { if ( errorStatusSize1 == errorStatusSize2 ) { // delete deletedEntriesSet.add( entryToDelete ); //entryToDelete.setChildrenInitialized( false ); // delete from parent entry entryToDelete.getParententry().setChildrenInitialized( false ); entryToDelete.getParententry().deleteChild( entryToDelete ); // delete from searches List<ISearch> searches = browserConnection.getSearchManager().getSearches(); for ( ISearch search : searches ) { if ( search.getSearchResults() != null ) { ISearchResult[] searchResults = search.getSearchResults(); List<ISearchResult> searchResultList = new ArrayList<ISearchResult>(); searchResultList.addAll( Arrays.asList( searchResults ) ); for ( Iterator<ISearchResult> it = searchResultList.iterator(); it.hasNext(); ) { ISearchResult result = it.next(); if ( entryToDelete.equals( result.getEntry() ) ) { it.remove(); searchesToUpdateSet.add( search ); } } if ( searchesToUpdateSet.contains( search ) ) { search.setSearchResults( searchResultList.toArray( new ISearchResult[searchResultList .size()] ) ); } } } // delete from cache browserConnection.uncacheEntryRecursive( entryToDelete ); } } else { entryToDelete.setChildrenInitialized( false ); } monitor.worked( 1 ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { // don't fire an EntryDeletedEvent for each deleted entry // that would cause massive UI updates // instead we unset children information and fire a BulkModificationEvent IBrowserConnection browserConnection = entriesToDelete.iterator().next().getBrowserConnection(); EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); for ( ISearch search : searchesToUpdateSet ) { EventRegistry.fireSearchUpdated( new SearchUpdateEvent( search, SearchUpdateEvent.EventDetail.SEARCH_PERFORMED ), this ); } } /** * Deletes the entry recursively in a optimistic way: * <ol> * <li>Deletes the entry * <li>If that fails then perform a one-level search and call the * method for each found entry * </ol> * * @param browserConnection the browser connection * @param dn the Dn to delete * @param useManageDsaItControl true to use the ManageDsaIT control * @param useTreeDeleteControl true to use the tree delete control * @param numberOfDeletedEntries the number of deleted entries * @param dummyMonitor the dummy monitor * @param monitor the progress monitor * * @return the cumulative number of deleted entries */ static int optimisticDeleteEntryRecursive( IBrowserConnection browserConnection, Dn dn, boolean useManageDsaItControl, boolean useTreeDeleteControl, int numberOfDeletedEntries, StudioProgressMonitor dummyMonitor, StudioProgressMonitor monitor ) { // try to delete entry dummyMonitor.reset(); deleteEntry( browserConnection, dn, useManageDsaItControl, useTreeDeleteControl, dummyMonitor ); if ( !dummyMonitor.errorsReported() ) { numberOfDeletedEntries++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.model__deleted_n_entries, new String[] { "" + numberOfDeletedEntries } ) ); //$NON-NLS-1$ } else if ( StudioLdapException.isContextNotEmptyException( dummyMonitor.getException() ) ) { // do not follow referrals or dereference aliases when deleting entries AliasDereferencingMethod aliasDereferencingMethod = AliasDereferencingMethod.NEVER; ReferralHandlingMethod referralsHandlingMethod = ReferralHandlingMethod.IGNORE; // perform one-level search and delete recursively int numberInBatch; dummyMonitor.reset(); do { numberInBatch = 0; SearchControls searchControls = new SearchControls(); searchControls.setCountLimit( 1000 ); searchControls.setReturningAttributes( new String[0] ); searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); StudioSearchResultEnumeration result = browserConnection .getConnection() .getConnectionWrapper() .search( dn.getName(), ISearch.FILTER_TRUE, searchControls, aliasDereferencingMethod, referralsHandlingMethod, null, dummyMonitor, null ); try { // delete all child entries while ( !dummyMonitor.isCanceled() && !dummyMonitor.errorsReported() && result.hasMore() ) { Dn childDn = result.next().getDn(); numberOfDeletedEntries = optimisticDeleteEntryRecursive( browserConnection, childDn, false, false, numberOfDeletedEntries, dummyMonitor, monitor ); numberInBatch++; } } catch ( Exception e ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( e ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { // continue with search } else { dummyMonitor.reportError( e ); break; } } } while ( numberInBatch > 0 && !monitor.isCanceled() && !dummyMonitor.errorsReported() ); // try to delete the entry again if ( !dummyMonitor.errorsReported() ) { deleteEntry( browserConnection, dn, false, false, dummyMonitor ); } if ( !dummyMonitor.errorsReported() ) { numberOfDeletedEntries++; monitor.reportProgress( BrowserCoreMessages.bind( BrowserCoreMessages.model__deleted_n_entries, new String[] { "" + numberOfDeletedEntries } ) ); //$NON-NLS-1$ } } else { Exception exception = dummyMonitor.getException(); // we have another exception // report it to the dummy monitor if we are in the recursion dummyMonitor.reportError( exception ); // also report it to the real monitor monitor.reportError( exception ); } return numberOfDeletedEntries; } static void deleteEntry( IBrowserConnection browserConnection, Dn dn, boolean useManageDsaItControl, boolean useTreeDeleteControl, StudioProgressMonitor monitor ) { // controls List<Control> controlList = new ArrayList<Control>(); if ( useTreeDeleteControl && browserConnection.getRootDSE().isControlSupported( StudioControl.TREEDELETE_CONTROL.getOid() ) ) { controlList.add( Controls.TREEDELETE_CONTROL ); } if ( useManageDsaItControl && browserConnection.getRootDSE().isControlSupported( StudioControl.MANAGEDSAIT_CONTROL.getOid() ) ) { controlList.add( Controls.MANAGEDSAIT_CONTROL ); } Control[] controls = controlList.toArray( new Control[controlList.size()] ); // delete entry if ( browserConnection.getConnection() != null ) { browserConnection.getConnection().getConnectionWrapper() .deleteEntry( dn, controls, monitor, 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IContinuation.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IContinuation.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.ldapbrowser.core.model; import org.apache.directory.api.ldap.model.url.LdapUrl; /** * A tagging interface for search continuations. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IContinuation { enum State { /** The search continuation URL is unresolved.*/ UNRESOLVED, /** The search continuation URL is unresolved. The user didn't select a suitable connection for the URL. */ CANCELED, /** The search continuation URL is resolved. The user selected a suitable connection for the URL. */ RESOLVED } /** * Gets the resolve state. * * @return the resolve state */ State getState(); /** * Resolves the search continuation URL, asks the user which connection to use. */ void resolve(); /** * Gets the search continuation URL. * * @return the search continuation URL */ LdapUrl getUrl(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/BookmarkParameter.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/BookmarkParameter.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.api.ldap.model.name.Dn; /** * A Bean class to hold the bookmark parameters. * It is used to make bookmarks persistent. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class BookmarkParameter implements Serializable { /** The serialVersionUID. */ private static final long serialVersionUID = 105108281861642267L; /** The target Dn. */ private Dn dn; /** The symbolic name. */ private String name; /** * Creates a new instance of BookmarkParameter. */ public BookmarkParameter() { } /** * Creates a new instance of BookmarkParameter. * * @param dn the target Dn * @param name the symbolic name */ public BookmarkParameter( Dn dn, String name ) { this.dn = dn; this.name = name; } /** * Gets the target Dn. * * @return the target Dn */ public Dn getDn() { return dn; } /** * Sets the target Dn. * * @param dn the target Dn */ public void setDn( Dn dn ) { this.dn = dn; } /** * Gets the symbolic name. * * @return the symbolic name */ public String getName() { return name; } /** * Sets the symbolic name. * * @param name the symbolic name */ public void setName( String name ) { this.name = name; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/ISearchResult.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/ISearchResult.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.EntryPropertyPageProvider; import org.eclipse.core.runtime.IAdaptable; /** * The ISearchResult represents a single search result. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ISearchResult extends Serializable, IAdaptable, EntryPropertyPageProvider, ConnectionPropertyPageProvider { /** * Returns the Dn of the search result entry. * * @return the Dn of the search result entry. */ Dn getDn(); /** * Returns the attributes of the search result entry. * * @return the attributes of the search result entry. */ IAttribute[] getAttributes(); /** * Returns the attribute of the search result entry. * * @param attributeDescription * the attribute description of the attribute to return * @return the attribute with the given description or null. */ IAttribute getAttribute( String attributeDescription ); /** * Returns the AttributeHierachie of the search result entry. * * @param attributeDescription * the description of the attribute to return * @return the AttributeHierachie with the given description or null. */ AttributeHierarchy getAttributeWithSubtypes( String attributeDescription ); /** * Returns the entry of the search result. * * @return the entry */ IEntry getEntry(); /** * Return the search, the parent of this search result. * * @return the search */ ISearch getSearch(); /** * Sets the search. * * @param search the search */ void setSearch( ISearch search ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/AttributeDescription.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/AttributeDescription.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.ldapbrowser.core.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.schema.ObjectClass; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils; /** * This class implements an attribute description as * specified in RFC4512, section 2.5: * * An attribute description is represented by the ABNF: * * attributedescription = attributetype options * attributetype = oid * options = *( SEMI option ) * option = 1*keychar * * where &lt;attributetype> identifies the attribute type and each <option> * identifies an attribute option. Both &lt;attributetype> and <option> * productions are case insensitive. The order in which <option>s * appear is irrelevant. That is, any two &lt;attributedescription>s that * consist of the same &lt;attributetype> and same set of <option>s are * equivalent. * * Examples of valid attribute descriptions: * * 2.5.4.0 * cn;lang-de;lang-en * owner * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class AttributeDescription implements Serializable { private static final long serialVersionUID = 1L; /** The user provided description. */ private String description; /** The parsed attribute type. */ private String parsedAttributeType; /** The parsed language tag option list. */ private List<String> parsedLangList; /** The parsed option list, except the language tags. */ private List<String> parsedOptionList; /** * Creates a new instance of AttributeDescription. * * @param description the user provided description */ public AttributeDescription( String description ) { this.description = description; String[] attributeDescriptionComponents = description.split( IAttribute.OPTION_DELIMITER ); this.parsedAttributeType = attributeDescriptionComponents[0]; this.parsedLangList = new ArrayList<String>(); this.parsedOptionList = new ArrayList<String>(); for ( int i = 1; i < attributeDescriptionComponents.length; i++ ) { String component = attributeDescriptionComponents[i]; if ( component.startsWith( IAttribute.OPTION_LANG_PREFIX ) ) { this.parsedLangList.add( component ); } else { this.parsedOptionList.add( component ); } } } /** * Gets the user provided description. * * @return the user provided description */ public String getDescription() { return description; } /** * Gets the parsed attribute type. * * @return the parsed attribute type */ public String getParsedAttributeType() { return parsedAttributeType; } /** * Gets the list of parsed language tags. * * @return the list of parsed language tags */ public List<String> getParsedLangList() { return parsedLangList; } /** * Gets the list of parsed options, except the language tags. * * @return the list of parsed options, except the language tags */ public List<String> getParsedOptionList() { return parsedOptionList; } /** * Returns the attribute description with the numeric OID * instead of the descriptive attribute type. * * @param schema the schema * * @return the attribute description with the numeric OID */ public String toOidString( Schema schema ) { if ( schema == null ) { return description; } AttributeType atd = schema.getAttributeTypeDescription( parsedAttributeType ); String oidString = atd.getOid(); if ( !parsedLangList.isEmpty() ) { for ( Iterator<String> it = parsedLangList.iterator(); it.hasNext(); ) { String element = it.next(); oidString += element; if ( it.hasNext() || !parsedOptionList.isEmpty() ) { oidString += IAttribute.OPTION_DELIMITER; } } } if ( !parsedOptionList.isEmpty() ) { for ( Iterator<String> it = parsedOptionList.iterator(); it.hasNext(); ) { String element = it.next(); oidString += element; if ( it.hasNext() ) { oidString += IAttribute.OPTION_DELIMITER; } } } return oidString; } /** * Checks if the given attribute description is subtype of * this attribute description. * * @param other the other attribute description * @param schema the schema * * @return true, if the other attribute description is a * subtype of this attribute description. */ public boolean isSubtypeOf( AttributeDescription other, Schema schema ) { // this=name, other=givenName;lang-de -> false // this=name;lang-en, other=givenName;lang-de -> false // this=givenName, other=name -> true // this=givenName;lang-de, other=givenName -> true // this=givenName;lang-de, other=name -> true // this=givenName;lang-en, other=name;lang-de -> false // this=givenName, other=givenName;lang-de -> false // check equal descriptions if ( this.toOidString( schema ).equals( other.toOidString( schema ) ) ) { return false; } AttributeType myAtd = schema.getAttributeTypeDescription( this.getParsedAttributeType() ); AttributeType otherAtd = schema.getAttributeTypeDescription( other.getParsedAttributeType() ); // special case *: all user attributes (RFC4511) if ( SchemaConstants.ALL_USER_ATTRIBUTES.equals( other.description ) && !SchemaUtils.isOperational( myAtd ) ) { return true; } // special case +: all operational attributes (RFC3673) if ( SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES.equals( other.description ) && SchemaUtils.isOperational( myAtd ) ) { return true; } // special case @: attributes by object class (RFC4529) if ( other.description.length() > 1 && other.description.startsWith( "@" ) ) //$NON-NLS-1$ { String objectClass = other.description.substring( 1 ); ObjectClass ocd = schema.getObjectClassDescription( objectClass ); ocd.getMayAttributeTypes(); ocd.getMustAttributeTypes(); Collection<String> names = new HashSet<String>(); names.addAll( SchemaUtils.getMayAttributeTypeDescriptionNamesTransitive( ocd, schema ) ); names.addAll( SchemaUtils.getMustAttributeTypeDescriptionNamesTransitive( ocd, schema ) ); for ( String name : names ) { AttributeType atd = schema.getAttributeTypeDescription( name ); if ( myAtd == atd ) { return true; } } } // check type if ( myAtd != otherAtd ) { AttributeType superiorAtd = null; String superiorName = myAtd.getSuperiorOid(); while ( superiorName != null ) { superiorAtd = schema.getAttributeTypeDescription( superiorName ); if ( superiorAtd == otherAtd ) { break; } superiorName = superiorAtd.getSuperiorOid(); } if ( superiorAtd != otherAtd ) { return false; } } // check options List<String> myOptionsList = new ArrayList<String>( this.getParsedOptionList() ); List<String> otherOptionsList = new ArrayList<String>( other.getParsedOptionList() ); otherOptionsList.removeAll( myOptionsList ); if ( !otherOptionsList.isEmpty() ) { return false; } // check language tags List<String> myLangList = new ArrayList<String>( this.getParsedLangList() ); List<String> otherLangList = new ArrayList<String>( other.getParsedLangList() ); for ( String myLang : myLangList ) { for ( Iterator<String> otherIt = otherLangList.iterator(); otherIt.hasNext(); ) { String otherLang = otherIt.next(); if ( otherLang.endsWith( "-" ) ) //$NON-NLS-1$ { if ( Strings.toLowerCase( myLang ).startsWith( Strings.toLowerCase( otherLang ) ) ) { otherIt.remove(); } } else { if ( myLang.equalsIgnoreCase( otherLang ) ) { otherIt.remove(); } } } } if ( !otherLangList.isEmpty() ) { 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/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IBrowserConnection.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IBrowserConnection.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.BookmarkManager; import org.apache.directory.studio.ldapbrowser.core.SearchManager; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.eclipse.core.runtime.IAdaptable; /** * An IBrowserConnection represents a connection for the LDAP browser. * It holds an instance to the underlying connection of the connection plugin, * additional it includes advanced connection parameters for the LDAP browser. * It also provides an entry cache. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IBrowserConnection extends Serializable, IAdaptable, ConnectionPropertyPageProvider { /** * Enum for the modify mode of attributes * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ enum ModifyMode { /** Default mode */ DEFAULT(0), /** Always use replace operation */ REPLACE(1), /** Always use add/delete operation */ ADD_DELETE(2); private final int ordinal; private ModifyMode( int ordinal ) { this.ordinal = ordinal; } /** * Gets the ordinal. * * @return the ordinal */ public int getOrdinal() { return ordinal; } /** * Gets the ModifyMode by ordinal. * * @param ordinal the ordinal * * @return the ModifyMode */ public static ModifyMode getByOrdinal( int ordinal ) { switch ( ordinal ) { case 0: return DEFAULT; case 1: return REPLACE; case 2: return ADD_DELETE; default: return null; } } } /** * Enum for modify order when using add/delete operations * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ enum ModifyOrder { /** Delete first */ DELETE_FIRST(0), /** Add first */ ADD_FIRST(1); private final int ordinal; private ModifyOrder( int ordinal ) { this.ordinal = ordinal; } /** * Gets the ordinal. * * @return the ordinal */ public int getOrdinal() { return ordinal; } /** * Gets the ModifyOrder by ordinal. * * @param ordinal the ordinal * * @return the ModifyOrder */ public static ModifyOrder getByOrdinal( int ordinal ) { switch ( ordinal ) { case 0: return DELETE_FIRST; case 1: return ADD_FIRST; default: return null; } } } /** The key for the connection parameter "Get Base DNs from Root DSE". */ String CONNECTION_PARAMETER_FETCH_BASE_DNS = "ldapbrowser.fetchBaseDns"; //$NON-NLS-1$ /** The key for the connection parameter "Base Dn". */ String CONNECTION_PARAMETER_BASE_DN = "ldapbrowser.baseDn"; //$NON-NLS-1$ /** The key for the connection parameter "Count Limit". */ String CONNECTION_PARAMETER_COUNT_LIMIT = "ldapbrowser.countLimit"; //$NON-NLS-1$ /** The key for the connection parameter "Time Limit". */ String CONNECTION_PARAMETER_TIME_LIMIT = "ldapbrowser.timeLimit"; //$NON-NLS-1$ /** The key for the connection parameter "Alias Dereferencing". */ String CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD = "ldapbrowser.aliasesDereferencingMethod"; //$NON-NLS-1$ /** The key for the connection parameter "Referrals Handling". */ String CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD = "ldapbrowser.referralsHandlingMethod"; //$NON-NLS-1$ /** The key for the connection parameter "Fetch Operational Attributes. */ String CONNECTION_PARAMETER_FETCH_OPERATIONAL_ATTRIBUTES = "ldapbrowser.fetchOperationalAttributes"; //$NON-NLS-1$ /** The key for the connection parameter "Fetch Sub-entries". */ String CONNECTION_PARAMETER_FETCH_SUBENTRIES = "ldapbrowser.fetchSubentries"; //$NON-NLS-1$ /** The key for the connection parameter "Paged Search". */ String CONNECTION_PARAMETER_PAGED_SEARCH = "ldapbrowser.pagedSearch"; //$NON-NLS-1$ /** The key for the connection parameter "Paged Search Size". */ String CONNECTION_PARAMETER_PAGED_SEARCH_SIZE = "ldapbrowser.pagedSearchSize"; //$NON-NLS-1$ /** The key for the connection parameter "Paged Search Scroll Mode". */ String CONNECTION_PARAMETER_PAGED_SEARCH_SCROLL_MODE = "ldapbrowser.pagedSearchScrollMode"; //$NON-NLS-1$ /** The key for the connection parameter "Modify Mode for attributes with equality matching rule". */ String CONNECTION_PARAMETER_MODIFY_MODE = "ldapbrowser.modifyMode"; //$NON-NLS-1$ /** The key for the connection parameter "Modify Mode for attributes without equality matching rule". */ String CONNECTION_PARAMETER_MODIFY_MODE_NO_EMR = "ldapbrowser.modifyModeNoEMR"; //$NON-NLS-1$ /** The key for the connection parameter "Modify add delete order". */ String CONNECTION_PARAMETER_MODIFY_ORDER = "ldapbrowser.modifyOrder"; //$NON-NLS-1$ /** The key for the connection parameter "Use ManageDsaIT Control" */ String CONNECTION_PARAMETER_MANAGE_DSA_IT = "ldapbrowser.manageDsaIT"; //$NON-NLS-1$ /** * Gets the URL of this connection. * * @return the URL of this connection */ LdapUrl getUrl(); /** * Gets the flag whether the base DNs is retrieved * from Root DSE or whether the base Dn is defined manually. * * @return true, if the base DNs are fetched from Root DSE, * false, if the base Dn is defined manually */ boolean isFetchBaseDNs(); /** * Sets the flag whether the base DNs should be retrieved * from Root DSE or whether the base Dn is defined manually. * * @param fetchBaseDNs true to get the base DNs from Root DSE, * false to define one manually */ void setFetchBaseDNs( boolean fetchBaseDNs ); /** * Gets the manually defined base Dn. * * @return the manually defined base ND */ Dn getBaseDN(); /** * Sets the manually defined base Dn. * * @param baseDn the new base Dn */ void setBaseDN( Dn baseDn ); /** * Gets the count limit. * * @return the count limit */ int getCountLimit(); /** * Sets the count limit. * * @param countLimit the new count limit */ void setCountLimit( int countLimit ); /** * Gets the aliases dereferencing method. * * @return the aliases dereferencing method */ AliasDereferencingMethod getAliasesDereferencingMethod(); /** * Sets the aliases dereferencing method. * * @param aliasesDereferencingMethod the new aliases dereferencing method */ void setAliasesDereferencingMethod( AliasDereferencingMethod aliasesDereferencingMethod ); /** * Gets the referrals handling method. * * @return the referrals handling method */ ReferralHandlingMethod getReferralsHandlingMethod(); /** * Sets the referrals handling method. * * @param referralsHandlingMethod the new referrals handling method */ void setReferralsHandlingMethod( ReferralHandlingMethod referralsHandlingMethod ); /** * Gets the time limit. * * @return the time limit */ int getTimeLimit(); /** * Sets the time limit. * * @param timeLimit the new time limit */ void setTimeLimit( int timeLimit ); /** * Checks if subentries should be fetched. * * @return the true if subentries should be fetched */ boolean isFetchSubentries(); /** * Sets if subentries should be fetched. * * @param fetchSubentries true to fetch subentries */ void setFetchSubentries( boolean fetchSubentries ); /** * Checks if ManageDsaIT control should be used. * * @return true if ManageDsaIT control should be used */ boolean isManageDsaIT(); /** * Sets if ManageDsaIT control should be used. * * @param manageDsaIT true to use ManageDsaIT control */ void setManageDsaIT( boolean manageDsaIT ); /** * Checks if operational attributes should be fetched. * * @return the true if operational attributes should be fetched */ boolean isFetchOperationalAttributes(); /** * Sets if operational attributes should be fetched. * * @param fetchSubentries true to fetch operational attributes */ void setFetchOperationalAttributes( boolean fetchOperationalAttributes ); /** * Checks if paged search should be used. * * @return the true if paged search should be used */ boolean isPagedSearch(); /** * Sets if paged search should be used. * * @param pagedSearch true to use paged search */ void setPagedSearch( boolean pagedSearch ); /** * Gets the paged search size. * * @return the paged search size */ int getPagedSearchSize(); /** * Sets the paged search size. * * @param pagedSearchSize the new paged search size */ void setPagedSearchSize( int pagedSearchSize ); /** * Checks if paged search scroll mode should be used. * * @return the true if paged search scroll mode should be used */ boolean isPagedSearchScrollMode(); /** * Sets if paged search scroll mode should be used. * * @param pagedSearch true to use paged search scroll mode */ void setPagedSearchScrollMode( boolean pagedSearchScrollMode ); /** * Gets the modify mode for attributes. * * @return the modify mode for attributes */ ModifyMode getModifyMode(); /** * Sets the modify mode for attributes. * * @param mode the modify mode for attributes */ void setModifyMode( ModifyMode mode ); /** * Gets the modify mode for attributes without equality matching rule. * * @return the modify mode for attributes without equality matching rule */ ModifyMode getModifyModeNoEMR(); /** * Sets the modify mode for attributes without equality matching rule. * * @param mode the modify mode for attributes without equality matching rule */ void setModifyModeNoEMR( ModifyMode mode ); /** * Gets the modify add/delete order. * * @return the modify add/delete order */ ModifyOrder getModifyAddDeleteOrder(); /** * Sets the modify add/delete order. * * @param mode the modify add/delete order */ void setModifyAddDeleteOrder( ModifyOrder mode ); /** * Sets the quick search. * * @param quickSearch the new quick search */ void setQuickSearch( IQuickSearch quickSearch ); /** * Gets the quick search. * * @return the quick search */ IQuickSearch getQuickSearch(); /** * Gets the root DSE. * * @return the root DSE */ IRootDSE getRootDSE(); /** * Gets the schema. * * @return the schema, never null */ Schema getSchema(); /** * Sets the schema. * * @param schema the new schema */ void setSchema( Schema schema ); /** * Gets the search manager. * * @return the search manager */ SearchManager getSearchManager(); /** * Gets the bookmark manager. * * @return the bookmark manager */ BookmarkManager getBookmarkManager(); /** * Gets the entry from cache. * * @param dn the Dn of the entry * * @return the entry from cache or null if the entry isn't cached */ IEntry getEntryFromCache( Dn dn ); /** * Gets the connection. * * @return the connection */ Connection getConnection(); /** * Puts the entry to the cache. * * @param entry the entry to cache */ void cacheEntry( IEntry entry ); /** * Removes the entry and all children recursively from the cache. * * @param entry the entry to remove from cache */ void uncacheEntryRecursive( IEntry entry ); /** * Clears all caches. */ void clearCaches(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IQuickSearch.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IQuickSearch.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.ldapbrowser.core.model; /** * An IQuickSearch holds all search parameters and search results of an * LDAP quick search. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IQuickSearch extends ISearch { /** * Gets the search base entry. * * @return the search base entry */ IEntry getSearchBaseEntry(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/Password.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/Password.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.ldapbrowser.core.model; import org.apache.directory.api.ldap.model.constants.LdapSecurityConstants; import org.apache.directory.api.ldap.model.password.PasswordDetails; import org.apache.directory.api.ldap.model.password.PasswordUtil; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldifparser.LdifUtils; /** * The Password class is used to represent a hashed or plain text password. * It provides methods to retrieve information about the used hash method. * And it provides a verify method to check if the hashed password is equal to * a given plain text password. * * The following hash methods are supported: * <ul> * <li>SHA</li> * <li>SSHA</li> * <li>SHA-256</li> * <li>SSHA-256</li> * <li>SHA-384</li> * <li>SSHA-384</li> * <li>SHA-512</li> * <li>SSHA-512</li> * <li>MD5</li> * <li>SMD5</li> * <li>PKCS5S2</li> * <li>CRYPT</li> * </ul> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class Password { /** The password, either plain text or in encrypted format */ private final byte[] password; /** The password details */ private final PasswordDetails passwordDetails; /** * Creates a new instance of Password. * * @param password the password, either hashed or plain text */ public Password( byte[] password ) { if ( password == null ) { throw new IllegalArgumentException( BrowserCoreMessages.model__empty_password ); } else { this.password = password; this.passwordDetails = PasswordUtil.splitCredentials( password ); } } /** * Creates a new instance of Password. * * @param password the password, either hashed or plain text */ public Password( String password ) { if ( password == null ) { throw new IllegalArgumentException( BrowserCoreMessages.model__empty_password ); } else { this.password = Strings.getBytesUtf8( password ); this.passwordDetails = PasswordUtil.splitCredentials( this.password ); } } /** * Creates a new instance of Password and calculates the hashed password. * * @param hashMethod the hash method to use * @param passwordAsPlaintext the plain text password * * @throws IllegalArgumentException if the given password is null */ public Password( LdapSecurityConstants hashMethod, String passwordAsPlaintext ) { if ( passwordAsPlaintext == null ) { throw new IllegalArgumentException( BrowserCoreMessages.model__empty_password ); } else { this.password = PasswordUtil.createStoragePassword( passwordAsPlaintext, hashMethod ); this.passwordDetails = PasswordUtil.splitCredentials( this.password ); } } /** * Verifies if this password is equal to the given test password. * * @param testPasswordAsPlaintext the test password as plaintext * * @return true, if equal */ public boolean verify( String testPasswordAsPlaintext ) { if ( testPasswordAsPlaintext == null ) { return false; } return PasswordUtil.compareCredentials( Strings.getBytesUtf8( testPasswordAsPlaintext ), this.password ); } /** * Gets the hash method. * * @return the hash method */ public LdapSecurityConstants getHashMethod() { return passwordDetails.getAlgorithm(); } /** * Gets the hashed password. * * @return the hashed password */ public byte[] getHashedPassword() { return passwordDetails.getPassword(); } /** * Gets the hashed password as hex string. * * @return the hashed password as hex string */ public String getHashedPasswordAsHexString() { return LdifUtils.hexEncode( passwordDetails.getPassword() ); } /** * Gets the salt. * * @return the salt */ public byte[] getSalt() { return passwordDetails.getSalt(); } /** * Gets the salt as hex string. * * @return the salt as hex string */ public String getSaltAsHexString() { return LdifUtils.hexEncode( passwordDetails.getSalt() ); } /** * Gets the * * @return the byte[] */ public byte[] toBytes() { return LdifUtils.utf8encode( toString() ); } /** * @see java.lang.Object#toString() */ public String toString() { return Strings.utf8ToString( password ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/ICompareableEntry.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/ICompareableEntry.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.ldapbrowser.core.model; /** * A tagging interface for comparable entries. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface ICompareableEntry extends IEntry { }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IAttribute.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IAttribute.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.AttributePropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.EntryPropertyPageProvider; import org.eclipse.core.runtime.IAdaptable; /** * An IAttribute represents an LDAP attribute. */ public interface IAttribute extends Serializable, IAdaptable, AttributePropertyPageProvider, EntryPropertyPageProvider, ConnectionPropertyPageProvider { /** The options delimiter ';' */ String OPTION_DELIMITER = ";"; //$NON-NLS-1$ /** The language tag prefix 'lang-' */ String OPTION_LANG_PREFIX = "lang-"; //$NON-NLS-1$ /** * Gets the entry of this attribute. * * @return the entry of this attribute, never null */ IEntry getEntry(); /** * Returns true if this attribute is consistent. The following * conditions must be fulfilled: * * <ul> * <li>The attribute must contain at least one value</li> * <li>The attribute mustn't contain any empty value</li> * </ul> * * @return true if the attribute ist consistent */ boolean isConsistent(); /** * Returns true if this attribute is a must attribute of its entry * according to the schema and the entry's object classes. * * @return true if this attribute is a must attribute of its entry. */ boolean isMustAttribute(); /** * Returns true if this attribute is a may attribute of its entry * according to the schema and the entry's object classes. * * @return true if this attribute is a may attribute of its entry. */ boolean isMayAttribute(); /** * Returns true if this attribute is an operational attribute according * to the schema. * * @return true if this attribute is an operational attribute. */ boolean isOperationalAttribute(); /** * Return true if this attribute is the objeCtclass attribute. * * @return true if this attribute is the objectClass attribute. */ boolean isObjectClassAttribute(); /** * Return true if the attribute is of type String. * * @return true if the attribute is of type String. */ boolean isString(); /** * Return true if the attribute is of type byte[]. * * @return true if the attribute is of type byte[]. */ boolean isBinary(); /** * Adds an empty value. * */ void addEmptyValue(); /** * Removes one empty value if one is present. * */ void deleteEmptyValue(); /** * Adds the given value to this attribute. The value's attribute must be * this attribute. * * @param valueToAdd * the value to add * @throws IllegalArgumentException * if the value is null or if the value's attribute * isn't this attribute. */ void addValue( IValue valueToAdd ) throws IllegalArgumentException; /** * Deletes the given value from this attribute. * * @param valueToDelete * the value to delete * @throws IllegalArgumentException * if the value is null or if the value's attribute * isn't this attribute. */ void deleteValue( IValue valueToDelete ) throws IllegalArgumentException; /** * Replaces the old value with the new value. * * @param oldValue * the value that should be replaced * @param newValue * the value that should be added * @throws IllegalArgumentException * if the value is null or if the value's attribute * isn't this attribute. */ void modifyValue( IValue oldValue, IValue newValue ) throws IllegalArgumentException; /** * Gets the values of this attribute. * * @return the values of this attribute, may be an empty array, never null. */ IValue[] getValues(); /** * Gets the number of values in this attribute. * * @return the number of values in this attribute. */ int getValueSize(); /** * Gets the description of this attribute. The description * consists of the attribute type and optional options. * * @return the description of this attribute. */ String getDescription(); /** * Gets the type of this attribute (description without options). * * @return the attribute type. */ String getType(); /** * Gets all values as byte[]. If the values aren't binary they are * converted to byte[] using UTF-8 encoding. * * @return The binary values */ byte[][] getBinaryValues(); /** * Gets the first value as string if one is present, null otherwise * * @return The first value if one present, null otherwise */ String getStringValue(); /** * Gets all values as String. If the values aren't strings they are * converted using UTF-8 encoding. * * @return The string values */ String[] getStringValues(); /** * Returns true if the argument is also of type IAttribute and they are * equal. * * IAttributes are equal if there entries and there attribute * description are equal. * * @param o * The attribute to compare, must be of type IAttribute * @return true if the argument is equal to this. */ boolean equals( Object o ); /** * Gets the AttributeTypeDescription of this attribute. * * @return the AttributeTypeDescription of this attribute, may be the * default or a dummy */ AttributeType getAttributeTypeDescription(); /** * Gets the AttributeDescription of this attribute. * * @return the AttributeDescription of this attribute,. */ AttributeDescription getAttributeDescription(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/DirectoryTypeDetector.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/DirectoryTypeDetector.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.ldapbrowser.core.model; /** * A DirectoryTypeDetector detects the directory type. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface DirectoryTypeDetector { /** * Tries to detect the directory type from the given Root DSE. * * @param rootDSE the Root DSE * @return the directory type or null if unknown */ String detectDirectoryType( IRootDSE rootDSE ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/NameException.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/NameException.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.ldapbrowser.core.model; /** * @deprecated This class will be removed in the next version. The Dn/Rdn/RDNPart * classes are replaced with the shared-ldap LdapDN/Rdn/ATAV. This class just * remains to provide backward compatibility of the old browserconnections.xml * file that stores searches and bookmarks. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class NameException extends Exception { private static final long serialVersionUID = 1L; /** * Creates a new instance of NameException. * * @param message the message */ public NameException( String message ) { super( message ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IValue.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IValue.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.AttributePropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.EntryPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.ValuePropertyPageProvider; import org.eclipse.core.runtime.IAdaptable; /** * An IValue represents a value of a LDAP attribute. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IValue extends Serializable, IAdaptable, ValuePropertyPageProvider, AttributePropertyPageProvider, EntryPropertyPageProvider, ConnectionPropertyPageProvider { /** * EmptyValue is used to indicate an empty value. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ interface EmptyValue { /** * Gets the string value. * * @return the string value */ String getStringValue(); /** * Gets the binary value. * * @return the binary value */ byte[] getBinaryValue(); /** * Checks if is string. * * @return true, if is string */ boolean isString(); /** * Checks if is binary. * * @return true, if is binary */ boolean isBinary(); } /** * This object represents the empty string value. */ EmptyValue EMPTY_STRING_VALUE = new EmptyValue() { /** * {@inheritDoc} */ public String toString() { return BrowserCoreMessages.model__empty_string_value; } /** * {@inheritDoc} */ public boolean isString() { return true; } /** * {@inheritDoc} */ public boolean isBinary() { return false; } /** * {@inheritDoc} */ public byte[] getBinaryValue() { return new byte[0]; } /** * {@inheritDoc} */ public String getStringValue() { return ""; //$NON-NLS-1$ } }; /** * This object represents the empty binary value. */ EmptyValue EMPTY_BINARY_VALUE = new EmptyValue() { /** * {@inheritDoc} */ public String toString() { return BrowserCoreMessages.model__empty_binary_value; } /** * {@inheritDoc} */ public boolean isString() { return false; } /** * {@inheritDoc} */ public boolean isBinary() { return true; } /** * {@inheritDoc} */ public byte[] getBinaryValue() { return new byte[0]; } /** * {@inheritDoc} */ public String getStringValue() { return ""; //$NON-NLS-1$ } }; /** * The attribute of this value. * * @return The attribute of this value, never null. */ IAttribute getAttribute(); /** * Gets the raw value or an EmptyValue * * @return The raw value or an EmptyValue, never null. */ Object getRawValue(); /** * Gets the string value of this value. * * If the value is binary a String with UTF-8 decoded * byte[] is returned. * * @return the String value */ String getStringValue(); /** * Gets the binary value of this value. * * If the value is string a byte[] with the * UTF-8 encoded String is returned. * * @return the binary value */ byte[] getBinaryValue(); /** * Returns true if the value is empty. * * A value is empty if its raw value is an EmptyValue. * * @return true if the value is empty. */ boolean isEmpty(); /** * Convinience method to getAttribute().isString(). * * @return true if the values attribute is string. */ boolean isString(); /** * Convinience method to getAttribute().isBinary() * * @return true if the values attribute is binary. */ boolean isBinary(); /** * Returns true if this value is part of its entry's Rdn. * * @return true if this value is part of its entry's Rdn. */ boolean isRdnPart(); /** * Return true if the argument is also of type IValue and they are * equal. * * IValues are equal if there entries, there attributes and there raw * values are equal. * * @param o * The value to compare, must be of type IValue * @return true if the argument is equal to this. */ boolean equals( Object o ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IEntry.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IEntry.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.ldapbrowser.core.model; import java.io.Serializable; import java.util.Collection; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.api.ldap.model.schema.ObjectClass; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.EntryPropertyPageProvider; import org.eclipse.core.runtime.IAdaptable; /** * An IEntry represents an LDAP entry. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IEntry extends Serializable, IAdaptable, EntryPropertyPageProvider, ConnectionPropertyPageProvider { /** * Adds the given child to this entry. * * @param childToAdd * the child to add */ void addChild( IEntry childToAdd ); /** * Deletes the given child and all its children from this entry. * * @param childToDelete * the child to delete */ void deleteChild( IEntry childToDelete ); /** * Adds the given attribute to this entry. The attribute's entry must be * this entry. * * @param attributeToAdd * the attribute to add * @throws IllegalArgumentException * if the attribute is already present in this entry or * if the attribute's entry isn't this entry. */ void addAttribute( IAttribute attributeToAdd ) throws IllegalArgumentException; /** * Deletes the given attribute from this entry. * * @param attributeToDelete * the attribute to delete * @throws IllegalArgumentException * if the attribute isn't present in this entry. */ void deleteAttribute( IAttribute attributeToDelete ) throws IllegalArgumentException; /** * Sets whether this entry exists in directory. * * @param isDirectoryEntry * true if this entry exists in directory. */ void setDirectoryEntry( boolean isDirectoryEntry ); /** * Indicates whether this entry is an alias entry. * * An entry is an alias entry if it has the object class 'alias'. * * Even if the object class attribute is not initialized an entry * is supposed to be an alias entry if the alias flag is set. * * @return true, if this entry is an alias entry */ boolean isAlias(); /** * Sets a flag whether this entry is an alias entry. * * This method is called during a search if the initialization * of the alias flag is requested. * * @param b the alias flag */ void setAlias( boolean b ); /** * Indicates whether this entry is a referral entry. * * An entry is a referral entry if it has the objectClass 'referral'. * * Even if the object class attribute is not initialized an entry * is supposed to be a referral entry if the referral flag is set. * * @return true, if this entry is a referral entry */ boolean isReferral(); /** * Sets a flag whether this entry is a referral entry. * * This method is called during a search if the initialization * fo the referral hint is requested. * * @param b the referral flag */ void setReferral( boolean b ); /** * Indicates whether this entry is a subentry. * * An entry is a subentry if it has the objectClass 'subentry'. * * Even if the object class attribute is not initialized an entry * is supposed to be a subentry if the subentry flag is set. * * @return true, if this entry is a subentry entry */ boolean isSubentry(); /** * Sets a flag whether this entry is a subentry. * * This method is called during a search if the initialization * fo the subentry is requested. * * @param b the subentry flag */ void setSubentry( boolean b ); /** * Gets the Dn of this entry, never null. * * @return the Dn of this entry, never null. */ Dn getDn(); /** * Gets the Rdn of this entry, never null. * * @return the Rdn of this entry, never null. */ Rdn getRdn(); /** * Indicates whether this entry's attributes are initialized. * * True means that the entry's attributes are completely initialized * and getAttributes() will return all attributes. * * False means that the attributes are not or only partially * initialized. The getAttributes() method will return null * or only a part of the entry's attributes. * * @return true if this entry's attributes are initialized */ boolean isAttributesInitialized(); /** * Sets a flag whether this entry's attributes are initialized. * * @param b the attributes initialized flag */ void setAttributesInitialized( boolean b ); /** * Indicates whether this entry's operational attributes should be initialized. * * @return true if this entry's attributes should be initialized */ boolean isInitOperationalAttributes(); /** * Sets a flag whether this entry's operational attributes should be initialized. * * @param b the initialize operational attributes flag */ void setInitOperationalAttributes( boolean b ); /** * Indicates whether this entry's alias children should be fetched. * * @return true if this entry's alias children should be fetched */ boolean isFetchAliases(); /** * Sets a flag whether this entry's alias children should be fetched. * * @param b the fetch aliases flag */ void setFetchAliases( boolean b ); /** * Indicates whether this entry's referral children should be fetched. * * @return true if this entry's referral children should be fetched */ boolean isFetchReferrals(); /** * Sets a flag whether this entry's referral children should be fetched. * * @param b the fetch referral flag */ void setFetchReferrals( boolean b ); /** * Indicates whether this entry's sub-entries should be fetched. * * @return true if this entry's sub-entries should be fetched */ boolean isFetchSubentries(); /** * Sets a flag whether this entry's sub-entries should be fetched. * * @param b the fetch sub-entries flag */ void setFetchSubentries( boolean b ); /** * Gets the attributes of the entry. * * If isAttributesInitialized() returns false the returned attributes * may only be a subset of the attributes in directory. * * @return The attributes of the entry or null if no attribute was added yet */ IAttribute[] getAttributes(); /** * Gets the attribute of the entry. * * @param attributeDescription the attribute description * @return The attributes of the entry or null if the attribute doesn't * exist or if the attributes aren't initialized */ IAttribute getAttribute( String attributeDescription ); /** * Gets a AttributeHierachie containing the requested attribute and * all its subtypes. * * @param attributeDescription the attribute description * @return The attributes of the entry or null if the attribute doesn't * exist or if the attributes aren't initialized */ AttributeHierarchy getAttributeWithSubtypes( String attributeDescription ); /** * Indicates whether the entry's children are initialized. * * True means that the entry's children are completely initialized * and getChildren() will return all children. * * False means that the children are not or only partially * initialized. The getChildren() method will return null * or only a part of the entry's children. * * @return true if this entry's children are initialized */ boolean isChildrenInitialized(); /** * Sets a flag whether this entry's children are initialized.. * * @param b the children initialized flag */ void setChildrenInitialized( boolean b ); /** * Returns true if the entry has children. * * @return true if the entry has children. */ boolean hasChildren(); /** * Sets a hint whether this entry has children. * * @param b the has children hint */ void setHasChildrenHint( boolean b ); /** * Gets the children of the entry. * * If isChildrenInitialized() returns false the returned children * may only be a subset of the children in directory. * * @return The children of the entry or null if no child was added yet. */ IEntry[] getChildren(); /** * Gets the number of children of the entry. * * @return The number of children of the entry or -1 if no child was added yet */ int getChildrenCount(); /** * Indicates whether this entry has more children than * getChildrenCount() returns. This occurs if the count or time limit * was exceeded while fetching children. * * @return true if this entry has (maybe) more children. */ boolean hasMoreChildren(); /** * Sets a flag whether this entry more children. * * @param b the has more children flag */ void setHasMoreChildren( boolean b ); /** * Gets the runnable used to fetch the top page of children. * * @return the runnable used to fetch the top page of children, null if none */ StudioConnectionBulkRunnableWithProgress getTopPageChildrenRunnable(); /** * Sets the runnable used to fetch the top page of children. * * @param moreChildrenRunnable the runnable used to fetch the top page of children */ void setTopPageChildrenRunnable( StudioConnectionBulkRunnableWithProgress topPageChildrenRunnable ); /** * Gets the runnable used to fetch the next page of children. * * @return the runnable used to fetch the next page of children, null if none */ StudioConnectionBulkRunnableWithProgress getNextPageChildrenRunnable(); /** * Sets the runnable used to fetch the next page of children. * * @param moreChildrenRunnable the runnable used to fetch the next page of children */ void setNextPageChildrenRunnable( StudioConnectionBulkRunnableWithProgress nextPageChildrenRunnable ); /** * Indicates whether this entry has a parent entry. Each entry except * the root DSE and the base entries should have a parent entry. * * @return true if the entry has a parent entry. */ boolean hasParententry(); /** * Gets the parent entry. * * @return the parent entry or null if this entry hasn't a parent. */ IEntry getParententry(); /** * Gets the children filter or null if none is set * * @return the children filter or null if none is set */ String getChildrenFilter(); /** * Sets the children filter. Null clears the filter. * * @param filter the children filter */ void setChildrenFilter( String filter ); /** * Gets the browser connection of this entry. * * @return the browser connection of this entry, never null. */ IBrowserConnection getBrowserConnection(); /** * Gets the LDAP URL of this entry. * * @return the LDAP URL of this entry */ LdapUrl getUrl(); /** * Gets the object class descriptions of this entry. * * @return the object class descriptions of this entry */ Collection<ObjectClass> getObjectClassDescriptions(); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IRootDSE.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IRootDSE.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.ldapbrowser.core.model; /** * An IRootDSE represents a Root DSE of an LDAP server. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IRootDSE extends IEntry { /** * Gets the supported extensions. * * @return the OIDs of the supported extensions */ String[] getSupportedExtensions(); /** * Gets the supported controls. * * @return the OIDs of the the supported controls */ String[] getSupportedControls(); /** * Gets the supported features. * * @return the OIDs of the the supported features */ String[] getSupportedFeatures(); /** * Checks if extension is supported. * * @param oid the OID * * @return true, if extension is supported */ boolean isExtensionSupported( String oid ); /** * Checks if control is supported. * * @param oid the OID * * @return true, if control is supported */ boolean isControlSupported( String oid ); /** * Checks if feature is supported. * * @param oid the OID * * @return true, if feature is supported */ boolean isFeatureSupported( String oid ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IBookmark.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/IBookmark.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.ldapbrowser.core.model; import java.io.Serializable; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.ConnectionPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.BookmarkPropertyPageProvider; import org.apache.directory.studio.ldapbrowser.core.propertypageproviders.EntryPropertyPageProvider; import org.eclipse.core.runtime.IAdaptable; /** * An IBookmark is used as shortcut to an entry in the DIT. * The target entry is defined by a connection a Dn. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface IBookmark extends Serializable, IAdaptable, BookmarkPropertyPageProvider, EntryPropertyPageProvider, ConnectionPropertyPageProvider { /** * Gets the target Dn. * * @return the Dn */ Dn getDn(); /** * Sets the target Dn. * * @param dn the Dn */ void setDn( Dn dn ); /** * Gets the symbolic name. * * @return the name */ String getName(); /** * Sets the symbolic name. * * @param name the name */ void setName( String name ); /** * Gets the browser connection. * * @return the browser connection */ IBrowserConnection getBrowserConnection(); /** * Gets the entry. * * @return the entry */ IEntry getEntry(); /** * Gets the bookmark parameter. * * @return the bookmark parameter */ BookmarkParameter getBookmarkParameter(); /** * Sets the bookmark parameter. * * @param bookmarkParameter the bookmark parameter */ void setBookmarkParameter( BookmarkParameter bookmarkParameter ); }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/SearchParameter.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/SearchParameter.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.ldapbrowser.core.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; /** * A Bean class to hold the search parameters. * It is used to make searches persistent. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SearchParameter implements Serializable { /** The serialVersionUID. */ private static final long serialVersionUID = 2447490121520960805L; /** The symbolic name. */ private String name; /** The search base. */ private Dn searchBase; /** The filter. */ private String filter; /** The returning attributes. */ private String[] returningAttributes; /** The search scope. */ private SearchScope scope; /** The time limit in seconds, 0 means no limit. */ private int timeLimit; /** The count limit, 0 means no limit. */ private int countLimit; /** The alias dereferencing method. */ private AliasDereferencingMethod aliasesDereferencingMethod; /** The referrals handling method. */ private ReferralHandlingMethod referralsHandlingMethod; /** The controls */ private List<Control> controls; /** The response controls */ private List<Control> responseControls; /** The paged search scroll mode flag. */ protected boolean pagedSearchScrollModeFlag; /** Flag indicating weather the hasChildren flag of IEntry should be initialized */ private boolean initHasChildrenFlag; /** * Creates a new instance of SearchParameter with default search parameters: * <ul> * <li>null search name * <li>null search base * <li>default filter (objectClass=*) * <li>no returning attributes * <li>search scope one level * <li>no count limit * <li>no time limit * <li>always dereference aliases * <li>follow referrals * <li>no initialization of hasChildren flag * <li>no initialization of isAlias and isReferral flag * <li>no controls * <li>no response controls * </ul> */ public SearchParameter() { name = null; searchBase = null; filter = ISearch.FILTER_TRUE; returningAttributes = ISearch.NO_ATTRIBUTES; scope = SearchScope.ONELEVEL; timeLimit = 0; countLimit = 0; aliasesDereferencingMethod = AliasDereferencingMethod.ALWAYS; referralsHandlingMethod = ReferralHandlingMethod.FOLLOW; controls = new ArrayList<>(); responseControls = new ArrayList<>(); pagedSearchScrollModeFlag = true; initHasChildrenFlag = false; } /** * Gets the count limit, 0 means no limit. * * @return the count limit */ public int getCountLimit() { return countLimit; } /** * Sets the count limit, 0 means no limit. * * @param countLimit the count limit */ public void setCountLimit( int countLimit ) { this.countLimit = countLimit; } /** * Gets the filter. * * @return the filter */ public String getFilter() { return filter; } /** * Sets the filter, a null or empty filter will be * transformed to (objectClass=*). * * @param filter the filter */ public void setFilter( String filter ) { if ( filter == null || "".equals( filter ) ) //$NON-NLS-1$ { filter = ISearch.FILTER_TRUE; } this.filter = filter; } /** * Gets the symbolic name. * * @return the name */ public String getName() { return name; } /** * Sets the symbolic name. * * @param name the name */ public void setName( String name ) { this.name = name; } /** * Gets the returning attributes. * * @return the returning attributes */ public String[] getReturningAttributes() { return returningAttributes; } /** * Sets the returning attributes, an empty array indicates none, * null will be transformed to '*' (all user attributes). * * @param returningAttributes the returning attributes */ public void setReturningAttributes( String[] returningAttributes ) { if ( returningAttributes == null ) { returningAttributes = new String[] { SchemaConstants.ALL_USER_ATTRIBUTES }; } this.returningAttributes = returningAttributes; } /** * Gets the scope. * * @return the scope */ public SearchScope getScope() { return scope; } /** * Sets the scope. * * @param scope the scope */ public void setScope( SearchScope scope ) { this.scope = scope; } /** * Gets the aliases dereferencing method. * * @return the aliases dereferencing method */ public AliasDereferencingMethod getAliasesDereferencingMethod() { return aliasesDereferencingMethod; } /** * Sets the aliases dereferencing method. * * @param aliasesDereferencingMethod the aliases dereferencing method */ public void setAliasesDereferencingMethod( AliasDereferencingMethod aliasesDereferencingMethod ) { this.aliasesDereferencingMethod = aliasesDereferencingMethod; } /** * Gets the referrals handling method. * * @return the referrals handling method */ public ReferralHandlingMethod getReferralsHandlingMethod() { return referralsHandlingMethod; } /** * Sets the referrals handling method. * * @param referralsHandlingMethod the referrals handling method */ public void setReferralsHandlingMethod( ReferralHandlingMethod referralsHandlingMethod ) { this.referralsHandlingMethod = referralsHandlingMethod; } /** * Gets the search base. * * @return the search base */ public Dn getSearchBase() { return searchBase; } /** * Sets the search base, a null search base is not allowed. * * @param searchBase the search base */ public void setSearchBase( Dn searchBase ) { assert searchBase != null; this.searchBase = searchBase; } /** * Gets the time limit in seconds, 0 means no limit. * * @return the time limit */ public int getTimeLimit() { return timeLimit; } /** * Sets the time limit in seconds, 0 means no limit. * * @param timeLimit the time limit */ public void setTimeLimit( int timeLimit ) { this.timeLimit = timeLimit; } /** * {@inheritDoc} */ public Object clone() { SearchParameter clone = new SearchParameter(); clone.setName( getName() ); clone.setSearchBase( getSearchBase() ); clone.setFilter( getFilter() ); clone.setReturningAttributes( getReturningAttributes() ); clone.setScope( getScope() ); clone.setTimeLimit( getTimeLimit() ); clone.setCountLimit( getCountLimit() ); clone.setAliasesDereferencingMethod( getAliasesDereferencingMethod() ); clone.setReferralsHandlingMethod( getReferralsHandlingMethod() ); clone.setInitHasChildrenFlag( isInitHasChildrenFlag() ); clone.getControls().addAll( getControls() ); clone.getResponseControls().addAll( getResponseControls() ); return clone; } /** * Checks if the hasChildren flag of IEntry should be initialized. * * @return true, if the hasChildren flag of IEntry should be initialized */ public boolean isInitHasChildrenFlag() { return initHasChildrenFlag; } /** * Sets if the hasChildren flag of IEntry should be initialized. * * @param initHasChildrenFlag the init hasChildren flag */ public void setInitHasChildrenFlag( boolean initHasChildrenFlag ) { this.initHasChildrenFlag = initHasChildrenFlag; } /** * Gets the request controls. * * @return the request controls */ public List<Control> getControls() { return controls; } /** * Gets the response controls. * * @return the response controls */ public List<Control> getResponseControls() { return responseControls; } public boolean isPagedSearchScrollMode() { return pagedSearchScrollModeFlag; } public void setPagedSearchScrollMode( boolean pagedSearchScrollModeFlag ) { this.pagedSearchScrollModeFlag = pagedSearchScrollModeFlag; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/AttributeHierarchy.java
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/AttributeHierarchy.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.ldapbrowser.core.model; import java.util.Arrays; import java.util.Iterator; /** * An AttributeHierarchy is a container for an attribute including all its subtypes. * <p> * Example: * <ul> * <li>attributeDescription is <code>name</code> * <li>attributes contains <code>cn:test1</code>, <code>sn:test2</code> and <code>givenName:test3</code> * </ul> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class AttributeHierarchy implements Iterable<IAttribute> { /** The entry */ private IEntry entry; /** The attribute description */ private String attributeDescription; /** The attributes */ private IAttribute[] attributes; /** * Creates a new instance of AttributeHierarchy. * * @param entry the entry * @param attributeDescription the attribute description * @param attributes the attributes */ public AttributeHierarchy( IEntry entry, String attributeDescription, IAttribute[] attributes ) { if ( entry == null || attributeDescription == null || attributes == null || attributes.length < 1 || attributes[0] == null ) { throw new IllegalArgumentException( "Empty AttributeHierachie" ); //$NON-NLS-1$ } this.entry = entry; this.attributeDescription = attributeDescription; this.attributes = attributes; } /** * Gets the attributes. * * @return the attributes */ public IAttribute[] getAttributes() { return attributes; } /** * Checks whether the given attribute is contained * in this attribute hierarchy. * * @param attribute the attribute to check * @return true if the attribute is contained in this attribute hierarchy */ public boolean contains( IAttribute attribute ) { return Arrays.asList( attributes ).contains( attribute ); } /** * Returns an iterator over the elements of this attribute hierarchy. * * @return an iterator over the elements of this attribute hierarchy */ public Iterator<IAttribute> iterator() { return Arrays.asList( attributes ).iterator(); } /** * Gets the first attribute. * * @return the first attribute */ public IAttribute getAttribute() { return attributes[0]; } /** * Gets the number of attributes. * * @return the number of attributes */ public int size() { return attributes.length; } /** * Gets the number of all values in all attributes. * * @return the number of all values in all attributes */ public int getValueSize() { int size = 0; for ( IAttribute attribute : attributes ) { size += attribute.getValueSize(); } return size; } /** * Gets the attribute description. * * @return the attribute description */ public String getAttributeDescription() { return attributeDescription; } /** * Gets the entry. * * @return the entry */ public IEntry getEntry() { return entry; } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false