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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/Messages.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapbrowser.common.dialogs;
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/TextDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/TextDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs;
import java.util.HashMap;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
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.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog with an text area.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TextDialog extends Dialog
{
/** The dialog title. */
private static final String DIALOG_TITLE = Messages.getString( "TextDialog.TextEditor" ); //$NON-NLS-1$
/** The initial value. */
private String initialValue;
/** The return value. */
private String returnValue;
/** The button ID for the save button. */
private static final int TOGGLE_BUTTON_ID = 9999;
/**
* Collection of buttons created by the <code>createButton</code> method.
*/
private HashMap<Integer, Button> buttons = new HashMap<>();
/** The text area. */
private Text text;
private int defaultTextStyle = SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL;
/** The check box to enable line wrap */
GridData gd = new GridData();
/**
* Creates a new instance of TextDialog.
*
* @param parentShell the parent shell
* @param initialValue the initial value
*/
public TextDialog( Shell parentShell, String initialValue )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE | SWT.MAX );
this.initialValue = initialValue;
this.returnValue = null;
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButton(org.eclipse.swt.widgets.Composite, int, String, boolean)
*/
@Override
protected Button createButton( Composite parent, int id, String label, boolean defaultButton )
{
return createButton( parent, id, label, defaultButton, SWT.PUSH );
}
protected Button createButton( Composite parent, int id, String label, boolean defaultButton, int style )
{
// increment the number of columns in the button bar
( ( GridLayout ) parent.getLayout() ).numColumns++;
Button button = new Button( parent, style );
button.setText( label );
button.setFont( JFaceResources.getDialogFont() );
button.setData( Integer.valueOf( id ) );
button.addSelectionListener(
new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent event )
{
buttonPressed( ( ( Integer ) event.widget.getData() ).intValue() );
}
});
if ( defaultButton )
{
Shell shell = parent.getShell();
if ( shell != null )
{
shell.setDefaultButton( button );
}
}
buttons.put( Integer.valueOf( id ), button );
setButtonLayoutData( button );
return button;
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( DIALOG_TITLE );
shell.setImage( BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_TEXTEDITOR ) );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar( Composite parent )
{
createButton( parent, TOGGLE_BUTTON_ID, Messages.getString( "TextDialog.WrapLines" ), false, SWT.TOGGLE ); //$NON-NLS-1$
createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void buttonPressed( int buttonId )
{
if ( TOGGLE_BUTTON_ID == buttonId )
{
String currentValue = text.getText();
Composite composite = text.getParent();
text.dispose();
createText(composite, currentValue, getButton( TOGGLE_BUTTON_ID ).getSelection() );
text.requestLayout();
}
super.buttonPressed( buttonId );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#getButton()
*/
@Override
protected Button getButton( int id )
{
return buttons.get( Integer.valueOf( id ) );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed()
{
returnValue = text.getText();
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea( Composite parent )
{
// create composite
Composite composite = ( Composite ) super.createDialogArea( parent );
composite.setLayoutData( new GridData( SWT.FILL,SWT.FILL,true,true ) );
// text widget
createText( composite, this.initialValue, false );
return composite;
}
protected void createText( Composite composite, String value, boolean wrap )
{
if ( wrap )
{
text = new Text( composite, defaultTextStyle | SWT.WRAP);
}
else
{
text = new Text( composite, defaultTextStyle );
}
text.setText( value );
gd = new GridData( SWT.FILL,SWT.FILL,true,true );
gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH * 2);
gd.heightHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
text.setLayoutData( gd );
applyDialogFont( composite );
}
/**
* Gets the text.
*
* @return the text
*/
public String getText()
{
return returnValue;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/DnDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/DnDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.EntryWidget;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
/**
* The DnDialog is used from the Dn value editor to edit and select a Dn.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DnDialog extends Dialog
{
/** The title. */
private String title;
/** The description. */
private String description;
/** The entry widget. */
private EntryWidget entryWidget;
/** The connection. */
private IBrowserConnection connection;
/** The dn */
private Dn dn;
/**
* Creates a new instance of DnDialog.
*
* @param parentShell the parent shell
* @param title the title of the dialog
* @param description the description of the dialog
* @param connection the connection used to browse the directory
* @param dn the initial Dn, may be null
*/
public DnDialog( Shell parentShell, String title, String description, IBrowserConnection connection, Dn dn )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.title = title;
this.description = description;
this.connection = connection;
this.dn = dn;
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( title );
shell.setImage( BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_DNEDITOR ) );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed()
{
dn = entryWidget.getDn();
entryWidget.saveDialogSettings();
super.okPressed();
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected Control createButtonBar( Composite parent )
{
Control control = super.createButtonBar( parent );
updateWidgets();
return control;
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 3 / 2;
composite.setLayoutData( gd );
if ( description != null )
{
BaseWidgetUtils.createLabel( composite, description, 1 );
}
Composite innerComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
entryWidget = new EntryWidget( connection, dn );
entryWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
updateWidgets();
}
} );
entryWidget.createWidget( innerComposite );
applyDialogFont( composite );
return composite;
}
/**
* Updates the widgets.
*/
private void updateWidgets()
{
if ( getButton( IDialogConstants.OK_ID ) != null )
{
getButton( IDialogConstants.OK_ID ).setEnabled(
entryWidget.getDn() != null && !"".equals( entryWidget.getDn().toString() ) ); //$NON-NLS-1$
}
}
/**
* Gets the dn.
*
* @return the dn
*/
public Dn getDn()
{
return dn;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/HexDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/HexDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.directory.api.util.FileUtils;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to display binary data in hex format. It could be
* used to load and save binary data from and to disk.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class HexDialog extends Dialog
{
public static final String LOAD_FILE_NAME_TOOLTIP = "LoadFileName";
/** The default title. */
private static final String DIALOG_TITLE = Messages.getString( "HexDialog.HexEditor" ); //$NON-NLS-1$
/** The button ID for the edit as text button. */
private static final int EDIT_AS_TEXT_BUTTON_ID = 9997;
/** The button ID for the load button. */
private static final int LOAD_BUTTON_ID = 9998;
/** The button ID for the save button. */
private static final int SAVE_BUTTON_ID = 9999;
/** Hidden text to set the filename, used for UI tests. */
private Text loadFilenameText;
/** The current data. */
private byte[] currentData;
/** The return data. */
private byte[] returnData;
/** The text field with the binary data. */
private Text hexText;
/**
* Creates a new instance of HexDialog.
*
* @param parentShell the parent shell
* @param initialData the initial data
*/
public HexDialog( Shell parentShell, byte[] initialData )
{
super( parentShell );
super.setShellStyle( super.getShellStyle() | SWT.RESIZE );
this.currentData = initialData;
}
/**
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void buttonPressed( int buttonId )
{
if ( buttonId == IDialogConstants.OK_ID )
{
returnData = currentData;
}
else if ( buttonId == EDIT_AS_TEXT_BUTTON_ID )
{
TextDialog dialog = new TextDialog( getShell(), new String( currentData, StandardCharsets.UTF_8 ) );
if ( dialog.open() == TextDialog.OK )
{
String text = dialog.getText();
currentData = text.getBytes( StandardCharsets.UTF_8 );
hexText.setText( toFormattedHex( currentData ) );
}
}
else if ( buttonId == SAVE_BUTTON_ID )
{
FileDialog fileDialog = new FileDialog( getShell(), SWT.SAVE );
fileDialog.setText( Messages.getString( "HexDialog.SaveData" ) ); //$NON-NLS-1$
String returnedFileName = fileDialog.open();
if ( returnedFileName != null )
{
try
{
File file = new File( returnedFileName );
FileUtils.writeByteArrayToFile( file, currentData );
}
catch ( IOException e )
{
ConnectionUIPlugin.getDefault().getExceptionHandler().handleException(
new Status( IStatus.ERROR, BrowserCommonConstants.PLUGIN_ID, IStatus.ERROR, Messages
.getString( "HexDialog.CantWriteToFile" ), e ) ); //$NON-NLS-1$
}
}
}
else if ( buttonId == LOAD_BUTTON_ID )
{
FileDialog fileDialog = new FileDialog( getShell(), SWT.OPEN );
fileDialog.setText( Messages.getString( "HexDialog.LoadData" ) ); //$NON-NLS-1$
String returnedFileName = fileDialog.open();
if ( returnedFileName != null )
{
loadFile( returnedFileName );
}
}
else
{
returnData = null;
}
super.buttonPressed( buttonId );
}
private void loadFile( String fileName )
{
try
{
File file = new File( fileName );
currentData = FileUtils.readFileToByteArray( file );
hexText.setText( toFormattedHex( currentData ) );
}
catch ( IOException e )
{
ConnectionUIPlugin.getDefault().getExceptionHandler().handleException(
new Status( IStatus.ERROR, BrowserCommonConstants.PLUGIN_ID, IStatus.ERROR, Messages
.getString( "HexDialog.CantReadFile" ), e ) ); //$NON-NLS-1$
}
}
/**
* Small helper.
*/
private boolean isEditable( byte[] b )
{
if ( b == null )
{
return false;
}
return !( new String( b, StandardCharsets.UTF_8 ).contains( "\uFFFD" ) );
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell( Shell shell )
{
super.configureShell( shell );
shell.setText( DIALOG_TITLE );
shell.setImage( BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_HEXEDITOR ) );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected void createButtonsForButtonBar( Composite parent )
{
((GridLayout) parent.getLayout()).numColumns++;
loadFilenameText = new Text( parent, SWT.NONE );
loadFilenameText.setToolTipText( LOAD_FILE_NAME_TOOLTIP );
loadFilenameText.setBackground( parent.getBackground() );
loadFilenameText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
loadFile( loadFilenameText.getText() );
}
} );
if ( isEditable( currentData ) )
{
createButton( parent, EDIT_AS_TEXT_BUTTON_ID, Messages.getString( "HexDialog.EditAsText" ), false ); //$NON-NLS-1$
}
createButton( parent, LOAD_BUTTON_ID, Messages.getString( "HexDialog.LoadDataButton" ), false ); //$NON-NLS-1$
createButton( parent, SAVE_BUTTON_ID, Messages.getString( "HexDialog.SaveDataButton" ), false ); //$NON-NLS-1$
createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea( Composite parent )
{
// create composite
Composite composite = ( Composite ) super.createDialogArea( parent );
hexText = new Text( composite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY );
hexText.setFont( JFaceResources.getFont( JFaceResources.TEXT_FONT ) );
hexText.setText( toFormattedHex( currentData ) );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = convertHorizontalDLUsToPixels( ( int ) ( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH * 1.4 ) );
gd.heightHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH / 2 );
hexText.setLayoutData( gd );
applyDialogFont( composite );
return composite;
}
/**
* Formats the binary data in two columns. One containing the hex
* presentation and one containing the ASCII presentation of each byte.
*
* 91 a1 08 23 42 b1 c1 15 52 d1 f0 24 33 62 72 82 ...#B... R..$3br.
* 09 0a 16 17 18 19 1a 25 26 27 28 29 2a 34 35 36 .......% &'()*456
*
* @param data the data
*
* @return the formatted string
*/
private String toFormattedHex( byte[] data )
{
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < data.length; i++ )
{
// get byte
int b = ( int ) data[i];
if ( b < 0 )
{
b = 256 + b;
}
// format to hex, optionally prepend a 0
String s = Integer.toHexString( b );
if ( s.length() == 1 )
{
s = "0" + s; //$NON-NLS-1$
}
// space between hex numbers
sb.append( s ).append( " " ); //$NON-NLS-1$
// extra space after 8 hex numbers
if ( ( i + 1 ) % 8 == 0 && ( i + 1 ) % 16 != 0 )
{
sb.append( " " ); //$NON-NLS-1$
}
// if end of data is reached then fill with spaces
if ( i == data.length - 1 )
{
while ( ( i + 1 ) % 16 != 0 )
{
sb.append( " " ); //$NON-NLS-1$
if ( ( i + 1 ) % 8 == 0 )
{
sb.append( " " ); //$NON-NLS-1$
}
i++;
}
}
// print ASCII characters after 16 hex numbers
if ( ( i + 1 ) % 16 == 0 )
{
sb.append( " " ); //$NON-NLS-1$
for ( int x = i - 16 + 1; x <= i && x < data.length; x++ )
{
// print ASCII character if printable
// otherwise print a dot
if ( data[x] > 32 && data[x] < 127 )
{
sb.append( ( char ) data[x] );
}
else
{
sb.append( '.' );
}
// space after 8 characters
if ( ( x + 1 ) % 8 == 0 )
{
sb.append( " " ); //$NON-NLS-1$
}
}
}
// start new line after 16 hex numbers
if ( ( i + 1 ) % 16 == 0 )
{
sb.append( "\r\n" ); //$NON-NLS-1$
}
}
return sb.toString();
}
/**
* Gets the data.
*
* @return the data
*/
public byte[] getData()
{
return returnData;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/AttributeDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/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.ldapbrowser.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.schema.BinaryAttribute;
import org.eclipse.jface.dialogs.Dialog;
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.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributeDialog extends Dialog
{
/** The initial attribute. */
private BinaryAttribute currentAttribute;
/** The possible attribute types and OIDs. */
private String[] attributeTypesAndOids;
/** The selected attribute. */
private BinaryAttribute returnAttribute;
/** The combo. */
private Combo typeOrOidCombo;
/** The OK button of the dialog */
private Button okButton;
/**
* Creates a new instance of AttributeDialog.
*
* @param parentShell the parent shell
* @param currentAttribute the current attribute, null if none
* @param attributeNamesAndOids the possible attribute names and OIDs
*/
public AttributeDialog( Shell parentShell, BinaryAttribute currentAttribute, String[] attributeNamesAndOids )
{
super( parentShell );
this.currentAttribute = currentAttribute;
this.attributeTypesAndOids = attributeNamesAndOids;
this.returnAttribute = null;
}
/**
* {@inheritDoc}
*/
protected void configureShell( Shell newShell )
{
super.configureShell( newShell );
newShell.setText( Messages.getString( "AttributeDialog.SelectAttributeTypeOrOID" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
validate();
}
/**
* {@inheritDoc}
*/
protected void okPressed()
{
returnAttribute = new BinaryAttribute( typeOrOidCombo.getText() );
super.okPressed();
}
/**
* {@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 ( currentAttribute != null )
{
typeOrOidCombo.setText( currentAttribute.getAttributeNumericOidOrName() );
}
typeOrOidCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return composite;
}
private void validate()
{
okButton.setEnabled( !"".equals( typeOrOidCombo.getText() ) ); //$NON-NLS-1$
}
/**
* Gets the entered/selected attribute.
*
* @return the attribute
*/
public BinaryAttribute getAttribute()
{
return returnAttribute;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/BrowserPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/BrowserPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants;
import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The BrowserPreferencePage contains general settings for the browser view.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class BrowserPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
private static final String DN = Messages.getString( "BrowserPreferencePage.DN" ); //$NON-NLS-1$
private static final String RDN = Messages.getString( "BrowserPreferencePage.RDN" ); //$NON-NLS-1$
private static final String RDN_VALUE = Messages.getString( "BrowserPreferencePage.RDNValue" ); //$NON-NLS-1$
private Combo entryLabelCombo;
private Button entryAbbreviateButton;
private Text entryAbbreviateMaxLengthText;
private Combo searchResultLabelCombo;
private Button searchResultAbbreviateButton;
private Text searchResultAbbreviateMaxLengthText;
private Button enableFoldingButton;
private Label foldingSizeLabel;
private Text foldingSizeText;
private Button expandBaseEntriesButton;;
private Button checkForChildrenButton;
/**
* Creates a new instance of BrowserPreferencePage.
*/
public BrowserPreferencePage()
{
super( Messages.getString( "BrowserPreferencePage.Browser" ) ); //$NON-NLS-1$
super.setPreferenceStore( BrowserCommonActivator.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "BrowserPreferencePage.GeneralSettings" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
Group entryLabelGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ),
Messages.getString( "BrowserPreferencePage.EntryLabel" ), 1 ); //$NON-NLS-1$
Composite entryLabelComposite = BaseWidgetUtils.createColumnContainer( entryLabelGroup, 3, 1 );
BaseWidgetUtils.createLabel( entryLabelComposite,
Messages.getString( "BrowserPreferencePage.UseAsEntryLabel1" ), 1 ); //$NON-NLS-1$
entryLabelCombo = BaseWidgetUtils.createCombo( entryLabelComposite, new String[]
{ DN, RDN, RDN_VALUE }, 0, 1 );
entryLabelCombo.setLayoutData( new GridData() );
entryLabelCombo
.select( getPreferenceStore().getInt( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_LABEL ) == BrowserCommonConstants.SHOW_RDN_VALUE ? 2
: getPreferenceStore().getInt( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_LABEL ) == BrowserCommonConstants.SHOW_RDN ? 1
: 0 );
BaseWidgetUtils.createLabel( entryLabelComposite,
Messages.getString( "BrowserPreferencePage.UseAsEntryLabel2" ), 1 ); //$NON-NLS-1$
Composite entryAbbreviateComposite = BaseWidgetUtils.createColumnContainer( entryLabelGroup, 3, 1 );
entryAbbreviateButton = BaseWidgetUtils.createCheckbox( entryAbbreviateComposite, Messages
.getString( "BrowserPreferencePage.LimitLabelLength1" ), 1 ); //$NON-NLS-1$
entryAbbreviateButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE ) );
entryAbbreviateButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
updateEnabled();
}
} );
entryAbbreviateMaxLengthText = BaseWidgetUtils.createText( entryAbbreviateComposite, getPreferenceStore()
.getString( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE_MAX_LENGTH ), 3, 1 );
entryAbbreviateMaxLengthText.setEnabled( entryAbbreviateButton.getSelection() );
entryAbbreviateMaxLengthText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
if ( "".equals( entryAbbreviateMaxLengthText.getText() ) && e.text.matches( "[0]" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
e.doit = false;
}
}
} );
BaseWidgetUtils.createLabel( entryAbbreviateComposite, Messages
.getString( "BrowserPreferencePage.LimitLabelLength2" ), 1 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
Group searchResultLabelGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite,
1, 1 ), Messages.getString( "BrowserPreferencePage.SearchResultLabel" ), 1 ); //$NON-NLS-1$
Composite searchResultLabelComposite = BaseWidgetUtils.createColumnContainer( searchResultLabelGroup, 3, 1 );
BaseWidgetUtils.createLabel( searchResultLabelComposite, Messages
.getString( "BrowserPreferencePage.UseAsSearchResultLabel1" ), 1 ); //$NON-NLS-1$
searchResultLabelCombo = BaseWidgetUtils.createCombo( searchResultLabelComposite, new String[]
{ DN, RDN, RDN_VALUE }, 0, 1 );
searchResultLabelCombo.setLayoutData( new GridData() );
searchResultLabelCombo
.select( getPreferenceStore().getInt( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_LABEL ) == BrowserCommonConstants.SHOW_RDN_VALUE ? 2
: getPreferenceStore().getInt( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_LABEL ) == BrowserCommonConstants.SHOW_RDN ? 1
: 0 );
BaseWidgetUtils.createLabel( searchResultLabelComposite, Messages
.getString( "BrowserPreferencePage.UseAsSearchResultLabel2" ), 1 ); //$NON-NLS-1$
Composite searchResultAbbreviateComposite = BaseWidgetUtils
.createColumnContainer( searchResultLabelGroup, 3, 1 );
searchResultAbbreviateButton = BaseWidgetUtils.createCheckbox( searchResultAbbreviateComposite, Messages
.getString( "BrowserPreferencePage.LimitLabelLength1" ), 1 ); //$NON-NLS-1$
searchResultAbbreviateButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE ) );
searchResultAbbreviateButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
updateEnabled();
}
} );
searchResultAbbreviateMaxLengthText = BaseWidgetUtils.createText( searchResultAbbreviateComposite,
getPreferenceStore().getString(
BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE_MAX_LENGTH ), 3, 1 );
searchResultAbbreviateMaxLengthText.setEnabled( searchResultAbbreviateButton.getSelection() );
searchResultAbbreviateMaxLengthText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
if ( "".equals( searchResultAbbreviateMaxLengthText.getText() ) && e.text.matches( "[0]" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
e.doit = false;
}
}
} );
BaseWidgetUtils.createLabel( searchResultAbbreviateComposite, Messages
.getString( "BrowserPreferencePage.LimitLabelLength2" ), 1 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
Group foldingGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ),
Messages.getString( "BrowserPreferencePage.Folding" ), 1 ); //$NON-NLS-1$
Composite pagingGroupComposite = BaseWidgetUtils.createColumnContainer( foldingGroup, 2, 1 );
enableFoldingButton = BaseWidgetUtils.createCheckbox( pagingGroupComposite, Messages
.getString( "BrowserPreferencePage.EnableFolding" ), 2 ); //$NON-NLS-1$
enableFoldingButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_ENABLE_FOLDING ) );
enableFoldingButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
updateEnabled();
}
} );
foldingSizeLabel = BaseWidgetUtils.createLabel( pagingGroupComposite, Messages
.getString( "BrowserPreferencePage.FoldingSize" ), 1 ); //$NON-NLS-1$
foldingSizeLabel.setEnabled( enableFoldingButton.getSelection() );
foldingSizeText = BaseWidgetUtils.createText( pagingGroupComposite, getPreferenceStore().getString(
BrowserCommonConstants.PREFERENCE_BROWSER_FOLDING_SIZE ), 4, 1 );
foldingSizeText.setEnabled( enableFoldingButton.getSelection() );
foldingSizeText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
if ( "".equals( foldingSizeText.getText() ) && e.text.matches( "[0]" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
e.doit = false;
}
}
} );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
expandBaseEntriesButton = BaseWidgetUtils.createCheckbox( composite, Messages
.getString( "BrowserPreferencePage.ExpandBaseEntries" ), 1 ); //$NON-NLS-1$
expandBaseEntriesButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_EXPAND_BASE_ENTRIES ) );
Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences();
checkForChildrenButton = BaseWidgetUtils.createCheckbox( composite, Messages
.getString( "BrowserPreferencePage.CheckForChildren" ), 1 ); //$NON-NLS-1$
checkForChildrenButton
.setSelection( coreStore.getBoolean( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN ) );
updateEnabled();
applyDialogFont( composite );
return composite;
}
private void updateEnabled()
{
entryAbbreviateMaxLengthText.setEnabled( entryAbbreviateButton.getSelection() );
searchResultAbbreviateMaxLengthText.setEnabled( searchResultAbbreviateButton.getSelection() );
foldingSizeText.setEnabled( enableFoldingButton.getSelection() );
foldingSizeLabel.setEnabled( enableFoldingButton.getSelection() );
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences();
coreStore.setValue( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN, checkForChildrenButton.getSelection() );
BrowserCorePlugin.getDefault().savePluginPreferences();
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_EXPAND_BASE_ENTRIES,
expandBaseEntriesButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_ENABLE_FOLDING,
enableFoldingButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_FOLDING_SIZE,
foldingSizeText.getText().trim() );
getPreferenceStore().setValue(
BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_LABEL,
entryLabelCombo.getSelectionIndex() == 2 ? BrowserCommonConstants.SHOW_RDN_VALUE : entryLabelCombo
.getSelectionIndex() == 1 ? BrowserCommonConstants.SHOW_RDN : BrowserCommonConstants.SHOW_DN );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE,
entryAbbreviateButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE_MAX_LENGTH,
entryAbbreviateMaxLengthText.getText().trim() );
getPreferenceStore().setValue(
BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_LABEL,
searchResultLabelCombo.getSelectionIndex() == 2 ? BrowserCommonConstants.SHOW_RDN_VALUE
: searchResultLabelCombo.getSelectionIndex() == 1 ? BrowserCommonConstants.SHOW_RDN
: BrowserCommonConstants.SHOW_DN );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE,
searchResultAbbreviateButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE_MAX_LENGTH,
searchResultAbbreviateMaxLengthText.getText().trim() );
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
entryLabelCombo
.select( getPreferenceStore().getDefaultInt( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_LABEL ) == BrowserCommonConstants.SHOW_RDN_VALUE ? 2
: getPreferenceStore().getDefaultInt( BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_LABEL ) == BrowserCommonConstants.SHOW_RDN ? 1
: 0 );
entryAbbreviateButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE ) );
entryAbbreviateMaxLengthText.setText( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_BROWSER_ENTRY_ABBREVIATE_MAX_LENGTH ) );
searchResultLabelCombo
.select( getPreferenceStore().getDefaultInt( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_LABEL ) == BrowserCommonConstants.SHOW_RDN_VALUE ? 2
: getPreferenceStore().getDefaultInt( BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_LABEL ) == BrowserCommonConstants.SHOW_RDN ? 1
: 0 );
searchResultAbbreviateButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE ) );
searchResultAbbreviateMaxLengthText.setText( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_BROWSER_SEARCH_RESULT_ABBREVIATE_MAX_LENGTH ) );
enableFoldingButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_ENABLE_FOLDING ) );
foldingSizeText.setText( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_BROWSER_FOLDING_SIZE ) );
expandBaseEntriesButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_BROWSER_EXPAND_BASE_ENTRIES ) );
Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences();
checkForChildrenButton.setSelection( coreStore
.getDefaultBoolean( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN ) );
updateEnabled();
super.performDefaults();
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/ViewsPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/ViewsPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
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;
/**
* The BrowserPreferencePage contains general settings for the browser view.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ViewsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
/**
* Creates a new instance of ViewsPreferencePage.
*/
public ViewsPreferencePage()
{
super( Messages.getString( "ViewsPreferencePage.Views" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "ViewsPreferencePage.Description" ) ); //$NON-NLS-1$
// Removing Default and Apply buttons
noDefaultAndApplyButton();
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
// Nothing to do
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
// Nothing to do
return parent;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/EntryEditorPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/EntryEditorPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The EntryEditorPreferencePage contains general settings for the entry editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EntryEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
private Button autosaveSingleTabButton;
private Button autosaveMultiTabButton;
private Button enableFoldingButton;
private Label foldingThresholdLabel;
private Text foldingThresholdText;
private Button autoExpandFoldedAttributesButton;
/**
* Creates a new instance of EntryEditorPreferencePage.
*/
public EntryEditorPreferencePage()
{
super( Messages.getString( "EntryEditorPreferencePage.EntryEditor" ) ); //$NON-NLS-1$
super.setPreferenceStore( BrowserCommonActivator.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "EntryEditorPreferencePage.GeneralSettings" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
String foldingTooltip = Messages.getString( "EntryEditorPreferencePage.FoldingToolTip" ); //$NON-NLS-1$
Group foldingGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ),
Messages.getString( "EntryEditorPreferencePage.Folding" ), 1 ); //$NON-NLS-1$
Composite pagingGroupComposite = BaseWidgetUtils.createColumnContainer( foldingGroup, 3, 1 );
enableFoldingButton = BaseWidgetUtils.createCheckbox( pagingGroupComposite, Messages
.getString( "EntryEditorPreferencePage.EnableFolding" ), 3 ); //$NON-NLS-1$
enableFoldingButton.setToolTipText( foldingTooltip );
enableFoldingButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_ENABLE_FOLDING ) );
enableFoldingButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
updateEnabled();
}
} );
BaseWidgetUtils.createRadioIndent( pagingGroupComposite, 1 );
foldingThresholdLabel = BaseWidgetUtils.createLabel( pagingGroupComposite, Messages
.getString( "EntryEditorPreferencePage.FoldingThreshold" ), 1 ); //$NON-NLS-1$
foldingThresholdLabel.setToolTipText( foldingTooltip );
foldingThresholdLabel.setEnabled( enableFoldingButton.getSelection() );
foldingThresholdText = BaseWidgetUtils.createText( pagingGroupComposite, getPreferenceStore().getString(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_FOLDING_THRESHOLD ), 4, 1 );
foldingThresholdText.setToolTipText( foldingTooltip );
foldingThresholdText.setEnabled( enableFoldingButton.getSelection() );
foldingThresholdText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
if ( "".equals( foldingThresholdText.getText() ) && e.text.matches( "[0]" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
e.doit = false;
}
}
} );
BaseWidgetUtils.createRadioIndent( pagingGroupComposite, 1 );
autoExpandFoldedAttributesButton = BaseWidgetUtils.createCheckbox( pagingGroupComposite, Messages
.getString( "EntryEditorPreferencePage.AutoExpandFoldedAttributes" ), 2 ); //$NON-NLS-1$
autoExpandFoldedAttributesButton.setEnabled( enableFoldingButton.getSelection() );
autoExpandFoldedAttributesButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTO_EXPAND_FOLDED_ATTRIBUTES ) );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
Group autosaveGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ),
Messages.getString( "EntryEditorPreferencePage.Autosave" ), 1 ); //$NON-NLS-1$
Composite autosaveComposite = BaseWidgetUtils.createColumnContainer( autosaveGroup, 1, 1 );
autosaveSingleTabButton = BaseWidgetUtils.createCheckbox( autosaveComposite, Messages
.getString( "EntryEditorPreferencePage.AutosaveSingleTab" ), 1 ); //$NON-NLS-1$
autosaveSingleTabButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_SINGLE_TAB ) );
autosaveMultiTabButton = BaseWidgetUtils.createCheckbox( autosaveComposite, Messages
.getString( "EntryEditorPreferencePage.AutosaveMultiTab" ), 1 ); //$NON-NLS-1$
autosaveMultiTabButton.setSelection( getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_MULTI_TAB ) );
updateEnabled();
applyDialogFont( composite );
return composite;
}
private void updateEnabled()
{
foldingThresholdText.setEnabled( enableFoldingButton.getSelection() );
foldingThresholdLabel.setEnabled( enableFoldingButton.getSelection() );
autoExpandFoldedAttributesButton.setEnabled( enableFoldingButton.getSelection() );
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_SINGLE_TAB,
autosaveSingleTabButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_MULTI_TAB,
autosaveMultiTabButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_ENABLE_FOLDING,
enableFoldingButton.getSelection() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_FOLDING_THRESHOLD,
foldingThresholdText.getText() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTO_EXPAND_FOLDED_ATTRIBUTES,
autoExpandFoldedAttributesButton.getSelection() );
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
autosaveSingleTabButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_SINGLE_TAB ) );
autosaveMultiTabButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTOSAVE_MULTI_TAB ) );
enableFoldingButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_ENABLE_FOLDING ) );
foldingThresholdText.setText( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_FOLDING_THRESHOLD ) );
autoExpandFoldedAttributesButton.setSelection( getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_ENTRYEDITOR_AUTO_EXPAND_FOLDED_ATTRIBUTES ) );
updateEnabled();
super.performDefaults();
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/MainPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/MainPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
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;
/**
* The main preference page contains general settings for the LDAP browser.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class MainPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
/**
*
* Creates a new instance of MainPreferencePage.
*/
public MainPreferencePage()
{
super( Messages.getString( "MainPreferencePage.LDAP" ) ); //$NON-NLS-1$
super.setPreferenceStore( BrowserCommonActivator.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "MainPreferencePage.GeneralSettings" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
return composite;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
super.performDefaults();
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/TextFormatsPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/TextFormatsPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.widgets.BinaryEncodingInput;
import org.apache.directory.studio.ldapbrowser.common.widgets.FileEncodingInput;
import org.apache.directory.studio.ldapbrowser.common.widgets.LineSeparatorInput;
import org.apache.directory.studio.ldapbrowser.common.widgets.OptionsInput;
import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants;
import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The BinaryAttributesAndSyntaxesPreferencePage is used to specify
* binary attributes and syntaxes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TextFormatsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage,
WidgetModifyListener, ModifyListener
{
/** The constant used to preselect the 'LDIF' tab */
public static final String LDIF_TAB = "LDIF"; //$NON-NLS-1$
/** The constant used to preselect the 'CSV Export' tab */
public static final String CSV_TAB = "CSV"; //$NON-NLS-1$
/** The constant used to preselect the 'Excel Export' tab */
public static final String XLS_TAB = "XLS"; //$NON-NLS-1$
/** The constant used to preselect the 'ODF Export' tab */
public static final String ODF_TAB = "ODF"; //$NON-NLS-1$
/** The constant used to preselect the 'CSV Copy' tab */
public static final String TABLE_TAB = "TABLE"; //$NON-NLS-1$
private Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences();
private TabFolder tabFolder;
private TabItem ldifTab;
private TabItem tableTab;
private TabItem csvTab;
private TabItem xlsTab;
private TabItem odfTab;
private Text ldifLineLengthText;
private Button ldifSpaceAfterColonButton;
private Button includeVersionLineButton;
private LineSeparatorInput ldifLineSeparator;
private OptionsInput tableAttributeDelimiterWidget;
private OptionsInput tableValueDelimiterWidget;
private OptionsInput tableQuoteWidget;
private LineSeparatorInput tableLineSeparator;
private BinaryEncodingInput tableBinaryEncodingWidget;
private OptionsInput csvAttributeDelimiterWidget;
private OptionsInput csvValueDelimiterWidget;
private OptionsInput csvQuoteWidget;
private LineSeparatorInput csvLineSeparator;
private BinaryEncodingInput csvBinaryEncodingWidget;
private FileEncodingInput csvEncodingWidget;
private OptionsInput xlsValueDelimiterWidget;
private OptionsInput xlsBinaryEncodingWidget;
private OptionsInput odfValueDelimiterWidget;
private OptionsInput odfBinaryEncodingWidget;
/**
* Creates a new instance of TextFormatsPreferencePage.
*/
public TextFormatsPreferencePage()
{
super( Messages.getString( "TextFormatsPreferencePage.TextFormats" ) ); //$NON-NLS-1$
super.setPreferenceStore( BrowserCommonActivator.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "TextFormatsPreferencePage.SettingsForTextFormats" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
public void applyData( Object data )
{
if ( data != null && tabFolder != null )
{
if ( LDIF_TAB.equals( data ) )
{
tabFolder.setSelection( 0 );
}
else if ( TABLE_TAB.equals( data ) )
{
tabFolder.setSelection( 1 );
}
else if ( CSV_TAB.equals( data ) )
{
tabFolder.setSelection( 2 );
}
else if ( XLS_TAB.equals( data ) )
{
tabFolder.setSelection( 3 );
}
else if ( ODF_TAB.equals( data ) )
{
tabFolder.setSelection( 4 );
}
}
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
BaseWidgetUtils.createSpacer( parent, 1 );
tabFolder = new TabFolder( parent, SWT.TOP );
createLdifTab();
createTableTab();
createCsvTab();
createXlsTab();
createOdfTab();
validate();
applyDialogFont( tabFolder );
return tabFolder;
}
private void createTableTab()
{
tableTab = new TabItem( tabFolder, SWT.NONE );
tableTab.setText( Messages.getString( "TextFormatsPreferencePage.CSVCopy" ) ); //$NON-NLS-1$
Composite tableComposite = new Composite( tabFolder, SWT.NONE );
tableComposite.setLayout( new GridLayout( 1, false ) );
Composite tableInnerComposite = BaseWidgetUtils.createColumnContainer( tableComposite, 3, 1 );
BaseWidgetUtils.createLabel( tableInnerComposite,
Messages.getString( "TextFormatsPreferencePage.CSVCopyLabel" ), 3 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( tableInnerComposite, 3 );
tableAttributeDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.AttributeDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Tabulator" ), "\t", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Tabulator" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{ "\t", ",", ";" }, getPreferenceStore().getString( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_ATTRIBUTEDELIMITER ), false, true );
tableAttributeDelimiterWidget.createWidget( tableInnerComposite );
tableAttributeDelimiterWidget.addWidgetModifyListener( this );
tableValueDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.ValueDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Pipe" ), "|", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Pipe" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ), Messages.getString( "TextFormatsPreferencePage.Newline" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
{ "|", ",", ";", "\n" }, getPreferenceStore().getString( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_VALUEDELIMITER ), false, true );
tableValueDelimiterWidget.createWidget( tableInnerComposite );
tableValueDelimiterWidget.addWidgetModifyListener( this );
tableQuoteWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.QuoteCharacter" ), Messages.getString( "TextFormatsPreferencePage.DoubleQuote" ), "\"", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.DoubleQuote" ), Messages.getString( "TextFormatsPreferencePage.SingleQuote" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$
{ "\"", "'" }, getPreferenceStore().getString( //$NON-NLS-1$ //$NON-NLS-2$
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_QUOTECHARACTER ), false, true );
tableQuoteWidget.createWidget( tableInnerComposite );
tableQuoteWidget.addWidgetModifyListener( this );
tableLineSeparator = new LineSeparatorInput( getPreferenceStore().getString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_LINESEPARATOR ), false );
tableLineSeparator.createWidget( tableInnerComposite );
tableLineSeparator.addWidgetModifyListener( this );
tableBinaryEncodingWidget = new BinaryEncodingInput( getPreferenceStore().getString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_BINARYENCODING ), false );
tableBinaryEncodingWidget.createWidget( tableInnerComposite );
tableBinaryEncodingWidget.addWidgetModifyListener( this );
Composite copyTableHintComposite = BaseWidgetUtils.createColumnContainer( tableInnerComposite, 3, 3 );
Text hintText = BaseWidgetUtils.createWrappedLabeledText( copyTableHintComposite, Messages
.getString( "TextFormatsPreferencePage.CSVCopyHint" ), 1 ); //$NON-NLS-1$
GridData hintTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false );
hintTextGridData.widthHint = 300;
hintText.setLayoutData( hintTextGridData );
tableTab.setControl( tableComposite );
}
private void createCsvTab()
{
csvTab = new TabItem( tabFolder, SWT.NONE );
csvTab.setText( Messages.getString( "TextFormatsPreferencePage.CSVExport" ) ); //$NON-NLS-1$
Composite csvComposite = new Composite( tabFolder, SWT.NONE );
csvComposite.setLayout( new GridLayout( 1, false ) );
Composite csvInnerComposite = BaseWidgetUtils.createColumnContainer( csvComposite, 3, 1 );
BaseWidgetUtils.createLabel( csvInnerComposite,
Messages.getString( "TextFormatsPreferencePage.CSVExportLabel" ), 3 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( csvInnerComposite, 3 );
csvAttributeDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.AttributeDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), ",", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ), Messages.getString( "TextFormatsPreferencePage.Tabulator" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{ ",", ";", "\t" }, coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
false, true );
csvAttributeDelimiterWidget.createWidget( csvInnerComposite );
csvAttributeDelimiterWidget.addWidgetModifyListener( this );
csvValueDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.ValueDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Pipe" ), "|", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Pipe" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ), Messages.getString( "TextFormatsPreferencePage.Newline" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
{ "|", ",", ";", "\n" }, coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_VALUEDELIMITER ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
false, true );
csvValueDelimiterWidget.createWidget( csvInnerComposite );
csvValueDelimiterWidget.addWidgetModifyListener( this );
csvQuoteWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.QuoteCharacter" ), Messages.getString( "TextFormatsPreferencePage.DoubleQuote" ), "\"", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.DoubleQuote" ), Messages.getString( "TextFormatsPreferencePage.SingleQuote" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$
{ "\"", "'" }, coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_QUOTECHARACTER ), false, //$NON-NLS-1$ //$NON-NLS-2$
true );
csvQuoteWidget.createWidget( csvInnerComposite );
csvQuoteWidget.addWidgetModifyListener( this );
csvLineSeparator = new LineSeparatorInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_LINESEPARATOR ), false );
csvLineSeparator.createWidget( csvInnerComposite );
csvLineSeparator.addWidgetModifyListener( this );
csvBinaryEncodingWidget = new BinaryEncodingInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_BINARYENCODING ), false );
csvBinaryEncodingWidget.createWidget( csvInnerComposite );
csvBinaryEncodingWidget.addWidgetModifyListener( this );
csvEncodingWidget = new FileEncodingInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING ), false );
csvEncodingWidget.createWidget( csvInnerComposite );
csvEncodingWidget.addWidgetModifyListener( this );
csvTab.setControl( csvComposite );
}
private void createXlsTab()
{
xlsTab = new TabItem( tabFolder, SWT.NONE );
xlsTab.setText( Messages.getString( "TextFormatsPreferencePage.ExcelExport" ) ); //$NON-NLS-1$
Composite xlsComposite = new Composite( tabFolder, SWT.NONE );
xlsComposite.setLayout( new GridLayout( 1, false ) );
Composite xlsInnerComposite = BaseWidgetUtils.createColumnContainer( xlsComposite, 3, 1 );
BaseWidgetUtils.createLabel( xlsInnerComposite, Messages
.getString( "TextFormatsPreferencePage.ExcelExportLabel" ), 3 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( xlsInnerComposite, 3 );
xlsValueDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.ValueDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Pipe" ), "|", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Pipe" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ), Messages.getString( "TextFormatsPreferencePage.Newline" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
{ "|", ",", ";", "\n" }, coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
false, true );
xlsValueDelimiterWidget.createWidget( xlsInnerComposite );
xlsValueDelimiterWidget.addWidgetModifyListener( this );
xlsBinaryEncodingWidget = new BinaryEncodingInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING ), false );
xlsBinaryEncodingWidget.createWidget( xlsInnerComposite );
xlsBinaryEncodingWidget.addWidgetModifyListener( this );
xlsTab.setControl( xlsComposite );
}
private void createOdfTab()
{
odfTab = new TabItem( tabFolder, SWT.NONE );
odfTab.setText( Messages.getString( "TextFormatsPreferencePage.OdfExport" ) ); //$NON-NLS-1$
Composite odfComposite = new Composite( tabFolder, SWT.NONE );
odfComposite.setLayout( new GridLayout( 1, false ) );
Composite odfInnerComposite = BaseWidgetUtils.createColumnContainer( odfComposite, 3, 1 );
BaseWidgetUtils.createLabel( odfInnerComposite,
Messages.getString( "TextFormatsPreferencePage.OdfExportLabel" ), 3 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( odfInnerComposite, 3 );
odfValueDelimiterWidget = new OptionsInput(
Messages.getString( "TextFormatsPreferencePage.ValueDelimiter" ), Messages.getString( "TextFormatsPreferencePage.Pipe" ), "|", new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
Messages.getString( "TextFormatsPreferencePage.Pipe" ), Messages.getString( "TextFormatsPreferencePage.Comma" ), Messages.getString( "TextFormatsPreferencePage.Semicolon" ), Messages.getString( "TextFormatsPreferencePage.Newline" ) }, new String[] //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
{ "|", ",", ";", "\n" }, coreStore.getString( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_VALUEDELIMITER ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
false, true );
odfValueDelimiterWidget.createWidget( odfInnerComposite );
odfValueDelimiterWidget.addWidgetModifyListener( this );
odfBinaryEncodingWidget = new BinaryEncodingInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_FORMAT_ODF_BINARYENCODING ), false );
odfBinaryEncodingWidget.createWidget( odfInnerComposite );
odfBinaryEncodingWidget.addWidgetModifyListener( this );
odfTab.setControl( odfComposite );
}
private void createLdifTab()
{
ldifTab = new TabItem( tabFolder, SWT.NONE );
ldifTab.setText( Messages.getString( "TextFormatsPreferencePage.LDIF" ) ); //$NON-NLS-1$
Composite ldifComposite = new Composite( tabFolder, SWT.NONE );
ldifComposite.setLayout( new GridLayout( 1, false ) );
Composite ldifInnerComposite = BaseWidgetUtils.createColumnContainer( ldifComposite, 1, 1 );
BaseWidgetUtils
.createLabel( ldifInnerComposite, Messages.getString( "TextFormatsPreferencePage.LDIFLabel" ), 1 ); //$NON-NLS-1$
BaseWidgetUtils.createSpacer( ldifInnerComposite, 1 );
ldifLineSeparator = new LineSeparatorInput( coreStore
.getString( BrowserCoreConstants.PREFERENCE_LDIF_LINE_SEPARATOR ), true );
ldifLineSeparator.createWidget( ldifInnerComposite );
ldifLineSeparator.addWidgetModifyListener( this );
BaseWidgetUtils.createSpacer( ldifInnerComposite, 1 );
Composite lineLengthComposite = BaseWidgetUtils.createColumnContainer( ldifInnerComposite, 3, 1 );
BaseWidgetUtils.createLabel( lineLengthComposite,
Messages.getString( "TextFormatsPreferencePage.LineLength1" ), 1 ); //$NON-NLS-1$
ldifLineLengthText = BaseWidgetUtils.createText( lineLengthComposite, "", 3, 1 ); //$NON-NLS-1$
ldifLineLengthText.setText( coreStore.getString( BrowserCoreConstants.PREFERENCE_LDIF_LINE_WIDTH ) );
ldifLineLengthText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
if ( "".equals( ldifLineLengthText.getText() ) && e.text.matches( "[0]" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
e.doit = false;
}
}
} );
ldifLineLengthText.addModifyListener( this );
BaseWidgetUtils.createLabel( lineLengthComposite,
Messages.getString( "TextFormatsPreferencePage.LineLength2" ), 1 ); //$NON-NLS-1$
ldifSpaceAfterColonButton = BaseWidgetUtils.createCheckbox( ldifInnerComposite, Messages
.getString( "TextFormatsPreferencePage.SpaceAfterColon" ), 1 ); //$NON-NLS-1$
ldifSpaceAfterColonButton.setSelection( coreStore
.getBoolean( BrowserCoreConstants.PREFERENCE_LDIF_SPACE_AFTER_COLON ) );
includeVersionLineButton = BaseWidgetUtils.createCheckbox( ldifInnerComposite, Messages
.getString( "TextFormatsPreferencePage.IncludeVersionLine" ), 1 ); //$NON-NLS-1$
includeVersionLineButton.setSelection( coreStore
.getBoolean( BrowserCoreConstants.PREFERENCE_LDIF_INCLUDE_VERSION_LINE ) );
ldifTab.setControl( ldifComposite );
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
coreStore.setValue( BrowserCoreConstants.PREFERENCE_LDIF_LINE_WIDTH, ldifLineLengthText.getText() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_LDIF_LINE_SEPARATOR, ldifLineSeparator.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_LDIF_SPACE_AFTER_COLON, ldifSpaceAfterColonButton
.getSelection() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_LDIF_INCLUDE_VERSION_LINE, includeVersionLineButton
.getSelection() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER, csvAttributeDelimiterWidget
.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_VALUEDELIMITER, csvValueDelimiterWidget
.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_QUOTECHARACTER, csvQuoteWidget.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_LINESEPARATOR, csvLineSeparator.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_BINARYENCODING, csvBinaryEncodingWidget
.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING, csvEncodingWidget.getRawValue() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_ATTRIBUTEDELIMITER,
tableAttributeDelimiterWidget.getRawValue() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_VALUEDELIMITER,
tableValueDelimiterWidget.getRawValue() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_QUOTECHARACTER,
tableQuoteWidget.getRawValue() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_LINESEPARATOR,
tableLineSeparator.getRawValue() );
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_BINARYENCODING,
tableBinaryEncodingWidget.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER, xlsValueDelimiterWidget
.getRawValue() );
coreStore.setValue( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING, xlsBinaryEncodingWidget
.getRawValue() );
BrowserCorePlugin.getDefault().savePluginPreferences();
validate();
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
ldifLineLengthText.setText( coreStore.getDefaultString( BrowserCoreConstants.PREFERENCE_LDIF_LINE_WIDTH ) );
ldifLineSeparator
.setRawValue( coreStore.getDefaultString( BrowserCoreConstants.PREFERENCE_LDIF_LINE_SEPARATOR ) );
ldifSpaceAfterColonButton.setSelection( coreStore
.getDefaultBoolean( BrowserCoreConstants.PREFERENCE_LDIF_SPACE_AFTER_COLON ) );
includeVersionLineButton.setSelection( coreStore
.getDefaultBoolean( BrowserCoreConstants.PREFERENCE_LDIF_INCLUDE_VERSION_LINE ) );
csvAttributeDelimiterWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ATTRIBUTEDELIMITER ) );
csvValueDelimiterWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_VALUEDELIMITER ) );
csvQuoteWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_QUOTECHARACTER ) );
csvLineSeparator.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_LINESEPARATOR ) );
csvBinaryEncodingWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_BINARYENCODING ) );
csvEncodingWidget
.setRawValue( coreStore.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING ) );
tableAttributeDelimiterWidget.setRawValue( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_ATTRIBUTEDELIMITER ) );
tableValueDelimiterWidget.setRawValue( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_VALUEDELIMITER ) );
tableQuoteWidget.setRawValue( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_QUOTECHARACTER ) );
tableLineSeparator.setRawValue( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_LINESEPARATOR ) );
tableBinaryEncodingWidget.setRawValue( getPreferenceStore().getDefaultString(
BrowserCommonConstants.PREFERENCE_FORMAT_TABLE_BINARYENCODING ) );
xlsValueDelimiterWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER ) );
xlsBinaryEncodingWidget.setRawValue( coreStore
.getDefaultString( BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING ) );
validate();
super.performDefaults();
}
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
public void modifyText( ModifyEvent e )
{
validate();
}
protected void validate()
{
setValid( !"".equals( csvAttributeDelimiterWidget.getRawValue() ) //$NON-NLS-1$
&& !"".equals( csvValueDelimiterWidget.getRawValue() ) && !"".equals( csvQuoteWidget.getRawValue() ) //$NON-NLS-1$ //$NON-NLS-2$
&& !"".equals( csvLineSeparator.getRawValue() ) && !"".equals( csvBinaryEncodingWidget.getRawValue() ) //$NON-NLS-1$ //$NON-NLS-2$
&& !"".equals( csvEncodingWidget.getRawValue() ) && //$NON-NLS-1$
!"".equals( tableAttributeDelimiterWidget.getRawValue() ) //$NON-NLS-1$
&& !"".equals( tableValueDelimiterWidget.getRawValue() ) && !"".equals( tableQuoteWidget.getRawValue() ) //$NON-NLS-1$ //$NON-NLS-2$
&& !"".equals( tableLineSeparator.getRawValue() ) && !"".equals( tableBinaryEncodingWidget.getRawValue() ) //$NON-NLS-1$ //$NON-NLS-2$
&&
!"".equals( xlsValueDelimiterWidget.getRawValue() ) && !"".equals( xlsBinaryEncodingWidget.getRawValue() ) //$NON-NLS-1$ //$NON-NLS-2$
&&
!"".equals( ldifLineLengthText.getText() ) && !"".equals( ldifLineSeparator.getRawValue() ) ); //$NON-NLS-1$ //$NON-NLS-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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/SyntaxDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/SyntaxDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.schema.BinarySyntax;
import org.eclipse.jface.dialogs.Dialog;
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 SyntaxDialog is used to enter/select a syntax OID.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SyntaxDialog extends Dialog
{
/** The initial syntax. */
private BinarySyntax currentSyntax;
/** The possible syntax OIDs. */
private String[] syntaxOids;
/** The selected syntax. */
private BinarySyntax returnSyntax;
/** The combo. */
private Combo oidCombo;
/** The OK button of the dialog */
private Button okButton;
/**
* Creates a new instance of SyntaxDialog.
*
* @param parentShell the parent shell
* @param currentSyntax the current syntax, null if none
* @param syntaxOids the possible syntax OIDs
*/
public SyntaxDialog( Shell parentShell, BinarySyntax currentSyntax, String[] syntaxOids )
{
super( parentShell );
this.currentSyntax = currentSyntax;
this.syntaxOids = syntaxOids;
this.returnSyntax = null;
}
/**
* {@inheritDoc}
*/
protected void configureShell( Shell newShell )
{
super.configureShell( newShell );
newShell.setText( Messages.getString( "SyntaxDialog.SelectSyntaxOID" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
validate();
}
/**
* {@inheritDoc}
*/
protected void okPressed()
{
returnSyntax = new BinarySyntax( oidCombo.getText() );
super.okPressed();
}
/**
* {@inheritDoc}
*/
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
Composite c = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
BaseWidgetUtils.createLabel( c, Messages.getString( "SyntaxDialog.SyntaxOID" ), 1 ); //$NON-NLS-1$
oidCombo = BaseWidgetUtils.createCombo( c, syntaxOids, -1, 1 );
if ( currentSyntax != null )
{
oidCombo.setText( currentSyntax.getSyntaxNumericOid() );
}
oidCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return composite;
}
private void validate()
{
okButton.setEnabled( !"".equals( oidCombo.getText() ) ); //$NON-NLS-1$
}
/**
* Gets the entered/selected syntax.
*
* @return the syntax
*/
public BinarySyntax getSyntax()
{
return returnSyntax;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/Messages.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/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.ldapbrowser.common.dialogs.preferences;
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/AttributeValueEditorDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/AttributeValueEditorDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.schema.AttributeValueEditorRelation;
import org.apache.directory.studio.valueeditors.ValueEditorManager.ValueEditorExtension;
import org.eclipse.jface.dialogs.Dialog;
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 AttributeValueEditorDialog is used to specify
* value editors for attributes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributeValueEditorDialog extends Dialog
{
/** The initial attribute to value editor relation. */
private AttributeValueEditorRelation relation;
/** Map with class name => value editor extension. */
private SortedMap<String, ValueEditorExtension> class2ValueEditorExtensionMap;
/** The attribute types and OIDs. */
private String[] attributeTypesAndOids;
/** Map with value editor names => class name. */
private SortedMap<String, String> veName2classMap;
/** The selected attribute to value editor relation. */
private AttributeValueEditorRelation returnRelation;
/** The type or OID combo. */
private Combo typeOrOidCombo;
/** The value editor combo. */
private Combo valueEditorCombo;
/** The OK button of the dialog */
private Button okButton;
/**
* Creates a new instance of AttributeValueEditorDialog.
*
* @param parentShell the parent shell
* @param relation the initial attribute to value editor relation
* @param class2ValueEditorExtensionMap Map with class name => value editor extension
* @param attributeTypesAndOids the attribute types and OIDs
*/
public AttributeValueEditorDialog( Shell parentShell, AttributeValueEditorRelation relation,
SortedMap<String, ValueEditorExtension> class2ValueEditorExtensionMap, String[] attributeTypesAndOids )
{
super( parentShell );
this.relation = relation;
this.class2ValueEditorExtensionMap = class2ValueEditorExtensionMap;
this.attributeTypesAndOids = attributeTypesAndOids;
this.returnRelation = null;
this.veName2classMap = new TreeMap<String, String>();
for ( ValueEditorExtension vee : class2ValueEditorExtensionMap.values() )
{
veName2classMap.put( vee.name, vee.className );
}
}
/**
* {@inheritDoc}
*/
protected void configureShell( Shell newShell )
{
super.configureShell( newShell );
newShell.setText( Messages.getString( "AttributeValueEditorDialog.AttributeValueEditor" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
validate();
}
/**
* {@inheritDoc}
*/
protected void okPressed()
{
returnRelation = new AttributeValueEditorRelation( typeOrOidCombo.getText(), veName2classMap
.get( valueEditorCombo.getText() ) );
super.okPressed();
}
/**
* {@inheritDoc}
*/
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
Composite c = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
BaseWidgetUtils.createLabel( c, Messages.getString( "AttributeValueEditorDialog.AttributeTypeOrOID" ), 1 ); //$NON-NLS-1$
typeOrOidCombo = BaseWidgetUtils.createCombo( c, attributeTypesAndOids, -1, 1 );
if ( relation != null && relation.getAttributeNumericOidOrType() != null )
{
typeOrOidCombo.setText( relation.getAttributeNumericOidOrType() );
}
typeOrOidCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
BaseWidgetUtils.createLabel( c, Messages.getString( "AttributeValueEditorDialog.ValueEditor" ), 1 ); //$NON-NLS-1$
valueEditorCombo = BaseWidgetUtils.createReadonlyCombo( c, veName2classMap.keySet().toArray( new String[0] ),
-1, 1 );
if ( relation != null && relation.getValueEditorClassName() != null
&& class2ValueEditorExtensionMap.containsKey( relation.getValueEditorClassName() ) )
{
valueEditorCombo.setText( ( class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() ) ).name );
}
valueEditorCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return composite;
}
private void validate()
{
okButton.setEnabled(
!"".equals( valueEditorCombo.getText() ) && !"".equals( typeOrOidCombo.getText() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Gets the selected attribute to value editor relation.
*
* @return the selected attribute to value editor relation
*/
public AttributeValueEditorRelation getRelation()
{
return returnRelation;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/SyntaxValueEditorDialog.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/SyntaxValueEditorDialog.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SyntaxValueEditorRelation;
import org.apache.directory.studio.valueeditors.ValueEditorManager.ValueEditorExtension;
import org.eclipse.jface.dialogs.Dialog;
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 SyntaxValueEditorDialog is used to specify
* value editors for syntaxes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SyntaxValueEditorDialog extends Dialog
{
/** The initial syntax to value editor relation. */
private SyntaxValueEditorRelation relation;
/** Map with class name => value editor extension. */
private SortedMap<String, ValueEditorExtension> class2ValueEditorExtensionMap;
/** The syntax OIDs. */
private String[] syntaxOids;
/** Map with value editor names => class name. */
private SortedMap<String, String> veName2classMap;
/** The selected syntax to value editor relation. */
private SyntaxValueEditorRelation returnRelation;
/** The OID combo. */
private Combo oidCombo;
/** The value editor combo. */
private Combo valueEditorCombo;
/** The OK button of the dialog */
private Button okButton;
/**
* Creates a new instance of SyntaxValueEditorDialog.
*
* @param parentShell the parent shell
* @param relation the initial syntax to value editor relation
* @param class2ValueEditorExtensionMap Map with class name => value editor extension
* @param syntaxOids the syntax OIDs
*/
public SyntaxValueEditorDialog( Shell parentShell, SyntaxValueEditorRelation relation,
SortedMap<String, ValueEditorExtension> class2ValueEditorExtensionMap, String[] syntaxOids )
{
super( parentShell );
this.relation = relation;
this.class2ValueEditorExtensionMap = class2ValueEditorExtensionMap;
this.syntaxOids = syntaxOids;
this.returnRelation = null;
this.veName2classMap = new TreeMap<String, String>();
for ( ValueEditorExtension vee : class2ValueEditorExtensionMap.values() )
{
veName2classMap.put( vee.name, vee.className );
}
}
/**
* {@inheritDoc}
*/
protected void configureShell( Shell newShell )
{
super.configureShell( newShell );
newShell.setText( Messages.getString( "SyntaxValueEditorDialog.AttributeValueEditor" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
protected void createButtonsForButtonBar( Composite parent )
{
okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
validate();
}
/**
* {@inheritDoc}
*/
protected void okPressed()
{
returnRelation = new SyntaxValueEditorRelation( oidCombo.getText(), ( String ) veName2classMap
.get( valueEditorCombo.getText() ) );
super.okPressed();
}
/**
* {@inheritDoc}
*/
protected Control createDialogArea( Composite parent )
{
Composite composite = ( Composite ) super.createDialogArea( parent );
Composite c = BaseWidgetUtils.createColumnContainer( composite, 2, 1 );
BaseWidgetUtils.createLabel( c, Messages.getString( "SyntaxValueEditorDialog.SyntaxOID" ), 1 ); //$NON-NLS-1$
oidCombo = BaseWidgetUtils.createCombo( c, syntaxOids, -1, 1 );
if ( relation != null && relation.getSyntaxOID() != null )
{
oidCombo.setText( relation.getSyntaxOID() );
}
oidCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
BaseWidgetUtils.createLabel( c, Messages.getString( "SyntaxValueEditorDialog.ValueEditor" ), 1 ); //$NON-NLS-1$
valueEditorCombo = BaseWidgetUtils.createReadonlyCombo( c, veName2classMap.keySet().toArray( new String[0] ),
-1, 1 );
if ( relation != null && relation.getValueEditorClassName() != null
&& class2ValueEditorExtensionMap.containsKey( relation.getValueEditorClassName() ) )
{
valueEditorCombo.setText( ( class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() ) ).name );
}
valueEditorCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return composite;
}
private void validate()
{
okButton.setEnabled(
!"".equals( valueEditorCombo.getText() ) && !"".equals( oidCombo.getText() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Gets the selected syntax to value editor relation.
*
* @return the selected syntax to value editor relation
*/
public SyntaxValueEditorRelation getRelation()
{
return returnRelation;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/AttributesPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/AttributesPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.eclipse.jface.preference.ColorSelector;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
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;
/**
* The AttributesPreferencePage contains general settings for attributes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
private Button showDecoratedValuesButton;
private final String[] ATTRIBUTE_TYPES = new String[]
{
Messages.getString( "AttributesPreferencePage.ObjectClassAttribute" ), Messages.getString( "AttributesPreferencePage.MustAttributes" ), Messages.getString( "AttributesPreferencePage.MayAttributes" ), Messages.getString( "AttributesPreferencePage.OperationalAttributes" ) }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
private final String[] ATTRIBUTE_FONT_CONSTANTS = new String[]
{ BrowserCommonConstants.PREFERENCE_OBJECTCLASS_FONT, BrowserCommonConstants.PREFERENCE_MUSTATTRIBUTE_FONT,
BrowserCommonConstants.PREFERENCE_MAYATTRIBUTE_FONT,
BrowserCommonConstants.PREFERENCE_OPERATIONALATTRIBUTE_FONT };
private final String[] ATTRIBUTE_COLOR_CONSTANTS = new String[]
{ BrowserCommonConstants.PREFERENCE_OBJECTCLASS_COLOR, BrowserCommonConstants.PREFERENCE_MUSTATTRIBUTE_COLOR,
BrowserCommonConstants.PREFERENCE_MAYATTRIBUTE_COLOR,
BrowserCommonConstants.PREFERENCE_OPERATIONALATTRIBUTE_COLOR };
private Label[] attributeTypeLabels = new Label[ATTRIBUTE_TYPES.length];
private ColorSelector[] attributeColorSelectors = new ColorSelector[ATTRIBUTE_TYPES.length];
private Button[] attributeBoldButtons = new Button[ATTRIBUTE_TYPES.length];
private Button[] attributeItalicButtons = new Button[ATTRIBUTE_TYPES.length];
/**
* Creates a new instance of AttributesPreferencePage.
*/
public AttributesPreferencePage()
{
super( Messages.getString( "AttributesPreferencePage.Attributes" ) ); //$NON-NLS-1$
super.setPreferenceStore( BrowserCommonActivator.getDefault().getPreferenceStore() );
super.setDescription( Messages.getString( "AttributesPreferencePage.GeneralSettings" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( 1, false );
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginTop = 0;
layout.marginBottom = 0;
composite.setLayout( layout );
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
// Show Decorated Values
showDecoratedValuesButton = BaseWidgetUtils.createCheckbox( composite, Messages
.getString( "AttributesPreferencePage.ShowDecoratedValues" ), 1 ); //$NON-NLS-1$
showDecoratedValuesButton.setSelection( !getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES ) );
// Attributes Colors And Fonts
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
Group colorsAndFontsGroup = BaseWidgetUtils.createGroup( composite, Messages
.getString( "AttributesPreferencePage.AttributeColorsAndFonts" ), 1 ); //$NON-NLS-1$
colorsAndFontsGroup.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Composite colorsAndFontsComposite = BaseWidgetUtils.createColumnContainer( colorsAndFontsGroup, 4, 1 );
for ( int i = 0; i < ATTRIBUTE_TYPES.length; i++ )
{
attributeTypeLabels[i] = BaseWidgetUtils.createLabel( colorsAndFontsComposite, ATTRIBUTE_TYPES[i], 1 );
attributeTypeLabels[i].setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
attributeColorSelectors[i] = new ColorSelector( colorsAndFontsComposite );
attributeBoldButtons[i] = BaseWidgetUtils.createCheckbox( colorsAndFontsComposite, Messages
.getString( "AttributesPreferencePage.Bold" ), 1 ); //$NON-NLS-1$
attributeItalicButtons[i] = BaseWidgetUtils.createCheckbox( colorsAndFontsComposite, Messages
.getString( "AttributesPreferencePage.Italic" ), 1 ); //$NON-NLS-1$
FontData[] fontDatas = PreferenceConverter.getFontDataArray( getPreferenceStore(),
ATTRIBUTE_FONT_CONSTANTS[i] );
RGB rgb = PreferenceConverter.getColor( getPreferenceStore(), ATTRIBUTE_COLOR_CONSTANTS[i] );
setColorsAndFonts( i, fontDatas, rgb );
}
applyDialogFont( composite );
return composite;
}
private void setColorsAndFonts( int index, FontData[] fontDatas, RGB rgb )
{
boolean bold = isBold( fontDatas );
boolean italic = isItalic( fontDatas );
attributeColorSelectors[index].setColorValue( rgb );
attributeBoldButtons[index].setSelection( bold );
attributeItalicButtons[index].setSelection( italic );
}
private void setFontData( FontData[] fontDatas, Button boldButton, Button italicButton )
{
for ( FontData fontData : fontDatas )
{
int style = SWT.NORMAL;
if ( boldButton.getSelection() )
{
style |= SWT.BOLD;
}
if ( italicButton.getSelection() )
{
style |= SWT.ITALIC;
}
fontData.setStyle( style );
}
}
private boolean isBold( FontData[] fontDatas )
{
boolean bold = false;
for ( FontData fontData : fontDatas )
{
if ( ( fontData.getStyle() & SWT.BOLD ) != SWT.NORMAL )
{
bold = true;
}
}
return bold;
}
private boolean isItalic( FontData[] fontDatas )
{
boolean italic = false;
for ( FontData fontData : fontDatas )
{
if ( ( fontData.getStyle() & SWT.ITALIC ) != SWT.NORMAL )
{
italic = true;
}
}
return italic;
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
// Show Decorated Values
getPreferenceStore().setValue( BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES,
!showDecoratedValuesButton.getSelection() );
// Attributes Colors And Fonts
for ( int i = 0; i < ATTRIBUTE_TYPES.length; i++ )
{
FontData[] fontDatas = PreferenceConverter.getFontDataArray( getPreferenceStore(),
ATTRIBUTE_FONT_CONSTANTS[i] );
setFontData( fontDatas, attributeBoldButtons[i], attributeItalicButtons[i] );
RGB rgb = attributeColorSelectors[i].getColorValue();
PreferenceConverter.setValue( getPreferenceStore(), ATTRIBUTE_FONT_CONSTANTS[i], fontDatas );
PreferenceConverter.setValue( getPreferenceStore(), ATTRIBUTE_COLOR_CONSTANTS[i], rgb );
}
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
// Show Decorated Values
showDecoratedValuesButton.setSelection( !getPreferenceStore().getDefaultBoolean(
BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES ) );
// Attributes Colors And Fonts
for ( int i = 0; i < ATTRIBUTE_TYPES.length; i++ )
{
FontData[] fontDatas = PreferenceConverter.getDefaultFontDataArray( getPreferenceStore(),
ATTRIBUTE_FONT_CONSTANTS[i] );
getPreferenceStore().setToDefault( ATTRIBUTE_FONT_CONSTANTS[i] );
RGB rgb = PreferenceConverter.getDefaultColor( getPreferenceStore(), ATTRIBUTE_COLOR_CONSTANTS[i] );
getPreferenceStore().setToDefault( ATTRIBUTE_COLOR_CONSTANTS[i] );
setColorsAndFonts( i, fontDatas, rgb );
}
super.performDefaults();
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/BinaryAttributesAndSyntaxesPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/BinaryAttributesAndSyntaxesPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.LdapSyntax;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.connection.core.Utils;
import org.apache.directory.studio.ldapbrowser.core.BrowserConnectionManager;
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.schema.BinaryAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.schema.BinarySyntax;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.preference.PreferencePage;
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.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
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.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The BinaryAttributesAndSyntaxesPreferencePage is used to specify
* binary attributes and syntaxes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class BinaryAttributesAndSyntaxesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
/** Map with attribute OID => attribute type description */
private SortedMap<String, AttributeType> attributeOid2AtdMap;
/** Map with attribute name => attribute type description */
private SortedMap<String, AttributeType> attributeNames2AtdMap;
/** The attribute names and OIDs. */
private String[] attributeNamesAndOids;
/** Map with syntax OID => syntax description */
private SortedMap<String, LdapSyntax> syntaxOid2LsdMap;
/** Map with syntax DESC => syntax description */
private SortedMap<String, LdapSyntax> syntaxDesc2LsdMap;
/** The syntax OIDs. */
private String[] syntaxOids;
/** The attribute list. */
private List<BinaryAttribute> attributeList;
/** The attribute viewer. */
private TableViewer attributeViewer;
/** The attribute add button. */
private Button attributeAddButton;
/** The attribute edit button. */
private Button attributeEditButton;
/** The attribute remove button. */
private Button attributeRemoveButton;
/** The syntax list. */
private List<BinarySyntax> syntaxList;
/** The syntax viewer. */
private TableViewer syntaxViewer;
/** The syntax add button. */
private Button syntaxAddButton;
/** The syntax edit button. */
private Button syntaxEditButton;
/** The syntax remove button. */
private Button syntaxRemoveButton;
/**
* Creates a new instance of BinaryAttributesAndSyntaxesPreferencePage.
*/
public BinaryAttributesAndSyntaxesPreferencePage()
{
super( Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.BinaryAttributes" ) ); //$NON-NLS-1$
super.setDescription( Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.BinaryAttributesDescription" ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
// init available attribute types
attributeNames2AtdMap = new TreeMap<String, AttributeType>();
attributeOid2AtdMap = new TreeMap<String, AttributeType>();
BrowserConnectionManager cm = BrowserCorePlugin.getDefault().getConnectionManager();
IBrowserConnection[] connections = cm.getBrowserConnections();
for ( IBrowserConnection browserConnection : connections )
{
Schema schema = browserConnection.getSchema();
createAttributeMaps( schema );
}
createAttributeMaps( Schema.DEFAULT_SCHEMA );
attributeNamesAndOids = new String[attributeNames2AtdMap.size() + attributeOid2AtdMap.size()];
System.arraycopy( attributeNames2AtdMap.keySet().toArray(), 0, attributeNamesAndOids, 0, attributeNames2AtdMap
.size() );
System.arraycopy( attributeOid2AtdMap.keySet().toArray(), 0, attributeNamesAndOids, attributeNames2AtdMap
.size(), attributeOid2AtdMap.size() );
// init available syntaxes
syntaxOid2LsdMap = new TreeMap<String, LdapSyntax>();
syntaxDesc2LsdMap = new TreeMap<String, LdapSyntax>();
for ( IBrowserConnection browserConnection : connections )
{
Schema schema = browserConnection.getSchema();
createSyntaxMaps( schema );
}
createSyntaxMaps( Schema.DEFAULT_SCHEMA );
syntaxOids = new String[syntaxOid2LsdMap.size()];
System.arraycopy( syntaxOid2LsdMap.keySet().toArray(), 0, syntaxOids, 0, syntaxOid2LsdMap.size() );
// create attribute contents
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
createAttributeContents( composite );
attributeList = new ArrayList<BinaryAttribute>( Arrays.asList( BrowserCorePlugin.getDefault()
.getCorePreferences().getBinaryAttributes() ) );
attributeViewer.setInput( attributeList );
attributeViewer.getTable().getColumn( 0 ).pack();
// create syntax contents
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
createSyntaxContents( composite );
syntaxList = new ArrayList<BinarySyntax>( Arrays.asList( BrowserCorePlugin.getDefault().getCorePreferences()
.getBinarySyntaxes() ) );
syntaxViewer.setInput( syntaxList );
syntaxViewer.getTable().getColumn( 0 ).pack();
syntaxViewer.getTable().pack();
return composite;
}
private void createAttributeMaps( Schema schema )
{
Collection<AttributeType> atds = schema.getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
attributeOid2AtdMap.put( atd.getOid(), atd );
for ( String name : atd.getNames() )
{
attributeNames2AtdMap.put( name, atd );
}
}
}
private void createSyntaxMaps( Schema schema )
{
Collection<LdapSyntax> lsds = schema.getLdapSyntaxDescriptions();
for ( LdapSyntax lsd : lsds )
{
syntaxOid2LsdMap.put( lsd.getOid(), lsd );
if ( lsd.getDescription() != null )
{
syntaxDesc2LsdMap.put( lsd.getDescription(), lsd );
}
}
}
private void createAttributeContents( Composite parent )
{
BaseWidgetUtils.createLabel( parent, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.BinaryAttributes" ), 1 ); //$NON-NLS-1$
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite listComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
listComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite buttonComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
buttonComposite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) );
Table table = new Table( listComposite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.FULL_SELECTION );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = 360;
data.heightHint = convertHeightInCharsToPixels( 10 );
table.setLayoutData( data );
table.setHeaderVisible( true );
table.setLinesVisible( true );
attributeViewer = new TableViewer( table );
TableColumn c1 = new TableColumn( table, SWT.NONE );
c1.setText( Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Attribute" ) ); //$NON-NLS-1$
c1.setWidth( 300 );
TableColumn c2 = new TableColumn( table, SWT.NONE );
c2.setText( Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Alias" ) ); //$NON-NLS-1$
c2.setWidth( 60 );
attributeViewer.setColumnProperties( new String[]
{ Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Attribute" ) } ); //$NON-NLS-1$
attributeViewer.setContentProvider( new ArrayContentProvider() );
attributeViewer.setLabelProvider( new AttributeLabelProvider() );
attributeViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
editAttribute();
}
} );
attributeViewer.addSelectionChangedListener( new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
attributeEditButton.setEnabled( !attributeViewer.getSelection().isEmpty() );
attributeRemoveButton.setEnabled( !attributeViewer.getSelection().isEmpty() );
}
} );
attributeAddButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Add" ), 1 ); //$NON-NLS-1$
attributeAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addAttribute();
}
} );
attributeEditButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Edit" ), 1 ); //$NON-NLS-1$
attributeEditButton.setEnabled( false );
attributeEditButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editAttribute();
}
} );
attributeRemoveButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Remove" ), 1 ); //$NON-NLS-1$
attributeRemoveButton.setEnabled( false );
attributeRemoveButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
removeAttribute();
}
} );
}
private void createSyntaxContents( Composite parent )
{
BaseWidgetUtils.createLabel( parent, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.BinarySyntaxes" ), 1 ); //$NON-NLS-1$
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite listComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
listComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite buttonComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
buttonComposite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) );
Table table = new Table( listComposite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.FULL_SELECTION );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = 360;
data.heightHint = convertHeightInCharsToPixels( 10 );
table.setLayoutData( data );
table.setHeaderVisible( true );
table.setLinesVisible( true );
syntaxViewer = new TableViewer( table );
TableColumn c1 = new TableColumn( table, SWT.NONE );
c1.setText( Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Syntax" ) ); //$NON-NLS-1$
c1.setWidth( 300 );
TableColumn c2 = new TableColumn( table, SWT.NONE );
c2.setText( Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Desc" ) ); //$NON-NLS-1$
c2.setWidth( 60 );
syntaxViewer.setColumnProperties( new String[]
{ Messages.getString( "BinaryAttributesAndSyntaxesPreferencePage.Syntax" ) } ); //$NON-NLS-1$
syntaxViewer.setContentProvider( new ArrayContentProvider() );
syntaxViewer.setLabelProvider( new SyntaxLabelProvider() );
syntaxViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
editSyntax();
}
} );
syntaxViewer.addSelectionChangedListener( new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
syntaxEditButton.setEnabled( !syntaxViewer.getSelection().isEmpty() );
syntaxRemoveButton.setEnabled( !syntaxViewer.getSelection().isEmpty() );
}
} );
syntaxAddButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Add" ), 1 ); //$NON-NLS-1$
syntaxAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addSyntax();
}
} );
syntaxEditButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Edit" ), 1 ); //$NON-NLS-1$
syntaxEditButton.setEnabled( false );
syntaxEditButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editSyntax();
}
} );
syntaxRemoveButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "BinaryAttributesAndSyntaxesPreferencePage.Remove" ), 1 ); //$NON-NLS-1$
syntaxRemoveButton.setEnabled( false );
syntaxRemoveButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
removeSyntax();
}
} );
}
private void addAttribute()
{
AttributeDialog dialog = new AttributeDialog( getShell(), null, attributeNamesAndOids );
if ( dialog.open() == AttributeValueEditorDialog.OK )
{
BinaryAttribute attribute = dialog.getAttribute();
// Ensuring we use OID for consistency in the table viewer
if ( attributeNames2AtdMap.containsKey( attribute.getAttributeNumericOidOrName() ) )
{
attribute = new BinaryAttribute( attributeNames2AtdMap.get( attribute.getAttributeNumericOidOrName() )
.getOid() );
}
else if ( attributeOid2AtdMap.containsKey( attribute.getAttributeNumericOidOrName() ) )
{
attribute = new BinaryAttribute( attributeOid2AtdMap.get( attribute.getAttributeNumericOidOrName() )
.getOid() );
}
attributeList.add( attribute );
attributeViewer.refresh();
}
}
private void removeAttribute()
{
Object o = ( ( StructuredSelection ) attributeViewer.getSelection() ).getFirstElement();
attributeList.remove( o );
attributeViewer.refresh();
}
private void editAttribute()
{
StructuredSelection sel = ( StructuredSelection ) attributeViewer.getSelection();
if ( !sel.isEmpty() )
{
BinaryAttribute attribute = ( BinaryAttribute ) sel.getFirstElement();
AttributeDialog dialog = new AttributeDialog( getShell(), attribute, attributeNamesAndOids );
if ( dialog.open() == AttributeValueEditorDialog.OK )
{
int index = attributeList.indexOf( attribute );
attributeList.set( index, dialog.getAttribute() );
attributeViewer.refresh();
}
}
}
private void addSyntax()
{
SyntaxDialog dialog = new SyntaxDialog( getShell(), null, syntaxOids );
if ( dialog.open() == SyntaxValueEditorDialog.OK )
{
syntaxList.add( dialog.getSyntax() );
syntaxViewer.refresh();
}
}
private void removeSyntax()
{
Object o = ( ( StructuredSelection ) syntaxViewer.getSelection() ).getFirstElement();
syntaxList.remove( o );
syntaxViewer.refresh();
}
private void editSyntax()
{
StructuredSelection sel = ( StructuredSelection ) syntaxViewer.getSelection();
if ( !sel.isEmpty() )
{
BinarySyntax syntax = ( BinarySyntax ) sel.getFirstElement();
SyntaxDialog dialog = new SyntaxDialog( getShell(), syntax, syntaxOids );
if ( dialog.open() == SyntaxValueEditorDialog.OK )
{
int index = syntaxList.indexOf( syntax );
syntaxList.set( index, dialog.getSyntax() );
syntaxViewer.refresh();
}
}
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
BinaryAttribute[] attributes = attributeList.toArray( new BinaryAttribute[attributeList.size()] );
BrowserCorePlugin.getDefault().getCorePreferences().setBinaryAttributes( attributes );
BinarySyntax[] syntaxes = syntaxList.toArray( new BinarySyntax[syntaxList.size()] );
BrowserCorePlugin.getDefault().getCorePreferences().setBinarySyntaxes( syntaxes );
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
attributeList.clear();
attributeList.addAll( Arrays.asList( BrowserCorePlugin.getDefault().getCorePreferences()
.getDefaultBinaryAttributes() ) );
attributeViewer.refresh();
syntaxList.clear();
syntaxList.addAll( Arrays.asList( BrowserCorePlugin.getDefault().getCorePreferences()
.getDefaultBinarySyntaxes() ) );
syntaxViewer.refresh();
super.performDefaults();
}
class AttributeLabelProvider extends LabelProvider implements ITableLabelProvider
{
public String getColumnText( Object obj, int index )
{
if ( obj instanceof BinaryAttribute )
{
BinaryAttribute attribute = ( BinaryAttribute ) obj;
if ( index == 0 )
{
return attribute.getAttributeNumericOidOrName();
}
else if ( index == 1 )
{
if ( attribute.getAttributeNumericOidOrName() != null )
{
if ( attributeNames2AtdMap.containsKey( attribute.getAttributeNumericOidOrName() ) )
{
AttributeType atd = attributeNames2AtdMap.get( attribute.getAttributeNumericOidOrName() );
String s = atd.getOid();
for ( String attributeName : atd.getNames() )
{
if ( !attribute.getAttributeNumericOidOrName().equals( attributeName ) )
{
s += ", " + attributeName; //$NON-NLS-1$
}
}
return s;
}
else if ( attributeOid2AtdMap.containsKey( attribute.getAttributeNumericOidOrName() ) )
{
AttributeType atd = attributeOid2AtdMap.get( attribute.getAttributeNumericOidOrName() );
return SchemaUtils.toString( atd );
}
else if ( Utils.getOidDescription( attribute.getAttributeNumericOidOrName() ) != null )
{
return Utils.getOidDescription( attribute.getAttributeNumericOidOrName() );
}
}
}
}
return null;
}
public Image getColumnImage( Object obj, int index )
{
return null;
}
}
class SyntaxLabelProvider extends LabelProvider implements ITableLabelProvider
{
public String getColumnText( Object obj, int index )
{
if ( obj instanceof BinarySyntax )
{
BinarySyntax syntax = ( BinarySyntax ) obj;
if ( index == 0 )
{
return syntax.getSyntaxNumericOid();
}
else if ( index == 1 )
{
if ( syntax.getSyntaxNumericOid() != null )
{
if ( syntaxOid2LsdMap.containsKey( syntax.getSyntaxNumericOid() ) )
{
LdapSyntax lsd = ( LdapSyntax ) syntaxOid2LsdMap.get( syntax
.getSyntaxNumericOid() );
return SchemaUtils.toString( lsd );
}
else if ( Utils.getOidDescription( syntax.getSyntaxNumericOid() ) != null )
{
return Utils.getOidDescription( syntax.getSyntaxNumericOid() );
}
}
}
}
return null;
}
public Image getColumnImage( Object obj, int index )
{
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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/ValueEditorsPreferencePage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/dialogs/preferences/ValueEditorsPreferencePage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.dialogs.preferences;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.LdapSyntax;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.core.BrowserConnectionManager;
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.schema.AttributeValueEditorRelation;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SyntaxValueEditorRelation;
import org.apache.directory.studio.valueeditors.ValueEditorManager;
import org.apache.directory.studio.valueeditors.ValueEditorManager.ValueEditorExtension;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.ImageDescriptor;
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.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
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.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The ValueEditorsPreferencePage is used to specify
* value editors for attributes and syntaxes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ValueEditorsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage
{
private SortedMap<String, ValueEditorExtension> class2ValueEditorExtensionMap;
/** Map with attribute OID => attribute type description */
private SortedMap<String, AttributeType> attributeOid2AtdMap;
/** Map with attribute name => attribute type description */
private SortedMap<String, AttributeType> attributeNames2AtdMap;
/** The attribute names and OIDs. */
private String[] attributeTypesAndOids;
/** Map with syntax OID => syntax description */
private SortedMap<String, LdapSyntax> syntaxOid2LsdMap;
/** Map with syntax DESC => syntax description */
private SortedMap<String, LdapSyntax> syntaxDesc2LsdMap;
/** The syntax DESCs and OIDs. */
private String[] syntaxDescsAndOids;
/** The attribute list. */
private List<AttributeValueEditorRelation> attributeList;
/** The attribute viewer. */
private TableViewer attributeViewer;
/** The attribute add button. */
private Button attributeAddButton;
/** The attribute edit button. */
private Button attributeEditButton;
/** The attribute remove button. */
private Button attributeRemoveButton;
/** The syntax list. */
private List<SyntaxValueEditorRelation> syntaxList;
/** The syntax viewer. */
private TableViewer syntaxViewer;
/** The syntax add button. */
private Button syntaxAddButton;
/** The syntax edit button. */
private Button syntaxEditButton;
/** The syntax remove button. */
private Button syntaxRemoveButton;
/** The map of images */
private Map<ImageDescriptor, Image> imageMap;
/**
* Creates a new instance of ValueEditorsPreferencePage.
*/
public ValueEditorsPreferencePage()
{
super( Messages.getString( "ValueEditorsPreferencePage.ValueEditors" ) ); //$NON-NLS-1$
super.setDescription( Messages.getString( "ValueEditorsPreferencePage.SpecifyValueEditors" ) ); //$NON-NLS-1$
this.imageMap = new HashMap<ImageDescriptor, Image>();
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench )
{
}
/**
* {@inheritDoc}
*/
public void dispose()
{
if ( imageMap != null )
{
for ( Image image : imageMap.values() )
{
if ( image != null && !image.isDisposed() )
{
image.dispose();
}
}
}
super.dispose();
}
/**
* {@inheritDoc}
*/
protected Control createContents( Composite parent )
{
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
// init available value providers
class2ValueEditorExtensionMap = new TreeMap<String, ValueEditorExtension>();
Composite dummyComposite = new Composite( composite, SWT.NONE );
dummyComposite.setLayoutData( new GridData( 1, 1 ) );
Collection<ValueEditorExtension> valueEditorExtensions = ValueEditorManager.getValueEditorExtensions();
for ( ValueEditorExtension vee : valueEditorExtensions )
{
class2ValueEditorExtensionMap.put( vee.className, vee );
}
// init available attribute types
attributeNames2AtdMap = new TreeMap<String, AttributeType>();
attributeOid2AtdMap = new TreeMap<String, AttributeType>();
BrowserConnectionManager cm = BrowserCorePlugin.getDefault().getConnectionManager();
IBrowserConnection[] connections = cm.getBrowserConnections();
for ( IBrowserConnection browserConnection : connections )
{
Schema schema = browserConnection.getSchema();
createAttributeMapsAndArray( schema );
}
createAttributeMapsAndArray( Schema.DEFAULT_SCHEMA );
// init available syntaxes
syntaxOid2LsdMap = new TreeMap<String, LdapSyntax>();
syntaxDesc2LsdMap = new TreeMap<String, LdapSyntax>();
for ( IBrowserConnection browserConnection : connections )
{
Schema schema = browserConnection.getSchema();
createSyntaxMapsAndArray( schema );
}
createSyntaxMapsAndArray( Schema.DEFAULT_SCHEMA );
// create attribute contents
// BaseWidgetUtils.createSpacer(composite, 1);
BaseWidgetUtils.createSpacer( composite, 1 );
createAttributeContents( composite );
attributeList = new ArrayList<AttributeValueEditorRelation>( Arrays.asList( BrowserCommonActivator.getDefault()
.getValueEditorsPreferences().getAttributeValueEditorRelations() ) );
attributeViewer.setInput( attributeList );
attributeViewer.getTable().getColumn( 0 ).pack();
attributeViewer.getTable().getColumn( 2 ).pack();
attributeViewer.getTable().pack();
// create syntax contents
BaseWidgetUtils.createSpacer( composite, 1 );
BaseWidgetUtils.createSpacer( composite, 1 );
createSyntaxContents( composite );
syntaxList = new ArrayList<SyntaxValueEditorRelation>( Arrays.asList( BrowserCommonActivator.getDefault()
.getValueEditorsPreferences().getSyntaxValueEditorRelations() ) );
syntaxViewer.setInput( syntaxList );
syntaxViewer.getTable().getColumn( 0 ).pack();
syntaxViewer.getTable().getColumn( 2 ).pack();
syntaxViewer.getTable().pack();
return composite;
}
/**
* Creates the attribute maps and array.
*
* @param schema the schema
*/
private void createAttributeMapsAndArray( Schema schema )
{
List<String> attributeTypesList = new ArrayList<String>();
List<String> oidsList = new ArrayList<String>();
Collection<AttributeType> atds = schema.getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
attributeOid2AtdMap.put( atd.getOid(), atd );
oidsList.add( atd.getOid() );
for ( String name : atd.getNames() )
{
attributeNames2AtdMap.put( name.toLowerCase(), atd );
attributeTypesList.add( name );
}
}
Collections.sort( attributeTypesList );
Collections.sort( oidsList );
List<String> attributeTypesAndOidsList = new ArrayList<String>();
attributeTypesAndOidsList.addAll( attributeTypesList );
attributeTypesAndOidsList.addAll( oidsList );
attributeTypesAndOids = attributeTypesAndOidsList.toArray( new String[0] );
}
/**
* Create the syntax maps and array.
*
* @param schema the schema
*/
private void createSyntaxMapsAndArray( Schema schema )
{
List<String> syntaxDescsAndOidsList = new ArrayList<String>();
Collection<LdapSyntax> lsds = schema.getLdapSyntaxDescriptions();
for ( LdapSyntax lsd : lsds )
{
syntaxOid2LsdMap.put( lsd.getOid(), lsd );
syntaxDescsAndOidsList.add( lsd.getOid() );
if ( lsd.getDescription() != null )
{
syntaxDesc2LsdMap.put( lsd.getDescription(), lsd );
}
}
Collections.sort( syntaxDescsAndOidsList );
syntaxDescsAndOids = syntaxDescsAndOidsList.toArray( new String[0] );
}
private void createAttributeContents( Composite parent )
{
BaseWidgetUtils.createLabel( parent, Messages
.getString( "ValueEditorsPreferencePage.ValueEditorsByAttributeType" ), 1 ); //$NON-NLS-1$
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite listComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
listComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite buttonComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
buttonComposite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) );
Table table = new Table( listComposite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.FULL_SELECTION );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = 360;
data.heightHint = convertHeightInCharsToPixels( 10 );
table.setLayoutData( data );
table.setHeaderVisible( true );
table.setLinesVisible( true );
attributeViewer = new TableViewer( table );
TableColumn c1 = new TableColumn( table, SWT.NONE );
c1.setText( Messages.getString( "ValueEditorsPreferencePage.Attribute" ) ); //$NON-NLS-1$
c1.setWidth( 80 );
TableColumn c2 = new TableColumn( table, SWT.NONE );
c2.setText( Messages.getString( "ValueEditorsPreferencePage.Alias" ) ); //$NON-NLS-1$
c2.setWidth( 80 );
TableColumn c3 = new TableColumn( table, SWT.NONE );
c3.setText( Messages.getString( "ValueEditorsPreferencePage.ValueEditor" ) ); //$NON-NLS-1$
c3.setWidth( 200 );
attributeViewer
.setColumnProperties( new String[]
{
Messages.getString( "ValueEditorsPreferencePage.Attribute" ), Messages.getString( "ValueEditorsPreferencePage.ValueEditor" ) } ); //$NON-NLS-1$ //$NON-NLS-2$
attributeViewer.setContentProvider( new ArrayContentProvider() );
attributeViewer.setLabelProvider( new AttributeLabelProvider() );
attributeViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
editAttribute();
}
} );
attributeViewer.addSelectionChangedListener( new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
attributeEditButton.setEnabled( !attributeViewer.getSelection().isEmpty() );
attributeRemoveButton.setEnabled( !attributeViewer.getSelection().isEmpty() );
}
} );
attributeAddButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Add" ), 1 ); //$NON-NLS-1$
attributeAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addAttribute();
}
} );
attributeEditButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Edit" ), 1 ); //$NON-NLS-1$
attributeEditButton.setEnabled( false );
attributeEditButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editAttribute();
}
} );
attributeRemoveButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Remove" ), 1 ); //$NON-NLS-1$
attributeRemoveButton.setEnabled( false );
attributeRemoveButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
removeAttribute();
}
} );
}
private void createSyntaxContents( Composite parent )
{
BaseWidgetUtils.createLabel( parent, Messages.getString( "ValueEditorsPreferencePage.ValueEditorBySyntax" ), 1 ); //$NON-NLS-1$
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite listComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
listComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite buttonComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
buttonComposite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) );
Table table = new Table( listComposite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.FULL_SELECTION );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = 360;
data.heightHint = convertHeightInCharsToPixels( 10 );
table.setLayoutData( data );
table.setHeaderVisible( true );
table.setLinesVisible( true );
syntaxViewer = new TableViewer( table );
TableColumn c1 = new TableColumn( table, SWT.NONE );
c1.setText( Messages.getString( "ValueEditorsPreferencePage.Syntax" ) ); //$NON-NLS-1$
c1.setWidth( 80 );
TableColumn c2 = new TableColumn( table, SWT.NONE );
c2.setText( Messages.getString( "ValueEditorsPreferencePage.Description" ) ); //$NON-NLS-1$
c2.setWidth( 80 );
TableColumn c3 = new TableColumn( table, SWT.NONE );
c3.setText( Messages.getString( "ValueEditorsPreferencePage.ValueEditor" ) ); //$NON-NLS-1$
c3.setWidth( 200 );
syntaxViewer
.setColumnProperties( new String[]
{
Messages.getString( "ValueEditorsPreferencePage.Syntax" ), Messages.getString( "ValueEditorsPreferencePage.ValueEditor" ) } ); //$NON-NLS-1$ //$NON-NLS-2$
syntaxViewer.setContentProvider( new ArrayContentProvider() );
syntaxViewer.setLabelProvider( new SyntaxLabelProvider() );
syntaxViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
editSyntax();
}
} );
syntaxViewer.addSelectionChangedListener( new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
syntaxEditButton.setEnabled( !syntaxViewer.getSelection().isEmpty() );
syntaxRemoveButton.setEnabled( !syntaxViewer.getSelection().isEmpty() );
}
} );
syntaxAddButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Add" ), 1 ); //$NON-NLS-1$
syntaxAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addSyntax();
}
} );
syntaxEditButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Edit" ), 1 ); //$NON-NLS-1$
syntaxEditButton.setEnabled( false );
syntaxEditButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editSyntax();
}
} );
syntaxRemoveButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "ValueEditorsPreferencePage.Remove" ), 1 ); //$NON-NLS-1$
syntaxRemoveButton.setEnabled( false );
syntaxRemoveButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
removeSyntax();
}
} );
}
private void addAttribute()
{
AttributeValueEditorDialog dialog = new AttributeValueEditorDialog( getShell(), null,
class2ValueEditorExtensionMap, attributeTypesAndOids );
if ( dialog.open() == AttributeValueEditorDialog.OK )
{
attributeList.add( dialog.getRelation() );
attributeViewer.refresh();
}
}
private void removeAttribute()
{
Object o = ( ( StructuredSelection ) attributeViewer.getSelection() ).getFirstElement();
attributeList.remove( o );
attributeViewer.refresh();
}
private void editAttribute()
{
StructuredSelection sel = ( StructuredSelection ) attributeViewer.getSelection();
if ( !sel.isEmpty() )
{
AttributeValueEditorRelation relation = ( AttributeValueEditorRelation ) sel.getFirstElement();
AttributeValueEditorDialog dialog = new AttributeValueEditorDialog( getShell(), relation,
class2ValueEditorExtensionMap, attributeTypesAndOids );
if ( dialog.open() == AttributeValueEditorDialog.OK )
{
int index = attributeList.indexOf( relation );
attributeList.set( index, dialog.getRelation() );
attributeViewer.refresh();
}
}
}
private void addSyntax()
{
SyntaxValueEditorDialog dialog = new SyntaxValueEditorDialog( getShell(), null, class2ValueEditorExtensionMap,
syntaxDescsAndOids );
if ( dialog.open() == SyntaxValueEditorDialog.OK )
{
syntaxList.add( dialog.getRelation() );
syntaxViewer.refresh();
}
}
private void removeSyntax()
{
Object o = ( ( StructuredSelection ) syntaxViewer.getSelection() ).getFirstElement();
syntaxList.remove( o );
syntaxViewer.refresh();
}
private void editSyntax()
{
StructuredSelection sel = ( StructuredSelection ) syntaxViewer.getSelection();
if ( !sel.isEmpty() )
{
SyntaxValueEditorRelation relation = ( SyntaxValueEditorRelation ) sel.getFirstElement();
SyntaxValueEditorDialog dialog = new SyntaxValueEditorDialog( getShell(), relation,
class2ValueEditorExtensionMap, syntaxDescsAndOids );
if ( dialog.open() == SyntaxValueEditorDialog.OK )
{
int index = syntaxList.indexOf( relation );
syntaxList.set( index, dialog.getRelation() );
syntaxViewer.refresh();
}
}
}
/**
* {@inheritDoc}
*/
public boolean performOk()
{
AttributeValueEditorRelation[] aRelations = attributeList
.toArray( new AttributeValueEditorRelation[attributeList.size()] );
BrowserCommonActivator.getDefault().getValueEditorsPreferences().setAttributeValueEditorRelations( aRelations );
SyntaxValueEditorRelation[] sRelations = syntaxList.toArray( new SyntaxValueEditorRelation[syntaxList.size()] );
BrowserCommonActivator.getDefault().getValueEditorsPreferences().setSyntaxValueEditorRelations( sRelations );
return true;
}
/**
* {@inheritDoc}
*/
protected void performDefaults()
{
attributeList.clear();
attributeList.addAll( Arrays.asList( BrowserCommonActivator.getDefault().getValueEditorsPreferences()
.getDefaultAttributeValueEditorRelations() ) );
attributeViewer.refresh();
syntaxList.clear();
syntaxList.addAll( Arrays.asList( BrowserCommonActivator.getDefault().getValueEditorsPreferences()
.getDefaultSyntaxValueEditorRelations() ) );
syntaxViewer.refresh();
super.performDefaults();
}
class AttributeLabelProvider extends LabelProvider implements ITableLabelProvider
{
public String getColumnText( Object obj, int index )
{
if ( obj instanceof AttributeValueEditorRelation )
{
AttributeValueEditorRelation relation = ( AttributeValueEditorRelation ) obj;
if ( index == 0 )
{
return relation.getAttributeNumericOidOrType();
}
else if ( index == 1 )
{
if ( relation.getAttributeNumericOidOrType() != null )
{
if ( attributeNames2AtdMap.containsKey( relation.getAttributeNumericOidOrType().toLowerCase() ) )
{
AttributeType atd = ( AttributeType ) attributeNames2AtdMap
.get( relation.getAttributeNumericOidOrType().toLowerCase() );
String s = atd.getOid();
for ( String name : atd.getNames() )
{
if ( !relation.getAttributeNumericOidOrType().equalsIgnoreCase( name ) )
{
s += ", " + name; //$NON-NLS-1$
}
}
return s;
}
else if ( attributeOid2AtdMap.containsKey( relation.getAttributeNumericOidOrType() ) )
{
AttributeType atd = ( AttributeType ) attributeOid2AtdMap
.get( relation.getAttributeNumericOidOrType() );
return atd.toString();
}
}
}
else if ( index == 2 )
{
ValueEditorExtension vee = class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() );
return vee != null ? vee.name : null;
}
}
return null;
}
public Image getColumnImage( Object obj, int index )
{
if ( obj instanceof AttributeValueEditorRelation )
{
AttributeValueEditorRelation relation = ( AttributeValueEditorRelation ) obj;
if ( index == 2 )
{
ValueEditorExtension vee = class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() );
if ( vee != null )
{
if ( !imageMap.containsKey( vee.icon ) )
{
Image image = vee.icon.createImage();
imageMap.put( vee.icon, image );
}
return imageMap.get( vee.icon );
}
return null;
}
}
return null;
}
}
class SyntaxLabelProvider extends LabelProvider implements ITableLabelProvider
{
public String getColumnText( Object obj, int index )
{
if ( obj instanceof SyntaxValueEditorRelation )
{
SyntaxValueEditorRelation relation = ( SyntaxValueEditorRelation ) obj;
if ( index == 0 )
{
return relation.getSyntaxOID();
}
else if ( index == 1 )
{
if ( relation.getSyntaxOID() != null )
{
if ( syntaxOid2LsdMap.containsKey( relation.getSyntaxOID() ) )
{
LdapSyntax lsd = ( LdapSyntax ) syntaxOid2LsdMap.get( relation
.getSyntaxOID() );
return SchemaUtils.toString( lsd );
}
}
}
else if ( index == 2 )
{
ValueEditorExtension vee = class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() );
return vee != null ? vee.name : null;
}
}
return null;
}
public Image getColumnImage( Object obj, int index )
{
if ( obj instanceof SyntaxValueEditorRelation )
{
SyntaxValueEditorRelation relation = ( SyntaxValueEditorRelation ) obj;
if ( index == 2 )
{
ValueEditorExtension vee = class2ValueEditorExtensionMap.get( relation.getValueEditorClassName() );
if ( vee != null )
{
if ( !imageMap.containsKey( vee.icon ) )
{
Image image = vee.icon.createImage();
imageMap.put( vee.icon, image );
}
return imageMap.get( vee.icon );
}
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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterCharacterPairMatcher.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterCharacterPairMatcher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
import org.eclipse.jface.text.source.ISourceViewer;
/**
* The FilterCharacterPairMatcher implements the ICharacterPairMatcher interface
* to match the peer opening and closing parentesis.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterCharacterPairMatcher implements ICharacterPairMatcher
{
/** The filter parser. */
private LdapFilterParser parser;
/** The anchor. */
private int anchor;
/**
* Creates a new instance of FilterCharacterPairMatcher.
*
* @param sourceViewer the source viewer
* @param parser the filter parser
*/
public FilterCharacterPairMatcher( ISourceViewer sourceViewer, LdapFilterParser parser )
{
this.parser = parser;
clear();
}
/**
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#dispose()
*/
public void dispose()
{
}
/**
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear()
*/
public void clear()
{
anchor = LEFT;
}
/**
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#match(org.eclipse.jface.text.IDocument, int)
*/
public IRegion match( IDocument document, int offset )
{
LdapFilter model = parser.getModel();
if ( model != null )
{
LdapFilter filter = parser.getModel().getFilter( offset - 1 );
if ( filter != null && filter.getStartToken() != null && filter.getStopToken() != null )
{
int left = filter.getStartToken().getOffset();
int right = filter.getStopToken().getOffset();
if ( left == offset - 1 )
{
anchor = LEFT;
IRegion region = new Region( left, right - left + 1 );
return region;
}
if ( right == offset - 1 )
{
anchor = RIGHT;
IRegion region = new Region( left, right - left + 1 );
return region;
}
}
}
return null;
}
/**
* @see org.eclipse.jface.text.source.ICharacterPairMatcher#getAnchor()
*/
public int getAnchor()
{
return anchor;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterTextHover.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterTextHover.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
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.MatchingRule;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterExtensibleComponent;
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.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
/**
* The FilterTextHover is used to display error messages in a tooltip.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterTextHover implements ITextHover
{
/** The filter parser. */
private LdapFilterParser parser;
/** The schema, used to retrieve attributeType and objectClass information. */
private Schema schema;
/**
* Creates a new instance of FilterTextHover.
*
* @param parser filter parser
*/
public FilterTextHover( LdapFilterParser parser )
{
this.parser = parser;
}
/**
* Sets the schema, used to retrieve attributeType and objectClass information.
*
* @param schema the schema
*/
public void setSchema( Schema schema )
{
this.schema = schema;
}
/**
* @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getHoverInfo( ITextViewer textViewer, IRegion hoverRegion )
{
// check attribute type, object class or matching rule values
if ( schema != null )
{
LdapFilter filter = parser.getModel().getFilter( hoverRegion.getOffset() );
if ( filter.getFilterComponent() instanceof LdapFilterItemComponent )
{
LdapFilterItemComponent fc = ( LdapFilterItemComponent ) filter.getFilterComponent();
if ( fc.getAttributeToken() != null
&& fc.getAttributeToken().getOffset() <= hoverRegion.getOffset()
&& hoverRegion.getOffset() <= fc.getAttributeToken().getOffset()
+ fc.getAttributeToken().getLength() )
{
String attributeType = fc.getAttributeToken().getValue();
AttributeType attributeTypeDescription = schema
.getAttributeTypeDescription( attributeType );
String ldifLine = SchemaUtils.getLdifLine( attributeTypeDescription );
return ldifLine;
}
if ( fc.getAttributeToken() != null
&& SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( fc.getAttributeToken().getValue() )
&& fc.getValueToken() != null && fc.getValueToken().getOffset() <= hoverRegion.getOffset()
&& hoverRegion.getOffset() <= fc.getValueToken().getOffset() + fc.getValueToken().getLength() )
{
String objectClass = fc.getValueToken().getValue();
ObjectClass objectClassDescription = schema.getObjectClassDescription( objectClass );
String ldifLine = SchemaUtils.getLdifLine( objectClassDescription );
return ldifLine;
}
}
if ( filter.getFilterComponent() instanceof LdapFilterExtensibleComponent )
{
LdapFilterExtensibleComponent fc = ( LdapFilterExtensibleComponent ) filter.getFilterComponent();
if ( fc.getAttributeToken() != null
&& fc.getAttributeToken().getOffset() <= hoverRegion.getOffset()
&& hoverRegion.getOffset() <= fc.getAttributeToken().getOffset()
+ fc.getAttributeToken().getLength() )
{
String attributeType = fc.getAttributeToken().getValue();
AttributeType attributeTypeDescription = schema
.getAttributeTypeDescription( attributeType );
String ldifLine = SchemaUtils.getLdifLine( attributeTypeDescription );
return ldifLine;
}
if ( fc.getMatchingRuleToken() != null
&& fc.getMatchingRuleToken().getOffset() <= hoverRegion.getOffset()
&& hoverRegion.getOffset() <= fc.getMatchingRuleToken().getOffset()
+ fc.getMatchingRuleToken().getLength() )
{
String matchingRule = fc.getMatchingRuleToken().getValue();
MatchingRule matchingRuleDescription = schema.getMatchingRuleDescription( matchingRule );
String info = SchemaUtils.getLdifLine( matchingRuleDescription );
return info;
}
}
}
// check invalid tokens
LdapFilter[] invalidFilters = parser.getModel().getInvalidFilters();
for ( int i = 0; i < invalidFilters.length; i++ )
{
if ( invalidFilters[i].getStartToken() != null )
{
int start = invalidFilters[i].getStartToken().getOffset();
int stop = invalidFilters[i].getStopToken() != null ? invalidFilters[i].getStopToken().getOffset()
+ invalidFilters[i].getStopToken().getLength() : start
+ invalidFilters[i].getStartToken().getLength();
if ( start <= hoverRegion.getOffset() && hoverRegion.getOffset() < stop )
{
return invalidFilters[i].getInvalidCause();
}
}
}
// check error tokens
LdapFilterToken[] tokens = parser.getModel().getTokens();
for ( int i = 0; i < tokens.length; i++ )
{
if ( tokens[i].getType() == LdapFilterToken.ERROR )
{
int start = tokens[i].getOffset();
int stop = start + tokens[i].getLength();
if ( start <= hoverRegion.getOffset() && hoverRegion.getOffset() < stop )
{
return Messages.getString( "FilterTextHover.InvalidCharacters" ); //$NON-NLS-1$
}
}
}
return null;
}
/**
* @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getHoverRegion( ITextViewer textViewer, int offset )
{
return new Region( offset, 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterReconcilingStrategy.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterReconcilingStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.common.ui.CommonUIConstants;
import org.apache.directory.studio.common.ui.CommonUIPlugin;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterToken;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.PaintManager;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.reconciler.DirtyRegion;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.AnnotationPainter;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.MatchingCharacterPainter;
import org.eclipse.swt.graphics.Color;
/**
* The FilterReconcilingStrategy is used to maintain the error annotations
* (red squirrels).
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterReconcilingStrategy implements IReconcilingStrategy
{
/** The source viewer. */
private ISourceViewer sourceViewer;
/** The filter parser. */
private LdapFilterParser parser;
/** The paint manager. */
private PaintManager paintManager;
/**
* Creates a new instance of FilterReconcilingStrategy.
*
* @param sourceViewer the source viewer
* @param parser the filter parser
*/
public FilterReconcilingStrategy( ISourceViewer sourceViewer, LdapFilterParser parser )
{
this.sourceViewer = sourceViewer;
this.parser = parser;
this.paintManager = null;
}
/**
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument)
*/
public void setDocument( IDocument document )
{
if ( sourceViewer.getAnnotationModel() == null )
{
IAnnotationModel model = new AnnotationModel();
sourceViewer.setDocument( sourceViewer.getDocument(), model );
}
// add annotation painter
Color annotationColor = CommonUIPlugin.getDefault().getColor( CommonUIConstants.KEYWORD_1_COLOR );
if ( paintManager == null && annotationColor != null
&& sourceViewer.getAnnotationModel() instanceof IAnnotationModelExtension )
{
AnnotationPainter ap = new AnnotationPainter( sourceViewer, null );
ap.addAnnotationType( "DEFAULT" ); //$NON-NLS-1$
ap.setAnnotationTypeColor( "DEFAULT", //$NON-NLS-1$
CommonUIPlugin.getDefault().getColor( CommonUIConstants.ERROR_COLOR ) );
sourceViewer.getAnnotationModel().addAnnotationModelListener( ap );
FilterCharacterPairMatcher cpm = new FilterCharacterPairMatcher( sourceViewer, parser );
MatchingCharacterPainter mcp = new MatchingCharacterPainter( sourceViewer, cpm );
mcp.setColor( annotationColor );
paintManager = new PaintManager( sourceViewer );
paintManager.addPainter( ap );
paintManager.addPainter( mcp );
}
}
/**
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion)
*/
public void reconcile( DirtyRegion dirtyRegion, IRegion subRegion )
{
reconcile( dirtyRegion );
}
/**
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
*/
public void reconcile( IRegion partition )
{
LdapFilterToken[] tokens = parser.getModel().getTokens();
// annotations
if ( sourceViewer.getAnnotationModel() instanceof IAnnotationModelExtension )
{
( ( IAnnotationModelExtension ) sourceViewer.getAnnotationModel() ).removeAllAnnotations();
List<Position> positionList = new ArrayList<Position>();
LdapFilter[] invalidFilters = parser.getModel().getInvalidFilters();
for ( int i = 0; i < invalidFilters.length; i++ )
{
if ( invalidFilters[i].getStartToken() != null )
{
int start = invalidFilters[i].getStartToken().getOffset();
int stop = invalidFilters[i].getStopToken() != null ? invalidFilters[i].getStopToken().getOffset()
+ invalidFilters[i].getStopToken().getLength()
: start
+ invalidFilters[i].getStartToken().getLength();
Annotation annotation = new Annotation( "DEFAULT", true, invalidFilters[i].toString() ); //$NON-NLS-1$
Position position = new Position( start, stop - start );
positionList.add( position );
sourceViewer.getAnnotationModel().addAnnotation( annotation, position );
}
}
for ( int i = 0; i < tokens.length; i++ )
{
if ( tokens[i].getType() == LdapFilterToken.ERROR )
{
boolean overlaps = false;
for ( int k = 0; k < positionList.size(); k++ )
{
Position pos = positionList.get( k );
if ( pos.overlapsWith( tokens[i].getOffset(), tokens[i].getLength() ) )
{
overlaps = true;
break;
}
}
if ( !overlaps )
{
Annotation annotation = new Annotation( "DEFAULT", true, tokens[i].getValue() ); //$NON-NLS-1$
Position position = new Position( tokens[i].getOffset(), tokens[i].getLength() );
sourceViewer.getAnnotationModel().addAnnotation( annotation, position );
}
}
}
}
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapAndFilterComponent;
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.LdapNotFilterComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapOrFilterComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
/**
* The FilterAutoEditStrategy implements the IAutoEditStrategy for the filter editor widget.
* It provides smart parentesis handling when typing the filter.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterAutoEditStrategy extends DefaultIndentLineAutoEditStrategy implements IAutoEditStrategy
{
/** The Constant INDENT_STRING. */
public static final String INDENT_STRING = " "; //$NON-NLS-1$
/** The filter parser. */
private LdapFilterParser parser;
/**
* Creates a new instance of FilterAutoEditStrategy.
*
* @param parser the filter parser
*/
public FilterAutoEditStrategy( LdapFilterParser parser )
{
this.parser = parser;
}
/**
* @see org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand( IDocument d, DocumentCommand c )
{
super.customizeDocumentCommand( d, c );
AutoEditParameters aep = new AutoEditParameters( c.text, c.offset, c.length, c.caretOffset, c.shiftsCaret );
customizeAutoEditParameters( d.get(), aep );
c.offset = aep.offset;
c.length = aep.length;
c.text = aep.text;
c.caretOffset = aep.caretOffset;
c.shiftsCaret = aep.shiftsCaret;
}
/**
* Customizes auto edit parameters.
*
* @param currentFilter the current filter
* @param aep the auto edit parameters
*/
public void customizeAutoEditParameters( String currentFilter, AutoEditParameters aep )
{
parser.parse( currentFilter );
LdapFilter filter = parser.getModel().getFilter( aep.offset );
if ( filter == null )
{
return;
}
// check balanced parenthesis
int balanced = 0;
for ( int i = 0; i < currentFilter.length(); i++ )
{
if ( currentFilter.charAt( i ) == '(' )
{
balanced++;
}
else if ( currentFilter.charAt( i ) == ')' )
{
balanced--;
}
}
if ( aep.length > 0 && ( aep.text == null || "".equals( aep.text ) ) ) //$NON-NLS-1$
{
// delete surrounding parenthesis after deleting the last character
if ( filter.toString().length() - aep.length == 2 && filter.getStartToken() != null
&& filter.getStopToken() != null
&& aep.offset >= filter.getStartToken().getOffset() + filter.getStartToken().getLength()
&& aep.offset + aep.length <= filter.getStopToken().getOffset() )
{
if ( filter.toString().length() - aep.length == 2 )
{
aep.offset -= 1;
aep.length += 2;
aep.caretOffset = aep.offset;
aep.shiftsCaret = false;
}
}
// delete closing parenthesis after deleting the opening parenthesis
if ( filter.toString().length() - aep.length == 1 && filter.getStartToken() != null
&& filter.getStopToken() != null && aep.offset == filter.getStartToken().getOffset() )
{
aep.length += 1;
aep.caretOffset = aep.offset;
aep.shiftsCaret = false;
}
}
if ( ( aep.length == 0 || aep.length == currentFilter.length() ) && aep.text != null && !"".equals( aep.text ) ) //$NON-NLS-1$
{
boolean isNewFilter = aep.text.equals( "(" ); //$NON-NLS-1$
boolean isNewNestedFilter = aep.text.equals( "&" ) || aep.text.equals( "|" ) || aep.text.equals( "!" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
boolean isSurroundNew = false;
boolean isSurroundNested = false;
boolean isSurroundBeforeOtherFilter = false;
boolean isSurroundAfterOtherFilter = false;
if ( !Character.isWhitespace( aep.text.charAt( 0 ) )
&& !aep.text.startsWith( "(" ) && !aep.text.endsWith( ")" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
// isSurroundNew
isSurroundNew = aep.offset == 0;
// isSurroundNested
if ( filter.getStartToken() != null
&& ( filter.getFilterComponent() instanceof LdapAndFilterComponent
|| filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ) )
{
LdapFilterComponent fc = filter.getFilterComponent();
LdapFilter[] filters = fc.getFilters();
if ( filters.length == 0 && aep.offset > fc.getStartToken().getOffset() )
{
// no nested filter yet
isSurroundNested = true;
}
if ( filters.length > 0 && aep.offset > fc.getStartToken().getOffset()
&& aep.offset < filters[0].getStartToken().getOffset() )
{
// before first nested filter
isSurroundNested = true;
}
if ( filters.length > 0 && aep.offset > filters[filters.length - 1].getStopToken().getOffset()
&& aep.offset <= filter.getStopToken().getOffset() )
{
// after last nested filter
isSurroundNested = true;
}
for ( int i = 0; i < filters.length; i++ )
{
if ( filters.length > i + 1 )
{
if ( aep.offset > filters[i].getStopToken().getOffset()
&& aep.offset <= filters[i + 1].getStopToken().getOffset() )
{
// between nested filter
isSurroundNested = true;
}
}
}
}
// isSurroundBeforeOtherFilter
isSurroundBeforeOtherFilter = filter.getStartToken() != null
&& aep.offset == filter.getStartToken().getOffset();
// isSurroundAfterOtherFilter
isSurroundAfterOtherFilter = filter.getStopToken() != null
&& aep.offset == filter.getStopToken().getOffset()
&& ( filter.getFilterComponent() instanceof LdapAndFilterComponent
|| filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent );
}
// add opening parenthesis '('
if ( isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter )
{
aep.text = "(" + aep.text; //$NON-NLS-1$
aep.caretOffset = aep.offset + aep.text.length();
aep.shiftsCaret = false;
}
// add parenthesis for nested filters
if ( isNewNestedFilter )
{
aep.text = aep.text + "()"; //$NON-NLS-1$
aep.caretOffset = aep.offset + aep.text.length() - 1;
aep.shiftsCaret = false;
}
// add closing parenthesis ')'
if ( isNewFilter || isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter
|| isSurroundBeforeOtherFilter )
{
if ( balanced == 0 )
{
aep.text = aep.text + ")"; //$NON-NLS-1$
if ( aep.caretOffset == -1 )
{
aep.caretOffset = aep.offset + aep.text.length() - 1;
aep.shiftsCaret = false;
}
}
}
// translate tab to IDENT_STRING
if ( aep.text.equals( "\t" ) ) //$NON-NLS-1$
{
aep.text = INDENT_STRING;
}
}
}
/**
* Helper class.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public static class AutoEditParameters
{
/** The text. */
public String text;
/** The offset. */
public int offset;
/** The length. */
public int length;
/** The caret offset. */
public int caretOffset;
/** The shifts caret flag. */
public boolean shiftsCaret;
/**
* Creates a new instance of AutoEditParameters.
*
* @param text the text
* @param offset the offset
* @param length the length
* @param caretOffset the caret offset
* @param shiftsCaret the shifts caret flag
*/
public AutoEditParameters( String text, int offset, int length, int caretOffset, boolean shiftsCaret )
{
this.text = text;
this.offset = offset;
this.length = length;
this.caretOffset = caretOffset;
this.shiftsCaret = shiftsCaret;
}
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/Messages.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/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.ldapbrowser.common.filtereditor;
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterDamagerRepairer.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterDamagerRepairer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import org.apache.directory.studio.common.ui.CommonUIConstants;
import org.apache.directory.studio.common.ui.CommonUIPlugin;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterToken;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.presentation.IPresentationDamager;
import org.eclipse.jface.text.presentation.IPresentationRepairer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
/**
* The FilterDamagerRepairer is used for syntax highlighting.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterDamagerRepairer implements IPresentationDamager, IPresentationRepairer
{
/** The filter parser. */
private LdapFilterParser parser;
/** The document. */
private IDocument document;
/**
* Creates a new instance of FilterDamagerRepairer.
*
* @param parser the filter parser
*/
public FilterDamagerRepairer( LdapFilterParser parser )
{
this.parser = parser;
this.document = null;
}
/**
* @see org.eclipse.jface.text.presentation.IPresentationDamager#setDocument(org.eclipse.jface.text.IDocument)
*/
public void setDocument( IDocument document )
{
this.document = document;
}
/**
* @see org.eclipse.jface.text.presentation.IPresentationDamager#getDamageRegion(org.eclipse.jface.text.ITypedRegion, org.eclipse.jface.text.DocumentEvent, boolean)
*/
public IRegion getDamageRegion( ITypedRegion partition, DocumentEvent event, boolean documentPartitioningChanged )
{
return partition;
}
/**
* @see org.eclipse.jface.text.presentation.IPresentationRepairer#createPresentation(org.eclipse.jface.text.TextPresentation, org.eclipse.jface.text.ITypedRegion)
*/
public void createPresentation( TextPresentation presentation, ITypedRegion damage )
{
TextAttribute DEFAULT_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.DEFAULT_COLOR) );
TextAttribute AND_OR_NOT_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.KEYWORD_1_COLOR), null, SWT.BOLD );
TextAttribute ATTRIBUTE_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.ATTRIBUTE_TYPE_COLOR) );
TextAttribute FILTER_TYPE_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.SEPARATOR_COLOR), null, SWT.BOLD );
TextAttribute VALUE_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.VALUE_COLOR) );
TextAttribute PARENTHESIS_TEXT_ATTRIBUTE = new TextAttribute( getColor(CommonUIConstants.DEFAULT_COLOR), null, SWT.BOLD );
// parse the filter
parser.parse( this.document.get() );
// get tokens
LdapFilterToken[] tokens = parser.getModel().getTokens();
// syntax highlighting
for ( int i = 0; i < tokens.length; i++ )
{
switch ( tokens[i].getType() )
{
case LdapFilterToken.LPAR:
case LdapFilterToken.RPAR:
this.addStyleRange( presentation, tokens[i], PARENTHESIS_TEXT_ATTRIBUTE );
break;
case LdapFilterToken.AND:
case LdapFilterToken.OR:
case LdapFilterToken.NOT:
this.addStyleRange( presentation, tokens[i], AND_OR_NOT_TEXT_ATTRIBUTE );
break;
case LdapFilterToken.EQUAL:
case LdapFilterToken.GREATER:
case LdapFilterToken.LESS:
case LdapFilterToken.APROX:
case LdapFilterToken.PRESENT:
case LdapFilterToken.SUBSTRING:
case LdapFilterToken.EXTENSIBLE_DNATTR_COLON:
case LdapFilterToken.EXTENSIBLE_MATCHINGRULEOID_COLON:
case LdapFilterToken.EXTENSIBLE_EQUALS_COLON:
this.addStyleRange( presentation, tokens[i], FILTER_TYPE_TEXT_ATTRIBUTE );
break;
case LdapFilterToken.ATTRIBUTE:
case LdapFilterToken.EXTENSIBLE_ATTRIBUTE:
case LdapFilterToken.EXTENSIBLE_DNATTR:
case LdapFilterToken.EXTENSIBLE_MATCHINGRULEOID:
this.addStyleRange( presentation, tokens[i], ATTRIBUTE_TEXT_ATTRIBUTE );
break;
case LdapFilterToken.VALUE:
this.addStyleRange( presentation, tokens[i], VALUE_TEXT_ATTRIBUTE );
break;
default:
this.addStyleRange( presentation, tokens[i], DEFAULT_TEXT_ATTRIBUTE );
}
}
}
private Color getColor( String name )
{
return CommonUIPlugin.getDefault().getColor( name );
}
/**
* Adds the style range.
*
* @param presentation the presentation
* @param textAttribute the text attribute
* @param token the token
*/
private void addStyleRange( TextPresentation presentation, LdapFilterToken token, TextAttribute textAttribute )
{
if ( token.getLength() > 0 )
{
StyleRange range = new StyleRange( token.getOffset(), token.getLength(), textAttribute.getForeground(),
textAttribute.getBackground(), textAttribute.getStyle() );
presentation.addStyleRange( range );
}
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterContentAssistProcessor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterContentAssistProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
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.MatchingRule;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterExtensibleComponent;
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.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateCompletionProcessor;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.swt.graphics.Image;
/**
* The FilterContentAssistProcessor computes the content proposals for the filter editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterContentAssistProcessor extends TemplateCompletionProcessor implements IContentAssistProcessor,
IContentProposalProvider
{
private static final Comparator<String> NAME_AND_OID_COMPARATOR = new Comparator<String>()
{
public int compare( String s1, String s2 )
{
if ( s1.matches( "[0-9\\.]+" ) && !s2.matches( "[0-9\\.]+" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return 1;
}
else if ( !s1.matches( "[0-9\\.]+" ) && s2.matches( "[0-9\\.]+" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return -1;
}
else
{
return s1.compareToIgnoreCase( s2 );
}
}
};
/** The parser. */
private LdapFilterParser parser;
/** The source viewer, may be null. */
private ISourceViewer sourceViewer;
/** The auto activation characters. */
private char[] autoActivationCharacters;
/** The schema, used to retrieve attributeType and objectClass information. */
private Schema schema;
/** The possible attribute types. */
private Map<String, AttributeType> possibleAttributeTypes;
/** The possible filter types. */
private Map<String, String> possibleFilterTypes;
/** The possible object classes. */
private Map<String, ObjectClass> possibleObjectClasses;
/** The possible matching rules. */
private Map<String, MatchingRule> possibleMatchingRules;
/**
* Creates a new instance of FilterContentAssistProcessor.
*
* @param parser the parser
*/
public FilterContentAssistProcessor( LdapFilterParser parser )
{
this( null, parser );
}
/**
* Creates a new instance of FilterContentAssistProcessor.
*
* @param sourceViewer the source viewer
* @param parser the parser
*/
public FilterContentAssistProcessor( ISourceViewer sourceViewer, LdapFilterParser parser )
{
this.parser = parser;
this.sourceViewer = sourceViewer;
this.autoActivationCharacters = new char[7 + 10 + 26 + 26];
this.autoActivationCharacters[0] = '(';
this.autoActivationCharacters[1] = ')';
this.autoActivationCharacters[2] = '&';
this.autoActivationCharacters[3] = '|';
this.autoActivationCharacters[4] = '!';
this.autoActivationCharacters[5] = ':';
this.autoActivationCharacters[6] = '.';
int i = 7;
for ( char c = 'a'; c <= 'z'; c++, i++ )
{
this.autoActivationCharacters[i] = c;
}
for ( char c = 'A'; c <= 'Z'; c++, i++ )
{
this.autoActivationCharacters[i] = c;
}
for ( char c = '0'; c <= '9'; c++, i++ )
{
this.autoActivationCharacters[i] = c;
}
}
/**
* Sets the schema, used to retrieve attributeType and objectClass information.
*
* @param schema the schema
*/
public void setSchema( Schema schema )
{
this.schema = schema;
possibleAttributeTypes = new TreeMap<String, AttributeType>( NAME_AND_OID_COMPARATOR );
possibleFilterTypes = new LinkedHashMap<String, String>();
possibleObjectClasses = new TreeMap<String, ObjectClass>( NAME_AND_OID_COMPARATOR );
possibleMatchingRules = new TreeMap<String, MatchingRule>( NAME_AND_OID_COMPARATOR );
if ( schema != null )
{
Collection<AttributeType> attributeTypeDescriptions = schema.getAttributeTypeDescriptions();
for ( AttributeType atd : attributeTypeDescriptions )
{
possibleAttributeTypes.put( atd.getOid(), atd );
for ( String atdName : atd.getNames() )
{
possibleAttributeTypes.put( atdName, atd );
}
}
possibleFilterTypes.put( "=", Messages.getString( "FilterContentAssistProcessor.Equals" ) ); //$NON-NLS-1$ //$NON-NLS-2$
possibleFilterTypes.put( "=*", Messages.getString( "FilterContentAssistProcessor.Present" ) ); //$NON-NLS-1$ //$NON-NLS-2$
possibleFilterTypes.put( "<=", Messages.getString( "FilterContentAssistProcessor.LessThanOrEquals" ) ); //$NON-NLS-1$ //$NON-NLS-2$
possibleFilterTypes.put( ">=", Messages.getString( "FilterContentAssistProcessor.GreaterThanOrEquals" ) ); //$NON-NLS-1$ //$NON-NLS-2$
possibleFilterTypes.put( "~=", Messages.getString( "FilterContentAssistProcessor.Approximately" ) ); //$NON-NLS-1$ //$NON-NLS-2$
Collection<ObjectClass> ocds = schema.getObjectClassDescriptions();
for ( ObjectClass ocd : ocds )
{
possibleObjectClasses.put( ocd.getOid(), ocd );
for ( String name : ocd.getNames() )
{
possibleObjectClasses.put( name, ocd );
}
}
Collection<MatchingRule> matchingRuleDescriptions = schema.getMatchingRuleDescriptions();
for ( MatchingRule description : matchingRuleDescriptions )
{
possibleMatchingRules.put( description.getOid(), description );
for ( String name : description.getNames() )
{
possibleMatchingRules.put( name, description );
}
}
}
}
/**
* @see org.eclipse.jface.text.templates.TemplateCompletionProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters()
{
return autoActivationCharacters;
}
/**
* @see org.eclipse.jface.text.templates.TemplateCompletionProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals( ITextViewer viewer, int offset )
{
return computeCompletionProposals( offset );
}
/**
* @see org.eclipse.jface.fieldassist.IContentProposalProvider#getProposals(java.lang.String, int)
*/
public IContentProposal[] getProposals( final String contents, final int position )
{
parser.parse( contents );
ICompletionProposal[] oldProposals = computeCompletionProposals( position );
IContentProposal[] proposals = new IContentProposal[oldProposals.length];
for ( int i = 0; i < oldProposals.length; i++ )
{
final ICompletionProposal oldProposal = oldProposals[i];
final Document document = new Document( contents );
oldProposal.apply( document );
proposals[i] = new IContentProposal()
{
public String getContent()
{
return document.get();
}
public int getCursorPosition()
{
return oldProposal.getSelection( document ).x;
}
public String getDescription()
{
return oldProposal.getAdditionalProposalInfo();
}
public String getLabel()
{
return oldProposal.getDisplayString();
}
public String toString()
{
return getContent();
}
};
}
return proposals;
}
/**
* Computes completion proposals.
*
* @param offset the offset
*
* @return the matching completion proposals
*/
private ICompletionProposal[] computeCompletionProposals( int offset )
{
String[] possibleObjectClasses = schema == null ? new String[0] : SchemaUtils.getNamesAsArray( schema
.getObjectClassDescriptions() );
Arrays.sort( possibleObjectClasses );
List<ICompletionProposal> proposalList = new ArrayList<ICompletionProposal>();
LdapFilter filter = parser.getModel().getFilter( offset );
if ( filter != null && offset > 0 )
{
// case 0: open curly started, show templates and all attribute types
if ( filter.getStartToken() != null && filter.getFilterComponent() == null )
{
if ( sourceViewer != null )
{
ICompletionProposal[] templateProposals = super.computeCompletionProposals( sourceViewer, offset );
if ( templateProposals != null )
{
proposalList.addAll( Arrays.asList( templateProposals ) );
}
}
addPossibleAttributeTypes( proposalList, "", offset ); //$NON-NLS-1$
}
// case A: simple filter
if ( filter.getFilterComponent() instanceof LdapFilterItemComponent )
{
LdapFilterItemComponent fc = ( LdapFilterItemComponent ) filter.getFilterComponent();
// case A1: editing attribute type: show matching attribute types
if ( fc.getStartToken().getOffset() <= offset
&& offset <= fc.getStartToken().getOffset() + fc.getStartToken().getLength() )
{
addPossibleAttributeTypes( proposalList, fc.getAttributeToken().getValue(), fc.getAttributeToken()
.getOffset() );
}
String attributeType = null;
if ( schema != null && schema.hasAttributeTypeDescription( fc.getAttributeToken().getValue() ) )
{
attributeType = fc.getAttributeToken().getValue();
}
// case A2: after attribte type: show possible filter types and extensible match options
if ( attributeType != null )
{
if ( ( fc.getAttributeToken().getOffset() <= offset || fc.getFilterToken() != null )
&& offset <= fc.getAttributeToken().getOffset() + fc.getAttributeToken().getLength()
+ ( fc.getFilterToken() != null ? fc.getFilterToken().getLength() : 0 ) )
{
//String attributeType = fc.getAttributeToken().getValue();
String filterType = fc.getFilterToken() != null ? fc.getFilterToken().getValue() : ""; //$NON-NLS-1$
int filterTypeOffset = fc.getAttributeToken().getOffset() + fc.getAttributeToken().getLength();
addPossibleFilterTypes( proposalList, attributeType, filterType, filterTypeOffset );
}
}
// case A3: editing objectClass attribute: show matching object classes
if ( attributeType != null && SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( attributeType ) )
{
if ( ( fc.getValueToken() != null && fc.getValueToken().getOffset() <= offset || fc
.getFilterToken() != null )
&& offset <= fc.getAttributeToken().getOffset() + fc.getAttributeToken().getLength()
+ ( fc.getFilterToken() != null ? fc.getFilterToken().getLength() : 0 )
+ ( fc.getValueToken() != null ? fc.getValueToken().getLength() : 0 ) )
{
addPossibleObjectClasses( proposalList, fc.getValueToken() == null ? "" : fc.getValueToken() //$NON-NLS-1$
.getValue(), fc.getValueToken() == null ? offset : fc.getValueToken().getOffset() );
}
}
}
// case B: extensible filter
if ( filter.getFilterComponent() instanceof LdapFilterExtensibleComponent )
{
LdapFilterExtensibleComponent fc = ( LdapFilterExtensibleComponent ) filter.getFilterComponent();
// case B1: editing extensible attribute type: show matching attribute types
if ( fc.getAttributeToken() != null && fc.getAttributeToken().getOffset() <= offset
&& offset <= fc.getAttributeToken().getOffset() + fc.getAttributeToken().getLength() )
{
addPossibleAttributeTypes( proposalList, fc.getAttributeToken().getValue(), fc.getAttributeToken()
.getOffset() );
}
// case B2: editing dn
if ( fc.getDnAttrToken() != null && fc.getDnAttrToken().getOffset() <= offset
&& offset <= fc.getDnAttrToken().getOffset() + fc.getDnAttrToken().getLength() )
{
addDnAttr( proposalList, fc.getDnAttrToken().getValue(), fc.getDnAttrToken().getOffset() );
}
// case B3: editing matching rule
if ( fc.getMatchingRuleColonToken() != null
&& fc.getMatchingRuleToken() == null
&& fc.getMatchingRuleColonToken().getOffset() <= offset
&& offset <= fc.getMatchingRuleColonToken().getOffset()
+ fc.getMatchingRuleColonToken().getLength() )
{
if ( fc.getDnAttrColonToken() == null )
{
addDnAttr( proposalList, "", offset ); //$NON-NLS-1$
}
addPossibleMatchingRules( proposalList, "", offset, fc.getEqualsColonToken(), fc.getEqualsToken() ); //$NON-NLS-1$
}
if ( fc.getMatchingRuleToken() != null && fc.getMatchingRuleToken().getOffset() <= offset
&& offset <= fc.getMatchingRuleToken().getOffset() + fc.getMatchingRuleToken().getLength() )
{
if ( fc.getDnAttrColonToken() == null )
{
addDnAttr( proposalList, fc.getMatchingRuleToken().getValue(), fc.getMatchingRuleToken()
.getOffset() );
}
String matchingRuleValue = fc.getMatchingRuleToken().getValue();
addPossibleMatchingRules( proposalList, matchingRuleValue, fc.getMatchingRuleToken().getOffset(),
fc.getEqualsColonToken(), fc.getEqualsToken() );
}
}
}
return proposalList.toArray( new ICompletionProposal[0] );
}
/**
* Adds the possible attribute types to the proposal list.
*
* @param proposalList the proposal list
* @param attributeType the current attribute type
* @param offset the offset
*/
private void addPossibleAttributeTypes( List<ICompletionProposal> proposalList, String attributeType, int offset )
{
if ( schema != null )
{
for ( String possibleAttributeType : possibleAttributeTypes.keySet() )
{
AttributeType description = possibleAttributeTypes.get( possibleAttributeType );
if ( possibleAttributeType.toUpperCase().startsWith( attributeType.toUpperCase() ) )
{
String replacementString = possibleAttributeType;
String displayString = possibleAttributeType;
if ( displayString.equals( description.getOid() ) )
{
displayString += " (" + SchemaUtils.toString( description ) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
else
{
displayString += " (" + description.getOid() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
String info = SchemaUtils.getLdifLine( description );
ICompletionProposal proposal = new CompletionProposal( replacementString, offset, attributeType
.length(), replacementString.length(), getAttributeTypeImage(), displayString, null, info );
proposalList.add( proposal );
}
}
}
}
/**
* Adds the possible attribute types to the proposal list.
*
* @param proposalList the proposal list
* @param attributeType the current attribute type
* @param offset the offset
*/
private void addPossibleFilterTypes( List<ICompletionProposal> proposalList, String attributeType,
String filterType, int offset )
{
if ( schema != null )
{
Map<String, String> copy = new LinkedHashMap<String, String>( possibleFilterTypes );
if ( SchemaUtils.getEqualityMatchingRuleNameOrNumericOidTransitive( schema
.getAttributeTypeDescription( attributeType ), schema ) == null )
{
copy.remove( "=" ); //$NON-NLS-1$
copy.remove( "~=" ); //$NON-NLS-1$
}
if ( SchemaUtils.getOrderingMatchingRuleNameOrNumericOidTransitive( schema
.getAttributeTypeDescription( attributeType ), schema ) == null )
{
copy.remove( "<=" ); //$NON-NLS-1$
copy.remove( ">=" ); //$NON-NLS-1$
}
for ( String possibleFilterType : copy.keySet() )
{
String replacementString = possibleFilterType;
String displayString = copy.get( possibleFilterType );
ICompletionProposal proposal = new CompletionProposal( replacementString, offset, filterType.length(),
possibleFilterType.length(), getFilterTypeImage(), displayString, null, null );
proposalList.add( proposal );
}
}
}
/**
* Adds the possible object classes to the proposal list.
*
* @param proposalList the proposal list
* @param objectClasses the object class
* @param offset the offset
*/
private void addPossibleObjectClasses( List<ICompletionProposal> proposalList, String objectClass, int offset )
{
if ( schema != null )
{
for ( String possibleObjectClass : possibleObjectClasses.keySet() )
{
ObjectClass description = possibleObjectClasses.get( possibleObjectClass );
if ( possibleObjectClass.toUpperCase().startsWith( objectClass.toUpperCase() ) )
{
String replacementString = possibleObjectClass;
String displayString = possibleObjectClass;
if ( displayString.equals( description.getOid() ) )
{
displayString += " (" + SchemaUtils.toString( description ) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
else
{
displayString += " (" + description.getOid() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
ICompletionProposal proposal = new CompletionProposal( replacementString, offset, objectClass
.length(), replacementString.length(), getObjectClassImage(), displayString, null, SchemaUtils
.getLdifLine( schema.getObjectClassDescription( possibleObjectClass ) ) );
proposalList.add( proposal );
}
}
}
}
/**
* Adds the possible matching rules (that fits to the given attribute type) to the proposal list.
*
* @param proposalList the proposal list
* @param matchingRule the matching rule
* @param offset the offset
*/
private void addPossibleMatchingRules( List<ICompletionProposal> proposalList, String matchingRule, int offset,
LdapFilterToken equalsColonToken, LdapFilterToken equalsToken )
{
if ( schema != null )
{
for ( String possibleMatchingRule : possibleMatchingRules.keySet() )
{
if ( possibleMatchingRule.toUpperCase().startsWith( matchingRule.toUpperCase() ) )
{
MatchingRule description = schema.getMatchingRuleDescription( possibleMatchingRule );
String replacementString = possibleMatchingRule;
if ( equalsColonToken == null )
{
replacementString += ":"; //$NON-NLS-1$
}
if ( equalsToken == null )
{
replacementString += "="; //$NON-NLS-1$
}
String displayString = possibleMatchingRule;
if ( displayString.equals( description.getOid() ) )
{
displayString += " (" + SchemaUtils.toString( description ) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
else
{
displayString += " (" + description.getOid() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
String info = SchemaUtils.getLdifLine( description );
ICompletionProposal proposal = new CompletionProposal( replacementString, offset, matchingRule
.length(), replacementString.length(), getMatchingRuleImage(), displayString, null, info );
proposalList.add( proposal );
}
}
}
}
/**
* Adds the dn: proposal to the proposal list.
*
* @param proposalList the proposal list
* @param dnAttr the dn attr
* @param offset the offset
*/
private void addDnAttr( List<ICompletionProposal> proposalList, String dnAttr, int offset )
{
if ( "dn".toUpperCase().startsWith( dnAttr.toUpperCase() ) ) //$NON-NLS-1$
{
String replacementString = "dn:"; //$NON-NLS-1$
String displayString = "dn: ()"; //$NON-NLS-1$
ICompletionProposal proposal = new CompletionProposal( replacementString, offset, dnAttr.length(),
replacementString.length(), null, displayString, null, null );
proposalList.add( proposal );
}
}
/**
* Gets the attribute type image.
*
* @return the attribute type image
*/
private Image getAttributeTypeImage()
{
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_ATD );
}
/**
* Gets the filter type image.
*
* @return the filter type image
*/
private Image getFilterTypeImage()
{
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_FILTER_EDITOR );
}
/**
* Gets the object class image.
*
* @return the object class image
*/
private Image getObjectClassImage()
{
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_OCD );
}
/**
* Gets the matching rule image.
*
* @return the matching rule image
*/
private Image getMatchingRuleImage()
{
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_MRD );
}
/**
* @see org.eclipse.jface.text.templates.TemplateCompletionProcessor#getTemplates(java.lang.String)
*/
protected Template[] getTemplates( String contextTypeId )
{
Template[] templates = BrowserCommonActivator.getDefault().getFilterTemplateStore().getTemplates(
BrowserCommonConstants.FILTER_TEMPLATE_ID );
return templates;
}
/**
* @see org.eclipse.jface.text.templates.TemplateCompletionProcessor#getContextType(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
protected TemplateContextType getContextType( ITextViewer viewer, IRegion region )
{
TemplateContextType contextType = BrowserCommonActivator.getDefault().getFilterTemplateContextTypeRegistry()
.getContextType( BrowserCommonConstants.FILTER_TEMPLATE_ID );
return contextType;
}
/**
* @see org.eclipse.jface.text.templates.TemplateCompletionProcessor#getImage(org.eclipse.jface.text.templates.Template)
*/
protected Image getImage( Template template )
{
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_TEMPLATE );
}
/**
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
*/
public IContextInformation[] computeContextInformation( ITextViewer viewer, int documentOffset )
{
return null;
}
/**
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters()
{
return null;
}
/**
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage()
{
return null;
}
/**
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator()
{
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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterSourceViewerConfiguration.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterSourceViewerConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import org.apache.directory.studio.ldapbrowser.common.widgets.DialogContentAssistant;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.MonoReconciler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
/**
* The FilterSourceViewerConfiguration implements the configuration of
* the source viewer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterSourceViewerConfiguration extends SourceViewerConfiguration
{
/** The current connection, used to retrieve schema information. */
private IBrowserConnection connection;
/** The filter parser. */
private LdapFilterParser parser;
/** The presentation reconciler, used for syntax highlighting. */
private PresentationReconciler presentationReconciler;
/** The damager repairer, used for syntax highlighting. */
private FilterDamagerRepairer damagerRepairer;
/** The reconciler, used to maintain error annotations. */
private MonoReconciler reconciler;
/** The reconciling strategy, used to maintain error annotations. */
private FilterReconcilingStrategy reconcilingStrategy;
/** The text hover, used to display error message tooltips. */
private FilterTextHover textHover;
/** The auto edit strategy, used for smart parentesis handling. */
private FilterAutoEditStrategy[] autoEditStrategies;
/** The formatter, used to format the filter. */
private ContentFormatter formatter;
/** The formatting strategy, used to format the filter. */
private FilterFormattingStrategy formattingStrategy;
/** The content assistant, used for content proposals. */
private DialogContentAssistant contentAssistant;
/** The content assist processor, used for content proposals. */
private FilterContentAssistProcessor contentAssistProcessor;
/**
* Creates a new instance of FilterSourceViewerConfiguration.
*
* @param parser the filer parser
* @param connection the connection
*/
public FilterSourceViewerConfiguration( LdapFilterParser parser, IBrowserConnection connection )
{
this.parser = parser;
this.connection = connection;
}
/**
* Sets the connection.
*
* @param connection the connection
*/
public void setConnection( IBrowserConnection connection )
{
this.connection = connection;
contentAssistProcessor.setSchema( connection == null ? null : connection.getSchema() );
textHover.setSchema( connection == null ? null : connection.getSchema() );
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler( ISourceViewer sourceViewer )
{
if ( damagerRepairer == null )
{
damagerRepairer = new FilterDamagerRepairer( parser );
}
if ( presentationReconciler == null )
{
presentationReconciler = new PresentationReconciler();
presentationReconciler.setDamager( damagerRepairer, IDocument.DEFAULT_CONTENT_TYPE );
presentationReconciler.setRepairer( damagerRepairer, IDocument.DEFAULT_CONTENT_TYPE );
}
return presentationReconciler;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
public ITextHover getTextHover( ISourceViewer sourceViewer, String contentType )
{
if ( textHover == null )
{
textHover = new FilterTextHover( parser );
textHover.setSchema( connection == null ? null : connection.getSchema() );
}
return textHover;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getReconciler(org.eclipse.jface.text.source.ISourceViewer)
*/
public IReconciler getReconciler( ISourceViewer sourceViewer )
{
if ( reconcilingStrategy == null )
{
reconcilingStrategy = new FilterReconcilingStrategy( sourceViewer, parser );
}
if ( reconciler == null )
{
reconciler = new MonoReconciler( reconcilingStrategy, false );
}
return reconciler;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
public IAutoEditStrategy[] getAutoEditStrategies( ISourceViewer sourceViewer, String contentType )
{
if ( autoEditStrategies == null )
{
autoEditStrategies = new FilterAutoEditStrategy[]
{ new FilterAutoEditStrategy( parser ) };
}
return autoEditStrategies;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentFormatter(org.eclipse.jface.text.source.ISourceViewer)
*/
public IContentFormatter getContentFormatter( ISourceViewer sourceViewer )
{
if ( formattingStrategy == null )
{
formattingStrategy = new FilterFormattingStrategy( sourceViewer, parser );
}
if ( formatter == null )
{
formatter = new ContentFormatter();
formatter.enablePartitionAwareFormatting( false );
formatter.setFormattingStrategy( formattingStrategy, IDocument.DEFAULT_CONTENT_TYPE );
}
return formatter;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
*/
public IContentAssistant getContentAssistant( ISourceViewer sourceViewer )
{
if ( contentAssistProcessor == null )
{
contentAssistProcessor = new FilterContentAssistProcessor( sourceViewer, parser );
contentAssistProcessor.setSchema( connection == null ? null : connection.getSchema() );
}
if ( contentAssistant == null )
{
contentAssistant = new DialogContentAssistant();
contentAssistant.enableAutoInsert( true );
contentAssistant.setContentAssistProcessor( contentAssistProcessor, IDocument.DEFAULT_CONTENT_TYPE );
contentAssistant.enableAutoActivation( true );
contentAssistant.setAutoActivationDelay( 100 );
contentAssistant.setContextInformationPopupOrientation( IContentAssistant.CONTEXT_INFO_ABOVE );
contentAssistant.setInformationControlCreator( getInformationControlCreator( sourceViewer ) );
}
return contentAssistant;
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getInformationControlCreator(org.eclipse.jface.text.source.ISourceViewer)
*/
public IInformationControlCreator getInformationControlCreator( ISourceViewer sourceViewer )
{
return new IInformationControlCreator()
{
public IInformationControl createInformationControl( Shell parent )
{
return new DefaultInformationControl( parent, SWT.WRAP, 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterFormattingStrategy.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterFormattingStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.filtereditor;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapAndFilterComponent;
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.LdapFilterExtensibleComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterItemComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapNotFilterComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapOrFilterComponent;
import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.source.ISourceViewer;
/**
* The FilterFormattingStrategy is used to format the LDAP filter in the
* filter editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class FilterFormattingStrategy implements IFormattingStrategy
{
/** The filter parser. */
private LdapFilterParser parser;
/** The source viewer. */
private ISourceViewer sourceViewer;
/**
* Creates a new instance of FilterFormattingStrategy.
*
* @param sourceViewer the source viewer
* @param parser the filter parser
*/
public FilterFormattingStrategy( ISourceViewer sourceViewer, LdapFilterParser parser )
{
this.parser = parser;
this.sourceViewer = sourceViewer;
}
/**
* @see org.eclipse.jface.text.formatter.IFormattingStrategy#formatterStarts(java.lang.String)
*/
public void formatterStarts( String initialIndentation )
{
}
/**
* @see org.eclipse.jface.text.formatter.IFormattingStrategy#format(java.lang.String, boolean, java.lang.String, int[])
*/
public String format( String content, boolean isLineStart, String indentation, int[] positions )
{
// this.parser.parse(content);
LdapFilter model = parser.getModel();
if ( model != null && model.isValid() )
{
sourceViewer.getDocument().set( getFormattedFilter( model, 0 ) );
}
return null;
}
/**
* Gets the formatted string respresentation of the filter.
*
* @param filter the filter
* @param indent the indent
*
* @return the formatted string respresentation of the filter
*/
private String getFormattedFilter( LdapFilter filter, int indent )
{
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < indent; i++ )
{
sb.append( FilterAutoEditStrategy.INDENT_STRING );
}
LdapFilterComponent fc = filter.getFilterComponent();
if ( fc instanceof LdapFilterItemComponent )
{
sb.append( '(' ).append( ( ( LdapFilterItemComponent ) fc ).toString() ).append( ')' );
}
else if ( fc instanceof LdapFilterExtensibleComponent )
{
sb.append( '(' ).append( ( ( LdapFilterExtensibleComponent ) fc ).toString() ).append( ')' );
}
else if ( fc instanceof LdapNotFilterComponent )
{
sb.append( "(!" ); //$NON-NLS-1$
LdapNotFilterComponent lnfc = ( LdapNotFilterComponent ) fc;
if ( lnfc.getFilters().length > 0
&& lnfc.getFilters()[0].getFilterComponent() instanceof LdapFilterItemComponent )
{
sb.append( getFormattedFilter( ( lnfc ).getFilters()[0], 0 ) );
}
else
{
sb.append( '\n' );
sb.append( getFormattedFilter( ( lnfc ).getFilters()[0], indent + 1 ) );
sb.append( '\n' );
for ( int i = 0; i < indent; i++ )
sb.append( FilterAutoEditStrategy.INDENT_STRING );
}
sb.append( ')' );
}
else if ( fc instanceof LdapAndFilterComponent )
{
sb.append( "(&" ); //$NON-NLS-1$
sb.append( '\n' );
LdapFilter[] filters = ( ( LdapAndFilterComponent ) fc ).getFilters();
for ( int i = 0; i < filters.length; i++ )
{
sb.append( getFormattedFilter( filters[i], indent + 1 ) );
sb.append( '\n' );
}
for ( int i = 0; i < indent; i++ )
sb.append( FilterAutoEditStrategy.INDENT_STRING );
sb.append( ')' );
}
else if ( fc instanceof LdapOrFilterComponent )
{
sb.append( "(|" ); //$NON-NLS-1$
sb.append( '\n' );
LdapFilter[] filters = ( ( LdapOrFilterComponent ) fc ).getFilters();
for ( int i = 0; i < filters.length; i++ )
{
sb.append( getFormattedFilter( filters[i], indent + 1 ) );
sb.append( '\n' );
}
for ( int i = 0; i < indent; i++ )
sb.append( FilterAutoEditStrategy.INDENT_STRING );
sb.append( ')' );
}
return sb.toString();
}
/**
* @see org.eclipse.jface.text.formatter.IFormattingStrategy#formatterStops()
*/
public void formatterStops()
{
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryObjectclassWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryObjectclassWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import java.util.ArrayList;
import java.util.Collection;
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.ObjectClass;
import org.apache.directory.api.ldap.model.schema.ObjectClassTypeEnum;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.connection.ui.RunnableContextRunner;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry;
import org.apache.directory.studio.ldapbrowser.core.jobs.ReloadSchemaRunnable;
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.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Value;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The NewEntryTypeWizardPage is used to select the entry's object classes.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewEntryObjectclassWizardPage extends WizardPage
{
/** The Constant SIZING_SELECTION_WIDGET_HEIGHT. */
private final static int SIZING_SELECTION_WIDGET_HEIGHT = 250;
/** The Constant SIZING_SELECTION_WIDGET_WIDTH. */
private final static int SIZING_SELECTION_WIDGET_WIDTH = 400;
/** The wizard. */
private NewEntryWizard wizard;
/** The available object classes. */
private List<ObjectClass> availableObjectClasses;
/** The available object classes instant search. */
private Text availableObjectClassesInstantSearch;
/** The available object classes viewer. */
private TableViewer availableObjectClassesViewer;
/** The selected object classes. */
private List<ObjectClass> selectedObjectClasses;
/** The selected object classes viewer. */
private TableViewer selectedObjectClassesViewer;
/** The add button. */
private Button addButton;
/** The remove button. */
private Button removeButton;
private LabelProvider labelProvider = new LabelProvider()
{
/**
* {@inheritDoc}
*/
public String getText( Object element )
{
if ( element instanceof ObjectClass )
{
ObjectClass ocd = ( ObjectClass ) element;
return SchemaUtils.toString( ocd );
}
// Default
return super.getText( element );
}
/**
* {@inheritDoc}
*/
public Image getImage( Object element )
{
if ( element instanceof ObjectClass )
{
ObjectClass ocd = ( ObjectClass ) element;
switch ( ocd.getType() )
{
case STRUCTURAL:
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_OCD_STRUCTURAL );
case ABSTRACT:
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_OCD_ABSTRACT );
case AUXILIARY:
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_OCD_AUXILIARY );
default:
return BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_OCD );
}
}
// Default
return super.getImage( element );
}
};
/**
* Creates a new instance of NewEntryObjectclassWizardPage.
*
* @param pageName the page name
* @param wizard the wizard
*/
public NewEntryObjectclassWizardPage( String pageName, NewEntryWizard wizard )
{
super( pageName );
setTitle( Messages.getString( "NewEntryObjectclassWizardPage.ObjectClasses" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "NewEntryObjectclassWizardPage.ObjectClassesDescription" ) ); //$NON-NLS-1$
setImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_WIZARD ) );
setPageComplete( false );
this.wizard = wizard;
this.availableObjectClasses = new ArrayList<ObjectClass>();
this.selectedObjectClasses = new ArrayList<ObjectClass>();
}
/**
* Validates the input fields.
*/
private void validate()
{
if ( !selectedObjectClasses.isEmpty() )
{
boolean hasOneStructuralOC = false;
for ( ObjectClass ocd : selectedObjectClasses )
{
if ( ocd.getType() == ObjectClassTypeEnum.STRUCTURAL )
{
hasOneStructuralOC = true;
break;
}
}
if ( !hasOneStructuralOC )
{
setMessage(
Messages.getString( "NewEntryObjectclassWizardPage.SelectStructuralObjectClass" ), WizardPage.WARNING ); //$NON-NLS-1$
}
else
{
setMessage( null );
}
setPageComplete( true );
saveState();
}
else
{
setPageComplete( false );
setMessage( null );
}
}
/**
* Loads the state of selected and available object classes from
* the prototype entry. Called when this page becomes visible.
*/
private void loadState()
{
availableObjectClasses.clear();
selectedObjectClasses.clear();
if ( wizard.getSelectedConnection() != null )
{
availableObjectClasses.addAll( wizard.getSelectedConnection().getSchema().getObjectClassDescriptions() );
DummyEntry newEntry = wizard.getPrototypeEntry();
IAttribute ocAttribute = newEntry.getAttribute( SchemaConstants.OBJECT_CLASS_AT );
if ( ocAttribute != null )
{
for ( IValue ocValue : ocAttribute.getValues() )
{
if ( !ocValue.isEmpty() )
{
ObjectClass ocd = wizard.getSelectedConnection().getSchema()
.getObjectClassDescription( ocValue.getStringValue() );
availableObjectClasses.remove( ocd );
selectedObjectClasses.add( ocd );
}
}
}
}
availableObjectClassesViewer.refresh();
selectedObjectClassesViewer.refresh();
}
/**
* Saves the state of selected object classes to the entry.
*/
private void saveState()
{
DummyEntry newEntry = wizard.getPrototypeEntry();
try
{
EventRegistry.suspendEventFiringInCurrentThread();
// set new objectClass values
IAttribute ocAttribute = newEntry.getAttribute( SchemaConstants.OBJECT_CLASS_AT );
if ( ocAttribute == null )
{
ocAttribute = new Attribute( newEntry, SchemaConstants.OBJECT_CLASS_AT );
newEntry.addAttribute( ocAttribute );
}
IValue[] values = ocAttribute.getValues();
for ( IValue value : values )
{
ocAttribute.deleteValue( value );
}
for ( ObjectClass ocd : selectedObjectClasses )
{
ocAttribute.addValue( new Value( ocAttribute, ocd.getNames().get( 0 ) ) );
}
}
finally
{
EventRegistry.resumeEventFiringInCurrentThread();
}
}
/**
* {@inheritDoc}
*
* This implementation initializes the list of available and selected
* object classes when this page becomes visible.
*/
public void setVisible( boolean visible )
{
super.setVisible( visible );
if ( visible )
{
loadState();
validate();
availableObjectClassesInstantSearch.setFocus();
}
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 3, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Label availableLabel = new Label( composite, SWT.NONE );
availableLabel.setText( Messages.getString( "NewEntryObjectclassWizardPage.AvailableObjectClasses" ) ); //$NON-NLS-1$
Label buttonLabel = new Label( composite, SWT.NONE );
buttonLabel.setText( "" ); //$NON-NLS-1$
Label selectedLabel = new Label( composite, SWT.NONE );
selectedLabel.setText( Messages.getString( "NewEntryObjectclassWizardPage.SelectedObjectClasses" ) ); //$NON-NLS-1$
Composite availableObjectClassesComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 1 );
Composite availableObjectClassesInstantSearchComposite = BaseWidgetUtils.createColumnContainer(
availableObjectClassesComposite, 2, 1 );
availableObjectClassesInstantSearch = new Text( availableObjectClassesInstantSearchComposite, SWT.NONE
| SWT.BORDER | SWT.SEARCH | SWT.CANCEL );
availableObjectClassesInstantSearch.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
availableObjectClassesInstantSearch.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
availableObjectClassesViewer.refresh();
if ( availableObjectClassesViewer.getTable().getItemCount() >= 1 )
{
Object item = availableObjectClassesViewer.getElementAt( 0 );
availableObjectClassesViewer.setSelection( new StructuredSelection( item ) );
}
}
} );
availableObjectClassesInstantSearch.addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.ARROW_DOWN )
{
availableObjectClassesViewer.getTable().setFocus();
}
else if ( e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR )
{
add( availableObjectClassesViewer.getSelection() );
}
}
} );
ControlDecoration availableObjectClassesInstantSearchDecoration = new ControlDecoration(
availableObjectClassesInstantSearch, SWT.TOP | SWT.LEFT, composite );
availableObjectClassesInstantSearchDecoration.setDescriptionText( Messages
.getString( "NewEntryObjectclassWizardPage.FilterDescription" ) ); //$NON-NLS-1$
availableObjectClassesInstantSearchDecoration.setImage( FieldDecorationRegistry.getDefault()
.getFieldDecoration( FieldDecorationRegistry.DEC_CONTENT_PROPOSAL ).getImage() );
Button reloadButton = new Button( availableObjectClassesInstantSearchComposite, SWT.PUSH | SWT.FLAT );
reloadButton.setToolTipText( Messages.getString( "NewEntryObjectclassWizardPage.ReloadSchema" ) ); //$NON-NLS-1$
reloadButton.setImage( BrowserCommonActivator.getDefault().getImage( BrowserCommonConstants.IMG_REFRESH ) );
reloadButton.addSelectionListener( new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
IBrowserConnection browserConnection = wizard.getSelectedConnection();
ReloadSchemaRunnable runnable = new ReloadSchemaRunnable( browserConnection );
RunnableContextRunner.execute( runnable, wizard.getContainer(), true );
setVisible( true );
}
} );
availableObjectClassesViewer = new TableViewer( availableObjectClassesComposite );
GridData data = new GridData( GridData.FILL_BOTH );
data.heightHint = SIZING_SELECTION_WIDGET_HEIGHT;
data.widthHint = ( int ) ( SIZING_SELECTION_WIDGET_WIDTH * 0.4 );
availableObjectClassesViewer.getTable().setLayoutData( data );
availableObjectClassesViewer.setContentProvider( new ArrayContentProvider() );
availableObjectClassesViewer.setLabelProvider( labelProvider );
availableObjectClassesViewer.setSorter( new ViewerSorter() );
availableObjectClassesViewer.addFilter( new InstantSearchFilter( availableObjectClassesInstantSearch ) );
availableObjectClassesViewer.setInput( availableObjectClasses );
availableObjectClassesViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
add( event.getSelection() );
}
} );
availableObjectClassesViewer.getTable().addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.ARROW_UP )
{
if ( availableObjectClassesViewer.getTable().getSelectionIndex() <= 0 )
{
availableObjectClassesInstantSearch.setFocus();
}
}
}
} );
Composite buttonComposite = new Composite( composite, SWT.NONE );
gl = new GridLayout( 1, true );
buttonComposite.setLayout( gl );
data = new GridData( GridData.FILL_BOTH );
data.heightHint = SIZING_SELECTION_WIDGET_HEIGHT;
// data.widthHint = (int)(SIZING_SELECTION_WIDGET_WIDTH * 0.2);
data.horizontalAlignment = SWT.CENTER;
buttonComposite.setLayoutData( data );
Label label0 = new Label( buttonComposite, SWT.NONE );
data = new GridData();
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
label0.setLayoutData( data );
addButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "NewEntryObjectclassWizardPage.AddButton" ), 1 ); //$NON-NLS-1$
removeButton = BaseWidgetUtils.createButton( buttonComposite, Messages
.getString( "NewEntryObjectclassWizardPage.RemoveButton" ), 1 ); //$NON-NLS-1$
Label label3 = new Label( buttonComposite, SWT.NONE );
data = new GridData();
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
label3.setLayoutData( data );
addButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
add( availableObjectClassesViewer.getSelection() );
}
} );
removeButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
remove( selectedObjectClassesViewer.getSelection() );
}
} );
selectedObjectClassesViewer = new TableViewer( composite );
data = new GridData( GridData.FILL_BOTH );
data.heightHint = SIZING_SELECTION_WIDGET_HEIGHT;
data.widthHint = ( int ) ( SIZING_SELECTION_WIDGET_WIDTH * 0.4 );
selectedObjectClassesViewer.getTable().setLayoutData( data );
selectedObjectClassesViewer.setContentProvider( new ArrayContentProvider() );
selectedObjectClassesViewer.setLabelProvider( labelProvider );
selectedObjectClassesViewer.setSorter( new ViewerSorter() );
selectedObjectClassesViewer.setInput( selectedObjectClasses );
selectedObjectClassesViewer.addDoubleClickListener( new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
remove( event.getSelection() );
}
} );
setControl( composite );
}
/**
* Adds the selected object classes and all superiors
* to the list of selected object classes.
*
* @param iselection the selection
*/
private void add( ISelection iselection )
{
IStructuredSelection selection = ( IStructuredSelection ) iselection;
Schema schema = wizard.getSelectedConnection().getSchema();
Iterator<?> it = selection.iterator();
while ( it.hasNext() )
{
ObjectClass ocd = ( ObjectClass ) it.next();
if ( availableObjectClasses.contains( ocd ) && !selectedObjectClasses.contains( ocd ) )
{
availableObjectClasses.remove( ocd );
selectedObjectClasses.add( ocd );
// recursively add superior object classes
List<ObjectClass> superiorObjectClassDescriptions = SchemaUtils
.getSuperiorObjectClassDescriptions( ocd, schema );
if ( !superiorObjectClassDescriptions.isEmpty() )
{
add( new StructuredSelection( superiorObjectClassDescriptions ) );
}
}
}
availableObjectClassesViewer.refresh();
selectedObjectClassesViewer.refresh();
validate();
if ( !"".equals( availableObjectClassesInstantSearch.getText() ) ) //$NON-NLS-1$
{
availableObjectClassesInstantSearch.setText( "" ); //$NON-NLS-1$
availableObjectClassesInstantSearch.setFocus();
}
}
/**
* Removes the selected object classes and all sub classes
* from the list of selected object classes.
*
* @param iselection the iselection
*/
private void remove( ISelection iselection )
{
IStructuredSelection selection = ( IStructuredSelection ) iselection;
Schema schema = wizard.getSelectedConnection().getSchema();
Iterator<?> it = selection.iterator();
while ( it.hasNext() )
{
ObjectClass ocd = ( ObjectClass ) it.next();
if ( !availableObjectClasses.contains( ocd ) && selectedObjectClasses.contains( ocd ) )
{
selectedObjectClasses.remove( ocd );
availableObjectClasses.add( ocd );
// recursively remove sub object classes
List<ObjectClass> subObjectClassDescriptions = SchemaUtils
.getSuperiorObjectClassDescriptions( ocd, schema );
if ( !subObjectClassDescriptions.isEmpty() )
{
remove( new StructuredSelection( subObjectClassDescriptions ) );
}
}
}
// re-add superior object classes of remaining object classes
List<ObjectClass> copy = new ArrayList<ObjectClass>( selectedObjectClasses );
for ( ObjectClass ocd : copy )
{
List<ObjectClass> superiorObjectClassDescriptions = SchemaUtils
.getSuperiorObjectClassDescriptions( ocd, schema );
if ( !superiorObjectClassDescriptions.isEmpty() )
{
add( new StructuredSelection( superiorObjectClassDescriptions ) );
}
}
availableObjectClassesViewer.refresh();
selectedObjectClassesViewer.refresh();
validate();
}
/**
* The Class InstantSearchFilter.
*/
private class InstantSearchFilter extends ViewerFilter
{
/** The filter text. */
private Text filterText;
/**
* Creates a new instance of InstantSearchFilter.
*
* @param filterText the filter text
*/
private InstantSearchFilter( Text filterText )
{
this.filterText = filterText;
}
/**
* {@inheritDoc}
*/
public boolean select( Viewer viewer, Object parentElement, Object element )
{
if ( element instanceof ObjectClass )
{
ObjectClass ocd = ( ObjectClass ) element;
Collection<String> lowerCaseIdentifiers = SchemaUtils.getLowerCaseIdentifiers( ocd );
for ( String s : lowerCaseIdentifiers )
{
if ( Strings.toLowerCase( s ).startsWith( Strings.toLowerCase( filterText.getText() ) ) )
{
return true;
}
}
}
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeTypeWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeTypeWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.connection.ui.widgets.ExtendedContentAssistCommandAdapter;
import org.apache.directory.studio.ldapbrowser.common.widgets.ListContentProposalProvider;
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.schema.SchemaUtils;
import org.eclipse.jface.fieldassist.ComboContentAdapter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.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.Label;
import org.eclipse.swt.widgets.Text;
/**
* The AttributeTypeWizardPage provides a combo to select the attribute type,
* some filter and a preview field.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributeTypeWizardPage extends WizardPage
{
/** The parent wizard. */
private AttributeWizard wizard;
/** The initial show subschema attributes only. */
private boolean initialShowSubschemaAttributesOnly;
/** The initial hide existing attributes. */
private boolean initialHideExistingAttributes;
/** The parsed attribute type. */
private String parsedAttributeType;
/** The possible attribute types. */
private String[] possibleAttributeTypes;
/** The possible attribute types applicable to the entry's schema only. */
private String[] possibleAttributeTypesSubschemaOnly;
/** The possible attribute types applicable to the entry's schema only, existing attributes are hidden. */
private String[] possibleAttributeTypesSubschemaOnlyAndExistingHidden;
/** The attribute type combo. */
private Combo attributeTypeCombo;
/** The show subschem attributes only button. */
private Button showSubschemAttributesOnlyButton;
/** The hide existing attributes button. */
private Button hideExistingAttributesButton;
/** The preview text. */
private Text previewText;
/**
* Creates a new instance of AttributeTypeWizardPage.
*
* @param pageName the page name
* @param initialEntry the initial entry
* @param initialAttributeDescription the initial attribute description
* @param initialShowSubschemaAttributesOnly the initial show subschema attributes only
* @param initialHideExistingAttributes the initial hide existing attributes
* @param wizard the wizard
*/
public AttributeTypeWizardPage( String pageName, IEntry initialEntry, String initialAttributeDescription,
boolean initialShowSubschemaAttributesOnly, boolean initialHideExistingAttributes, AttributeWizard wizard )
{
super( pageName );
super.setTitle( Messages.getString( "AttributeTypeWizardPage.AttributeType" ) ); //$NON-NLS-1$
super.setDescription( Messages.getString( "AttributeTypeWizardPage.AttributeTypeDescription" ) ); //$NON-NLS-1$
super.setPageComplete( false );
this.wizard = wizard;
this.initialShowSubschemaAttributesOnly = initialShowSubschemaAttributesOnly;
this.initialHideExistingAttributes = initialHideExistingAttributes;
Collection<AttributeType> atds = initialEntry.getBrowserConnection().getSchema()
.getAttributeTypeDescriptions();
Collection<String> atdNames = SchemaUtils.getNames( atds );
possibleAttributeTypes = atdNames.toArray( new String[atdNames.size()] );
Arrays.sort( possibleAttributeTypes );
Collection<AttributeType> allAtds = SchemaUtils.getAllAttributeTypeDescriptions( initialEntry );
Collection<String> names = SchemaUtils.getNames( allAtds );
possibleAttributeTypesSubschemaOnly = names.toArray( new String[0] );
Arrays.sort( possibleAttributeTypesSubschemaOnly );
Set<String> set = new HashSet<>( Arrays.asList( possibleAttributeTypesSubschemaOnly ) );
IAttribute[] existingAttributes = initialEntry.getAttributes();
for ( int i = 0; existingAttributes != null && i < existingAttributes.length; i++ )
{
set.remove( existingAttributes[i].getDescription() );
}
possibleAttributeTypesSubschemaOnlyAndExistingHidden = set.toArray( new String[set.size()] );
Arrays.sort( possibleAttributeTypesSubschemaOnlyAndExistingHidden );
String attributeDescription = initialAttributeDescription;
if ( attributeDescription == null )
{
attributeDescription = ""; //$NON-NLS-1$
}
String[] attributeDescriptionComponents = attributeDescription.split( ";" ); //$NON-NLS-1$
parsedAttributeType = attributeDescriptionComponents[0];
}
/**
* Validates this page.
*/
private void validate()
{
previewText.setText( wizard.getAttributeDescription() );
setPageComplete( !"".equals( attributeTypeCombo.getText() ) ); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
@Override
public void setVisible( boolean visible )
{
super.setVisible( visible );
if ( visible )
{
validate();
}
}
/**
* {@inheritDoc}
*/
@Override
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 2, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
BaseWidgetUtils.createLabel( composite, Messages.getString( "AttributeTypeWizardPage.AttributeTypeLabel" ), 1 ); //$NON-NLS-1$
// attribute combo with field decoration and content proposal
attributeTypeCombo = BaseWidgetUtils.createCombo( composite, possibleAttributeTypes, -1, 1 );
attributeTypeCombo.setText( parsedAttributeType );
new ExtendedContentAssistCommandAdapter( attributeTypeCombo, new ComboContentAdapter(),
new ListContentProposalProvider( possibleAttributeTypes ), null, null, true );
BaseWidgetUtils.createSpacer( composite, 1 );
showSubschemAttributesOnlyButton = BaseWidgetUtils.createCheckbox( composite, Messages
.getString( "AttributeTypeWizardPage.ShowSubschemaAttributesOnly" ), //$NON-NLS-1$
1 );
showSubschemAttributesOnlyButton.setSelection( initialShowSubschemaAttributesOnly );
BaseWidgetUtils.createSpacer( composite, 1 );
hideExistingAttributesButton = BaseWidgetUtils.createCheckbox( composite, Messages
.getString( "AttributeTypeWizardPage.HideExistingAttributes" ), 1 ); //$NON-NLS-1$
hideExistingAttributesButton.setSelection( initialHideExistingAttributes );
Label l = new Label( composite, SWT.NONE );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.horizontalSpan = 2;
l.setLayoutData( gd );
BaseWidgetUtils.createLabel( composite, Messages.getString( "AttributeTypeWizardPage.PreviewLabel" ), 1 ); //$NON-NLS-1$
previewText = BaseWidgetUtils.createReadonlyText( composite, "", 1 ); //$NON-NLS-1$
// attribute type listener
attributeTypeCombo.addModifyListener( new ModifyListener()
{
@Override
public void modifyText( ModifyEvent e )
{
validate();
}
} );
// filter listener
showSubschemAttributesOnlyButton.addSelectionListener( new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
updateFilter();
validate();
}
} );
hideExistingAttributesButton.addSelectionListener( new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
updateFilter();
validate();
}
} );
updateFilter();
setControl( composite );
}
/**
* Updates the filter.
*/
private void updateFilter()
{
// enable/disable filter buttons
hideExistingAttributesButton.setEnabled( showSubschemAttributesOnlyButton.getSelection() );
if ( possibleAttributeTypesSubschemaOnly.length == 0 )
{
showSubschemAttributesOnlyButton.setSelection( false );
showSubschemAttributesOnlyButton.setEnabled( false );
}
if ( possibleAttributeTypesSubschemaOnlyAndExistingHidden.length == 0 )
{
hideExistingAttributesButton.setEnabled( false );
hideExistingAttributesButton.setSelection( false );
}
// update combo items and proposals
String value = attributeTypeCombo.getText();
if ( hideExistingAttributesButton.getSelection() && showSubschemAttributesOnlyButton.getSelection() )
{
attributeTypeCombo.setItems( possibleAttributeTypesSubschemaOnlyAndExistingHidden );
}
else if ( showSubschemAttributesOnlyButton.getSelection() )
{
attributeTypeCombo.setItems( possibleAttributeTypesSubschemaOnly );
}
else
{
attributeTypeCombo.setItems( possibleAttributeTypes );
}
attributeTypeCombo.setText( value );
}
/**
* Gets the attribute type.
*
* @return the attribute type
*/
String getAttributeType()
{
if ( attributeTypeCombo == null || attributeTypeCombo.isDisposed() )
{
return ""; //$NON-NLS-1$
}
return attributeTypeCombo.getText();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewContextEntryWizard.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewContextEntryWizard.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
/**
* The NewContextEntryWizard is used to create a new context entry from scratch or by
* using another entry as template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewContextEntryWizard extends NewEntryWizard
{
/**
* Creates a new instance of NewContextEntryWizard.
*/
public NewContextEntryWizard()
{
super();
}
/**
* Gets the id.
*
* @return the id
*/
public static String getId()
{
return BrowserCommonConstants.WIZARD_NEW_CONTEXT_ENTRY_WIZARD;
}
/**
* @return always true
*/
public boolean isNewContextEntry()
{
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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/EditEntryWizard.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/EditEntryWizard.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
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.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.ldifparser.model.container.LdifContentRecord;
/**
* The EditEntryWizard is used to edit an existing entry offline, on finish
* it computes the difference between the orignal entry and the changed entry
* and sends these changes to the server.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EditEntryWizard extends NewEntryWizard
{
/**
* Creates a new instance of EditEntryWizard.
*
* @param entry the entry to edit
*/
public EditEntryWizard( IEntry entry )
{
setWindowTitle( Messages.getString( "EditEntryWizard.EditEntry" ) ); //$NON-NLS-1$
setNeedsProgressMonitor( true );
selectedEntry = entry;
selectedConnection = entry.getBrowserConnection();
try
{
EventRegistry.suspendEventFiringInCurrentThread();
LdifContentRecord record = ModelConverter.entryToLdifContentRecord( selectedEntry );
prototypeEntry = ModelConverter.ldifContentRecordToEntry( record, selectedConnection );
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
finally
{
EventRegistry.resumeEventFiringInCurrentThread();
}
}
/**
* {@inheritDoc}
*/
public void addPages()
{
ocPage = new NewEntryObjectclassWizardPage( NewEntryObjectclassWizardPage.class.getName(), this );
addPage( ocPage );
attributePage = new NewEntryAttributesWizardPage( NewEntryAttributesWizardPage.class.getName(), this );
addPage( attributePage );
}
/**
* {@inheritDoc}
*/
public boolean performCancel()
{
return true;
}
/**
* {@inheritDoc}
*/
public boolean performFinish()
{
new CompoundModification().replaceAttributes( prototypeEntry, selectedEntry, this );
return true;
}
/**
* Gets the selected entry.
*
* @return the selected entry
*/
public IEntry getSelectedEntry()
{
return selectedEntry;
}
/**
* Gets the selected connection.
*
* @return the selected connection
*/
public IBrowserConnection getSelectedConnection()
{
return selectedConnection;
}
/**
* Gets the prototype entry.
*
* @return the prototype entry
*/
public DummyEntry getPrototypeEntry()
{
return prototypeEntry;
}
/**
* Sets the prototype entry.
*
* @param getPrototypeEntry the prototype entry
*/
public void setPrototypeEntry( DummyEntry getPrototypeEntry )
{
this.prototypeEntry = getPrototypeEntry;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryTypeWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryTypeWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.connection.ui.RunnableContextRunner;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.EntryWidget;
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.ReadEntryRunnable;
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.impl.DummyEntry;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.apache.directory.studio.ldapbrowser.core.utils.ModelConverter;
import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
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;
/**
* The NewEntryTypeWizardPage is used to choose the entry creation method.
*
* <pre>
* .-------------------------------------------------.
* | o o o New Entry |
* +-------------------------------------------------+
* | Entry Creation Method |
* | Please select the entry creation method |
* +-------------------------------------------------+
* | (o) Create entry from scratch |
* | ( ) Use existing entry as template |
* | |
* | [---------------------------|v] [m] (Browse) |
* | |
* | |
* | |
* | |
* +-------------------------------------------------+
* | (?) (< back) (Next >) (cancel) (finish) |
* +-------------------------------------------------+
* </pre>
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewEntryTypeWizardPage extends WizardPage implements WidgetModifyListener, SelectionListener
{
/** The Constant PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY. */
public static final String PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY = NewEntryTypeWizardPage.class
.getName()
+ ".preferredEntryCreationMethod"; //$NON-NLS-1$
/** The wizard. */
private NewEntryWizard wizard;
/** The schema button. */
private Button schemaButton;
/** The template button. */
private Button templateButton;
/** The entry widget to select the template entry. */
private EntryWidget entryWidget;
/**
* Creates a new instance of NewEntryTypeWizardPage.
*
* @param pageName the page name
* @param wizard the wizard
*/
public NewEntryTypeWizardPage( String pageName, NewEntryWizard wizard )
{
super( pageName );
setTitle( Messages.getString( "NewEntryTypeWizardPage.EntryCreationMethod" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "NewEntryTypeWizardPage.EntryCreationMethodDescription" ) ); //$NON-NLS-1$
setImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_WIZARD ) );
setPageComplete( false );
this.wizard = wizard;
}
/**
* Validates the input fields.
*/
private void validate()
{
if ( schemaButton.getSelection() )
{
setPageComplete( true );
}
else if ( templateButton.getSelection() )
{
setPageComplete( entryWidget.getBrowserConnection() != null && entryWidget.getDn() != null );
}
else
{
setPageComplete( false );
}
}
/**
* {@inheritDoc}
*
* This implementation just checks if this page is complete. IIt
* doesn't call {@link #getNextPage()} to avoid unneeded
* creations of new prototype entries.
*/
public boolean canFlipToNextPage()
{
return isPageComplete();
}
/**
* {@inheritDoc}
*
* This implementation creates the prototype entry depending on the
* selected entry creation method before flipping to the next page.
*/
public IWizardPage getNextPage()
{
if ( templateButton.getSelection() )
{
final IBrowserConnection browserConnection = entryWidget.getBrowserConnection();
final Dn dn = entryWidget.getDn();
IEntry templateEntry = null;
if ( browserConnection == null )
{
getShell().getDisplay().syncExec( new Runnable()
{
public void run()
{
MessageDialog
.openError(
getShell(),
Messages.getString( "NewEntryTypeWizardPage.Error" ), Messages.getString( "NewEntryTypeWizardPage.NoConnection" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
} );
return null;
}
if ( dn == null )
{
getShell().getDisplay().syncExec( new Runnable()
{
public void run()
{
MessageDialog
.openError(
getShell(),
Messages.getString( "NewEntryTypeWizardPage.Error" ), Messages.getString( "NewEntryTypeWizardPage.NoDN" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
} );
return null;
}
// check if selected Dn exists
ReadEntryRunnable readEntryRunnable = new ReadEntryRunnable( browserConnection, dn );
RunnableContextRunner.execute( readEntryRunnable, getContainer(), false );
templateEntry = readEntryRunnable.getReadEntry();
if ( templateEntry == null )
{
getShell().getDisplay().syncExec( new Runnable()
{
public void run()
{
MessageDialog
.openError(
getShell(),
Messages.getString( "NewEntryTypeWizardPage.Error" ), NLS.bind( Messages.getString( "NewEntryTypeWizardPage.EntryDoesNotExist" ), dn.toString() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
} );
return null;
}
// init attributes
if ( !templateEntry.isAttributesInitialized() )
{
InitializeAttributesRunnable runnable = new InitializeAttributesRunnable( templateEntry );
RunnableContextRunner.execute( runnable, getContainer(), true );
}
// clone entry and remove non-modifiable attributes
try
{
EventRegistry.suspendEventFiringInCurrentThread();
LdifContentRecord record = ModelConverter.entryToLdifContentRecord( templateEntry );
DummyEntry prototypeEntry = ModelConverter.ldifContentRecordToEntry( record, browserConnection );
IAttribute[] attributes = prototypeEntry.getAttributes();
for ( int i = 0; i < attributes.length; i++ )
{
if ( !SchemaUtils.isModifiable( attributes[i].getAttributeTypeDescription() ) )
{
prototypeEntry.deleteAttribute( attributes[i] );
}
}
wizard.setPrototypeEntry( prototypeEntry );
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
EventRegistry.resumeEventFiringInCurrentThread();
}
}
else
{
wizard.setPrototypeEntry( new DummyEntry( new Dn(), wizard.getSelectedConnection() ) );
}
return super.getNextPage();
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 1, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
schemaButton = BaseWidgetUtils.createRadiobutton( composite, Messages
.getString( "NewEntryTypeWizardPage.CreateEntryFromScratch" ), 1 ); //$NON-NLS-1$
schemaButton.addSelectionListener( this );
templateButton = BaseWidgetUtils.createRadiobutton( composite, Messages
.getString( "NewEntryTypeWizardPage.UseExistingEntryAsTemplate" ), 1 ); //$NON-NLS-1$
templateButton.addSelectionListener( this );
Composite entryComposite = BaseWidgetUtils.createColumnContainer( composite, 3, 1 );
BaseWidgetUtils.createRadioIndent( entryComposite, 1 );
entryWidget = new EntryWidget( wizard.getSelectedConnection(), wizard.getSelectedEntry() != null ? wizard
.getSelectedEntry().getDn() : null );
entryWidget.createWidget( entryComposite );
entryWidget.addWidgetModifyListener( this );
if ( BrowserCommonActivator.getDefault().getDialogSettings().get(
PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY ) == null )
{
BrowserCommonActivator.getDefault().getDialogSettings().put(
PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY, true );
}
schemaButton.setSelection( BrowserCommonActivator.getDefault().getDialogSettings().getBoolean(
PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY ) );
templateButton.setSelection( !BrowserCommonActivator.getDefault().getDialogSettings().getBoolean(
PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY ) );
widgetSelected( null );
setControl( composite );
}
/**
* {@inheritDoc}
*/
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
/**
* {@inheritDoc}
*/
public void widgetDefaultSelected( SelectionEvent e )
{
}
/**
* {@inheritDoc}
*/
public void widgetSelected( SelectionEvent e )
{
entryWidget.setEnabled( templateButton.getSelection() );
validate();
}
/**
* Saves the dialog settings.
*/
public void saveDialogSettings()
{
BrowserCommonActivator.getDefault().getDialogSettings().put( PREFERRED_ENTRY_CREATION_METHOD_DIALOGSETTING_KEY,
schemaButton.getSelection() );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/Messages.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapbrowser.common.wizards;
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeOptionsWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeOptionsWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.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.Shell;
import org.eclipse.swt.widgets.Text;
/**
* The AttributeOptionsWizardPageprovides input elements for various options
* and a preview field.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributeOptionsWizardPage extends WizardPage
{
/** The wizard. */
private AttributeWizard wizard;
/** The shell */
private Shell shell;
/** The possible languages. */
private String[] possibleLanguages;
/** The possible language to countries map. */
private Map<String, String[]> possibleLangToCountriesMap;
/** The parsed lang list. */
private List<String> parsedLangList;
/** The parsed option list. */
private List<String> parsedOptionList;
/** The parsed binary option. */
private boolean parsedBinary;
/** The language group. */
private Group langGroup;
/** The lang line list. */
private ArrayList<LangLine> langLineList;
/** The options group. */
private Group optionsGroup;
/** The option line list. */
private ArrayList<OptionLine> optionLineList;
/** The binary option button. */
private Button binaryOptionButton;
/** The preview text. */
private Text previewText;
/**
* Creates a new instance of AttributeOptionsWizardPage.
*
* @param pageName the page name
* @param initialAttributeDescription the initial attribute description
* @param wizard the wizard
*/
public AttributeOptionsWizardPage( String pageName, String initialAttributeDescription, AttributeWizard wizard )
{
super( pageName );
super.setTitle( Messages.getString( "AttributeOptionsWizardPage.Options" ) ); //$NON-NLS-1$
super.setDescription( Messages.getString( "AttributeOptionsWizardPage.OptionsDescription" ) ); //$NON-NLS-1$
// super.setImageDescriptor(BrowserUIPlugin.getDefault().getImageDescriptor(BrowserUIConstants.IMG_ATTRIBUTE_WIZARD));
super.setPageComplete( false );
this.wizard = wizard;
// init possible languages and countries
SortedSet<String> languageSet = new TreeSet<String>();
Map<String, SortedSet<String>> languageToCountrySetMap = new HashMap<String, SortedSet<String>>();
Locale[] locales = Locale.getAvailableLocales();
for ( int i = 0; i < locales.length; i++ )
{
Locale locale = locales[i];
languageSet.add( locale.getLanguage() );
if ( !languageToCountrySetMap.containsKey( locale.getLanguage() ) )
{
languageToCountrySetMap.put( locale.getLanguage(), new TreeSet<String>() );
}
SortedSet<String> countrySet = languageToCountrySetMap.get( locale.getLanguage() );
countrySet.add( locale.getCountry() );
}
possibleLanguages = languageSet.toArray( new String[languageSet.size()] );
possibleLangToCountriesMap = new HashMap<String, String[]>();
for ( Iterator<String> it = languageToCountrySetMap.keySet().iterator(); it.hasNext(); )
{
String language = it.next();
SortedSet<String> countrySet = languageToCountrySetMap.get( language );
String[] countries = countrySet.toArray( new String[countrySet.size()] );
possibleLangToCountriesMap.put( language, countries );
}
// parse options
if ( initialAttributeDescription == null )
{
initialAttributeDescription = ""; //$NON-NLS-1$
}
String[] attributeDescriptionComponents = initialAttributeDescription.split( ";" ); //$NON-NLS-1$
parsedLangList = new ArrayList<String>();
parsedOptionList = new ArrayList<String>();
parsedBinary = false;
for ( int i = 1; i < attributeDescriptionComponents.length; i++ )
{
if ( attributeDescriptionComponents[i].startsWith( "lang-" ) ) //$NON-NLS-1$
{
parsedLangList.add( attributeDescriptionComponents[i] );
}
else if ( attributeDescriptionComponents[i].equals( "binary" ) ) //$NON-NLS-1$
{
parsedBinary = true;
}
else
{
parsedOptionList.add( attributeDescriptionComponents[i] );
}
}
}
/**
* Validates the options.
*/
private void validate()
{
previewText.setText( wizard.getAttributeDescription() );
setPageComplete( true );
}
/**
* {@inheritDoc}
*/
public void setVisible( boolean visible )
{
super.setVisible( visible );
if ( visible )
{
validate();
}
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
shell = parent.getShell();
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 2, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
// Lang group
langGroup = BaseWidgetUtils.createGroup( composite, Messages
.getString( "AttributeOptionsWizardPage.LanguageTags" ), 2 ); //$NON-NLS-1$
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
langGroup.setLayoutData( gd );
Composite langComposite = BaseWidgetUtils.createColumnContainer( langGroup, 6, 1 );
langLineList = new ArrayList<LangLine>();
BaseWidgetUtils.createSpacer( composite, 2 );
// Options group with binary option
optionsGroup = BaseWidgetUtils.createGroup( composite, Messages
.getString( "AttributeOptionsWizardPage.OtherOptions" ), 2 ); //$NON-NLS-1$
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
optionsGroup.setLayoutData( gd );
Composite optionsComposite = BaseWidgetUtils.createColumnContainer( optionsGroup, 3, 1 );
optionLineList = new ArrayList<OptionLine>();
Composite binaryComposite = BaseWidgetUtils.createColumnContainer( optionsGroup, 1, 1 );
binaryOptionButton = BaseWidgetUtils.createCheckbox( binaryComposite, Messages
.getString( "AttributeOptionsWizardPage.BinaryOption" ), 1 ); //$NON-NLS-1$
binaryOptionButton.setSelection( parsedBinary );
Label la = new Label( composite, SWT.NONE );
gd = new GridData( GridData.GRAB_VERTICAL );
gd.horizontalSpan = 2;
la.setLayoutData( gd );
// Preview text
BaseWidgetUtils.createLabel( composite, Messages.getString( "AttributeOptionsWizardPage.Preview" ), 1 ); //$NON-NLS-1$
previewText = BaseWidgetUtils.createReadonlyText( composite, "", 1 ); //$NON-NLS-1$
// fill lang
if ( parsedLangList.isEmpty() )
{
addLangLine( langComposite, 0 );
}
else
{
for ( int i = 0; i < parsedLangList.size(); i++ )
{
addLangLine( langComposite, i );
String l = parsedLangList.get( i );
String[] ls = l.split( "-", 3 ); //$NON-NLS-1$
if ( ls.length > 1 )
{
langLineList.get( i ).languageCombo.setText( ls[1] );
}
if ( ls.length > 2 )
{
langLineList.get( i ).countryCombo.setText( ls[2] );
}
}
}
// fill options
if ( parsedOptionList.isEmpty() )
{
addOptionLine( optionsComposite, 0 );
}
else
{
for ( int i = 0; i < parsedOptionList.size(); i++ )
{
addOptionLine( optionsComposite, i );
optionLineList.get( i ).optionText.setText( parsedOptionList.get( i ) );
}
}
// binary listener
binaryOptionButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
validate();
setControl( composite );
}
/**
* Gets the attribute options.
*
* @return the attribute options
*/
String getAttributeOptions()
{
if ( binaryOptionButton == null || binaryOptionButton.isDisposed() )
{
return ""; //$NON-NLS-1$
}
// attribute type
StringBuffer sb = new StringBuffer();
// options
// sort and unique options
Comparator<String> comparator = new Comparator<String>()
{
public int compare( String s1, String s2 )
{
if ( s1 == null || s2 == null )
{
throw new ClassCastException( Messages.getString( "AttributeOptionsWizardPage.MustNotBeNull" ) ); //$NON-NLS-1$
}
return s1.compareToIgnoreCase( s2 );
}
};
SortedSet<String> options = new TreeSet<String>( comparator );
if ( binaryOptionButton.getSelection() )
{
options.add( "binary" ); //$NON-NLS-1$
}
for ( int i = 0; i < optionLineList.size(); i++ )
{
OptionLine optionLine = optionLineList.get( i );
if ( !"".equals( optionLine.optionText.getText() ) ) //$NON-NLS-1$
{
options.add( optionLine.optionText.getText() );
}
if ( optionLineList.size() > 1 )
{
optionLine.optionDeleteButton.setEnabled( true );
}
else
{
optionLine.optionDeleteButton.setEnabled( false );
}
}
for ( int i = 0; i < langLineList.size(); i++ )
{
LangLine langLine = langLineList.get( i );
String l = langLine.languageCombo.getText();
String c = langLine.countryCombo.getText();
if ( !"".equals( l ) ) //$NON-NLS-1$
{
String s = "lang-" + l; //$NON-NLS-1$
if ( !"".equals( c ) ) //$NON-NLS-1$
{
s += "-" + c; //$NON-NLS-1$
}
options.add( s );
}
if ( langLineList.size() > 1 )
{
langLine.deleteButton.setEnabled( true );
}
else
{
langLine.deleteButton.setEnabled( false );
}
}
// append options
for ( Iterator<String> it = options.iterator(); it.hasNext(); )
{
String option = it.next();
sb.append( ';' );
sb.append( option );
}
return sb.toString();
}
/**
* Adds an option line at the given index.
*
* @param optionComposite the option composite
* @param index the index
*/
private void addOptionLine( Composite optionComposite, int index )
{
OptionLine[] optionLines = optionLineList.toArray( new OptionLine[optionLineList.size()] );
if ( optionLines.length > 0 )
{
for ( int i = 0; i < optionLines.length; i++ )
{
OptionLine oldOptionLine = optionLines[i];
// remember values
String oldValue = oldOptionLine.optionText.getText();
// delete old
oldOptionLine.optionText.dispose();
oldOptionLine.optionAddButton.dispose();
oldOptionLine.optionDeleteButton.dispose();
optionLineList.remove( oldOptionLine );
// add new
OptionLine newOptionLine = createOptionLine( optionComposite );
optionLineList.add( newOptionLine );
// restore value
newOptionLine.optionText.setText( oldValue );
// check
if ( index == i + 1 )
{
OptionLine optionLine = createOptionLine( optionComposite );
optionLineList.add( optionLine );
}
}
}
else
{
OptionLine optionLine = createOptionLine( optionComposite );
optionLineList.add( optionLine );
}
shell.layout( true, true );
}
/**
* Creates the option line.
*
* @param optionComposite the option composite
*
* @return the option line
*/
private OptionLine createOptionLine( final Composite optionComposite )
{
OptionLine optionLine = new OptionLine();
optionLine.optionText = new Text( optionComposite, SWT.BORDER );
GridData gd = new GridData( GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL );
optionLine.optionText.setLayoutData( gd );
optionLine.optionAddButton = new Button( optionComposite, SWT.PUSH );
optionLine.optionAddButton.setText( " + " ); //$NON-NLS-1$
optionLine.optionAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
int index = optionLineList.size();
for ( int i = 0; i < optionLineList.size(); i++ )
{
OptionLine optionLine = optionLineList.get( i );
if ( optionLine.optionAddButton == e.widget )
{
index = i + 1;
}
}
addOptionLine( optionComposite, index );
validate();
}
} );
optionLine.optionDeleteButton = new Button( optionComposite, SWT.PUSH );
optionLine.optionDeleteButton.setText( " \u2212 " ); //$NON-NLS-1$
optionLine.optionDeleteButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
int index = 0;
for ( int i = 0; i < optionLineList.size(); i++ )
{
OptionLine optionLine = optionLineList.get( i );
if ( optionLine.optionDeleteButton == e.widget )
{
index = i;
}
}
deleteOptionLine( optionComposite, index );
validate();
}
} );
optionLine.optionText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return optionLine;
}
/**
* Deletes the option line at the given index.
*
* @param optionComposite the option composite
* @param index the index
*/
private void deleteOptionLine( Composite optionComposite, int index )
{
OptionLine optionLine = optionLineList.remove( index );
if ( optionLine != null )
{
optionLine.optionText.dispose();
optionLine.optionAddButton.dispose();
optionLine.optionDeleteButton.dispose();
if ( !optionComposite.isDisposed() )
{
shell.layout( true, true );
}
}
}
/**
* The class OptionLine is a wrapper for all input elements of an option.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OptionLine
{
/** The option text. */
public Text optionText;
/** The option add button. */
public Button optionAddButton;
/** The option delete button. */
public Button optionDeleteButton;
}
/**
* Adds a language line at the given index.
*
* @param langComposite the language composite
* @param index the index
*/
private void addLangLine( Composite langComposite, int index )
{
LangLine[] langLines = langLineList.toArray( new LangLine[langLineList.size()] );
if ( langLines.length > 0 )
{
for ( int i = 0; i < langLines.length; i++ )
{
LangLine oldLangLine = langLines[i];
// remember values
String oldLanguage = oldLangLine.languageCombo.getText();
String oldCountry = oldLangLine.countryCombo.getText();
// delete old
oldLangLine.langLabel.dispose();
oldLangLine.languageCombo.dispose();
oldLangLine.minusLabel.dispose();
oldLangLine.countryCombo.dispose();
oldLangLine.addButton.dispose();
oldLangLine.deleteButton.dispose();
langLineList.remove( oldLangLine );
// add new
LangLine newLangLine = createLangLine( langComposite );
langLineList.add( newLangLine );
// restore value
newLangLine.languageCombo.setText( oldLanguage );
newLangLine.countryCombo.setText( oldCountry );
// check
if ( index == i + 1 )
{
LangLine langLine = createLangLine( langComposite );
langLineList.add( langLine );
}
}
}
else
{
LangLine langLine = createLangLine( langComposite );
langLineList.add( langLine );
}
shell.layout( true, true );
}
/**
* Creates a language line.
*
* @param langComposite the language composite
*
* @return the language line
*/
private LangLine createLangLine( final Composite langComposite )
{
final LangLine langLine = new LangLine();
langLine.langLabel = BaseWidgetUtils.createLabel( langComposite, "lang-", 1 ); //$NON-NLS-1$
langLine.languageCombo = BaseWidgetUtils.createCombo( langComposite, possibleLanguages, -1, 1 );
langLine.minusLabel = BaseWidgetUtils.createLabel( langComposite, "-", 1 ); //$NON-NLS-1$
langLine.countryCombo = BaseWidgetUtils.createCombo( langComposite, new String[0], -1, 1 );
langLine.countryCombo.setEnabled( false );
langLine.addButton = new Button( langComposite, SWT.PUSH );
langLine.addButton.setText( " + " ); //$NON-NLS-1$
langLine.addButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
int index = langLineList.size();
for ( int i = 0; i < langLineList.size(); i++ )
{
LangLine langLine = langLineList.get( i );
if ( langLine.addButton == e.widget )
{
index = i + 1;
}
}
addLangLine( langComposite, index );
validate();
}
} );
langLine.deleteButton = new Button( langComposite, SWT.PUSH );
langLine.deleteButton.setText( " \u2212 " ); //$NON-NLS-1$
langLine.deleteButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
int index = 0;
for ( int i = 0; i < langLineList.size(); i++ )
{
LangLine langLine = langLineList.get( i );
if ( langLine.deleteButton == e.widget )
{
index = i;
}
}
deleteLangLine( langComposite, index );
validate();
}
} );
langLine.languageCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
if ( "".equals( langLine.languageCombo.getText() ) ) //$NON-NLS-1$
{
langLine.countryCombo.setEnabled( false );
}
else
{
langLine.countryCombo.setEnabled( true );
String oldValue = langLine.countryCombo.getText();
if ( possibleLangToCountriesMap.containsKey( langLine.languageCombo.getText() ) )
{
langLine.countryCombo.setItems( possibleLangToCountriesMap.get( langLine.languageCombo
.getText() ) );
}
else
{
langLine.countryCombo.setItems( new String[0] );
}
langLine.countryCombo.setText( oldValue );
}
validate();
}
} );
langLine.countryCombo.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
return langLine;
}
/**
* Deletes the language line at the given index.
*
* @param langComposite the language composite
* @param index the index
*/
private void deleteLangLine( Composite langComposite, int index )
{
LangLine langLine = langLineList.remove( index );
if ( langLine != null )
{
langLine.langLabel.dispose();
langLine.languageCombo.dispose();
langLine.minusLabel.dispose();
langLine.countryCombo.dispose();
langLine.addButton.dispose();
langLine.deleteButton.dispose();
if ( !langComposite.isDisposed() )
{
shell.layout( true, true );
}
}
}
/**
* The class LangLine is a wrapper for all input elements of a language tag.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LangLine
{
/** The lang label. */
public Label langLabel;
/** The language combo. */
public Combo languageCombo;
/** The minus label. */
public Label minusLabel;
/** The country combo. */
public Combo countryCombo;
/** The add button. */
public Button addButton;
/** The delete button. */
public Button deleteButton;
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryWizard.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryWizard.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.connection.ui.RunnableContextRunner;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.widgets.browser.BrowserCategory;
import org.apache.directory.studio.ldapbrowser.common.widgets.browser.BrowserEntryPage;
import org.apache.directory.studio.ldapbrowser.common.widgets.browser.BrowserSearchResultPage;
import org.apache.directory.studio.ldapbrowser.core.jobs.CreateEntryRunnable;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
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.core.model.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* The NewEntryWizard is used to create a new entry from scratch or by
* using another entry as template.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewEntryWizard extends Wizard implements INewWizard
{
/** The type page. */
protected NewEntryTypeWizardPage typePage;
/** The object class page. */
protected NewEntryObjectclassWizardPage ocPage;
/** The dn page. */
protected NewEntryDnWizardPage dnPage;
/** The attributes page. */
protected NewEntryAttributesWizardPage attributePage;
/** The selected entry. */
protected IEntry selectedEntry;
/** The selected connection. */
protected IBrowserConnection selectedConnection;
/** The read only flag of the selected connection. */
protected boolean originalReadOnlyFlag;
/** The prototype entry. */
protected DummyEntry prototypeEntry;
/**
* Creates a new instance of NewEntryWizard.
*/
public NewEntryWizard()
{
setNeedsProgressMonitor( true );
}
/**
* Gets the id.
*
* @return the id
*/
public static String getId()
{
return BrowserCommonConstants.WIZARD_NEW_ENTRY_WIZARD;
}
/**
* {@inheritDoc}
*/
public void init( IWorkbench workbench, IStructuredSelection selection )
{
// determine the currently selected entry
Object selected = selection.getFirstElement();
if ( isNewContextEntry() )
{
setWindowTitle( Messages.getString( "NewEntryWizard.NewContextEntry" ) ); //$NON-NLS-1$
}
else
{
setWindowTitle( Messages.getString( "NewEntryWizard.NewEntry" ) ); //$NON-NLS-1$
}
if ( selected instanceof IEntry )
{
selectedEntry = ( ( IEntry ) selected );
selectedConnection = selectedEntry.getBrowserConnection();
}
else if ( selected instanceof ISearchResult )
{
selectedEntry = ( ( ISearchResult ) selected ).getEntry();
selectedConnection = selectedEntry.getBrowserConnection();
}
else if ( selected instanceof IBookmark )
{
selectedEntry = ( ( IBookmark ) selected ).getEntry();
selectedConnection = selectedEntry.getBrowserConnection();
}
else if ( selected instanceof IAttribute )
{
selectedEntry = ( ( IAttribute ) selected ).getEntry();
selectedConnection = selectedEntry.getBrowserConnection();
}
else if ( selected instanceof IValue )
{
selectedEntry = ( ( IValue ) selected ).getAttribute().getEntry();
selectedConnection = selectedEntry.getBrowserConnection();
}
else if ( selected instanceof ISearch )
{
selectedEntry = null;
selectedConnection = ( ( ISearch ) selected ).getBrowserConnection();
}
else if ( selected instanceof IBrowserConnection )
{
selectedEntry = null;
selectedConnection = ( IBrowserConnection ) selected;
}
else if ( selected instanceof BrowserCategory )
{
selectedEntry = null;
selectedConnection = ( ( BrowserCategory ) selected ).getParent();
}
else if ( selected instanceof BrowserSearchResultPage )
{
selectedEntry = null;
selectedConnection = ( ( BrowserSearchResultPage ) selected ).getSearch().getBrowserConnection();
}
else if ( selected instanceof BrowserEntryPage )
{
selectedEntry = null;
selectedConnection = ( ( BrowserEntryPage ) selected ).getEntry().getBrowserConnection();
}
else
{
selectedEntry = null;
selectedConnection = null;
}
if ( selectedConnection != null )
{
if ( selectedConnection.getConnection() != null )
{
originalReadOnlyFlag = selectedConnection.getConnection().isReadOnly();
selectedConnection.getConnection().setReadOnly( true );
}
prototypeEntry = new DummyEntry( new Dn(), selectedConnection );
}
}
/**
* {@inheritDoc}
*/
public void addPages()
{
if ( selectedConnection != null )
{
typePage = new NewEntryTypeWizardPage( NewEntryTypeWizardPage.class.getName(), this );
addPage( typePage );
ocPage = new NewEntryObjectclassWizardPage( NewEntryObjectclassWizardPage.class.getName(), this );
addPage( ocPage );
dnPage = new NewEntryDnWizardPage( NewEntryDnWizardPage.class.getName(), this );
addPage( dnPage );
attributePage = new NewEntryAttributesWizardPage( NewEntryAttributesWizardPage.class.getName(), this );
addPage( attributePage );
}
else
{
IWizardPage page = new DummyWizardPage();
addPage( page );
}
}
/**
* {@inheritDoc}
*/
public void createPageControls( Composite pageContainer )
{
super.createPageControls( pageContainer );
// set help context ID
if ( selectedConnection != null )
{
if ( typePage != null )
{
PlatformUI.getWorkbench().getHelpSystem().setHelp( typePage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_newentry_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
}
if ( ocPage != null )
{
PlatformUI.getWorkbench().getHelpSystem().setHelp( ocPage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_newentry_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
}
if ( dnPage != null )
{
PlatformUI.getWorkbench().getHelpSystem().setHelp( dnPage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_newentry_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
}
if ( attributePage != null )
{
PlatformUI.getWorkbench().getHelpSystem().setHelp( attributePage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_newentry_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
/**
* Just a dummy page.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
class DummyWizardPage extends WizardPage
{
/**
* Creates a new instance of DummyWizardPage.
*/
protected DummyWizardPage()
{
super( "" ); //$NON-NLS-1$
setTitle( Messages.getString( "NewEntryWizard.NoConnectonSelected" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "NewEntryWizard.NoConnectonSelectedDescription" ) ); //$NON-NLS-1$
setImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_WIZARD ) );
setPageComplete( true );
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 1, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
setControl( composite );
}
}
/**
* {@inheritDoc}
*/
public boolean performCancel()
{
if ( selectedConnection != null && selectedConnection.getConnection() != null )
{
selectedConnection.getConnection().setReadOnly( originalReadOnlyFlag );
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean performFinish()
{
try
{
if ( selectedConnection != null && selectedConnection.getConnection() != null )
{
selectedConnection.getConnection().setReadOnly( originalReadOnlyFlag );
typePage.saveDialogSettings();
dnPage.saveDialogSettings();
CreateEntryRunnable runnable = new CreateEntryRunnable( prototypeEntry, selectedConnection );
IStatus status = RunnableContextRunner.execute( runnable, getContainer(), true );
if ( !status.isOK() )
{
selectedConnection.getConnection().setReadOnly( true );
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
catch ( Throwable t )
{
t.printStackTrace();
return false;
}
}
/**
* Gets the selected entry.
*
* @return the selected entry, may be null
*/
public IEntry getSelectedEntry()
{
return selectedEntry;
}
/**
* Gets the selected connection.
*
* @return the selected connection
*/
public IBrowserConnection getSelectedConnection()
{
return selectedConnection;
}
/**
* Gets the prototype entry.
*
* @return the prototype entry
*/
public DummyEntry getPrototypeEntry()
{
return prototypeEntry;
}
/**
* Sets the prototype entry.
*
* @param getPrototypeEntry the prototype entry
*/
public void setPrototypeEntry( DummyEntry getPrototypeEntry )
{
this.prototypeEntry = getPrototypeEntry;
}
/**
* Checks if is new context entry.
*
* @return true, if is new context entry
*/
public boolean isNewContextEntry()
{
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeWizard.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/AttributeWizard.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* The AttributeWizard is used to create a new attribute or
* to modify an existing attribute description.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class AttributeWizard extends Wizard implements INewWizard
{
/** The type page. */
private AttributeTypeWizardPage typePage;
/** The options page. */
private AttributeOptionsWizardPage optionsPage;
/** The initial show subschema attributes only. */
private boolean initialShowSubschemaAttributesOnly;
/** The initial hide existing attributes. */
private boolean initialHideExistingAttributes;
/** The initial attribute description. */
private String initialAttributeDescription;
/** The initial entry. */
private IEntry initialEntry;
/** The final attribute description. */
private String finalAttributeDescription = null;
/**
* Creates a new instance of AttributeWizard with an empty
* attribute description.
*/
public AttributeWizard()
{
super.setWindowTitle( Messages.getString( "AttributeWizard.NewAttribute" ) ); //$NON-NLS-1$
super.setNeedsProgressMonitor( false );
this.initialShowSubschemaAttributesOnly = true;
this.initialHideExistingAttributes = true;
this.initialAttributeDescription = ""; //$NON-NLS-1$
this.initialEntry = null;
}
/**
* Creates a new instance of AttributeWizard with the given initial attribute description.
*
* @param title the title
* @param entry the entry
* @param showSubschemaAttributesOnly the show subschema attributes only
* @param hideExistingAttributes the hide existing attributes
* @param attributeDescription the attribute description
*/
public AttributeWizard( String title, boolean showSubschemaAttributesOnly, boolean hideExistingAttributes,
String attributeDescription, IEntry entry )
{
super.setWindowTitle( title );
super.setNeedsProgressMonitor( false );
this.initialShowSubschemaAttributesOnly = showSubschemaAttributesOnly;
this.initialHideExistingAttributes = hideExistingAttributes;
this.initialAttributeDescription = attributeDescription;
this.initialEntry = entry;
}
/**
* Gets the id.
*
* @return the id
*/
public static String getId()
{
return BrowserCommonConstants.WIZARD_ATTRIBUTE_WIZARD;
}
/**
* {@inheritDoc}}
*/
public void init( IWorkbench workbench, IStructuredSelection selection )
{
}
/**
* {@inheritDoc}}
*/
public void addPages()
{
if ( initialEntry != null )
{
typePage = new AttributeTypeWizardPage( AttributeTypeWizardPage.class.getName(), initialEntry,
initialAttributeDescription, initialShowSubschemaAttributesOnly, initialHideExistingAttributes, this );
addPage( typePage );
optionsPage = new AttributeOptionsWizardPage( AttributeOptionsWizardPage.class.getName(),
initialAttributeDescription, this );
addPage( optionsPage );
}
else
{
IWizardPage page = new DummyWizardPage();
addPage( page );
}
}
/**
* {@inheritDoc}
*/
public void createPageControls( Composite pageContainer )
{
super.createPageControls( pageContainer );
// set help context ID
PlatformUI.getWorkbench().getHelpSystem().setHelp( typePage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_attribute_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
PlatformUI.getWorkbench().getHelpSystem().setHelp( optionsPage.getControl(),
BrowserCommonConstants.PLUGIN_ID + "." + "tools_attribute_wizard" ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* A dummy wizard page to show the user that no entry is selected.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
class DummyWizardPage extends WizardPage
{
/**
* Creates a new instance of DummyWizardPage.
*/
protected DummyWizardPage()
{
super( "" ); //$NON-NLS-1$
super.setTitle( Messages.getString( "AttributeWizard.NoEntrySelected" ) ); //$NON-NLS-1$
super.setDescription( Messages.getString( "AttributeWizard.NoeEntrySelectedDescription" ) ); //$NON-NLS-1$
// super.setImageDescriptor(BrowserUIPlugin.getDefault().getImageDescriptor(BrowserUIConstants.IMG_ATTRIBUTE_WIZARD));
super.setPageComplete( true );
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 1, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
setControl( composite );
}
}
/**
* {@inheritDoc}
*/
public boolean performFinish()
{
finalAttributeDescription = getAttributeDescription();
return true;
}
/**
* Gets the attribute description.
*
* @return the attribute description
*/
public String getAttributeDescription()
{
if ( finalAttributeDescription != null )
{
return finalAttributeDescription;
}
return typePage.getAttributeType() + optionsPage.getAttributeOptions();
}
}
| 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.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryDnWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryDnWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Ava;
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.AttributeType;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.connection.ui.RunnableContextRunner;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.widgets.DnBuilderWidget;
import org.apache.directory.studio.ldapbrowser.common.widgets.ListContentProposalProvider;
import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry;
import org.apache.directory.studio.ldapbrowser.core.jobs.ReadEntryRunnable;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Value;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.fieldassist.ComboContentAdapter;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
/**
* The NewEntryDnWizardPage is used to compose the new entry's
* distinguished name.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewEntryDnWizardPage extends WizardPage implements WidgetModifyListener
{
/** The wizard. */
private NewEntryWizard wizard;
/** The Dn builder widget. */
private DnBuilderWidget dnBuilderWidget;
/** The context entry Dn combo. */
private Combo contextEntryDnCombo;
/** The content proposal adapter for the context entry Dn combo. */
private ContentProposalAdapter contextEntryDnComboCPA;
/**
* Creates a new instance of NewEntryDnWizardPage.
*
* @param pageName the page name
* @param wizard the wizard
*/
public NewEntryDnWizardPage( String pageName, NewEntryWizard wizard )
{
super( pageName );
setTitle( Messages.getString( "NewEntryDnWizardPage.DistinguishedName" ) ); //$NON-NLS-1$
if ( wizard.isNewContextEntry() )
{
setDescription( Messages.getString( "NewEntryDnWizardPage.EnterDN" ) ); //$NON-NLS-1$
}
else
{
setDescription( Messages.getString( "NewEntryDnWizardPage.SelectParent" ) ); //$NON-NLS-1$
}
setImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_WIZARD ) );
setPageComplete( false );
this.wizard = wizard;
}
/**
* {@inheritDoc}
*/
public void dispose()
{
if ( dnBuilderWidget != null )
{
dnBuilderWidget.removeWidgetModifyListener( this );
dnBuilderWidget.dispose();
dnBuilderWidget = null;
}
super.dispose();
}
/**
* Validates the input fields.
*/
private void validate()
{
if ( wizard.isNewContextEntry() && !"".equals( contextEntryDnCombo.getText() ) //$NON-NLS-1$
&& Dn.isValid( contextEntryDnCombo.getText() ) )
{
setPageComplete( true );
saveState();
}
else if ( !wizard.isNewContextEntry() && dnBuilderWidget.getRdn() != null
&& dnBuilderWidget.getParentDn() != null )
{
setPageComplete( true );
saveState();
}
else
{
setPageComplete( false );
}
}
/**
* Initializes the Dn builder widget with the Dn of
* the prototype entry. Called when this page becomes visible.
*/
private void loadState()
{
DummyEntry newEntry = wizard.getPrototypeEntry();
if ( wizard.isNewContextEntry() )
{
IAttribute attribute = wizard.getSelectedConnection().getRootDSE().getAttribute(
SchemaConstants.NAMING_CONTEXTS_AT );
if ( attribute != null )
{
String[] values = attribute.getStringValues();
// content proposals
contextEntryDnComboCPA.setContentProposalProvider( new ListContentProposalProvider( values ) );
// fill namingContext values into combo
contextEntryDnCombo.setItems( values );
// preset combo text
if ( Arrays.asList( values ).contains( newEntry.getDn().getName() ) )
{
contextEntryDnCombo.setText( newEntry.getDn().getName() );
}
}
}
else
{
Collection<AttributeType> atds = SchemaUtils.getAllAttributeTypeDescriptions( newEntry );
String[] attributeNames = SchemaUtils.getNames( atds ).toArray( ArrayUtils.EMPTY_STRING_ARRAY );
Dn parentDn = null;
boolean hasSelectedEntry = wizard.getSelectedEntry() != null;
boolean newEntryParentDnNotNullOrEmpty = !Dn.isNullOrEmpty( newEntry.getDn().getParent() );
if ( hasSelectedEntry )
{
boolean newEntryDnEqualsSelectedEntryDn = newEntry.getDn().equals( wizard.getSelectedEntry().getDn() );
if ( newEntryDnEqualsSelectedEntryDn && newEntryParentDnNotNullOrEmpty )
{
parentDn = newEntry.getDn().getParent();
}
else
{
parentDn = wizard.getSelectedEntry().getDn();
}
}
else if ( newEntryParentDnNotNullOrEmpty )
{
parentDn = newEntry.getDn().getParent();
}
Rdn rdn = newEntry.getRdn();
dnBuilderWidget.setInput( wizard.getSelectedConnection(), attributeNames, rdn, parentDn );
}
}
/**
* Saves the Dn of the Dn builder widget to the prototype entry.
*/
private void saveState()
{
DummyEntry newEntry = wizard.getPrototypeEntry();
try
{
EventRegistry.suspendEventFiringInCurrentThread();
// remove old Rdn
if ( newEntry.getRdn().size() > 0 )
{
Iterator<Ava> atavIterator = newEntry.getRdn().iterator();
while ( atavIterator.hasNext() )
{
Ava atav = atavIterator.next();
IAttribute attribute = newEntry.getAttribute( atav.getType() );
if ( attribute != null )
{
IValue[] values = attribute.getValues();
for ( int v = 0; v < values.length; v++ )
{
if ( values[v].getStringValue().equals( atav.getValue().getNormalized() ) )
{
attribute.deleteValue( values[v] );
}
}
// If we have removed all the values of the attribute,
// then we also need to remove this attribute from the
// entry.
// This test has been added to fix DIRSTUDIO-222
if ( attribute.getValueSize() == 0 )
{
newEntry.deleteAttribute( attribute );
}
}
}
}
// set new Dn
Dn dn;
if ( wizard.isNewContextEntry() )
{
try
{
dn = new Dn( contextEntryDnCombo.getText() );
}
catch ( LdapInvalidDnException e )
{
dn = Dn.EMPTY_DN;
}
}
else
{
try
{
dn = dnBuilderWidget.getParentDn().add( dnBuilderWidget.getRdn() );
}
catch ( LdapInvalidDnException lide )
{
// Do nothing
dn = Dn.EMPTY_DN;
}
}
newEntry.setDn( dn );
// add new Rdn
if ( dn.getRdn().size() > 0 )
{
Iterator<Ava> atavIterator = dn.getRdn().iterator();
while ( atavIterator.hasNext() )
{
Ava atav = atavIterator.next();
IAttribute rdnAttribute = newEntry.getAttribute( atav.getType() );
if ( rdnAttribute == null )
{
rdnAttribute = new Attribute( newEntry, atav.getType() );
newEntry.addAttribute( rdnAttribute );
}
Object rdnValue = atav.getValue().getNormalized();
String[] stringValues = rdnAttribute.getStringValues();
if ( !Arrays.asList( stringValues ).contains( rdnValue ) )
{
rdnAttribute.addValue( new Value( rdnAttribute, rdnValue ) );
}
}
}
}
finally
{
EventRegistry.resumeEventFiringInCurrentThread();
}
}
/**
* {@inheritDoc}
*
* This implementation initializes Dn builder widghet with the
* Dn of the protoype entry.
*/
public void setVisible( boolean visible )
{
super.setVisible( visible );
if ( visible )
{
loadState();
validate();
if ( wizard.isNewContextEntry() )
{
contextEntryDnCombo.setFocus();
}
}
}
/**
* {@inheritDoc}
*
* This implementation just checks if this page is complete. It
* doesn't call {@link #getNextPage()} to avoid unneeded
* invokings of {@link ReadEntryRunnable}s.
*/
@Override
public boolean canFlipToNextPage()
{
return isPageComplete();
}
/**
* {@inheritDoc}
*
* This implementation invokes a {@link ReadEntryRunnable} to check if an
* entry with the composed Dn already exists.
*/
@Override
public IWizardPage getNextPage()
{
if ( !wizard.isNewContextEntry() )
{
dnBuilderWidget.validate();
Rdn rdn = dnBuilderWidget.getRdn();
Dn parentDn = dnBuilderWidget.getParentDn();
try
{
final Dn dn = parentDn.add( rdn );
// check if parent exists
ReadEntryRunnable readEntryRunnable1 = new ReadEntryRunnable( wizard.getSelectedConnection(), parentDn );
RunnableContextRunner.execute( readEntryRunnable1, getContainer(), false );
IEntry parentEntry = readEntryRunnable1.getReadEntry();
if ( parentEntry == null )
{
getShell().getDisplay().syncExec( () ->
{
MessageDialog
.openError( getShell(),
Messages.getString( "NewEntryDnWizardPage.Error" ), //$NON-NLS-1$
NLS
.bind(
Messages.getString( "NewEntryDnWizardPage.ParentDoesNotExist" ), dnBuilderWidget.getParentDn().toString() ) ); //$NON-NLS-1$
}
);
return null;
}
// check that new entry does not exists yet
ReadEntryRunnable readEntryRunnable2 = new ReadEntryRunnable( wizard.getSelectedConnection(), dn );
RunnableContextRunner.execute( readEntryRunnable2, getContainer(), false );
IEntry entry = readEntryRunnable2.getReadEntry();
if ( entry != null )
{
getShell().getDisplay().syncExec( () ->
{
MessageDialog
.openError(
getShell(),
Messages.getString( "NewEntryDnWizardPage.Error" ), NLS.bind( Messages.getString( "NewEntryDnWizardPage.EntryAlreadyExists" ), dn.toString() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
);
return null;
}
}
catch ( LdapInvalidDnException lide )
{
return null;
}
}
else
{
try
{
final Dn dn = new Dn( contextEntryDnCombo.getText() );
// check that new entry does not exists yet
ReadEntryRunnable readEntryRunnable2 = new ReadEntryRunnable( wizard.getSelectedConnection(), dn );
RunnableContextRunner.execute( readEntryRunnable2, getContainer(), false );
IEntry entry = readEntryRunnable2.getReadEntry();
if ( entry != null )
{
getShell().getDisplay().syncExec( () ->
{
MessageDialog
.openError(
getShell(),
Messages.getString( "NewEntryDnWizardPage.Error" ), NLS.bind( Messages.getString( "NewEntryDnWizardPage.EntryAlreadyExists" ), dn.toString() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
);
return null;
}
}
catch ( LdapInvalidDnException e )
{
return null;
}
}
return super.getNextPage();
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
if ( wizard.isNewContextEntry() )
{
// the combo
Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 );
contextEntryDnCombo = BaseWidgetUtils.createCombo( composite, ArrayUtils.EMPTY_STRING_ARRAY, 0, 1 );
contextEntryDnCombo.addModifyListener( event -> validate() );
// attach content proposal behavior
contextEntryDnComboCPA = new ContentProposalAdapter( contextEntryDnCombo, new ComboContentAdapter(), null,
null, null );
contextEntryDnComboCPA.setFilterStyle( ContentProposalAdapter.FILTER_NONE );
contextEntryDnComboCPA.setProposalAcceptanceStyle( ContentProposalAdapter.PROPOSAL_REPLACE );
setControl( composite );
}
else
{
dnBuilderWidget = new DnBuilderWidget( true, true );
dnBuilderWidget.addWidgetModifyListener( this );
Composite composite = dnBuilderWidget.createContents( parent );
setControl( composite );
}
}
/**
* {@inheritDoc}
*/
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
/**
* Saves the dialogs settings.
*/
public void saveDialogSettings()
{
if ( !wizard.isNewContextEntry() )
{
dnBuilderWidget.saveDialogSettings();
}
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryAttributesWizardPage.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/wizards/NewEntryAttributesWizardPage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.common.wizards;
import java.util.Collection;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
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.EntryEditorWidgetActionGroupWithAttribute;
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.common.widgets.entryeditor.OpenDefaultEditorAction;
import org.apache.directory.studio.ldapbrowser.core.events.EntryModificationEvent;
import org.apache.directory.studio.ldapbrowser.core.events.EntryUpdateListener;
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.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute;
import org.apache.directory.studio.ldapbrowser.core.model.impl.DummyEntry;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.jface.dialogs.IPageChangedListener;
import org.eclipse.jface.dialogs.PageChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardContainer;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;
/**
* The NewEntryAttributesWizardPage is used to fill the attributes of
* the new entry.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class NewEntryAttributesWizardPage extends WizardPage implements EntryUpdateListener
{
/** The wizard. */
private NewEntryWizard wizard;
/** The configuration. */
private EntryEditorWidgetConfiguration configuration;
/** The action group. */
private EntryEditorWidgetActionGroup actionGroup;
/** The main widget. */
private EntryEditorWidget mainWidget;
/** The universal listener. */
private EntryEditorWidgetUniversalListener universalListener;
/** Token used to activate and deactivate shortcuts in the editor */
private IContextActivation contextActivation;
/**
* Creates a new instance of NewEntryAttributesWizardPage.
*
* @param pageName the page name
* @param wizard the wizard
*/
public NewEntryAttributesWizardPage( String pageName, NewEntryWizard wizard )
{
super( pageName );
setTitle( Messages.getString( "NewEntryAttributesWizardPage.Attributes" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "NewEntryAttributesWizardPage.PleaseEnterAttributesForEntry" ) ); //$NON-NLS-1$
setImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_WIZARD ) );
setPageComplete( false );
this.wizard = wizard;
IWizardContainer container = wizard.getContainer();
if ( container instanceof WizardDialog )
{
WizardDialog dialog = ( WizardDialog ) container;
dialog.addPageChangedListener( new IPageChangedListener()
{
public void pageChanged( PageChangedEvent event )
{
if ( getControl().isVisible() )
{
for ( IAttribute attribute : NewEntryAttributesWizardPage.this.wizard.getPrototypeEntry()
.getAttributes() )
{
for ( IValue value : attribute.getValues() )
{
if ( value.isEmpty() )
{
mainWidget.getViewer().setSelection( new StructuredSelection( value ), true );
OpenDefaultEditorAction openDefaultEditorAction = actionGroup
.getOpenDefaultEditorAction();
if ( openDefaultEditorAction.isEnabled() )
{
openDefaultEditorAction.run();
}
return;
}
}
}
}
}
} );
}
}
/**
* {@inheritDoc}
*/
public void dispose()
{
if ( configuration != null )
{
EventRegistry.removeEntryUpdateListener( this );
universalListener.dispose();
universalListener = null;
mainWidget.dispose();
mainWidget = null;
actionGroup.dispose();
actionGroup = null;
configuration.dispose();
configuration = null;
if ( contextActivation != null )
{
IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
IContextService.class );
contextService.deactivateContext( contextActivation );
contextActivation = null;
}
}
super.dispose();
}
/**
* {@inheritDoc}
*
* This implementation initializes the must attributes of the
* prototype entry and initializes the entry widget when this
* page becomes visible.
*/
public void setVisible( boolean visible )
{
super.setVisible( visible );
if ( visible )
{
DummyEntry newEntry = wizard.getPrototypeEntry();
try
{
EventRegistry.suspendEventFiringInCurrentThread();
// remove empty must attributes
// necessary when navigating back, modifying object classes
// and Dn and navigating forward again.
Collection<AttributeType> oldMusts = SchemaUtils.getMustAttributeTypeDescriptions( newEntry );
for ( AttributeType oldMust : oldMusts )
{
IAttribute attribute = newEntry.getAttribute( oldMust.getOid() );
if ( attribute != null )
{
IValue[] values = attribute.getValues();
for ( int v = 0; v < values.length; v++ )
{
if ( values[v].isEmpty() )
{
attribute.deleteValue( values[v] );
}
}
if ( attribute.getValueSize() == 0 )
{
newEntry.deleteAttribute( attribute );
}
}
}
// add must attributes
Collection<AttributeType> newMusts = SchemaUtils.getMustAttributeTypeDescriptions( newEntry );
for ( AttributeType newMust : newMusts )
{
if ( newEntry.getAttributeWithSubtypes( newMust.getOid() ) == null )
{
String friendlyIdentifier = SchemaUtils.getFriendlyIdentifier( newMust );
IAttribute att = new Attribute( newEntry, friendlyIdentifier );
newEntry.addAttribute( att );
att.addEmptyValue();
}
}
}
finally
{
EventRegistry.resumeEventFiringInCurrentThread();
}
// set the input
universalListener.setInput( newEntry );
mainWidget.getViewer().refresh();
validate();
// set focus to the viewer
mainWidget.getViewer().getControl().setFocus();
}
else
{
mainWidget.getViewer().setInput( "" ); //$NON-NLS-1$
mainWidget.getViewer().refresh();
setPageComplete( false );
}
}
/**
* Checks if the prototype entry is completed.
*/
private void validate()
{
if ( wizard.getPrototypeEntry() != null )
{
Collection<String> messages = SchemaUtils.getEntryIncompleteMessages( wizard.getPrototypeEntry() );
if ( messages != null && !messages.isEmpty() )
{
StringBuffer sb = new StringBuffer();
for ( String message : messages )
{
sb.append( message );
sb.append( ' ' );
}
setMessage( sb.toString(), WizardPage.WARNING );
}
else
{
setMessage( null );
}
setPageComplete( true );
}
else
{
setPageComplete( false );
}
}
/**
* {@inheritDoc}
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gl = new GridLayout( 1, false );
composite.setLayout( gl );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
// create configuration
configuration = new EntryEditorWidgetConfiguration();
// create main widget
mainWidget = new EntryEditorWidget( configuration );
mainWidget.createWidget( composite );
mainWidget.getViewer().getTree().setFocus();
// create actions
actionGroup = new EntryEditorWidgetActionGroupWithAttribute( mainWidget, configuration );
actionGroup.fillToolBar( mainWidget.getToolBarManager() );
actionGroup.fillMenu( mainWidget.getMenuManager() );
actionGroup.fillContextMenu( mainWidget.getContextMenuManager() );
IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
IContextService.class );
contextActivation = contextService.activateContext( BrowserCommonConstants.CONTEXT_DIALOGS );
actionGroup.activateGlobalActionHandlers();
// create the listener
universalListener = new EntryEditorWidgetUniversalListener( mainWidget.getViewer(), configuration, actionGroup,
actionGroup.getOpenDefaultEditorAction() );
EventRegistry.addEntryUpdateListener( this, BrowserCommonActivator.getDefault().getEventRunner() );
setControl( composite );
}
/**
* {@inheritDoc}
*/
public void entryUpdated( EntryModificationEvent event )
{
if ( event.getModifiedEntry() == wizard.getPrototypeEntry() && !isDisposed() && getControl().isVisible() )
{
validate();
}
}
/**
* Checks if is disposed.
*
* @return true, if is disposed
*/
private boolean isDisposed()
{
return configuration == 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.common/src/main/java/org/apache/directory/studio/valueeditors/ValueEditorManager.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/ValueEditorManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.LdapSyntax;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
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.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* A ValueEditorManager is used to manage value editors. It provides methods to get
* the best or alternative value editors for a given attribute or value. It takes
* user preferences into account when determine the best value editor. At least
* it provides default text and binary value editors.
*
* The available value editors are specified by the extension point
* <code>org.apache.directory.studio.valueeditors</code>.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class ValueEditorManager
{
private static final String ATTRIBUTE_TYPE = "attributeType"; //$NON-NLS-1$
private static final String ATTRIBUTE = "attribute"; //$NON-NLS-1$
private static final String SYNTAX_OID = "syntaxOID"; //$NON-NLS-1$
private static final String SYNTAX = "syntax"; //$NON-NLS-1$
private static final String ICON = "icon"; //$NON-NLS-1$
private static final String NAME = "name"; //$NON-NLS-1$
private static final String CLASS = "class"; //$NON-NLS-1$
/** The extension point ID for value editors */
private static final String EXTENSION_POINT = BrowserCommonConstants.EXTENSION_POINT_VALUE_EDITORS;
/** The composite used to create the value editors **/
private Composite parent;
/**
* The value editor explicitly selected by the user. If this
* member is not null it is always returned as current value editor.
*/
private IValueEditor userSelectedValueEditor;
/** The special value editor for multi-valued attributes */
private MultivaluedValueEditor multiValuedValueEditor;
/** The special value editor to edit the entry in an wizard */
private EntryValueEditor entryValueEditor;
/** The special value editor to rename the entry */
private RenameValueEditor renameValueEditor;
/** The default string editor for single-line values */
private IValueEditor defaultStringSingleLineValueEditor;
/** The default string editor for multi-line values */
private IValueEditor defaultStringMultiLineValueEditor;
/** The default binary editor */
private IValueEditor defaultBinaryValueEditor;
/** A map containing all available value editors. */
private Map<String, IValueEditor> class2ValueEditors;
/**
* Creates a new instance of ValueEditorManager.
*
* @param parent the composite used to create the value editors
*/
public ValueEditorManager( Composite parent, boolean useEntryValueEditor, boolean useRenameValueEditor )
{
this.parent = parent;
userSelectedValueEditor = null;
// init value editor map
class2ValueEditors = new HashMap<String, IValueEditor>();
Collection<IValueEditor> valueEditors = createValueEditors( parent );
for ( IValueEditor valueEditor : valueEditors )
{
class2ValueEditors.put( valueEditor.getClass().getName(), valueEditor );
}
// special case: multivalued editor
multiValuedValueEditor = new MultivaluedValueEditor( this.parent, this );
multiValuedValueEditor.setValueEditorName( Messages.getString( "ValueEditorManager.MulitivaluedEditor" ) ); //$NON-NLS-1$
multiValuedValueEditor.setValueEditorImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_MULTIVALUEDEDITOR ) );
// special case: entry editor
if ( useEntryValueEditor )
{
entryValueEditor = new EntryValueEditor( this.parent, this );
entryValueEditor.setValueEditorName( Messages.getString( "ValueEditorManager.EntryEditor" ) ); //$NON-NLS-1$
entryValueEditor.setValueEditorImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_ENTRY_EDITOR ) );
}
// special case: rename editor
if ( useRenameValueEditor )
{
renameValueEditor = new RenameValueEditor( this.parent, this );
renameValueEditor.setValueEditorName( Messages.getString( "ValueEditorManager.RenameEditor" ) ); //$NON-NLS-1$
renameValueEditor.setValueEditorImageDescriptor( BrowserCommonActivator.getDefault().getImageDescriptor(
BrowserCommonConstants.IMG_RENAME ) );
}
// get default editors from value editor map
defaultStringSingleLineValueEditor = class2ValueEditors.get( InPlaceTextValueEditor.class.getName() );
defaultStringMultiLineValueEditor = class2ValueEditors.get( TextValueEditor.class.getName() );
defaultBinaryValueEditor = class2ValueEditors.get( HexValueEditor.class.getName() );
}
/**
* Disposes all value editors.
*/
public void dispose()
{
if ( parent != null )
{
userSelectedValueEditor = null;
multiValuedValueEditor.dispose();
if ( entryValueEditor != null )
{
entryValueEditor.dispose();
}
if ( renameValueEditor != null )
{
renameValueEditor.dispose();
}
defaultStringSingleLineValueEditor.dispose();
defaultStringMultiLineValueEditor.dispose();
defaultBinaryValueEditor.dispose();
for ( IValueEditor ve : class2ValueEditors.values() )
{
ve.dispose();
}
parent = null;
}
}
/**
* Sets the value editor explicitly selected by the user. Set
* userSelectedValueEditor to null to remove the selection.
*
* @param userSelectedValueEditor the user selected value editor, may be null.
*/
public void setUserSelectedValueEditor( IValueEditor userSelectedValueEditor )
{
this.userSelectedValueEditor = userSelectedValueEditor;
}
/**
* Gets the value editor explicitly selected by the user.
*
* @return the user selected value editor, null if non is set
*/
public IValueEditor getUserSelectedValueEditor()
{
return userSelectedValueEditor;
}
/**
* Returns the current (best) value editor for the given attribute.
*
* <ol>
* <li>If a user selected value editor is selected, this is returned.
* <li>If a specific value editor is defined for the attribute type this
* value editor is returned. See preferences.
* <li>If a specific value editor is defined for the attribute's syntax this
* value editor is returned. See preferences.
* <li>Otherwise a default value editor is returned. If the attribute is
* binary the default Hex Editor is returned. Otherwise the default
* Text Editor is returned.
* </ol>
*
* @param schema the schema
* @param attributeType the attribute type
* @return the current value editor
*/
public IValueEditor getCurrentValueEditor( Schema schema, String attributeType )
{
// check user-selected (forced) value editor
if ( userSelectedValueEditor != null )
{
return userSelectedValueEditor;
}
AttributeType atd = schema.getAttributeTypeDescription( attributeType );
// check attribute preferences
Map<String, String> attributeValueEditorMap = BrowserCommonActivator.getDefault().getValueEditorsPreferences()
.getAttributeValueEditorMap();
String oidStr = Strings.toLowerCase( atd.getOid() );
if ( atd.getOid() != null && attributeValueEditorMap.containsKey( oidStr ) )
{
return ( IValueEditor ) class2ValueEditors.get( attributeValueEditorMap.get( oidStr ) );
}
List<String> names = atd.getNames();
for ( String name : names )
{
String nameStr = Strings.toLowerCase( name );
if ( attributeValueEditorMap.containsKey( nameStr ) )
{
return ( IValueEditor ) class2ValueEditors.get( attributeValueEditorMap.get( nameStr ) );
}
}
// check syntax preferences
String syntaxNumericOid = SchemaUtils.getSyntaxNumericOidTransitive( atd, schema );
Map<String, String> syntaxValueEditorMap = BrowserCommonActivator.getDefault().getValueEditorsPreferences()
.getSyntaxValueEditorMap();
String syntaxtNumericOidStr = Strings.toLowerCase( syntaxNumericOid );
if ( ( syntaxNumericOid != null ) && syntaxValueEditorMap.containsKey( syntaxtNumericOidStr ) )
{
return ( IValueEditor ) class2ValueEditors.get( syntaxValueEditorMap.get( syntaxtNumericOidStr ) );
}
// return default
LdapSyntax lsd = schema.getLdapSyntaxDescription( syntaxNumericOid );
if ( SchemaUtils.isBinary( lsd ) )
{
return defaultBinaryValueEditor;
}
else
{
return defaultStringSingleLineValueEditor;
}
}
/**
* Returns the current (best) value editor for the given attribute.
*
* @param entry the entry
* @param attributeType the attributge type
* @return the current value editor
* @see #getCurrentValueEditor( Schema, String )
*/
public IValueEditor getCurrentValueEditor( IEntry entry, String attributeType )
{
return getCurrentValueEditor( entry.getBrowserConnection().getSchema(), attributeType );
}
/**
* Returns the current (best) value editor for the given value.
*
* @param value the value
* @return the current value editor
* @see #getCurrentValueEditor( Schema, String )
*/
public IValueEditor getCurrentValueEditor( IValue value )
{
IAttribute attribute = value.getAttribute();
IValueEditor ve = getCurrentValueEditor( attribute.getEntry(), attribute.getDescription() );
// special case objectClass: always return entry editor
if ( userSelectedValueEditor == null )
{
if ( attribute.isObjectClassAttribute() && ( entryValueEditor != null ) )
{
return entryValueEditor;
}
// special case Rdn attribute: always return rename editor
if ( value.isRdnPart() && ( renameValueEditor != null ) )
{
return renameValueEditor;
}
}
// here the value is known, we can check for single-line or multi-line
if ( ve == defaultStringSingleLineValueEditor )
{
String stringValue = value.getStringValue();
if ( ( stringValue.indexOf( '\n' ) == -1 ) && ( stringValue.indexOf( '\r' ) == -1 ) )
{
ve = defaultStringSingleLineValueEditor;
}
else
{
ve = defaultStringMultiLineValueEditor;
}
}
return ve;
}
/**
* Returns the current (best) value editor for the given attribute.
*
* @param attributeHierarchy the attribute hierarchy
* @return the current value editor
* @see #getCurrentValueEditor( Schema, String )
*/
public IValueEditor getCurrentValueEditor( AttributeHierarchy attributeHierarchy )
{
if ( attributeHierarchy == null )
{
return null;
}
else if ( ( userSelectedValueEditor == null ) && attributeHierarchy.getAttribute().isObjectClassAttribute()
&& entryValueEditor != null )
{
// special case objectClass: always return entry editor
return entryValueEditor;
}
else if ( ( userSelectedValueEditor == entryValueEditor ) && ( entryValueEditor != null ) )
{
// special case objectClass: always return entry editor
return entryValueEditor;
}
else if ( ( attributeHierarchy.size() == 1 ) && ( attributeHierarchy.getAttribute().getValueSize() == 0 ) )
{
return getCurrentValueEditor( attributeHierarchy.getAttribute().getEntry(), attributeHierarchy
.getAttribute().getDescription() );
}
else if ( ( attributeHierarchy.size() == 1 ) &&
( attributeHierarchy.getAttribute().getValueSize() == 1 ) &&
attributeHierarchy.getAttributeDescription().equalsIgnoreCase(
attributeHierarchy.getAttribute().getValues()[0].getAttribute().getDescription() ) )
{
// special case Rdn: always return MV-editor
if ( ( userSelectedValueEditor == null ) && attributeHierarchy.getAttribute().getValues()[0].isRdnPart() )
{
if ( renameValueEditor != null )
{
return renameValueEditor;
}
else
{
return multiValuedValueEditor;
}
}
return getCurrentValueEditor( attributeHierarchy.getAttribute().getValues()[0] );
}
else
{
return multiValuedValueEditor;
}
}
/**
* Returns alternative value editors for the given attribute. For now these
* are the three default editors.
*
* @param entry the entry
* @param attributeName the attribute
* @return alternative value editors
*/
public IValueEditor[] getAlternativeValueEditors( IEntry entry, String attributeName )
{
Schema schema = entry.getBrowserConnection().getSchema();
return getAlternativeValueEditors( schema, attributeName );
}
/**
* Returns alternative value editors for the given attribute. For now these
* are the three default editors.
*
* @param schema the schema
* @param attributeName the attribute
* @return the alternative value editors
*/
public IValueEditor[] getAlternativeValueEditors( Schema schema, String attributeName )
{
List<IValueEditor> alternativeList = new ArrayList<IValueEditor>();
AttributeType atd = schema.getAttributeTypeDescription( attributeName );
if ( SchemaUtils.isBinary( atd, schema ) )
{
alternativeList.add( defaultBinaryValueEditor );
alternativeList.add( defaultStringSingleLineValueEditor );
alternativeList.add( defaultStringMultiLineValueEditor );
}
else if ( SchemaUtils.isString( atd, schema ) )
{
alternativeList.add( defaultStringSingleLineValueEditor );
alternativeList.add( defaultStringMultiLineValueEditor );
alternativeList.add( defaultBinaryValueEditor );
}
alternativeList.add( multiValuedValueEditor );
alternativeList.remove( getCurrentValueEditor( schema, attributeName ) );
return alternativeList.toArray( new IValueEditor[alternativeList.size()] );
}
/**
* Returns alternative value editors for the given value. For now these
* are the three default editors.
*
* @param value the value
* @return the alternative value editors
*/
public IValueEditor[] getAlternativeValueEditors( IValue value )
{
List<IValueEditor> alternativeList = new ArrayList<IValueEditor>();
if ( value.isBinary() )
{
alternativeList.add( defaultBinaryValueEditor );
alternativeList.add( defaultStringSingleLineValueEditor );
alternativeList.add( defaultStringMultiLineValueEditor );
}
else if ( value.isString() )
{
alternativeList.add( defaultStringSingleLineValueEditor );
alternativeList.add( defaultStringMultiLineValueEditor );
alternativeList.add( defaultBinaryValueEditor );
}
alternativeList.add( multiValuedValueEditor );
alternativeList.remove( getCurrentValueEditor( value ) );
return alternativeList.toArray( new IValueEditor[alternativeList.size()] );
}
/**
* Returns alternative value editors for the given value. For now these
* are the three default editors.
*
* @param ah the attribute hierarchy
* @return alternative value editors
*/
public IValueEditor[] getAlternativeValueEditors( AttributeHierarchy ah )
{
if ( ah == null )
{
return new IValueEditor[0];
}
// special case Rdn: no alternative to the rename editor, except the MV editor
// perhaps this should be moved somewhere else
if ( multiValuedValueEditor != null )
{
for ( IAttribute attribute : ah )
{
for ( IValue value : attribute.getValues() )
{
if ( value.isRdnPart() )
{
return new IValueEditor[]
{ multiValuedValueEditor };
}
}
}
}
// special case objectClass: no alternative to the entry editor
// perhaps this should be moved somewhere else
for ( IAttribute attribute : ah )
{
if ( attribute.isObjectClassAttribute() )
{
return new IValueEditor[0];
}
}
if ( ( ah.size() == 1 ) && ( ah.getAttribute().getValueSize() == 0 ) )
{
return getAlternativeValueEditors( ah.getAttribute().getEntry(), ah.getAttribute().getDescription() );
}
else if ( ( ah.size() == 1 ) &&
( ah.getAttribute().getValueSize() == 1 ) &&
ah.getAttributeDescription().equalsIgnoreCase(
ah.getAttribute().getValues()[0].getAttribute().getDescription() ) )
{
return getAlternativeValueEditors( ah.getAttribute().getValues()[0] );
}
else
{
return new IValueEditor[0];
}
}
/**
* Returns all available value editors.
*
* @return all available value editors
*/
public IValueEditor[] getAllValueEditors()
{
// use a set to avoid double entries
Set<IValueEditor> list = new LinkedHashSet<IValueEditor>();
list.add( defaultStringSingleLineValueEditor );
list.add( defaultStringMultiLineValueEditor );
list.add( defaultBinaryValueEditor );
list.addAll( class2ValueEditors.values() );
list.add( multiValuedValueEditor );
if ( entryValueEditor != null )
{
list.add( entryValueEditor );
}
if ( renameValueEditor != null )
{
list.add( renameValueEditor );
}
return list.toArray( new IValueEditor[list.size()] );
}
/**
* Returns the default binary editor (a HexEditor).
*
* @return the default binary editor
*/
public IValueEditor getDefaultBinaryValueEditor()
{
return defaultBinaryValueEditor;
}
/**
* Returns the default string editor (a TextEditor).
*
* @return the default string editor
*/
public IValueEditor getDefaultStringValueEditor()
{
return defaultStringMultiLineValueEditor;
}
/**
* Returns the multi-valued editor.
*
* @return the multi-valued editor
*/
public MultivaluedValueEditor getMultiValuedValueEditor()
{
return multiValuedValueEditor;
}
/**
* Returns the entry value editor.
*
* @return the entry value editor
*/
public EntryValueEditor getEntryValueEditor()
{
return entryValueEditor;
}
/**
* Returns the rename value editor.
*
* @return the rename value editor
*/
public RenameValueEditor getRenameValueEditor()
{
return renameValueEditor;
}
/**
* Creates and returns the value editors specified by value editors extensions.
*
* @param parent the parent composite
* @return the value editors
*/
private Collection<IValueEditor> createValueEditors( Composite parent )
{
Collection<IValueEditor> valueEditors = new ArrayList<IValueEditor>();
Collection<ValueEditorExtension> valueEditorExtensions = getValueEditorExtensions();
for ( ValueEditorExtension vee : valueEditorExtensions )
{
try
{
IValueEditor valueEditor = ( IValueEditor ) vee.member.createExecutableExtension( CLASS );
valueEditor.create( parent );
valueEditor.setValueEditorName( vee.name );
valueEditor.setValueEditorImageDescriptor( vee.icon );
valueEditors.add( valueEditor );
}
catch ( Exception e )
{
BrowserCommonActivator.getDefault().getLog().log(
new Status( IStatus.ERROR, BrowserCommonConstants.PLUGIN_ID, 1, Messages
.getString( "ValueEditorManager.UnableToCreateValueEditor" ) //$NON-NLS-1$
+ vee.className, e ) );
}
}
return valueEditors;
}
/**
* Returns all value editor extensions specified by value editor extensions.
*
* @return the value editor extensions
*/
public static Collection<ValueEditorExtension> getValueEditorExtensions()
{
Map<String, ValueEditorExtension> valueEditorExtensions = new LinkedHashMap<>();
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry.getExtensionPoint( EXTENSION_POINT );
IConfigurationElement[] members = extensionPoint.getConfigurationElements();
// For each extension:
for ( IConfigurationElement member : members )
{
String className = member.getAttribute( CLASS );
String name = member.getAttribute( NAME );
String iconPath = member.getAttribute( ICON );
ValueEditorExtension proxy;
if ( valueEditorExtensions.containsKey( className ) )
{
proxy = valueEditorExtensions.get( className );
}
else
{
proxy = new ValueEditorExtension();
proxy.className = className;
proxy.member = member;
valueEditorExtensions.put( className, proxy );
}
if ( name != null )
{
proxy.name = name;
}
if ( iconPath != null )
{
IExtension extension = member.getDeclaringExtension();
String extendingPluginId = extension.getNamespaceIdentifier();
proxy.icon = AbstractUIPlugin.imageDescriptorFromPlugin( extendingPluginId, iconPath );
if ( proxy.icon == null )
{
proxy.icon = ImageDescriptor.getMissingImageDescriptor();
}
}
IConfigurationElement[] children = member.getChildren();
for ( IConfigurationElement child : children )
{
String type = child.getName();
if ( SYNTAX.equals( type ) )
{
String syntaxOID = child.getAttribute( SYNTAX_OID );
proxy.syntaxOids.add( syntaxOID );
}
else if ( ATTRIBUTE.equals( type ) )
{
String attributeType = child.getAttribute( ATTRIBUTE_TYPE );
proxy.attributeTypes.add( attributeType );
}
}
}
return valueEditorExtensions.values();
}
/**
* This class is a bean to hold the data defined in value editor extension
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public static class ValueEditorExtension
{
/** The name. */
public String name = null;
/** The icon. */
public ImageDescriptor icon = null;
/** The class name. */
public String className = null;
/** The syntax oids. */
public Collection<String> syntaxOids = new ArrayList<String>( 3 );
/** The attribute types. */
public Collection<String> attributeTypes = new ArrayList<String>( 3 );
/** The configuration element. */
private IConfigurationElement member = null;
/**
* @see Object#toString()
*/
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( '<' );
sb.append( name ).append( ", " );
sb.append( className );
if ( ( attributeTypes != null ) && ( attributeTypes.size() > 0 ) )
{
sb.append( ", {" );
boolean isFirst = true;
for ( String attributeType : attributeTypes )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " );
}
sb.append( attributeType );
}
sb.append( '}' );
}
if ( ( syntaxOids != null ) && ( syntaxOids.size() > 0 ) )
{
sb.append( ", {" );
boolean isFirst = true;
for ( String syntaxOid : syntaxOids )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " );
}
sb.append( syntaxOid );
}
sb.append( '}' );
}
sb.append( '>' );
return sb.toString();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/InPlaceTextValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/InPlaceTextValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
/**
* The default editor for string values.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class InPlaceTextValueEditor extends AbstractInPlaceStringValueEditor
{
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/StringValueEditorUtils.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/StringValueEditorUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.nio.charset.StandardCharsets;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
/**
* Common code used by {@link AbstractInPlaceStringValueEditor} and
* {@link AbstractDialogStringValueEditor}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class StringValueEditorUtils
{
static String getDisplayValue( Object rawValue )
{
if ( rawValue == null )
{
return IValueEditor.NULL;
}
else
{
return rawValue.toString();
}
}
static Object getRawValue( IValue value )
{
if ( value == null )
{
return null;
}
else if ( value.isString() )
{
return value.getStringValue();
}
else if ( value.isBinary() && StringValueEditorUtils.isEditable( value.getBinaryValue() ) )
{
return value.getStringValue();
}
else
{
return null;
}
}
static Object getStringOrBinaryValue( Object rawValue )
{
if ( rawValue instanceof String )
{
return rawValue;
}
else
{
return null;
}
}
static boolean isEditable( byte[] b )
{
if ( b == null )
{
return false;
}
return !( new String( b, StandardCharsets.UTF_8 ).contains( "\uFFFD" ) );
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogStringValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogStringValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
/**
* Abstract base class for value editors that handle string values
* in a dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractDialogStringValueEditor extends AbstractDialogValueEditor
{
/**
* Creates a new instance of AbstractDialogStringValueEditor.
*/
protected AbstractDialogStringValueEditor()
{
super();
}
/**
* {@inheritDoc}
*
* This implementation just returns the raw value
*/
public String getDisplayValue( IValue value )
{
Object obj = getRawValue( value );
return StringValueEditorUtils.getDisplayValue( obj );
}
/**
* {@inheritDoc}
*
* This implementation returns IValue.EMPTY_STRING_VALUE if
* the attribute is string.
*/
protected Object getEmptyRawValue( IAttribute attribute )
{
if ( attribute.isString() )
{
return IValue.EMPTY_STRING_VALUE;
}
else
{
return IValue.EMPTY_BINARY_VALUE;
}
}
/**
* {@inheritDoc}
*
* This implementation returns the string value
* of the given value.
*/
public Object getRawValue( IValue value )
{
return StringValueEditorUtils.getRawValue( value );
}
/**
* {@inheritDoc}
*
* This implementation always return the string value
* as String.
*/
public Object getStringOrBinaryValue( Object rawValue )
{
return StringValueEditorUtils.getStringOrBinaryValue( rawValue );
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/EntryValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/EntryValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.ldapbrowser.common.wizards.EditEntryWizard;
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.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* Special ValueEditor to edit an entry off-line in the {@link EditEntryWizard}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class EntryValueEditor extends CellEditor implements IValueEditor
{
/** The value to handle */
private Object value;
/** The parent composite, used to instantiate a new control */
private Composite parent;
/** The name of this value editor */
private String name;
/** The image of this value editor */
private ImageDescriptor imageDescriptor;
/** The value editor manager, used to get proper value editors */
protected ValueEditorManager valueEditorManager;
/**
* Creates a new instance of EntryValueEditor.
*
* @param parent the parent composite
* @param valueEditorManager the value editor manager, used to get
* proper value editors
*/
public EntryValueEditor( Composite parent, ValueEditorManager valueEditorManager )
{
super( parent );
this.parent = parent;
this.valueEditorManager = valueEditorManager;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, it doesn't create a control.
*/
protected Control createControl( Composite parent )
{
return null;
}
/**
* {@inheritDoc}
*
* Returns the value object stored in a member.
*/
protected final Object doGetValue()
{
return value;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, doesn't set focus.
*/
protected void doSetFocus()
{
}
/**
* {@inheritDoc}
*
* Stores the value object in a member.
*/
protected void doSetValue( Object value )
{
this.value = value;
}
/**
* {@inheritDoc}
*
* Opens the EditEntryWizard. Expects that an IEntry
* object is in value member.
*/
public void activate()
{
Object value = getValue();
if ( value instanceof IEntry )
{
IEntry entry = ( IEntry ) value;
if ( entry != null )
{
EditEntryWizard wizard = new EditEntryWizard( entry );
WizardDialog dialog = new WizardDialog( parent.getShell(), wizard );
dialog.setBlockOnOpen( true );
dialog.create();
dialog.open();
}
}
fireCancelEditor();
}
/**
* {@inheritDoc}
*
* Returns this.
*/
public CellEditor getCellEditor()
{
return this;
}
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue() returns a
* comma-separated list of all values.
*/
public String getDisplayValue( AttributeHierarchy attributeHierarchy )
{
List<IValue> valueList = new ArrayList<IValue>();
for ( IAttribute attribute : attributeHierarchy )
{
valueList.addAll( Arrays.asList( attribute.getValues() ) );
}
StringBuffer sb = new StringBuffer();
if ( valueList.size() > 1 )
{
sb.append( NLS.bind( Messages.getString( "EntryValueEditor.n_values" ), valueList.size() ) ); //$NON-NLS-1$
}
boolean isFirst = true;
for ( IValue value : valueList )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " );
}
IValueEditor vp = getValueEditor( value );
sb.append( vp.getDisplayValue( value ) );
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* This implementation gets the display value of the real value editor.
*/
public String getDisplayValue( IValue value )
{
IValueEditor vp = getValueEditor( value );
return vp.getDisplayValue( value );
}
private IValueEditor getValueEditor( IValue value )
{
IValueEditor vp = valueEditorManager.getCurrentValueEditor( value.getAttribute().getEntry(), value
.getAttribute().getDescription() );
// avoid recursion: unset the user selected value editor
if ( vp instanceof EntryValueEditor )
{
IValueEditor userSelectedValueEditor = valueEditorManager.getUserSelectedValueEditor();
valueEditorManager.setUserSelectedValueEditor( null );
vp = valueEditorManager.getCurrentValueEditor( value.getAttribute().getEntry(), value.getAttribute()
.getDescription() );
valueEditorManager.setUserSelectedValueEditor( userSelectedValueEditor );
}
return vp;
}
/**
* {@inheritDoc}
*
* Returns the entry.
*/
public Object getRawValue( AttributeHierarchy attributeHierarchy )
{
return attributeHierarchy.getEntry();
}
/**
* {@inheritDoc}
* @return
*/
public boolean hasValue( IValue value )
{
return value.getAttribute().getEntry() != null;
}
/**
* {@inheritDoc}
*
* Returns the entry.
*/
public Object getRawValue( IValue value )
{
return value.getAttribute().getEntry();
}
/**
* {@inheritDoc}
*
* Modification is performed by the wizard. No need to return a value.
*/
public Object getStringOrBinaryValue( Object rawValue )
{
return null;
}
/**
* {@inheritDoc}
*/
public void setValueEditorName( String name )
{
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getValueEditorName()
{
return name;
}
/**
* {@inheritDoc}
*/
public void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor )
{
this.imageDescriptor = imageDescriptor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getValueEditorImageDescriptor()
{
return imageDescriptor;
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/IValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/IValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import org.apache.directory.studio.ldapbrowser.core.model.AttributeHierarchy;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.widgets.Composite;
/**
* A ValueEditor knows how to display and edit values of a LDAP attribute.
* ValueEditors are used from the entry editor or search result editor
* to display and edit values in a user-friendly way.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface IValueEditor
{
/**
* Returns the string representation of the given attribute hierarchy
* presented to the user.
* <p>
* This method is called from the search result editor. A attribute hierarchy may
* contain multiple attributes each with multiple values. It is common that
* a ValueEditor returns a comma-separated list.
*
* @param attributeHierarchy the attribute hierarchy
* @return the string representation of the attribute hierarchy
*/
String getDisplayValue( AttributeHierarchy attributeHierarchy );
/**
* Returns the string representation of the given value
* presented to the user.
* <p>
* This method is called from the entry editor.
*
* @param value the value
* @return the string representation of the value
*/
String getDisplayValue( IValue value );
/**
* Returns the raw value if this value editor can handle the given
* attribute hierarchy. The returned value is used as input for
* the CellEditor returned by getCellEditor().
* <p>
* If this value editor can't handle the given attribute hierarchy
* it must return null.
* <p>
* Note: It is also possible that the attribute hierarchy doesn't contain
* a value. This means the value is up to be created.
* <p>
* This method is called from the search result editor. It is common
* to return null if the attribute hierarchy contains more than
* one value.
*
* @param attributeHierarchy the attribute hierarchy
* @return the raw value of the attribute hierarchy or null
*/
Object getRawValue( AttributeHierarchy attributeHierarchy );
/**
* Tells if there is a value
*
* @return true if there is a value, false if it's null.
*/
boolean hasValue( IValue value );
/**
* Returns the raw value if this value editor can handle the given
* value. The returned value is used as input for the CellEditor
* returned by getCellEditor().
* <p>
* If this value editor can't handle the given value it must
* return null.
* <p>
* Note: It is also possible that the value is empty!
* <p>
* This method is called from the entry editor.
*
* @param value the value
* @return the raw value of the value or null
*/
Object getRawValue( IValue value );
/**
* Returns the String or binary byte[] value of the given raw value.
* The return value is used to create, modify or delete the value
* in directory.
* <p>
* This method is called after editing has been finished. The
* given rawValue is the one returned by the CellEditor.
*
* @param rawValue the raw value return from cell editor
* @return the String or byte[] value
*/
Object getStringOrBinaryValue( Object rawValue );
/**
* Returns the editors name, previously set with
* setValueEditorName().
*
* @return the editors name
*/
String getValueEditorName();
/**
* Sets the editors name.
*
* This method is called during initialization of the
* value editor, the name specified in value editor
* extension is assigned.
*
* @param name the editors name
*/
void setValueEditorName( String name );
/**
* Returns the editors image, previously set with
* setValueEditorImageDescriptor().
*
* @return the editors image
*/
ImageDescriptor getValueEditorImageDescriptor();
/**
* Sets the editors image.
*
* This method is called during initialization of the
* value editor, the icon specified in value editor
* extension is assigned.
*
* @param imageDescriptor the editors image
*/
void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor );
/**
* Creates the control for this value editor under the given parent control.
*
* @param parent the parent control
*/
void create( Composite parent );
/**
* Disposes of this value editor and frees any associated SWT resources.
*/
void dispose();
/**
* Returns the JFace CellEditor that is able to handle values returned by
* one of the getRawValue() or the getEmptyRawValue() methods.
*
* The object returned by the CellEditor's getValue() method is
* then sent to the getStringOrBinary() method to get the
* directory value.
*
* @return the JFace CellEditor
*
*/
CellEditor getCellEditor();
// A constant for the emtpy string and null string.
String EMPTY = ""; //$NON-NLS-1$
String NULL = ">>> Error, the configured value editor can not handle this value! <<<"; //$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.common/src/main/java/org/apache/directory/studio/valueeditors/Messages.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/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.valueeditors;
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/RenameValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/RenameValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.studio.ldapbrowser.common.dialogs.RenameEntryDialog;
import org.apache.directory.studio.ldapbrowser.common.dialogs.SimulateRenameDialogImpl;
import org.apache.directory.studio.ldapbrowser.core.jobs.RenameEntryRunnable;
import org.apache.directory.studio.ldapbrowser.core.jobs.StudioBrowserJob;
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.IEntry;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* Special ValueEditor to rename an entry using the {@link RenameEntryDialog}.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class RenameValueEditor extends CellEditor implements IValueEditor
{
/** The value to handle */
private Object value;
/** The parent composite, used to instantiate a new control */
private Composite parent;
/** The name of this value editor */
private String name;
/** The image of this value editor */
private ImageDescriptor imageDescriptor;
/** The value editor manager, used to get proper value editors */
protected ValueEditorManager valueEditorManager;
/**
* Creates a new instance of RenameValueEditor.
*
* @param parent the parent composite
* @param valueEditorManager the value editor manager, used to get
* proper value editors
*/
public RenameValueEditor( Composite parent, ValueEditorManager valueEditorManager )
{
super( parent );
this.parent = parent;
this.valueEditorManager = valueEditorManager;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, it doesn't create a control.
*/
protected Control createControl( Composite parent )
{
return null;
}
/**
* {@inheritDoc}
*
* Returns the value object stored in a member.
*/
protected final Object doGetValue()
{
return value;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, doesn't set focus.
*/
protected void doSetFocus()
{
}
/**
* {@inheritDoc}
*
* Stores the value object in a member.
*/
protected void doSetValue( Object value )
{
this.value = value;
}
/**
* {@inheritDoc}
*
* Opens the RenameEntryDialog. Expects that an IEntry
* object is in value member.
*/
public void activate()
{
if ( getValue() instanceof IEntry )
{
IEntry entry = ( IEntry ) getValue();
RenameEntryDialog renameDialog = new RenameEntryDialog( parent.getShell(), entry );
if ( renameDialog.open() == Dialog.OK )
{
Rdn newRdn = renameDialog.getRdn();
if ( ( newRdn != null ) && !newRdn.equals( entry.getRdn() ) )
{
IEntry originalEntry = entry.getBrowserConnection().getEntryFromCache( entry.getDn() );
new StudioBrowserJob( new RenameEntryRunnable( originalEntry, newRdn,
new SimulateRenameDialogImpl( parent.getShell() ) ) ).execute();
}
}
}
fireCancelEditor();
}
/**
* {@inheritDoc}
*
* Returns this.
*/
public CellEditor getCellEditor()
{
return this;
}
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue() returns a
* comma-separated list of all values.
*/
public String getDisplayValue( AttributeHierarchy attributeHierarchy )
{
List<IValue> valueList = new ArrayList<IValue>();
for ( IAttribute attribute : attributeHierarchy )
{
valueList.addAll( Arrays.asList( attribute.getValues() ) );
}
StringBuffer sb = new StringBuffer();
if ( valueList.size() > 1 )
{
sb.append( NLS.bind( Messages.getString( "EntryValueEditor.n_values" ), valueList.size() ) ); //$NON-NLS-1$
}
boolean isFirst = true;
for ( IValue value : valueList )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " );
}
IValueEditor vp = getValueEditor( value );
sb.append( vp.getDisplayValue( value ) );
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* This implementation gets the display value of the real value editor.
*/
public String getDisplayValue( IValue value )
{
IValueEditor vp = getValueEditor( value );
return vp.getDisplayValue( value );
}
private IValueEditor getValueEditor( IValue value )
{
IValueEditor vp = valueEditorManager.getCurrentValueEditor( value.getAttribute().getEntry(), value
.getAttribute().getDescription() );
// avoid recursion: unset the user selected value editor
if ( vp instanceof RenameValueEditor )
{
IValueEditor userSelectedValueEditor = valueEditorManager.getUserSelectedValueEditor();
valueEditorManager.setUserSelectedValueEditor( null );
vp = valueEditorManager.getCurrentValueEditor( value.getAttribute().getEntry(), value.getAttribute()
.getDescription() );
valueEditorManager.setUserSelectedValueEditor( userSelectedValueEditor );
}
return vp;
}
/**
* {@inheritDoc}
*
* Returns the entry.
*/
public Object getRawValue( AttributeHierarchy attributeHierarchy )
{
return attributeHierarchy.getEntry();
}
/**
* {@inheritDoc}
*/
public boolean hasValue( IValue value )
{
return value.getAttribute().getEntry() != null;
}
/**
* {@inheritDoc}
*
* Returns the entry.
*/
public Object getRawValue( IValue value )
{
return value.getAttribute().getEntry();
}
/**
* {@inheritDoc}
*
* Modification is performed by the wizard. No need to return a value.
*/
public Object getStringOrBinaryValue( Object rawValue )
{
return null;
}
/**
* {@inheritDoc}
*/
public void setValueEditorName( String name )
{
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getValueEditorName()
{
return name;
}
/**
* {@inheritDoc}
*/
public void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor )
{
this.imageDescriptor = imageDescriptor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getValueEditorImageDescriptor()
{
return imageDescriptor;
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/MultivaluedValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/MultivaluedValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.ldapbrowser.common.dialogs.MultivaluedDialog;
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.IValue;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* Special ValueEditor to handle attributes with multiple values in a dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class MultivaluedValueEditor extends CellEditor implements IValueEditor
{
/** The value to handle */
private Object value;
/** The parent composite, used to instantiate a new control */
private Composite parent;
/** The name of this value editor */
private String name;
/** The image of this value editor */
private ImageDescriptor imageDescriptor;
/** The value editor manager, used to get proper value editors */
protected ValueEditorManager valueEditorManager;
/**
* Creates a new instance of MultivaluedValueEditor.
*
* @param parent the parent composite
* @param valueEditorManager the value editor manager, used to get
* proper value editors
*/
public MultivaluedValueEditor( Composite parent, ValueEditorManager valueEditorManager )
{
super( parent );
this.parent = parent;
this.valueEditorManager = valueEditorManager;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, it doesn't create a control.
*/
protected Control createControl( Composite parent )
{
return null;
}
/**
* {@inheritDoc}
*
* Returns the value object stored in a member.
*/
protected final Object doGetValue()
{
return value;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, doesn't set focus.
*/
protected void doSetFocus()
{
}
/**
* {@inheritDoc}
*
* Stores the value object in a member.
*/
protected void doSetValue( Object value )
{
this.value = value;
}
/**
* {@inheritDoc}
*
* Opens the MulitvaluedDialog. Expects that an AttributeHierarchy
* object is in value member.
*/
public void activate()
{
if ( getValue() instanceof AttributeHierarchy )
{
AttributeHierarchy ah = ( AttributeHierarchy ) getValue();
if ( ah != null )
{
MultivaluedDialog dialog = new MultivaluedDialog( parent.getShell(), ah );
dialog.open();
}
}
fireCancelEditor();
}
/**
* {@inheritDoc}
*
* Returns this.
*/
public CellEditor getCellEditor()
{
return this;
}
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue() returns a
* comma-separated list of all values.
*/
public String getDisplayValue( AttributeHierarchy attributeHierarchy )
{
List<IValue> valueList = new ArrayList<IValue>();
for ( IAttribute attribute : attributeHierarchy )
{
valueList.addAll( Arrays.asList( attribute.getValues() ) );
}
StringBuffer sb = new StringBuffer();
if ( valueList.size() > 1 )
{
sb.append( NLS.bind( Messages.getString( "EntryValueEditor.n_values" ), valueList.size() ) ); //$NON-NLS-1$
}
boolean isFirst = true;
for ( IValue value : valueList )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " );
}
IValueEditor vp = valueEditorManager.getCurrentValueEditor( value.getAttribute().getEntry(), value
.getAttribute().getDescription() );
sb.append( vp.getDisplayValue( value ) );
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* It doesn't make sense to use the MultivaluedValueEditor with a single value.
* Returns an empty string.
*/
public String getDisplayValue( IValue value )
{
return EMPTY; //$NON-NLS-1$
}
/**
* {@inheritDoc}
*
* Returns the attributeHierarchy.
*/
public Object getRawValue( AttributeHierarchy attributeHierarchy )
{
return attributeHierarchy;
}
/**
* {@inheritDoc}
*/
public boolean hasValue( IValue value )
{
return false;
}
/**
* {@inheritDoc}
*
* It doesn't make sense to use the MultivaluedValueEditor with a single value.
* Returns null.
*/
public Object getRawValue( IValue value )
{
return null;
}
/**
* {@inheritDoc}
*
* Modification is performed in the concrete single-ValueEditors. No need
* to return a value.
*/
public Object getStringOrBinaryValue( Object rawValue )
{
return null;
}
/**
* {@inheritDoc}
*/
public void setValueEditorName( String name )
{
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getValueEditorName()
{
return name;
}
/**
* {@inheritDoc}
*/
public void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor )
{
this.imageDescriptor = imageDescriptor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getValueEditorImageDescriptor()
{
return imageDescriptor;
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/HexValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/HexValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import org.apache.directory.studio.ldapbrowser.common.dialogs.HexDialog;
import org.eclipse.swt.widgets.Shell;
/**
* The default editor for binary values. Uses the HexDialog.
*
* The HexDialog is currently only able to save and load binary data
* to and from file. It is not possible to edit the data in the dialog
* directly.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class HexValueEditor extends AbstractDialogBinaryValueEditor
{
/**
* {@inheritDoc}
*
* This implementation opens the HexDialog.
*/
protected boolean openDialog( Shell shell )
{
Object value = getValue();
if ( value instanceof byte[] )
{
byte[] initialData = ( byte[] ) value;
HexDialog dialog = new HexDialog( shell, initialData );
if ( ( dialog.open() == HexDialog.OK ) && dialog.getData() != null )
{
setValue( dialog.getData() );
return true;
}
}
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/TextValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/TextValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import org.apache.directory.studio.ldapbrowser.common.dialogs.TextDialog;
import org.eclipse.swt.widgets.Shell;
/**
* The default editor for string values.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class TextValueEditor extends AbstractDialogStringValueEditor
{
/**
* {@inheritDoc}
*
* This implementation opens the TextDialog.
*/
@Override
public boolean openDialog( Shell shell )
{
Object value = getValue();
if ( value instanceof String )
{
TextDialog dialog = new TextDialog( shell, ( String ) value );
if ( ( dialog.open() == TextDialog.OK ) && ( dialog.getText() != null )
&& ( dialog.getText().length() != 0 ) )
{
setValue( dialog.getText() );
return true;
}
}
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/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogBinaryValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogBinaryValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldapbrowser.core.model.IValue;
import org.eclipse.osgi.util.NLS;
/**
* Abstract base class for value editors that handle binary values
* in a dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractDialogBinaryValueEditor extends AbstractDialogValueEditor
{
/**
* Creates a new instance of AbstractDialogBinaryValueEditor.
*/
protected AbstractDialogBinaryValueEditor()
{
}
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue just returns a note,
* that the value is binary and the size of the data.
*/
public String getDisplayValue( IValue value )
{
if ( showRawValues() )
{
return getPrintableString( value );
}
else
{
Object rawValue = getRawValue( value );
if ( rawValue == null )
{
return NULL;
}
else if ( rawValue instanceof byte[] )
{
byte[] data = ( byte[] ) rawValue;
return NLS.bind( Messages.getString( "AbstractDialogBinaryValueEditor.BinaryDateNBytes" ), //$NON-NLS-1$
data.length );
}
else
{
return Messages.getString( "AbstractDialogBinaryValueEditor.InvalidData" ); //$NON-NLS-1$
}
}
}
/**
* Helper method, returns a printable string if the value
* is binary.
*
* @param value the value
*
* @return the printable string
*/
public static String getPrintableString( IValue value )
{
if ( value == null )
{
return NULL; //$NON-NLS-1$
}
else if ( value.isBinary() )
{
byte[] data = value.getBinaryValue();
StringBuffer sb = new StringBuffer();
for ( int i = 0; ( data != null ) && ( i < data.length ) && ( i < 512 ); i++ )
{
if ( data[i] > 32 && data[i] < 127 )
sb.append( ( char ) data[i] );
else
sb.append( '.' );
}
return sb.toString();
}
else if ( value.isString() )
{
return value.getStringValue();
}
else
{
return NULL; //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* This implementation returns IValue.EMPTY_BINARY_VALUE if
* the attribute is binary.
*/
protected Object getEmptyRawValue( IAttribute attribute )
{
if ( attribute.isBinary() )
{
return IValue.EMPTY_BINARY_VALUE;
}
else
{
return null;
}
}
/**
* {@inheritDoc}
*
* This implementation returns the binary (byte[]) value
* of the given value.
*/
public Object getRawValue( IValue value )
{
if ( value == null )
{
return null;
}
else if ( value.isString() )
{
return value.getBinaryValue();
}
else if ( value.isBinary() )
{
return value.getBinaryValue();
}
else
{
return null;
}
}
/**
* {@inheritDoc}
*
* This implementation always return the binary value
* as byte[].
*/
public Object getStringOrBinaryValue( Object rawValue )
{
if ( rawValue instanceof byte[] )
{
return rawValue;
}
else
{
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.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractDialogValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
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.IValue;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
/**
* Abstract base class for value editors that handle values
* in a dialog.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractDialogValueEditor extends CellEditor implements IValueEditor
{
/** The value to handle */
private Object value;
/** The shell, used to open the editor */
private Shell shell;
/** The name of this value editor */
private String name;
/** The image of this value editor */
private ImageDescriptor imageDescriptor;
/**
*
* Creates a new instance of AbstractDialogEditor.
*/
protected AbstractDialogValueEditor()
{
}
/**
* Returns true if the user wishes to show raw values rather than
* user-friendly values. If true the getDisplayValue() methods
* should not modify the value.
*
* @return true if raw values should be displayed
*/
protected boolean showRawValues()
{
return BrowserCommonActivator.getDefault().getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES );
}
/**
* {@inheritDoc}
*
* This implementation simple returns itself.
*/
public CellEditor getCellEditor()
{
return this;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, it doesn't create a control.
* It just extracts and saves the shell reference from parent.
*/
protected final Control createControl( Composite parent )
{
this.shell = parent.getShell();
return null;
}
/**
* {@inheritDoc}
*
* This is a dialog editor, doesn't set focus.
*/
protected final void doSetFocus()
{
}
/**
* {@inheritDoc}
*
* Returns the value object stored in a member.
*/
protected final Object doGetValue()
{
return this.value;
}
/**
* {@inheritDoc}
*
* Stores the value object in a member.
*/
protected final void doSetValue( Object value )
{
if ( value instanceof IValue.EmptyValue )
{
IValue.EmptyValue emptyValue = ( IValue.EmptyValue ) value;
if ( emptyValue.isBinary() )
{
value = emptyValue.getBinaryValue();
}
else
{
value = emptyValue.getStringValue();
}
}
this.value = value;
}
/**
* {@inheritDoc}
*
* The activate method is called from the JFace framework
* to start editing.
*/
public final void activate()
{
boolean save = this.openDialog( shell );
//doSetValue( newValue );
if ( !save || this.value == null )
{
this.value = null;
fireCancelEditor();
}
else
{
fireApplyEditorValue();
deactivate();
}
}
/**
* Opens the edit dialog.
* Call getValue() to get the current value to edit.
* Call setValue() to set the new value after editing.
*
* @param shell The shell to use to open the dialog
* @return true if the new value should be stored, false
* to cancel the editor.
*/
protected abstract boolean openDialog( Shell shell );
/**
* Returns a raw value that represents an empty value.
*
* @param attribute the attribute
* @return a raw value that represents an empty value
*/
protected abstract Object getEmptyRawValue( IAttribute attribute );
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue() returns a
* comma-separated list of all values.
*/
public String getDisplayValue( AttributeHierarchy attributeHierarchy )
{
if ( attributeHierarchy == null )
{
return NULL; //$NON-NLS-1$
}
List<IValue> valueList = new ArrayList<IValue>();
for ( IAttribute attribute : attributeHierarchy )
{
valueList.addAll( Arrays.asList( attribute.getValues() ) );
}
StringBuffer sb = new StringBuffer();
for ( Iterator<IValue> it = valueList.iterator(); it.hasNext(); )
{
IValue value = it.next();
sb.append( getDisplayValue( value ) );
if ( it.hasNext() )
{
sb.append( ", " ); //$NON-NLS-1$
}
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* This implementation calls getEmptyRawValue(IAttribute) if there are no values
* in attributeHierarchy and getRawValue(IValue) if attributeHierarchy
* contains exactly one value. Otherwise null is returned.
*/
public Object getRawValue( AttributeHierarchy attributeHierarchy )
{
if ( attributeHierarchy == null )
{
return null;
}
else if ( attributeHierarchy.size() == 1 && attributeHierarchy.getAttribute().getValueSize() == 0 )
{
return getEmptyRawValue( attributeHierarchy.getAttribute() );
}
else if ( attributeHierarchy.size() == 1 && attributeHierarchy.getAttribute().getValueSize() == 1 )
{
return getRawValue( attributeHierarchy.getAttribute().getValues()[0] );
}
else
{
return null;
}
}
/**
* {@inheritDoc}
*/
public boolean hasValue( IValue value )
{
return ( value != null ) && ( value.isString() || value.isBinary() );
}
/**
* {@inheritDoc}
*/
public void setValueEditorName( String name )
{
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getValueEditorName()
{
return name;
}
/**
* {@inheritDoc}
*/
public void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor )
{
this.imageDescriptor = imageDescriptor;
}
/**
* {@inheritDoc}
*/
public ImageDescriptor getValueEditorImageDescriptor()
{
return imageDescriptor;
}
}
| 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.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractInPlaceStringValueEditor.java | plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/valueeditors/AbstractInPlaceStringValueEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.valueeditors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
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.IValue;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TextCellEditor;
/**
*
* Abstract base class for value editors that handle string values
* within the table or tree control.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class AbstractInPlaceStringValueEditor extends TextCellEditor implements IValueEditor
{
/** The name of this value editor */
private String name;
/** The image of this value editor */
private ImageDescriptor imageDescriptor;
/**
* Creates a new instance of AbstractInPlaceStringValueEditor.
*/
protected AbstractInPlaceStringValueEditor()
{
super();
}
/**
* Returns true if the user wishes to show raw values rather than
* user-friendly values. If true the getDisplayValue() methods
* should not modify the value.
*
* @return true if raw values should be displayed
*/
protected boolean showRawValues()
{
return BrowserCommonActivator.getDefault().getPreferenceStore().getBoolean(
BrowserCommonConstants.PREFERENCE_SHOW_RAW_VALUES );
}
/**
* {@inheritDoc}
*
* This implementation of getDisplayValue() returns a
* comma-separated list of all values.
*/
@Override
public String getDisplayValue( AttributeHierarchy attributeHierarchy )
{
if ( attributeHierarchy == null )
{
return NULL;
}
List<IValue> valueList = new ArrayList<>();
for ( IAttribute attribute : attributeHierarchy )
{
valueList.addAll( Arrays.asList( attribute.getValues() ) );
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for ( IValue value : valueList )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( ", " ); //$NON-NLS-1$
}
sb.append( getDisplayValue( value ) );
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* This implementation just returns the raw value
*/
@Override
public String getDisplayValue( IValue value )
{
Object obj = getRawValue( value );
return StringValueEditorUtils.getDisplayValue( obj );
}
/**
* {@inheritDoc}
*
* This implementation returns IValue.EMPTY_xx_VALUE if there are no values
* in attributeHierarchy or calls getRawValue(IValue) if attributeHierarchy
* contains exactly one value. Otherwise null is returned.
*/
@Override
public Object getRawValue( AttributeHierarchy attributeHierarchy )
{
if ( ( attributeHierarchy != null ) && ( attributeHierarchy.size() == 1 ) )
{
if ( attributeHierarchy.getAttribute().getValueSize() == 0 )
{
if ( attributeHierarchy.getAttribute().isString() )
{
return IValue.EMPTY_STRING_VALUE;
}
else
{
return IValue.EMPTY_BINARY_VALUE;
}
}
else if ( attributeHierarchy.getAttribute().getValueSize() == 1 )
{
return getRawValue( attributeHierarchy.getAttribute().getValues()[0] );
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasValue( IValue value )
{
return ( value != null ) && ( value.isString() || value.isBinary() );
}
/**
* {@inheritDoc}
*
* This implementation returns the string value
* of the given value.
*/
@Override
public Object getRawValue( IValue value )
{
return StringValueEditorUtils.getRawValue( value );
}
/**
* {@inheritDoc}
*
* This implementation always return the string value
* as String.
*/
@Override
public Object getStringOrBinaryValue( Object rawValue )
{
return StringValueEditorUtils.getStringOrBinaryValue( rawValue );
}
/**
* {@inheritDoc}
*/
@Override
public CellEditor getCellEditor()
{
return this;
}
/**
* {@inheritDoc}
*/
@Override
protected Object doGetValue()
{
if ( EMPTY.equals( text.getText() ) )
{
return null;
}
else
{
return text.getText();
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doSetValue( Object value )
{
if ( value instanceof IValue.EmptyValue )
{
super.doSetValue( ( ( IValue.EmptyValue ) value ).getStringValue() );
}
else
{
super.doSetValue( value );
}
}
/**
* {@inheritDoc}
*/
@Override
public void setValueEditorName( String name )
{
this.name = name;
}
/**
* {@inheritDoc}
*/
@Override
public String getValueEditorName()
{
return name;
}
/**
* {@inheritDoc}
*/
@Override
public void setValueEditorImageDescriptor( ImageDescriptor imageDescriptor )
{
this.imageDescriptor = imageDescriptor;
}
/**
* {@inheritDoc}
*/
@Override
public ImageDescriptor getValueEditorImageDescriptor()
{
return imageDescriptor;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/model/lines/LdifAttrValLineTest.java | plugins/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/model/lines/LdifAttrValLineTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.junit.jupiter.api.Test;
public class LdifAttrValLineTest
{
@Test
public void testToFormattedStringSimple()
{
LdifAttrValLine line = LdifAttrValLine.create( "cn", "abc" ); //$NON-NLS-1$ //$NON-NLS-2$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = line.toFormattedString( formatParameters );
assertEquals( formattedString, "cn: abc\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringLineWrap()
{
LdifAttrValLine line = LdifAttrValLine.create( "cn", //$NON-NLS-1$
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = line.toFormattedString( formatParameters );
assertEquals( formattedString,
"cn: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvw\n xyzabcdefghijklmnopqrstuvwxy\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringNoSpaceAfterColon()
{
LdifAttrValLine line = LdifAttrValLine.create( "cn", "abc" ); //$NON-NLS-1$ //$NON-NLS-2$
LdifFormatParameters formatParameters = new LdifFormatParameters( false, 78, "\n" ); //$NON-NLS-1$
String formattedString = line.toFormattedString( formatParameters );
assertEquals( formattedString, "cn:abc\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringBase64()
{
LdifAttrValLine line = LdifAttrValLine.create( "cn", "\u00e4\u00f6\u00fc" ); //$NON-NLS-1$ //$NON-NLS-2$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = line.toFormattedString( formatParameters );
assertEquals( formattedString, "cn:: w6TDtsO8\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedString_DIRSERVER_285()
{
LdifAttrValLine line = LdifAttrValLine.create( "cn", "abc::def:<ghi" ); //$NON-NLS-1$ //$NON-NLS-2$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = line.toFormattedString( formatParameters );
assertEquals( formattedString, "cn: abc::def:<ghi\n" ); //$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/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/model/lines/LdifDnLineTest.java | plugins/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/model/lines/LdifDnLineTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.junit.jupiter.api.Test;
public class LdifDnLineTest
{
@Test
public void testToFormattedStringSimple()
{
LdifDnLine dnLine = LdifDnLine.create( "cn=abc,ou=department,o=org,dc=example,dc=com" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = dnLine.toFormattedString( formatParameters );
assertEquals( formattedString, "dn: cn=abc,ou=department,o=org,dc=example,dc=com\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringNewline()
{
LdifDnLine dnLine = LdifDnLine.create( "cn=abc,ou=department,o=org,dc=example,dc=com" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\r\n" ); //$NON-NLS-1$
String formattedString = dnLine.toFormattedString( formatParameters );
assertEquals( formattedString, "dn: cn=abc,ou=department,o=org,dc=example,dc=com\r\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringLineWrap()
{
LdifDnLine dnLine = LdifDnLine
.create( "cn=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy,ou=department,o=org,dc=example,dc=com" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = dnLine.toFormattedString( formatParameters );
assertEquals( formattedString, "dn: cn=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy,ou=department,o=org" //$NON-NLS-1$
+ "\n ,dc=example,dc=com\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringNoSpaceAfterColon()
{
LdifDnLine dnLine = LdifDnLine.create( "cn=abc,ou=department,o=org,dc=example,dc=com" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( false, 78, "\n" ); //$NON-NLS-1$
String formattedString = dnLine.toFormattedString( formatParameters );
assertEquals( formattedString, "dn:cn=abc,ou=department,o=org,dc=example,dc=com\n" ); //$NON-NLS-1$
}
@Test
public void testToFormattedStringBase64()
{
LdifDnLine dnLine = LdifDnLine.create( "cn=\u00e4\u00f6\u00fc,ou=department,o=org,dc=example,dc=com" ); //$NON-NLS-1$
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" ); //$NON-NLS-1$
String formattedString = dnLine.toFormattedString( formatParameters );
assertEquals( formattedString, "dn:: Y249w6TDtsO8LG91PWRlcGFydG1lbnQsbz1vcmcsZGM9ZXhhbXBsZSxkYz1jb20=\n" ); //$NON-NLS-1$
}
/**
* Test for DIRSTUDIO-598
* (Base64 encoded Dn marked as invalid in LDIF editor)
*/
@Test
public void testIsValid()
{
LdifDnLine dnLine = LdifDnLine.create( "cn=\\#\\\\\\+\\, \\\"\u00f6\u00e9\\\",ou=users,ou=system" ); //$NON-NLS-1$
assertTrue( dnLine.isValid() );
assertEquals( "Y249XCNcXFwrXCwgXCLDtsOpXCIsb3U9dXNlcnMsb3U9c3lzdGVt", dnLine.getUnfoldedDn() ); //$NON-NLS-1$
assertEquals( "cn=\\#\\\\\\+\\, \\\"\u00f6\u00e9\\\",ou=users,ou=system", dnLine.getValueAsString() ); //$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/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/parser/LdifParserTest.java | plugins/ldifparser/src/test/java/org/apache/directory/studio/ldifparser/parser/LdifParserTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.parser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.model.LdifFile;
import org.junit.jupiter.api.Test;
public class LdifParserTest
{
@Test
public void testLdifNull()
{
String ldif = null;
LdifParser parser = new LdifParser();
LdifFile model = parser.parse( ldif );
assertEquals( 0, model.getRecords().length );
}
@Test
public void testParseAndFormatWithLdifWindowsLineBreak()
{
String ldif = ""
+ "dn: cn=foo,ou=users,ou=system\r\n"
+ "cn: foo\r\n"
+ "description: 12345678901234567890123456789012345678901234567890123456789012345\r\n"
+ " 678901234567890\r\n"
+ "description:: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4\r\n"
+ " OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAK\r\n";
LdifParser parser = new LdifParser();
LdifFile model = parser.parse( ldif );
assertEquals( 1, model.getRecords().length );
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\r\n" );
String formatted = model.toFormattedString( formatParameters );
assertEquals( ldif, formatted );
}
@Test
public void testParseAndFormatWithLdifUnixLineBreak()
{
String ldif = ""
+ "dn: cn=foo,ou=users,ou=system\n"
+ "cn: foo\n"
+ "description: 12345678901234567890123456789012345678901234567890123456789012345\n"
+ " 678901234567890\n"
+ "description:: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4\n"
+ " OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAK\n";
LdifParser parser = new LdifParser();
LdifFile model = parser.parse( ldif );
assertEquals( 1, model.getRecords().length );
LdifFormatParameters formatParameters = new LdifFormatParameters( true, 78, "\n" );
String formatted = model.toFormattedString( formatParameters );
assertEquals( ldif, formatted );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifFormatParameters.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifFormatParameters.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser;
public class LdifFormatParameters
{
/** The default LDIF format parameters */
public static final LdifFormatParameters DEFAULT = new LdifFormatParameters();
private boolean spaceAfterColon;
private int lineWidth;
private String lineSeparator;
/**
* Creates a new instance of LdifFormatParameters with the following parameters:
* <ul>
* <li>Space after colon
* <li>Line width 78
* <li>The system specific line separator
* </ul>
*/
private LdifFormatParameters()
{
this.spaceAfterColon = true;
this.lineWidth = LdifParserConstants.LINE_WIDTH;
this.lineSeparator = LdifParserConstants.LINE_SEPARATOR;
}
public LdifFormatParameters( boolean spaceAfterColon, int lineWidth, String lineSeparator )
{
this.spaceAfterColon = spaceAfterColon;
this.lineWidth = lineWidth;
this.lineSeparator = lineSeparator;
}
public boolean isSpaceAfterColon()
{
return spaceAfterColon;
}
public void setSpaceAfterColon( boolean spaceAfterColon )
{
this.spaceAfterColon = spaceAfterColon;
}
public int getLineWidth()
{
return lineWidth;
}
public void setLineWidth( int lineWidth )
{
this.lineWidth = lineWidth;
}
public String getLineSeparator()
{
return lineSeparator;
}
public void setLineSeparator( String lineSeparator )
{
this.lineSeparator = lineSeparator;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifParserConstants.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifParserConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser;
/**
* Constants for the LDIF Parser.
* Final reference -> class shouldn't be extended
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class LdifParserConstants
{
/**
* 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 LdifParserConstants()
{
}
/** The system specific line separator. */
public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); //$NON-NLS-1$
/** The default line width, value is 78. */
public static final int LINE_WIDTH = 78;
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifUtils.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/LdifUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
* Utilities for LDAP related encoding and decoding.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifUtils
{
/**
* Encodes the given string to UTF-8
*
* @param s the string to encode
*
* @return the byte[] the encoded value
*/
public static byte[] utf8encode( String s )
{
try
{
return s.getBytes( "UTF-8" ); //$NON-NLS-1$
}
catch ( UnsupportedEncodingException e )
{
return s.getBytes();
}
}
/**
* Encodes the given string into URL format.
*
* @param s the string to encode
*
* @return the string the URL encoded string
*/
public static String urlEncode( String s )
{
try
{
return URLEncoder.encode( s, "UTF-8" ); //$NON-NLS-1$
}
catch ( UnsupportedEncodingException e )
{
return s;
}
}
/**
* Encodes the given byte array using BASE-64 encoding.
*
* @param b the b the byte array to encode
*
* @return the BASE-64 encoded string
*/
public static String base64encode( byte[] b )
{
return utf8decode( Base64.encodeBase64( b ) );
}
/**
* Encodes the given byte array to a sequence of
* its hex values.
*
* @param data the data to encode
* @return the HEX encoded string
*/
public static String hexEncode( byte[] data )
{
if ( data == null )
{
return null;
}
char[] c = Hex.encodeHex( data );
String s = new String( c );
return s;
}
/**
* Decodes the given UTF-8 byte array to an string.
*
* @param b the b the byte array to decode
*
* @return the decoded string
*/
public static String utf8decode( byte[] b )
{
try
{
return new String( b, "UTF-8" ); //$NON-NLS-1$
}
catch ( UnsupportedEncodingException e )
{
return new String( b );
}
}
/**
* Decodes the given BASE-64 encoded string to its
* bytes presentation.
*
* @param s the s the BASE-64 encoded string
*
* @return the byte[] the decoded byte array
*/
public static byte[] base64decodeToByteArray( String s )
{
return Base64.decodeBase64( utf8encode( s ) );
}
/**
* Checks if the given distinguished name must be encoded.
*
* @param dn the dn to check
*
* @return true, if must encode Dn
*/
public static boolean mustEncodeDN( String dn )
{
return mustEncode( dn );
}
/**
* Checks if the given string must be encoded to be
* used in an LDIF.
*
* @param value the value to check
*
* @return true, if must encode
*/
public static boolean mustEncode( String value )
{
if ( ( value == null ) || ( value.length() < 1 ) )
{
return false;
}
if ( value.startsWith( " " ) || value.startsWith( ":" ) || value.startsWith( "<" ) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
return true;
}
if ( value.endsWith( " " ) ) //$NON-NLS-1$
{
return true;
}
for ( int i = 0; i < value.length(); i++ )
{
if ( ( value.charAt( i ) == '\r' ) || ( value.charAt( i ) == '\n' ) || ( value.charAt( i ) == '\u0000' )
|| ( value.charAt( i ) > '\u007F' ) )
{
return true;
}
}
return false;
}
/**
* Convert all the '\n' and '\r' to a String
* @param s The String to be converted
* @return The resulting String
*/
public static String convertNlRcToString( String s )
{
if ( s == null )
{
return "";
}
// Worth case, the new string is three times bigger
char[] result = new char[s.length() * 3];
int pos = 0;
for ( char c : s.toCharArray() )
{
if ( c == '\n' )
{
result[pos++] = '\\';
result[pos++] = 'n';
}
else if ( c == '\r' )
{
result[pos++] = '\\';
result[pos++] = 'r';
}
else
{
result[pos++] = c;
}
}
return new String( result, 0, pos );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifEnumeration.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifEnumeration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.studio.ldifparser.model.container.LdifContainer;
/**
* A LdifContainer enumeration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface LdifEnumeration
{
/**
* @return true if this enumeration has more elements.
*/
boolean hasNext() throws LdapException;
/**
*
* @return the next LDIF container or null if hasNext() returns false.
*/
LdifContainer next() throws LdapException;
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifFile.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifFile.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
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.LdifModSpec;
import org.apache.directory.studio.ldifparser.model.container.LdifRecord;
/**
* A LDIF file, as we manipulate it in Studio. It's a list of LdifContainer.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifFile implements Serializable
{
/** The serialVersionUID */
private static final long serialVersionUID = 846864138240517008L;
/** The list of container constituting this LDIF file */
private List<LdifContainer> containerList = new ArrayList<LdifContainer>();
/** A flag which is set if a LdifChange is added into the LdifFile */
private boolean hasChanges = false;
/**
* Create an instance of a LdifFile.
*/
public LdifFile()
{
}
/**
* Tells if the LDIF file is a Content LDIF (there will be no changes)
*
* @return true if the LDIF file does not contain any change
*/
public boolean isContentType()
{
return !hasChanges;
}
/**
* Tells if the LDIF file is a Change LDIF (there will be no changes)
*
* @return true if the LDIF file is a Change LDIF
*/
public boolean isChangeType()
{
return hasChanges;
}
/**
* Add a new LdifContainer to the LdifFile
*
* @param container The added LdifContainer
*/
public void addContainer( LdifContainer container )
{
containerList.add( container );
if ( container instanceof LdifChangeRecord )
{
hasChanges = true;
}
}
/**
* @return A list of LdifContainers, including version, comments, records and unknown
*/
public List<LdifContainer> getContainers()
{
return containerList;
}
/**
* @return An array of LdifRecords (even invalid), no LdifVersion, LdifComments, or LdifUnknown
*/
public LdifRecord[] getRecords()
{
List<LdifRecord> recordList = new ArrayList<LdifRecord>();
for ( LdifContainer container : containerList )
{
if ( container instanceof LdifRecord )
{
recordList.add( ( LdifRecord ) container );
}
}
return recordList.toArray( new LdifRecord[recordList.size()] );
}
/**
* @return the last LdifContainer, or null
*/
public LdifContainer getLastContainer()
{
if ( containerList.isEmpty() )
{
return null;
}
else
{
return containerList.get( containerList.size() - 1 );
}
}
public String toRawString()
{
StringBuilder sb = new StringBuilder();
for ( LdifContainer container : containerList )
{
sb.append( container.toRawString() );
}
return sb.toString();
}
public String toFormattedString( LdifFormatParameters formatParameters )
{
StringBuilder sb = new StringBuilder();
for ( LdifContainer ldifContainer : containerList )
{
sb.append( ldifContainer.toFormattedString( formatParameters ) );
}
return sb.toString();
}
public String toString()
{
StringBuilder sb = new StringBuilder();
for ( LdifContainer ldifContainer : containerList )
{
sb.append( ldifContainer );
}
return sb.toString();
}
/**
* Retrieve the container at the given offset
*
* @param model The Ldif file containing the containers
* @param offset The position in the file
* @return The container if we found one
*/
public static LdifContainer getContainer( LdifFile model, int offset )
{
if ( ( model == null ) || ( offset < 0 ) )
{
return null;
}
List<LdifContainer> containers = model.getContainers();
if ( containers.size() > 0 )
{
for ( LdifContainer ldifContainer : containers )
{
if ( ( ldifContainer.getOffset() <= offset ) &&
( offset < ldifContainer.getOffset() + ldifContainer.getLength() ) )
{
return ldifContainer;
}
}
}
return null;
}
public static LdifModSpec getInnerContainer( LdifContainer container, int offset )
{
if ( ( container == null ) ||
( offset < container.getOffset() ) ||
( offset > container.getOffset() + container.getLength() ) )
{
return null;
}
LdifModSpec innerContainer = null;
LdifPart[] parts = container.getParts();
if ( parts.length > 0 )
{
for ( LdifPart ldifPart : parts )
{
int start = ldifPart.getOffset();
int end = ldifPart.getOffset() + ldifPart.getLength();
if ( ( start <= offset ) && ( offset < end ) && ( ldifPart instanceof LdifModSpec ) )
{
innerContainer = ( LdifModSpec ) ldifPart;
break;
}
}
}
return innerContainer;
}
public static LdifContainer[] getContainers( LdifFile model, int offset, int length )
{
if ( ( model == null ) || ( offset < 0 ) )
{
return null;
}
List<LdifContainer> containerList = new ArrayList<LdifContainer>();
List<LdifContainer> containers = model.getContainers();
if ( containers.size() > 0 )
{
for ( LdifContainer container : containers )
{
int containerOffset = container.getOffset();
if ( ( offset < containerOffset + container.getLength() ) &&
( offset + length > containerOffset ) )
{
containerList.add( container );
}
}
}
return containerList.toArray( new LdifContainer[containerList.size()] );
}
public static LdifPart[] getParts( LdifFile model, int offset, int length )
{
if ( ( model == null ) || ( offset < 0 ) )
{
return null;
}
List<LdifContainer> containers = model.getContainers();
return getParts( containers, offset, length );
}
public static LdifPart[] getParts( List<LdifContainer> containers, int offset, int length )
{
if ( ( containers == null ) || ( offset < 0 ) )
{
return null;
}
List<LdifPart> partList = new ArrayList<LdifPart>();
for ( LdifContainer ldifContainer : containers )
{
int ldifContainerOffset = ldifContainer.getOffset();
if ( ( offset < ldifContainerOffset + ldifContainer.getLength() )
&& ( offset + length >= ldifContainerOffset ) )
{
LdifPart[] ldifParts = ldifContainer.getParts();
LdifPart previousLdifPart = null;
for ( LdifPart ldifPart : ldifParts )
{
int ldifPartOffset = ldifPart.getOffset();
if ( ( offset < ldifPartOffset + ldifPart.getLength() ) && ( offset + length >= ldifPartOffset ) )
{
if ( ldifPart instanceof LdifModSpec )
{
LdifModSpec spec = ( LdifModSpec ) ldifPart;
List<LdifContainer> newLdifContainer = new ArrayList<LdifContainer>();
newLdifContainer.add( spec );
partList.addAll( Arrays.asList( getParts( newLdifContainer, offset, length ) ) );
}
else
{
if ( ( ldifPart instanceof LdifInvalidPart ) && ( previousLdifPart != null ) )
{
ldifPart = previousLdifPart;
}
partList.add( ldifPart );
}
previousLdifPart = ldifPart;
}
}
}
}
return partList.toArray( new LdifPart[partList.size()] );
}
public static LdifPart getContainerContent( LdifContainer container, int offset )
{
int containerOffset = container.getOffset();
if ( ( container == null ) || ( offset < containerOffset ) ||
( offset > containerOffset + container.getLength() ) )
{
return null;
}
LdifPart part = null;
LdifPart[] parts = container.getParts();
if ( parts.length > 0 )
{
for ( LdifPart ldifPart : parts )
{
int start = ldifPart.getOffset();
int end = ldifPart.getOffset() + ldifPart.getLength();
if ( ( start <= offset ) && ( offset < end ) )
{
if ( ldifPart instanceof LdifModSpec )
{
part = getContainerContent( ( LdifModSpec ) ldifPart, offset );
}
break;
}
}
}
return part;
}
public void replace( LdifContainer[] oldContainers, List<LdifContainer> newContainers )
{
// find index
int index = 0;
if ( oldContainers.length > 0 )
{
index = containerList.indexOf( oldContainers[0] );
}
// remove old containers
int removeLength = 0;
int removeOffset = 0;
if ( oldContainers.length > 0 )
{
removeOffset = oldContainers[0].getOffset();
for ( int i = 0; i < oldContainers.length; i++ )
{
containerList.remove( index );
removeLength += oldContainers[i].getLength();
}
}
// add new containers
int insertLength = 0;
int pos = 0;
for ( LdifContainer ldifContainer : newContainers )
{
ldifContainer.adjustOffset( removeOffset );
insertLength += ldifContainer.getLength();
containerList.add( index + pos, ldifContainer );
pos++;
}
// adjust offset of following containers
int adjust = insertLength - removeLength;
for ( int i = index + newContainers.size(); i < containerList.size(); i++ )
{
LdifContainer container = containerList.get( i );
container.adjustOffset( adjust );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifInvalidPart.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifInvalidPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.LdifUtils;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class LdifInvalidPart implements LdifPart
{
private int offset;
private String unknown;
public LdifInvalidPart( int offset, String unknown )
{
this.offset = offset;
this.unknown = unknown;
}
public int getOffset()
{
return offset;
}
public int getLength()
{
return toRawString().length();
}
/**
* @return The raw version of a Invalid part : the invalid String, unchanged
*/
public String toRawString()
{
return unknown;
}
public String toFormattedString( LdifFormatParameters formatParameters )
{
return unknown;
}
public String toString()
{
String text = toRawString();
text = LdifUtils.convertNlRcToString( text );
return getClass().getName() + " (" + getOffset() + "," + getLength() + "): '" + text + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
public boolean isValid()
{
return false;
}
public String getInvalidString()
{
return "Unexpected Token";
}
public void adjustOffset( int adjust )
{
offset += adjust;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifPart.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
/**
* An interface representing a part of a LDIF file
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface LdifPart
{
/**
* @return The position of this part in the LDIF file
*/
int getOffset();
/**
* @return The length of this part
*/
int getLength();
/**
* Tells if the part is valid or not
*
* @return <code>true</code> if the part is valid.
*/
boolean isValid();
String getInvalidString();
String toRawString();
String toFormattedString( LdifFormatParameters formatParameters );
void adjustOffset( int adjust );
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifEOFPart.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/LdifEOFPart.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class LdifEOFPart implements LdifPart
{
/** The offset of this part */
private int offset;
public LdifEOFPart( int offset )
{
this.offset = offset;
}
public int getOffset()
{
return offset;
}
public int getLength()
{
return 0;
}
/**
* @return The raw version of a EOF part : an empty String
*/
public String toRawString()
{
return ""; //$NON-NLS-1$
}
/**
* @return The formatted version of a EOF part : an empty String
*/
public String toFormattedString( LdifFormatParameters formatParameters )
{
return ""; //$NON-NLS-1$
}
public String toString()
{
return getClass().getName() + " (" + getOffset() + "," + getLength() + "): ''"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
public boolean isValid()
{
return true;
}
public String getInvalidString()
{
return ""; //$NON-NLS-1$
}
public void adjustOffset( int adjust )
{
offset += adjust;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifEOFContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifEOFContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.LdifEOFPart;
/**
* A LDIF container for the LDIF EOF
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifEOFContainer extends LdifContainer
{
public LdifEOFContainer( LdifEOFPart eofPart )
{
super( eofPart );
}
public boolean isValid()
{
return getLastPart() instanceof LdifEOFPart;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifInvalidContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifInvalidContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.LdifInvalidPart;
/**
* A LDIF container for invalid LDIF lines
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifInvalidContainer extends LdifContainer
{
public LdifInvalidContainer( LdifInvalidPart invalid )
{
super( invalid );
}
public boolean isValid()
{
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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.LdifEOFPart;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine;
/**
* A LDIF container for a LDIF record (change or content)
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class LdifRecord extends LdifContainer
{
protected LdifRecord( LdifDnLine dn )
{
super( dn );
}
public void addComment( LdifCommentLine comment )
{
if ( comment == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( comment );
}
public void finish( LdifSepLine sep )
{
if ( sep == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( sep );
}
public void finish( LdifEOFPart eof )
{
if ( eof == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( eof );
}
public LdifDnLine getDnLine()
{
return ( LdifDnLine ) ldifParts.get( 0 );
}
public LdifSepLine getSepLine()
{
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifSepLine )
{
return ( LdifSepLine ) ldifPart;
}
}
return null;
}
public String getInvalidString()
{
LdifDnLine dnLine = getDnLine();
LdifSepLine sepLine = getSepLine();
if ( dnLine == null )
{
return "Record must start with Dn";
}
else if ( !dnLine.isValid() )
{
return dnLine.getInvalidString();
}
if ( sepLine == null )
{
return "Record must end with an empty line";
}
else if ( !sepLine.isValid() )
{
return sepLine.getInvalidString();
}
return super.getInvalidString();
}
protected boolean isAbstractValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
LdifPart lastPart = getLastPart();
return getDnLine().isValid() && ( ( lastPart instanceof LdifSepLine ) || ( lastPart instanceof LdifEOFPart ) )
&& lastPart.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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifContentRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifContentRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
/**
* A LDIF container for content records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifContentRecord extends LdifRecord
{
public LdifContentRecord( LdifDnLine dn )
{
super( dn );
}
public void addAttrVal( LdifAttrValLine attrVal )
{
if ( attrVal == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( attrVal );
}
public LdifAttrValLine[] getAttrVals()
{
List<LdifAttrValLine> ldifAttrValLines = new ArrayList<LdifAttrValLine>();
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifAttrValLine )
{
ldifAttrValLines.add( ( LdifAttrValLine ) ldifPart );
}
}
return ldifAttrValLines.toArray( new LdifAttrValLine[ldifAttrValLines.size()] );
}
private int getSize()
{
int size = 0;
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifAttrValLine )
{
size++;
}
}
return size;
}
public static LdifContentRecord create( String dn )
{
return new LdifContentRecord( LdifDnLine.create( dn ) );
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
return getSize() > 0;
}
public String getInvalidString()
{
if ( getSize() > 0 )
{
return super.getInvalidString();
}
else
{
return "Record must contain attribute value lines";
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.model.LdifInvalidPart;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifLineBase;
/**
* A base class for any LDIF container.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class LdifContainer implements LdifPart
{
/** The contained Ldif Parts */
protected List<LdifPart> ldifParts = new ArrayList<LdifPart>();
protected LdifContainer( LdifPart part )
{
if ( part == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( part );
}
public final int getOffset()
{
return ldifParts.get( 0 ).getOffset();
}
public final int getLength()
{
LdifPart lastPart = getLastPart();
return lastPart.getOffset() + lastPart.getLength() - getOffset();
}
public final void addInvalid( LdifInvalidPart invalid )
{
if ( invalid == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( invalid );
}
public final LdifPart getLastPart()
{
return ldifParts.get( ldifParts.size() - 1 );
}
public final LdifPart[] getParts()
{
return ( LdifPart[] ) ldifParts.toArray( new LdifPart[ldifParts
.size()] );
}
public final String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( getClass().getSimpleName() );
sb.append( ":" ); //$NON-NLS-1$
sb.append( LdifParserConstants.LINE_SEPARATOR );
for ( LdifPart part : ldifParts )
{
sb.append( " " ); //$NON-NLS-1$
sb.append( part.toString() );
sb.append( LdifParserConstants.LINE_SEPARATOR );
}
return sb.toString();
}
public final String toRawString()
{
StringBuilder sb = new StringBuilder();
for ( LdifPart part : ldifParts )
{
sb.append( part.toRawString() );
}
return sb.toString();
}
public final String toFormattedString( LdifFormatParameters formatParameters )
{
StringBuilder sb = new StringBuilder();
for ( LdifPart part : ldifParts )
{
sb.append( part.toFormattedString( formatParameters ) );
}
return sb.toString();
}
public abstract boolean isValid();
/**
* true if
* <ul>
* <li>at least one line
* <li>no LdifInvalidPart
* <li>all parts are valid
* </ul>
*/
protected boolean isAbstractValid()
{
if ( ldifParts.isEmpty() )
{
return false;
}
for ( LdifPart ldifPart : ldifParts )
{
if ( ( ldifPart instanceof LdifInvalidPart ) || ( !ldifPart.isValid() ) )
{
return false;
}
if ( ldifPart instanceof LdifLineBase )
{
return true;
}
}
return false;
}
public String getInvalidString()
{
if ( ldifParts.isEmpty() )
{
return "Empty Container";
}
for ( LdifPart ldifPart : ldifParts )
{
if ( !ldifPart.isValid() )
{
return ldifPart.getInvalidString();
}
}
return null;
}
public final void adjustOffset( int adjust )
{
for ( LdifPart ldifPart : ldifParts )
{
ldifPart.adjustOffset( adjust );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifSepContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifSepContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine;
/**
* A LDIF container for SEP (ie, 'r', '\n' or '\n\r' or '\r\n')
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifSepContainer extends LdifContainer
{
public LdifSepContainer( LdifSepLine sep )
{
super( sep );
}
public void addSep( LdifSepLine sep )
{
if ( sep == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( sep );
}
public boolean isValid()
{
return super.isAbstractValid();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeAddRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeAddRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
/**
* A LDIF container for LDIF add change records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeAddRecord extends LdifChangeRecord
{
public LdifChangeAddRecord( LdifDnLine dn )
{
super( dn );
}
public void addAttrVal( LdifAttrValLine attrVal )
{
if ( attrVal == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( attrVal );
}
public LdifAttrValLine[] getAttrVals()
{
List<LdifAttrValLine> ldifAttrValLines = new ArrayList<LdifAttrValLine>();
for ( LdifPart part : ldifParts )
{
if ( part instanceof LdifAttrValLine )
{
ldifAttrValLines.add( ( LdifAttrValLine ) part );
}
}
return ldifAttrValLines.toArray( new LdifAttrValLine[ldifAttrValLines.size()] );
}
public static LdifChangeAddRecord create( String dn )
{
LdifChangeAddRecord record = new LdifChangeAddRecord( LdifDnLine.create( dn ) );
record.setChangeType( LdifChangeTypeLine.createAdd() );
return record;
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
for ( LdifPart part : ldifParts )
{
if ( part instanceof LdifAttrValLine )
{
return true;
}
}
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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifModSpec.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifModSpec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecSepLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecTypeLine;
/**
* A LDIF container for a ModSpec
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifModSpec extends LdifContainer
{
public LdifModSpec( LdifModSpecTypeLine modSpecTypeLine )
{
super( modSpecTypeLine );
}
public void addAttrVal( LdifAttrValLine attrVal )
{
if ( attrVal == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( attrVal );
}
public void finish( LdifModSpecSepLine modSpecSepLine )
{
if ( modSpecSepLine == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( modSpecSepLine );
}
public LdifModSpecTypeLine getModSpecType()
{
return ( LdifModSpecTypeLine ) ldifParts.get( 0 );
}
public LdifAttrValLine[] getAttrVals()
{
List<LdifAttrValLine> ldifAttrValLines = new ArrayList<LdifAttrValLine>();
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifAttrValLine )
{
ldifAttrValLines.add( ( LdifAttrValLine ) ldifPart );
}
}
return ldifAttrValLines.toArray( new LdifAttrValLine[ldifAttrValLines.size()] );
}
public LdifModSpecSepLine getModSpecSep()
{
LdifPart lastPart = getLastPart();
if ( lastPart instanceof LdifModSpecSepLine )
{
return ( LdifModSpecSepLine ) lastPart;
}
else
{
return null;
}
}
public boolean isAdd()
{
return getModSpecType().isAdd();
}
public boolean isReplace()
{
return getModSpecType().isReplace();
}
public boolean isDelete()
{
return getModSpecType().isDelete();
}
public static LdifModSpec createAdd( String attributeName )
{
return new LdifModSpec( LdifModSpecTypeLine.createAdd( attributeName ) );
}
public static LdifModSpec createReplace( String attributeName )
{
return new LdifModSpec( LdifModSpecTypeLine.createReplace( attributeName ) );
}
public static LdifModSpec createDelete( String attributeName )
{
return new LdifModSpec( LdifModSpecTypeLine.createDelete( attributeName ) );
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
if ( getModSpecType() == null )
{
return false;
}
String att = getModSpecType().getUnfoldedAttributeDescription();
int sizeAttrVals = 0;
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifAttrValLine )
{
if ( !att.equalsIgnoreCase( ( ( LdifAttrValLine ) ldifPart ).getUnfoldedAttributeDescription() ) )
{
return false;
}
else
{
sizeAttrVals++;
}
}
}
if ( isAdd() )
{
return sizeAttrVals > 0;
}
else
{
return isDelete() || isReplace();
}
}
public String getInvalidString()
{
if ( getModSpecType() == null )
{
return "Missing mod spec line ";
}
int sizeAttrVals = 0;
String att = getModSpecType().getUnfoldedAttributeDescription();
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifAttrValLine )
{
if ( !att.equalsIgnoreCase( ( ( LdifAttrValLine ) ldifPart ).getUnfoldedAttributeDescription() ) )
{
return "Attribute descriptions don't match";
}
sizeAttrVals++;
}
}
if ( isAdd() && sizeAttrVals == 0 )
{
return "Modification must contain attribute value lines ";
}
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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeDeleteRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeDeleteRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
/**
* A LDIF container for LDIF delete change records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeDeleteRecord extends LdifChangeRecord
{
public LdifChangeDeleteRecord( LdifDnLine dn )
{
super( dn );
}
public static LdifChangeDeleteRecord create( String dn )
{
LdifChangeDeleteRecord record = new LdifChangeDeleteRecord( LdifDnLine.create( dn ) );
record.setChangeType( LdifChangeTypeLine.createDelete() );
return record;
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
return ( getChangeTypeLine() != null ) && ( getSepLine() != 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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifControlLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
/**
* A LDIF container for LDIF change records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeRecord extends LdifRecord
{
public LdifChangeRecord( LdifDnLine dn )
{
super( dn );
}
public void addControl( LdifControlLine controlLine )
{
if ( controlLine == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( controlLine );
}
public void setChangeType( LdifChangeTypeLine changeTypeLine )
{
if ( changeTypeLine == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
if ( getChangeTypeLine() != null )
{
throw new IllegalArgumentException( "changetype is already set" );
}
ldifParts.add( changeTypeLine );
}
public LdifControlLine[] getControls()
{
List<LdifControlLine> ldifControlLines = new ArrayList<LdifControlLine>();
for ( Object part : ldifParts )
{
if ( part instanceof LdifControlLine )
{
ldifControlLines.add( ( LdifControlLine ) part );
}
}
return ldifControlLines.toArray( new LdifControlLine[ldifControlLines.size()] );
}
public LdifChangeTypeLine getChangeTypeLine()
{
for ( Object part : ldifParts )
{
if ( part instanceof LdifChangeTypeLine )
{
return ( LdifChangeTypeLine ) part;
}
}
return null;
}
protected boolean isAbstractValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
return getChangeTypeLine() != null;
}
public boolean isValid()
{
return isAbstractValid();
}
public String getInvalidString()
{
if ( getChangeTypeLine() == null )
{
return "Missing changetype line";
}
return super.getInvalidString();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifVersionContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifVersionContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.lines.LdifVersionLine;
/**
* A LDIF container for the "version: 1" line
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifVersionContainer extends LdifContainer
{
public LdifVersionContainer( LdifVersionLine versionLine )
{
super( versionLine );
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
return getLastPart() instanceof LdifVersionLine;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeModDnRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeModDnRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDeloldrdnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifNewrdnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifNewsuperiorLine;
/**
* A LDIF container for LDIF moddn change records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeModDnRecord extends LdifChangeRecord
{
public LdifChangeModDnRecord( LdifDnLine dn )
{
super( dn );
}
public void setNewrdn( LdifNewrdnLine newrdn )
{
if ( newrdn == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( newrdn );
}
public void setDeloldrdn( LdifDeloldrdnLine deloldrdn )
{
if ( deloldrdn == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( deloldrdn );
}
public void setNewsuperior( LdifNewsuperiorLine newsuperior )
{
if ( newsuperior == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( newsuperior );
}
public LdifNewrdnLine getNewrdnLine()
{
for ( LdifPart part : ldifParts )
{
if ( part instanceof LdifNewrdnLine )
{
return ( LdifNewrdnLine ) part;
}
}
return null;
}
public LdifDeloldrdnLine getDeloldrdnLine()
{
for ( Object part : ldifParts )
{
if ( part instanceof LdifDeloldrdnLine )
{
return ( LdifDeloldrdnLine ) part;
}
}
return null;
}
public LdifNewsuperiorLine getNewsuperiorLine()
{
for ( Object part : ldifParts )
{
if ( part instanceof LdifNewsuperiorLine )
{
return ( LdifNewsuperiorLine ) part;
}
}
return null;
}
public static LdifChangeModDnRecord create( String dn )
{
LdifChangeModDnRecord record = new LdifChangeModDnRecord( LdifDnLine.create( dn ) );
record.setChangeType( LdifChangeTypeLine.createModDn() );
return record;
}
public boolean isValid()
{
if ( !super.isAbstractValid() )
{
return false;
}
return ( getNewrdnLine() != null ) && ( getDeloldrdnLine() != null );
}
public String getInvalidString()
{
if ( getNewrdnLine() == null )
{
return "Missing new Rdn";
}
else if ( getDeloldrdnLine() == null )
{
return "Missing delete old Rdn";
}
else
{
return super.getInvalidString();
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeModifyRecord.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifChangeModifyRecord.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
/**
* A LDIF container for LDIF modify change records
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeModifyRecord extends LdifChangeRecord
{
public LdifChangeModifyRecord( LdifDnLine dn )
{
super( dn );
}
public void addModSpec( LdifModSpec modSpec )
{
if ( modSpec == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( modSpec );
}
public LdifModSpec[] getModSpecs()
{
List<LdifModSpec> ldifModSpecs = new ArrayList<LdifModSpec>();
for ( LdifPart part : ldifParts )
{
if ( part instanceof LdifModSpec )
{
ldifModSpecs.add( ( LdifModSpec ) part );
}
}
return ldifModSpecs.toArray( new LdifModSpec[ldifModSpecs.size()] );
}
public static LdifChangeModifyRecord create( String dn )
{
LdifChangeModifyRecord record = new LdifChangeModifyRecord( LdifDnLine.create( dn ) );
record.setChangeType( LdifChangeTypeLine.createModify() );
return record;
}
public boolean isValid()
{
return super.isAbstractValid();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifCommentContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/container/LdifCommentContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.container;
import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine;
/**
* A LDIF container for LDIF comments
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifCommentContainer extends LdifContainer
{
public LdifCommentContainer( LdifCommentLine comment )
{
super( comment );
}
public void addComment( LdifCommentLine comment )
{
if ( comment == null )
{
throw new IllegalArgumentException( "null argument" ); //$NON-NLS-1$
}
ldifParts.add( comment );
}
public boolean isValid()
{
return super.isAbstractValid();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifCommentLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifCommentLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifCommentLine extends LdifNonEmptyLineBase
{
public LdifCommentLine( int offset, String rawComment, String rawNewLine )
{
super( offset, rawComment, rawNewLine );
}
public String getRawComment()
{
return super.getRawLineStart();
}
public String getUnfoldedComment()
{
return super.getUnfoldedLineStart();
}
public static LdifCommentLine create( String comment )
{
return new LdifCommentLine( 0, comment, LdifParserConstants.LINE_SEPARATOR );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNewsuperiorLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNewsuperiorLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.LdifUtils;
public class LdifNewsuperiorLine extends LdifValueLineBase
{
public LdifNewsuperiorLine( int offset, String rawNewSuperiorSpec, String rawValueType, String rawNewSuperiorDn,
String rawNewLine )
{
super( offset, rawNewSuperiorSpec, rawValueType, rawNewSuperiorDn, rawNewLine );
}
public String getRawNewSuperiorSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedNewSuperiorSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawNewSuperiorDn()
{
return super.getRawValue();
}
public String getUnfoldedNewSuperiorDn()
{
return super.getUnfoldedValue();
}
public String getInvalidString()
{
if ( getUnfoldedNewSuperiorSpec().length() == 0 )
{
return "Missing new superior spec 'newsuperior'";
}
else if ( getUnfoldedNewSuperiorDn().length() == 0 )
{
return "Missing new superior Dn";
}
else
{
return super.getInvalidString();
}
}
public static LdifNewsuperiorLine create( String newsuperior )
{
if ( LdifUtils.mustEncode( newsuperior ) )
{
return new LdifNewsuperiorLine( 0, "newsuperior", "::", LdifUtils.base64encode( LdifUtils //$NON-NLS-1$ //$NON-NLS-2$
.utf8encode( newsuperior ) ), LdifParserConstants.LINE_SEPARATOR );
}
else
{
return new LdifNewsuperiorLine( 0, "newsuperior", ":", newsuperior, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifSepLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifSepLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifSepLine extends LdifLineBase
{
public LdifSepLine( int offset, String rawNewLine )
{
super( offset, rawNewLine );
}
public static LdifSepLine create()
{
return new LdifSepLine( 0, LdifParserConstants.LINE_SEPARATOR );
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifModSpecTypeLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifModSpecTypeLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifModSpecTypeLine extends LdifValueLineBase
{
public LdifModSpecTypeLine( int offset, String rawModType, String rawValueType, String rawAttributeDescription,
String rawNewLine )
{
super( offset, rawModType, rawValueType, rawAttributeDescription, rawNewLine );
}
public String getRawModType()
{
return super.getRawLineStart();
}
public String getUnfoldedModType()
{
return super.getUnfoldedLineStart();
}
public String getRawAttributeDescription()
{
return super.getRawValue();
}
public String getUnfoldedAttributeDescription()
{
return super.getUnfoldedValue();
}
public boolean isAdd()
{
return getUnfoldedModType().equals( "add" ); //$NON-NLS-1$
}
public boolean isReplace()
{
return getUnfoldedModType().equals( "replace" ); //$NON-NLS-1$
}
public boolean isDelete()
{
return getUnfoldedModType().equals( "delete" ); //$NON-NLS-1$
}
public boolean isValid()
{
return super.isValid() && ( isAdd() || isReplace() || isDelete() );
}
public String getInvalidString()
{
if ( getUnfoldedModType().length() == 0 )
{
return "Missing modification type 'add', 'replace' or 'delete'";
}
else if ( !isAdd() && !isReplace() && !isDelete() )
{
return "Invalid modification type, expected 'add', 'replace' or 'delete'";
}
else if ( getUnfoldedAttributeDescription().length() == 0 )
{
return "Missing attribute";
}
else
{
return super.getInvalidString();
}
}
public static LdifModSpecTypeLine createAdd( String attributeName )
{
return new LdifModSpecTypeLine( 0, "add", ":", attributeName, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$
}
public static LdifModSpecTypeLine createReplace( String attributeName )
{
return new LdifModSpecTypeLine( 0, "replace", ":", attributeName, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$
}
public static LdifModSpecTypeLine createDelete( String attributeName )
{
return new LdifModSpecTypeLine( 0, "delete", ":", attributeName, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifDeloldrdnLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifDeloldrdnLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifDeloldrdnLine extends LdifValueLineBase
{
public LdifDeloldrdnLine( int offset, String rawDeleteOldrdnSpec, String rawValueType, String rawDeleteOldrdn,
String rawNewLine )
{
super( offset, rawDeleteOldrdnSpec, rawValueType, rawDeleteOldrdn, rawNewLine );
}
public String getRawDeleteOldrdnSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedDeleteOldrdnSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawDeleteOldrdn()
{
return super.getRawValue();
}
public String getUnfoldedDeleteOldrdn()
{
return super.getUnfoldedValue();
}
public boolean isDeleteOldRdn()
{
return "1".equals( getUnfoldedDeleteOldrdn() ); //$NON-NLS-1$
}
public boolean isValid()
{
if ( !super.isValid() )
{
return false;
}
return ( "0".equals( getUnfoldedDeleteOldrdn() ) || "1".equals( getUnfoldedDeleteOldrdn() ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
public String getInvalidString()
{
if ( getUnfoldedDeleteOldrdnSpec().length() == 0 )
{
return "Missing delete old Rdn spec 'deleteoldrdn'";
}
else if ( !"0".equals( getUnfoldedDeleteOldrdn() ) && !"1".equals( getUnfoldedDeleteOldrdn() ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return "Invalid value of delete old Rdn, must be '0' or '1'";
}
else
{
return super.getInvalidString();
}
}
public static LdifDeloldrdnLine create0()
{
return new LdifDeloldrdnLine( 0, "deleteoldrdn", ":", "0", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static LdifDeloldrdnLine create1()
{
return new LdifDeloldrdnLine( 0, "deleteoldrdn", ":", "1", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifChangeTypeLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifChangeTypeLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifChangeTypeLine extends LdifValueLineBase
{
public LdifChangeTypeLine( int offset, String rawChangeTypeSpec, String rawValueType, String rawChangeType,
String rawNewLine )
{
super( offset, rawChangeTypeSpec, rawValueType, rawChangeType, rawNewLine );
}
public String getRawChangeTypeSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedChangeTypeSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawChangeType()
{
return super.getRawValue();
}
public String getUnfoldedChangeType()
{
return super.getUnfoldedValue();
}
public boolean isAdd()
{
return getUnfoldedChangeType().equals( "add" ); //$NON-NLS-1$
}
public boolean isDelete()
{
return getUnfoldedChangeType().equals( "delete" ); //$NON-NLS-1$
}
public boolean isModify()
{
return getUnfoldedChangeType().equals( "modify" ); //$NON-NLS-1$
}
public boolean isModDn()
{
String unfoldedChangeType = getUnfoldedChangeType();
return "moddn".equalsIgnoreCase( unfoldedChangeType ) || "modrdn".equalsIgnoreCase( unfoldedChangeType ); //$NON-NLS-1$ //$NON-NLS-2$
}
public String getInvalidString()
{
if ( getUnfoldedChangeTypeSpec().length() == 0 )
{
return "Missing spec 'changetype'";
}
else if ( getUnfoldedChangeType().length() == 0 )
{
return "Missing changetype";
}
else
{
return super.getInvalidString();
}
}
public static LdifChangeTypeLine createDelete()
{
return new LdifChangeTypeLine( 0, "changetype", ":", "delete", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static LdifChangeTypeLine createAdd()
{
return new LdifChangeTypeLine( 0, "changetype", ":", "add", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static LdifChangeTypeLine createModify()
{
return new LdifChangeTypeLine( 0, "changetype", ":", "modify", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static LdifChangeTypeLine createModDn()
{
return new LdifChangeTypeLine( 0, "changetype", ":", "moddn", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static LdifChangeTypeLine createModRdn()
{
return new LdifChangeTypeLine( 0, "changetype", ":", "modrdn", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifLineBase.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifLineBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.LdifUtils;
import org.apache.directory.studio.ldifparser.model.LdifPart;
/**
* Base class for all lines in a LDIF file.
*
*
*/
public abstract class LdifLineBase implements LdifPart
{
/** The position of this LdifPart in the Ldif */
protected int offset;
protected String rawNewLine;
protected LdifLineBase()
{
super();
}
protected LdifLineBase( int offset, String rawNewLine )
{
this.offset = offset;
this.rawNewLine = rawNewLine;
}
public final int getOffset()
{
return offset;
}
public final String getRawNewLine()
{
return getNonNull( rawNewLine );
}
public String getUnfoldedNewLine()
{
return unfold( getRawNewLine() );
}
public final void adjustOffset( int adjust )
{
offset += adjust;
}
public final int getLength()
{
return toRawString().length();
}
public boolean isValid()
{
return rawNewLine != null;
}
public String getInvalidString()
{
if ( rawNewLine == null )
{
return "Missing new line";
}
else
{
return null;
}
}
public String toRawString()
{
return getRawNewLine();
}
public String toFormattedString( LdifFormatParameters formatParameters )
{
String raw = toRawString();
String unfolded = unfold( raw );
if ( rawNewLine != null )
{
int index = unfolded.lastIndexOf( rawNewLine );
if ( index > -1 )
{
unfolded = unfolded.substring( 0, unfolded.length() - rawNewLine.length() );
unfolded = unfolded + formatParameters.getLineSeparator();
}
}
return unfolded;
}
public final String toString()
{
String text = toRawString();
text = LdifUtils.convertNlRcToString( text ); //$NON-NLS-1$ //$NON-NLS-2$
return getClass().getName() + " (" + getOffset() + "," + getLength() + "): '" + text + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
protected static String getNonNull( String s )
{
return s != null ? s : ""; //$NON-NLS-1$
}
protected static String unfold( String s )
{
char[] newString = s.toCharArray();
int pos = 0;
int length = newString.length;
for ( int i = 0; i < length; i++ )
{
char c = newString[ i ];
if ( c == '\n' )
{
if ( i + 1 < length )
{
switch ( newString[ i + 1 ] )
{
case ' ' :
i++;
break;
case '\r' :
if ( ( i + 2 < length ) && ( newString[ i + 2 ] == ' ' ) )
{
i += 2;
}
else
{
newString[pos++] = c;
newString[pos++] = '\r';
i++;
}
break;
default :
newString[pos++] = c;
break;
}
}
else
{
newString[pos++] = c;
}
}
else if ( c == '\r' )
{
if ( i + 1 < length )
{
switch ( newString[ i + 1 ] )
{
case ' ' :
i++;
break;
case '\n' :
if ( ( i + 2 < length ) && ( newString[ i + 2 ] == ' ' ) )
{
i += 2;
}
else
{
newString[pos++] = c;
newString[pos++] = '\n';
i++;
}
break;
default :
newString[pos++] = c;
break;
}
}
else
{
newString[pos++] = c;
}
}
else
{
newString[pos++] = c;
}
}
return new String( newString, 0, pos );
}
protected static String fold( String value, int indent, LdifFormatParameters formatParameters )
{
StringBuffer formattedLdif = new StringBuffer();
int offset = formatParameters.getLineWidth() - indent;
int endIndex = 0 + offset;
while ( endIndex + formatParameters.getLineSeparator().length() < value.length() )
{
formattedLdif.append( value.substring( endIndex - offset, endIndex ) );
formattedLdif.append( formatParameters.getLineSeparator() );
formattedLdif.append( ' ' );
offset = formatParameters.getLineWidth() - 1;
endIndex += offset;
}
String rest = value.substring( endIndex - offset, value.length() );
formattedLdif.append( rest );
// return
return formattedLdif.toString();
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifModSpecSepLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifModSpecSepLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifModSpecSepLine extends LdifNonEmptyLineBase
{
public LdifModSpecSepLine( int offset, String rawMinus, String rawNewLine )
{
super( offset, rawMinus, rawNewLine );
}
public String getRawMinus()
{
return super.getRawLineStart();
}
public String getUnfoldedMinus()
{
return super.getUnfoldedLineStart();
}
public boolean isValid()
{
return super.isValid() && getUnfoldedMinus().equals( "-" ); //$NON-NLS-1$
}
public String getInvalidString()
{
if ( !getUnfoldedMinus().equals( "-" ) ) //$NON-NLS-1$
{
return "Missing '-'";
}
else
{
return super.getInvalidString();
}
}
public static LdifModSpecSepLine create()
{
return new LdifModSpecSepLine( 0, "-", LdifParserConstants.LINE_SEPARATOR ); //$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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifControlLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifControlLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.LdifUtils;
public class LdifControlLine extends LdifValueLineBase
{
private String rawCriticality;
private String rawControlValueType;
private String rawControlValue;
public LdifControlLine( int offset, String rawControlSpec, String rawControlType, String rawOid,
String rawCriticality, String rawControlValueType, String rawControlValue, String rawNewLine )
{
super( offset, rawControlSpec, rawControlType, rawOid, rawNewLine );
this.rawCriticality = rawCriticality;
this.rawControlValueType = rawControlValueType;
this.rawControlValue = rawControlValue;
}
public String getRawControlSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedControlSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawControlType()
{
return super.getRawValueType();
}
public String getUnfoldedControlType()
{
return super.getUnfoldedValueType();
}
public String getRawOid()
{
return super.getRawValue();
}
public String getUnfoldedOid()
{
return super.getUnfoldedValue();
}
public String getRawCriticality()
{
return getNonNull( rawCriticality );
}
public String getUnfoldedCriticality()
{
return unfold( getRawCriticality() );
}
public boolean isCritical()
{
return getUnfoldedCriticality().endsWith( "true" ); //$NON-NLS-1$
}
public String getRawControlValueType()
{
return getNonNull( rawControlValueType );
}
public String getUnfoldedControlValueType()
{
return unfold( getRawControlValueType() );
}
public String getRawControlValue()
{
return getNonNull( rawControlValue );
}
public String getUnfoldedControlValue()
{
return unfold( getRawControlValue() );
}
public String toRawString()
{
return getRawControlSpec() + getRawControlType() + getRawOid() + getRawCriticality()
+ getRawControlValueType() + getRawControlValue() + getRawNewLine();
}
public boolean isValid()
{
return getUnfoldedControlSpec().length() > 0
&& getUnfoldedControlType().length() > 0
&& getUnfoldedOid().length() > 0
&& ( rawCriticality == null || getUnfoldedCriticality().endsWith( "true" ) || this //$NON-NLS-1$
.getUnfoldedCriticality().endsWith( "false" ) ) //$NON-NLS-1$
&& ( ( rawControlValueType == null && rawControlValue == null ) || ( rawControlValueType != null && rawControlValue != null ) )
&& getUnfoldedNewLine().length() > 0;
}
public String getInvalidString()
{
if ( getUnfoldedControlSpec().length() == 0 )
{
return "Missing 'control'";
}
else if ( getUnfoldedOid().length() == 0 )
{
return "Missing OID";
}
else if ( ( rawCriticality != null && !getUnfoldedCriticality().endsWith( "true" ) && !this //$NON-NLS-1$
.getUnfoldedCriticality().endsWith( "false" ) ) ) //$NON-NLS-1$
{
return "Invalid criticality, must be 'true' or 'false'";
}
else
{
return super.getInvalidString();
}
}
/**
*
* @return the binary representation of the control value, may be null
*/
public final byte[] getControlValueAsBinary()
{
Object o = getControlValueAsObject();
if ( o instanceof String )
{
return LdifUtils.utf8encode( ( String ) o );
}
else if ( o instanceof byte[] )
{
return ( byte[] ) o;
}
else
{
return new byte[0];
}
}
public final Object getControlValueAsObject()
{
if ( isControlValueTypeSafe() )
{
return getUnfoldedControlValue();
}
else if ( isControlValueTypeBase64() )
{
return LdifUtils.base64decodeToByteArray( getUnfoldedControlValue() );
}
else
{
return null;
}
}
public boolean isControlValueTypeBase64()
{
return getUnfoldedControlValueType().startsWith( "::" ); //$NON-NLS-1$
}
public boolean isControlValueTypeSafe()
{
return getUnfoldedControlValueType().startsWith( ":" ) && !isControlValueTypeBase64(); //$NON-NLS-1$
}
public static LdifControlLine create( String oid, String criticality, String controlValue )
{
if ( LdifUtils.mustEncode( controlValue ) )
{
return create( oid, criticality, LdifUtils.utf8encode( controlValue ) );
}
else
{
LdifControlLine controlLine = new LdifControlLine( 0, "control", ":", oid, criticality, //$NON-NLS-1$ //$NON-NLS-2$
controlValue != null ? ":" : null, controlValue != null ? controlValue : null, //$NON-NLS-1$
LdifParserConstants.LINE_SEPARATOR );
return controlLine;
}
}
public static LdifControlLine create( String oid, String criticality, byte[] controlValue )
{
LdifControlLine controlLine = new LdifControlLine( 0, "control", ":", oid, criticality, controlValue != null //$NON-NLS-1$ //$NON-NLS-2$
&& controlValue.length > 0 ? "::" : null, controlValue != null && controlValue.length > 0 ? LdifUtils //$NON-NLS-1$
.base64encode( controlValue ) : null, LdifParserConstants.LINE_SEPARATOR );
return controlLine;
}
public static LdifControlLine create( String oid, boolean isCritical, String controlValue )
{
return create( oid, isCritical ? " true" : " false", controlValue ); //$NON-NLS-1$ //$NON-NLS-2$
}
public static LdifControlLine create( String oid, boolean isCritical, byte[] controlValue )
{
return create( oid, isCritical ? " true" : " false", controlValue ); //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNonEmptyLineBase.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNonEmptyLineBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
public abstract class LdifNonEmptyLineBase extends LdifLineBase
{
private String rawLineStart;
protected LdifNonEmptyLineBase()
{
}
public LdifNonEmptyLineBase( int offset, String rawLineStart, String rawNewLine )
{
super( offset, rawNewLine );
this.rawLineStart = rawLineStart;
}
public String getRawLineStart()
{
return getNonNull( rawLineStart );
}
public String getUnfoldedLineStart()
{
return unfold( getRawLineStart() );
}
public boolean isValid()
{
return super.isValid() && rawLineStart != null;
}
public String getInvalidString()
{
if ( rawLineStart == null )
{
return "Missing line start";
}
else
{
return super.getInvalidString();
}
}
public String toRawString()
{
return getRawLineStart() + getRawNewLine();
}
public boolean isFolded()
{
String rawString = toRawString();
return rawString.indexOf( "\n " ) > -1 || rawString.indexOf( "\r " ) > -1; //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifAttrValLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifAttrValLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.LdifUtils;
/**
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifAttrValLine extends LdifValueLineBase
{
public LdifAttrValLine( int offset, String attributeDescripton, String valueType, String value, String newLine )
{
super( offset, attributeDescripton, valueType, value, newLine );
}
public String getRawAttributeDescription()
{
return super.getRawLineStart();
}
public String getUnfoldedAttributeDescription()
{
return super.getUnfoldedLineStart();
}
public String getInvalidString()
{
if ( getUnfoldedAttributeDescription().length() == 0 )
{
return "Missing attribute name";
}
else
{
return super.getInvalidString();
}
}
public static LdifAttrValLine create( String name, String value )
{
if ( LdifUtils.mustEncode( value ) )
{
return create( name, LdifUtils.utf8encode( value ) );
}
else
{
return new LdifAttrValLine( 0, name, ":", value, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$
}
}
public static LdifAttrValLine create( String name, byte[] value )
{
return new LdifAttrValLine( 0, name, "::", LdifUtils.base64encode( value ), LdifParserConstants.LINE_SEPARATOR ); //$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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifVersionLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifVersionLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
public class LdifVersionLine extends LdifValueLineBase
{
public LdifVersionLine( int offset, String rawVersionSpec, String rawValueType, String rawVersion, String rawNewLine )
{
super( offset, rawVersionSpec, rawValueType, rawVersion, rawNewLine );
}
public String getRawVersionSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedVersionSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawVersion()
{
return super.getRawValue();
}
public String getUnfoldedVersion()
{
return super.getUnfoldedValue();
}
public String getInvalidString()
{
if ( getUnfoldedVersionSpec().length() == 0 )
{
return "Missing version spec";
}
else if ( getUnfoldedVersion().length() == 0 )
{
return "Missing version";
}
else
{
return super.getInvalidString();
}
}
public static LdifVersionLine create()
{
return new LdifVersionLine( 0, "version", ":", "1", LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifValueLineBase.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifValueLineBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.LdifUtils;
public class LdifValueLineBase extends LdifNonEmptyLineBase
{
private String rawValueType;
private String rawValue;
protected LdifValueLineBase()
{
}
public LdifValueLineBase( int offset, String rawLineStart, String rawValueType, String rawValue, String rawNewLine )
{
super( offset, rawLineStart, rawNewLine );
this.rawValueType = rawValueType;
this.rawValue = rawValue;
}
public String getRawValueType()
{
return getNonNull( rawValueType );
}
public String getUnfoldedValueType()
{
return unfold( getRawValueType() );
}
public String getRawValue()
{
return getNonNull( rawValue );
}
public String getUnfoldedValue()
{
return unfold( getRawValue() );
}
public String toRawString()
{
return getRawLineStart() + getRawValueType() + getRawValue() + getRawNewLine();
}
public String toFormattedString( LdifFormatParameters formatParameters )
{
String raw = toRawString();
String unfolded = unfold( raw );
// Fix for DIRSTUDIO-285: We must take care that we only check
// the first colon in the line. If there is another :: or :<
// in the value we must not use that as separator.
int firstColonIndex = unfolded.indexOf( ":" ); //$NON-NLS-1$
int firstDoubleColonIndex = unfolded.indexOf( "::" ); //$NON-NLS-1$
int firstColonLessIndex = unfolded.indexOf( ":<" ); //$NON-NLS-1$
if ( firstDoubleColonIndex > -1 && firstDoubleColonIndex == firstColonIndex )
{
unfolded = unfolded.replaceFirst( "::[ ]*", formatParameters.isSpaceAfterColon() ? ":: " : "::" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
else if ( firstColonLessIndex > -1 && firstColonLessIndex == firstColonIndex )
{
unfolded = unfolded.replaceFirst( ":<[ ]*", formatParameters.isSpaceAfterColon() ? ":< " : ":<" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
else if ( firstColonIndex > -1 )
{
unfolded = unfolded.replaceFirst( ":[ ]*", formatParameters.isSpaceAfterColon() ? ": " : ":" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if ( rawNewLine != null )
{
int index = unfolded.lastIndexOf( rawNewLine );
if ( index > -1 )
{
unfolded = unfolded.substring( 0, unfolded.length() - rawNewLine.length() );
unfolded = unfolded + formatParameters.getLineSeparator();
}
}
return fold( unfolded, 0, formatParameters );
}
public boolean isValid()
{
return super.isValid() && rawValueType != null && rawValue != null;
}
public String getInvalidString()
{
if ( rawValueType == null )
{
return "Missing value type ':', '::' or ':<'";
}
else if ( rawValue == null )
{
return "Missing value";
}
else
{
return super.getInvalidString();
}
}
/**
*
* @return the string representation of the value, non-base64, unfolded
*/
public final String getValueAsString()
{
Object o = getValueAsObject();
if ( o instanceof String )
{
return ( String ) o;
}
else if ( o instanceof byte[] )
{
return LdifUtils.utf8decode( ( byte[] ) o );
}
else
{
return ""; //$NON-NLS-1$
}
}
/**
*
* @return the binary representation of the real value, non-base64,
* unfolded
*/
public final byte[] getValueAsBinary()
{
Object o = getValueAsObject();
if ( o instanceof String )
{
return LdifUtils.utf8encode( ( String ) o );
}
else if ( o instanceof byte[] )
{
return ( byte[] ) o;
}
else
{
return new byte[0];
}
}
/**
* Returns the real data:
* <ul>
* <li>The unfolded String if value is a safe value.
* </li>
* <li>A byte array if value is base64 encoded.
* </li>
* <li>A byte array if value references an URL.
* </li>
* </ul>
*
* @return the real value or null
*/
public final Object getValueAsObject()
{
if ( isValueTypeSafe() )
{
return getUnfoldedValue();
}
else if ( isValueTypeBase64() )
{
return LdifUtils.base64decodeToByteArray( getUnfoldedValue() );
}
else if ( isValueTypeURL() )
{
FileInputStream fis = null;
try
{
try
{
File file = new File( getUnfoldedValue() );
byte[] data = new byte[( int ) file.length()];
fis = new FileInputStream( file );
fis.read( data );
return data;
}
finally
{
if ( fis != null )
{
fis.close();
}
}
}
catch ( IOException ioe )
{
return null;
}
}
else
{
return null;
}
}
public boolean isValueTypeURL()
{
return getUnfoldedValueType().startsWith( ":<" ); //$NON-NLS-1$
}
public boolean isValueTypeBase64()
{
return getUnfoldedValueType().startsWith( "::" ); //$NON-NLS-1$
}
public boolean isValueTypeSafe()
{
return getUnfoldedValueType().startsWith( ":" ) && !isValueTypeBase64() && !isValueTypeURL(); //$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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifDnLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifDnLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.LdifUtils;
public class LdifDnLine extends LdifValueLineBase
{
public LdifDnLine( int offset, String rawDnSpec, String rawValueType, String rawDn, String rawNewLine )
{
super( offset, rawDnSpec, rawValueType, rawDn, rawNewLine );
}
public String getRawDnSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedDnSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawDn()
{
return super.getRawValue();
}
public String getUnfoldedDn()
{
return super.getUnfoldedValue();
}
public boolean isValid()
{
return super.isValid() && Dn.isValid( getValueAsString() );
}
public String getInvalidString()
{
if ( getUnfoldedDnSpec().length() == 0 )
{
return "Missing Dn spec 'dn'";
}
else if ( getUnfoldedDn().length() == 0 )
{
return "Missing Dn";
}
else if ( !Dn.isValid( getValueAsString() ) )
{
return "Invalid Dn";
}
else
{
return super.getInvalidString();
}
}
public static LdifDnLine create( String dn )
{
if ( LdifUtils.mustEncode( dn ) )
{
return new LdifDnLine( 0, "dn", "::", LdifUtils.base64encode( LdifUtils.utf8encode( dn ) ), //$NON-NLS-1$ //$NON-NLS-2$
LdifParserConstants.LINE_SEPARATOR );
}
else
{
return new LdifDnLine( 0, "dn", ":", dn, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNewrdnLine.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/model/lines/LdifNewrdnLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.model.lines;
import org.apache.directory.studio.ldifparser.LdifParserConstants;
import org.apache.directory.studio.ldifparser.LdifUtils;
public class LdifNewrdnLine extends LdifValueLineBase
{
public LdifNewrdnLine( int offset, String rawNewrdnSpec, String rawValueType, String rawNewrdn, String rawNewLine )
{
super( offset, rawNewrdnSpec, rawValueType, rawNewrdn, rawNewLine );
}
public String getRawNewrdnSpec()
{
return super.getRawLineStart();
}
public String getUnfoldedNewrdnSpec()
{
return super.getUnfoldedLineStart();
}
public String getRawNewrdn()
{
return super.getRawValue();
}
public String getUnfoldedNewrdn()
{
return super.getUnfoldedValue();
}
public String getInvalidString()
{
if ( getUnfoldedNewrdnSpec().length() == 0 )
{
return "Missing new Rdn spec 'newrdn'";
}
else if ( getUnfoldedNewrdn().length() == 0 )
{
return "Missing new Rdn";
}
else
{
return super.getInvalidString();
}
}
public static LdifNewrdnLine create( String newrdn )
{
if ( LdifUtils.mustEncode( newrdn ) )
{
return new LdifNewrdnLine( 0, "newrdn", "::", LdifUtils.base64encode( LdifUtils.utf8encode( newrdn ) ), //$NON-NLS-1$ //$NON-NLS-2$
LdifParserConstants.LINE_SEPARATOR );
}
else
{
return new LdifNewrdnLine( 0, "newrdn", ":", newrdn, LdifParserConstants.LINE_SEPARATOR ); //$NON-NLS-1$ //$NON-NLS-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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifToken.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifToken.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.parser;
public class LdifToken implements Comparable<LdifToken>
{
public static final int NEW = Integer.MIN_VALUE;
public static final int ERROR = -2;
public static final int EOF = -1;
public static final int UNKNOWN = 0;
public static final int COMMENT = 1;
public static final int SEP = 2;
public static final int VERSION_SPEC = 4;
public static final int NUMBER = 5;
public static final int OID = 6;
public static final int DN_SPEC = 11;
public static final int DN = 12;
public static final int ATTRIBUTE = 21;
public static final int VALUE_TYPE_SAFE = 22;
public static final int VALUE_TYPE_BASE64 = 23;
public static final int VALUE_TYPE_URL = 24;
public static final int VALUE = 27;
public static final int CHANGETYPE_SPEC = 30;
public static final int CHANGETYPE_ADD = 31;
public static final int CHANGETYPE_DELETE = 32;
public static final int CHANGETYPE_MODIFY = 33;
public static final int CHANGETYPE_MODDN = 34;
public static final int MODTYPE_ADD_SPEC = 41;
public static final int MODTYPE_DELETE_SPEC = 42;
public static final int MODTYPE_REPLACE_SPEC = 43;
public static final int MODTYPE_SEP = 45; //
public static final int CONTROL_SPEC = 51; // control:FILL
public static final int CONTROL_LDAPOID = 52; //
public static final int CONTROL_CRITICALITY_TRUE = 53; // FILLtrue
public static final int CONTROL_CRITICALITY_FALSE = 54; // FILLfalse
public static final int MODDN_NEWRDN_SPEC = 61;
public static final int MODDN_DELOLDRDN_SPEC = 63;
public static final int MODDN_NEWSUPERIOR_SPEC = 65;
private int offset;
private int type;
private String value;
public LdifToken( int type, String value, int offset )
{
this.type = type;
this.value = value;
this.offset = offset;
}
/**
* Returns the start position of the token in the original ldif
*
* @return the start positon of the token
*/
public int getOffset()
{
return offset;
}
/**
* Returns the length of the token in the original ldif
*
* @return the length of the token
*/
public int getLength()
{
return value.length();
}
public int getType()
{
return type;
}
public String getValue()
{
return value;
}
public String toString()
{
return "(type=" + type + ") " + "(offset=" + offset + ") " + "(length=" + getLength() + ") '" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ value + "'"; //$NON-NLS-1$
}
public int compareTo( LdifToken ldifToken )
{
return offset - ldifToken.offset;
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifParser.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.parser;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifEOFPart;
import org.apache.directory.studio.ldifparser.model.LdifEnumeration;
import org.apache.directory.studio.ldifparser.model.LdifFile;
import org.apache.directory.studio.ldifparser.model.LdifInvalidPart;
import org.apache.directory.studio.ldifparser.model.LdifPart;
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.LdifCommentContainer;
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.LdifEOFContainer;
import org.apache.directory.studio.ldifparser.model.container.LdifInvalidContainer;
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.container.LdifSepContainer;
import org.apache.directory.studio.ldifparser.model.container.LdifVersionContainer;
import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifChangeTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifControlLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDeloldrdnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifDnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecSepLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifModSpecTypeLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifNewrdnLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifNewsuperiorLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifSepLine;
import org.apache.directory.studio.ldifparser.model.lines.LdifVersionLine;
public class LdifParser
{
private LdifScanner scanner;
public LdifParser()
{
scanner = new LdifScanner();
}
/**
* Parse a Ldif String. It will be stored in a LdifFile.
*
* @param ldif The String to parse
* @return The resulting LdifFile
*/
public LdifFile parse( String ldif )
{
LdifFile model = new LdifFile();
if ( ldif != null )
{
LdifEnumeration enumeration = parse( new StringReader( ldif ) );
try
{
while ( enumeration.hasNext() )
{
LdifContainer container = enumeration.next();
model.addContainer( container );
}
}
catch ( Exception e )
{
}
}
return model;
}
public LdifEnumeration parse( Reader ldifReader )
{
scanner.setLdif( ldifReader );
LdifEnumeration enumeration = new LdifEnumeration()
{
private List<LdifContainer> containerList = new ArrayList<LdifContainer>();
private boolean headerParsed = false;
private boolean bodyParsed = false;
private boolean footerParsed = false;
public boolean hasNext()
{
if ( containerList.isEmpty() )
{
LdifFile model = new LdifFile();
// parse header
if ( !headerParsed )
{
checkAndParseComment( model );
checkAndParseVersion( model );
checkAndParseComment( model );
headerParsed = true;
}
// parse body (in a loop)
bodyParsed = ( headerParsed &&
!bodyParsed &&
!checkAndParseComment( model ) && // parse comment lines
!checkAndParseRecord( model ) && // parse record
!checkAndParseOther( model ) ); // parse unknown
// parse footer
if ( headerParsed && bodyParsed && !footerParsed )
{
checkAndParseComment( model );
footerParsed = true;
}
List<LdifContainer> containers = model.getContainers();
containerList.addAll( containers );
return !containerList.isEmpty() && !( containers.get( 0 ) instanceof LdifEOFContainer );
}
else
{
return true;
}
}
public LdifContainer next()
{
if ( hasNext() )
{
return containerList.remove( 0 );
}
else
{
return null;
}
}
};
return enumeration;
}
/**
* Checks for version line. If version line is present it is parsed and
* added to the given model.
*
* @param model
* the model
* @return true if version line was added to the model, false otherwise
*/
private boolean checkAndParseRecord( LdifFile model )
{
// record starts with dn-spec
LdifToken dnSpecToken = scanner.matchDnSpec();
if ( dnSpecToken == null )
{
return false;
}
// get Dn
LdifToken dnValueTypeToken = null;
LdifToken dnToken = null;
LdifToken dnSepToken = null;
dnValueTypeToken = scanner.matchValueType();
if ( dnValueTypeToken != null )
{
dnToken = scanner.matchValue();
if ( dnToken != null )
{
dnSepToken = scanner.matchSep();
}
}
LdifDnLine dnLine = new LdifDnLine( dnSpecToken.getOffset(), getValueOrNull( dnSpecToken ),
getValueOrNull( dnValueTypeToken ), getValueOrNull( dnToken ), getValueOrNull( dnSepToken ) );
LdifToken dnErrorToken = null;
if ( dnSepToken == null )
{
dnErrorToken = scanner.matchCleanupLine();
}
// save comment lines after dns
LdifCommentLine[] commentLines = getCommentLines();
// check record type: to decide the record type we need the next token
// first check keywords 'control' and 'changetype'
LdifControlLine controlLine = getControlLine();
LdifChangeTypeLine changeTypeLine = getChangeTypeLine();
if ( controlLine != null || changeTypeLine != null )
{
LdifChangeRecord record = null;
// save all parts before changetype line
List<LdifPart> partList = new ArrayList<LdifPart>();
if ( dnErrorToken != null )
{
partList.add( new LdifInvalidPart( dnErrorToken.getOffset(), dnErrorToken.getValue() ) );
}
for ( LdifCommentLine ldifCommentLine : commentLines )
{
partList.add( ldifCommentLine );
}
if ( controlLine != null )
{
partList.add( controlLine );
if ( !controlLine.isValid() )
{
LdifToken errorToken = cleanupLine();
if ( errorToken != null )
{
partList.add( new LdifInvalidPart( errorToken.getOffset(), errorToken.getValue() ) );
}
}
}
// save comments and controls before changetype line
while ( changeTypeLine == null && ( commentLines.length > 0 || controlLine != null ) )
{
commentLines = getCommentLines();
for ( LdifCommentLine ldifCommentLine : commentLines )
{
partList.add( ldifCommentLine );
}
controlLine = getControlLine();
if ( controlLine != null )
{
partList.add( controlLine );
if ( !controlLine.isValid() )
{
LdifToken errorToken = cleanupLine();
if ( errorToken != null )
{
partList.add( new LdifInvalidPart( errorToken.getOffset(), errorToken.getValue() ) );
}
}
}
changeTypeLine = getChangeTypeLine();
}
if ( changeTypeLine != null )
{
if ( changeTypeLine.isAdd() )
{
record = new LdifChangeAddRecord( dnLine );
append( record, partList );
record.setChangeType( changeTypeLine );
if ( !changeTypeLine.isValid() )
{
this.cleanupLine( record );
}
parseAttrValRecord( record );
}
else if ( changeTypeLine.isDelete() )
{
record = new LdifChangeDeleteRecord( dnLine );
append( record, partList );
record.setChangeType( changeTypeLine );
if ( !changeTypeLine.isValid() )
{
this.cleanupLine( record );
}
parseChangeDeleteRecord( record );
}
else if ( changeTypeLine.isModify() )
{
record = new LdifChangeModifyRecord( dnLine );
append( record, partList );
record.setChangeType( changeTypeLine );
if ( !changeTypeLine.isValid() )
{
this.cleanupLine( record );
}
parseChangeModifyRecord( ( LdifChangeModifyRecord ) record );
}
else if ( changeTypeLine.isModDn() )
{
record = new LdifChangeModDnRecord( dnLine );
append( record, partList );
record.setChangeType( changeTypeLine );
if ( !changeTypeLine.isValid() )
{
this.cleanupLine( record );
}
parseChangeModDnRecord( ( LdifChangeModDnRecord ) record );
}
else
{
record = new LdifChangeRecord( dnLine );
append( record, partList );
record.setChangeType( changeTypeLine );
if ( !changeTypeLine.isValid() )
{
this.cleanupLine( record );
}
}
}
else
{
record = new LdifChangeRecord( dnLine );
append( record, partList );
}
model.addContainer( record );
}
else
{
// match attr-val-record
LdifContentRecord record = new LdifContentRecord( dnLine );
if ( dnErrorToken != null )
{
record.addInvalid( new LdifInvalidPart( dnErrorToken.getOffset(), dnErrorToken.getValue() ) );
}
for ( LdifCommentLine ldifCommentLine : commentLines )
{
record.addComment( ldifCommentLine );
}
parseAttrValRecord( record );
model.addContainer( record );
}
return true;
}
private void append( LdifChangeRecord record, List<LdifPart> partList )
{
for ( LdifPart ldifPart : partList )
{
if ( ldifPart instanceof LdifCommentLine )
{
record.addComment( ( LdifCommentLine ) ldifPart );
}
if ( ldifPart instanceof LdifControlLine )
{
record.addControl( ( LdifControlLine ) ldifPart );
}
if ( ldifPart instanceof LdifInvalidPart )
{
record.addInvalid( ( LdifInvalidPart ) ldifPart );
}
}
}
private void parseChangeDeleteRecord( LdifRecord record )
{
do
{
if ( checkAndParseEndOfRecord( record ) )
{
return;
}
if ( !checkAndParseComment( record ) && !checkAndParseOther( record ) )
{
return;
}
}
while ( true );
}
private void parseChangeModDnRecord( LdifChangeModDnRecord record )
{
boolean newrdnRead = false;
boolean deleteoldrdnRead = false;
boolean newsuperiorRead = false;
do
{
if ( checkAndParseEndOfRecord( record ) )
{
return;
}
// comments
checkAndParseComment( record );
LdifToken newrdnSpecToken = null;
LdifToken deleteoldrdnSpecToken = null;
LdifToken newsuperiorSpecToken = null;
if ( !newrdnRead )
{
newrdnSpecToken = scanner.matchNewrdnSpec();
}
if ( !deleteoldrdnRead && newrdnSpecToken == null )
{
deleteoldrdnSpecToken = scanner.matchDeleteoldrdnSpec();
}
if ( !newsuperiorRead && newrdnSpecToken == null && newsuperiorSpecToken == null )
{
newsuperiorSpecToken = scanner.matchNewsuperiorSpec();
}
if ( newrdnSpecToken != null )
{
// read newrdn line
newrdnRead = true;
LdifToken newrdnValueTypeToken = scanner.matchValueType();
LdifToken newrdnValueToken = scanner.matchValue();
LdifToken newrdnSepToken = null;
if ( newrdnValueTypeToken != null || newrdnValueToken != null )
{
newrdnSepToken = scanner.matchSep();
}
LdifNewrdnLine newrdnLine = new LdifNewrdnLine( newrdnSpecToken.getOffset(),
getValueOrNull( newrdnSpecToken ), getValueOrNull( newrdnValueTypeToken ),
getValueOrNull( newrdnValueToken ), getValueOrNull( newrdnSepToken ) );
record.setNewrdn( newrdnLine );
if ( newrdnSepToken == null )
{
cleanupLine( record );
}
}
else if ( deleteoldrdnSpecToken != null )
{
// read deleteoldrdnline
deleteoldrdnRead = true;
LdifToken deleteoldrdnValueTypeToken = scanner.matchValueType();
LdifToken deleteoldrdnValueToken = scanner.matchValue();
LdifToken deleteoldrdnSepToken = null;
if ( deleteoldrdnValueTypeToken != null || deleteoldrdnValueToken != null )
{
deleteoldrdnSepToken = scanner.matchSep();
}
LdifDeloldrdnLine deloldrdnLine = new LdifDeloldrdnLine( deleteoldrdnSpecToken.getOffset(),
getValueOrNull( deleteoldrdnSpecToken ), getValueOrNull( deleteoldrdnValueTypeToken ),
getValueOrNull( deleteoldrdnValueToken ), getValueOrNull( deleteoldrdnSepToken ) );
record.setDeloldrdn( deloldrdnLine );
if ( deleteoldrdnSepToken == null )
{
cleanupLine( record );
}
}
else if ( newsuperiorSpecToken != null )
{
// read newsuperior line
newsuperiorRead = true;
LdifToken newsuperiorValueTypeToken = scanner.matchValueType();
LdifToken newsuperiorValueToken = scanner.matchValue();
LdifToken newsuperiorSepToken = null;
if ( newsuperiorValueTypeToken != null || newsuperiorValueToken != null )
{
newsuperiorSepToken = scanner.matchSep();
}
LdifNewsuperiorLine newsuperiorLine = new LdifNewsuperiorLine( newsuperiorSpecToken.getOffset(),
getValueOrNull( newsuperiorSpecToken ), getValueOrNull( newsuperiorValueTypeToken ),
getValueOrNull( newsuperiorValueToken ), getValueOrNull( newsuperiorSepToken ) );
record.setNewsuperior( newsuperiorLine );
if ( newsuperiorSepToken == null )
{
this.cleanupLine( record );
}
}
else
{
if ( !checkAndParseComment( record ) && !checkAndParseOther( record ) )
{
return;
}
}
// comments
checkAndParseComment( record );
}
while ( true );
}
private void parseChangeModifyRecord( LdifChangeModifyRecord record )
{
do
{
if ( checkAndParseEndOfRecord( record ) )
{
return;
}
// match mod type
LdifToken modSpecTypeSpecToken = scanner.matchModTypeSpec();
if ( modSpecTypeSpecToken != null )
{
// read mod type line
LdifToken modSpecTypeValueTypeToken = null;
LdifToken modSpecTypeAttributeDescriptionToken = null;
LdifToken sepToken = null;
modSpecTypeValueTypeToken = scanner.matchValueType();
if ( modSpecTypeValueTypeToken != null )
{
modSpecTypeAttributeDescriptionToken = scanner.matchAttributeDescription();
if ( modSpecTypeAttributeDescriptionToken != null )
{
sepToken = scanner.matchSep();
}
}
LdifModSpecTypeLine modSpecTypeLine = new LdifModSpecTypeLine( modSpecTypeSpecToken.getOffset(),
getValueOrNull( modSpecTypeSpecToken ), getValueOrNull( modSpecTypeValueTypeToken ),
getValueOrNull( modSpecTypeAttributeDescriptionToken ), getValueOrNull( sepToken ) );
LdifModSpec modSpec = new LdifModSpec( modSpecTypeLine );
record.addModSpec( modSpec );
// clean line
if ( sepToken == null )
{
this.cleanupLine( modSpec );
}
// comment
checkAndParseComment( record );
// read attr-val lines
do
{
LdifAttrValLine line = this.getAttrValLine();
if ( line != null )
{
modSpec.addAttrVal( line );
// clean line
if ( "".equals( line.getRawNewLine() ) ) //$NON-NLS-1$
{
this.cleanupLine( record );
}
}
else
{
if ( !checkAndParseComment( record ) )
{
break;
}
}
}
while ( true );
// comments
checkAndParseComment( record );
// read sep line
LdifToken modSpecSepToken = scanner.matchModSep();
if ( modSpecSepToken != null )
{
LdifToken modSpecSepSepToken = scanner.matchSep();
LdifModSpecSepLine modSpecSepLine = new LdifModSpecSepLine( modSpecSepToken.getOffset(),
getValueOrNull( modSpecSepToken ), getValueOrNull( modSpecSepSepToken ) );
modSpec.finish( modSpecSepLine );
}
}
if ( modSpecTypeSpecToken == null )
{
if ( !checkAndParseComment( record ) && !checkAndParseOther( record ) )
{
return;
}
}
}
while ( true );
}
private void parseAttrValRecord( LdifRecord record )
{
do
{
if ( checkAndParseEndOfRecord( record ) )
{
return;
}
// check attr-val line
LdifAttrValLine line = this.getAttrValLine();
if ( line != null )
{
if ( record instanceof LdifContentRecord )
{
( ( LdifContentRecord ) record ).addAttrVal( line );
}
else if ( record instanceof LdifChangeAddRecord )
{
( ( LdifChangeAddRecord ) record ).addAttrVal( line );
}
// clean line
if ( "".equals( line.getRawNewLine() ) ) //$NON-NLS-1$
{
this.cleanupLine( record );
}
}
else
{
if ( !checkAndParseComment( record ) && !checkAndParseOther( record ) )
{
return;
}
}
}
while ( true );
}
private boolean checkAndParseEndOfRecord( LdifRecord record )
{
// check end of record
LdifToken eorSepToken = scanner.matchSep();
if ( eorSepToken != null )
{
record.finish( new LdifSepLine( eorSepToken.getOffset(), getValueOrNull( eorSepToken ) ) );
return true;
}
// check end of file
LdifToken eofToken = scanner.matchEOF();
if ( eofToken != null )
{
record.finish( new LdifEOFPart( eofToken.getOffset() ) );
return true;
}
return false;
}
private boolean checkAndParseComment( LdifRecord record )
{
LdifToken commentToken = scanner.matchComment();
if ( commentToken != null )
{
while ( commentToken != null )
{
LdifToken sepToken = scanner.matchSep();
record.addComment( new LdifCommentLine( commentToken.getOffset(), getValueOrNull( commentToken ),
getValueOrNull( sepToken ) ) );
commentToken = scanner.matchComment();
}
return true;
}
else
{
return false;
}
}
private boolean checkAndParseOther( LdifRecord record )
{
LdifToken otherToken = scanner.matchOther();
if ( otherToken != null )
{
record.addInvalid( new LdifInvalidPart( otherToken.getOffset(), otherToken.getValue() ) );
return true;
}
else
{
return false;
}
}
/**
* Checks for version line. If version line is present it is parsed and
* added to the given model.
*
* @param model
* the model
* @return true if version line was added to the model, false otherwise
*/
private boolean checkAndParseVersion( LdifFile model )
{
LdifToken versionSpecToken = scanner.matchVersionSpec();
if ( versionSpecToken != null )
{
LdifToken versionTypeToken = null;
LdifToken versionToken = null;
LdifToken sepToken = null;
versionTypeToken = scanner.matchValueType();
if ( versionTypeToken != null )
{
versionToken = scanner.matchNumber();
if ( versionToken != null )
{
sepToken = scanner.matchSep();
}
}
LdifVersionContainer container = new LdifVersionContainer( new LdifVersionLine( versionSpecToken
.getOffset(), getValueOrNull( versionSpecToken ), getValueOrNull( versionTypeToken ),
getValueOrNull( versionToken ), getValueOrNull( sepToken ) ) );
model.addContainer( container );
// clean line
if ( sepToken == null )
{
this.cleanupLine( container );
}
return true;
}
else
{
return false;
}
}
/**
* Checks for comment lines or empty lines. If such lines are present
* they are parsed and added to the given model.
*
* @param model
* the model
* @return true if comment or empty lines were added to the model, false
* otherwise
*/
private boolean checkAndParseComment( LdifFile model )
{
LdifToken sepToken = scanner.matchSep();
LdifToken commentToken = scanner.matchComment();
if ( sepToken != null || commentToken != null )
{
while ( sepToken != null || commentToken != null )
{
if ( sepToken != null )
{
LdifSepLine sepLine = new LdifSepLine( sepToken.getOffset(), getValueOrNull( sepToken ) );
LdifSepContainer sepContainer = new LdifSepContainer( sepLine );
model.addContainer( sepContainer );
}
if ( commentToken != null )
{
LdifCommentContainer commentContainer = null;
while ( commentToken != null )
{
LdifToken commentSepToken = scanner.matchSep();
LdifCommentLine commentLine = new LdifCommentLine( commentToken.getOffset(),
getValueOrNull( commentToken ), getValueOrNull( commentSepToken ) );
if ( commentContainer == null )
{
commentContainer = new LdifCommentContainer( commentLine );
}
else
{
commentContainer.addComment( commentLine );
}
commentToken = scanner.matchComment();
}
model.addContainer( commentContainer );
}
sepToken = scanner.matchSep();
commentToken = scanner.matchComment();
}
return true;
}
else
{
return false;
}
}
/**
* Checks for other line. If such line is present it is parsed and added
* to the given model.
*
* @param model
* the model
* @return always true except if EOF reached
*/
private boolean checkAndParseOther( LdifFile model )
{
LdifToken token = scanner.matchOther();
if ( token != null )
{
LdifInvalidPart unknownLine = new LdifInvalidPart( token.getOffset(), getValueOrNull( token ) );
LdifInvalidContainer otherContainer = new LdifInvalidContainer( unknownLine );
model.addContainer( otherContainer );
return true;
}
else
{
return false;
}
}
private LdifControlLine getControlLine()
{
LdifToken controlSpecToken = scanner.matchControlSpec();
if ( controlSpecToken != null )
{
LdifToken controlTypeToken = null;
LdifToken oidToken = null;
LdifToken criticalityToken = null;
LdifToken valueTypeToken = null;
LdifToken valueToken = null;
LdifToken sepToken = null;
controlTypeToken = scanner.matchValueType();
if ( controlTypeToken != null )
{
oidToken = scanner.matchOid();
if ( oidToken != null )
{
criticalityToken = scanner.matchCriticality();
valueTypeToken = scanner.matchValueType();
if ( valueTypeToken != null )
{
valueToken = scanner.matchValue();
}
sepToken = scanner.matchSep();
}
}
LdifControlLine controlLine = new LdifControlLine( controlSpecToken.getOffset(),
getValueOrNull( controlSpecToken ), getValueOrNull( controlTypeToken ), getValueOrNull( oidToken ),
getValueOrNull( criticalityToken ), getValueOrNull( valueTypeToken ), getValueOrNull( valueToken ),
getValueOrNull( sepToken ) );
return controlLine;
}
return null;
}
private LdifChangeTypeLine getChangeTypeLine()
{
LdifToken changeTypeSpecToken = scanner.matchChangeTypeSpec();
if ( changeTypeSpecToken != null )
{
LdifToken changeTypeTypeToken = null;
LdifToken changeTypeToken = null;
LdifToken sepToken = null;
changeTypeTypeToken = scanner.matchValueType();
if ( changeTypeTypeToken != null )
{
changeTypeToken = scanner.matchChangeType();
if ( changeTypeToken != null )
{
sepToken = scanner.matchSep();
}
}
LdifChangeTypeLine ctLine = new LdifChangeTypeLine( changeTypeSpecToken.getOffset(),
getValueOrNull( changeTypeSpecToken ), getValueOrNull( changeTypeTypeToken ),
getValueOrNull( changeTypeToken ), getValueOrNull( sepToken ) );
return ctLine;
}
return null;
}
private LdifAttrValLine getAttrValLine()
{
LdifToken attrToken = scanner.matchAttributeDescription();
if ( attrToken != null )
{
LdifToken valueTypeToken = null;
LdifToken valueToken = null;
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | true |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/DummyLdifContainer.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/DummyLdifContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.parser;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldifparser.model.LdifPart;
import org.apache.directory.studio.ldifparser.model.container.LdifContainer;
import org.apache.directory.studio.ldifparser.model.lines.LdifCommentLine;
public class DummyLdifContainer extends LdifContainer
{
public DummyLdifContainer( LdifPart part )
{
super( part );
}
public LdifCommentLine[] getComments()
{
List<LdifPart> ldifPartList = new ArrayList<LdifPart>();
for ( LdifPart ldifPart : ldifParts )
{
if ( ldifPart instanceof LdifCommentLine )
{
ldifPartList.add( ldifPart );
}
}
return ( LdifCommentLine[] ) ldifPartList.toArray( new LdifCommentLine[ldifPartList.size()] );
}
public boolean isValid()
{
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/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifScanner.java | plugins/ldifparser/src/main/java/org/apache/directory/studio/ldifparser/parser/LdifScanner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifparser.parser;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
// RFC 2849
//
// ldif-file = ldif-content / ldif-changes
// ldif-content = version-spec 1*(1*SEP ldif-attrval-record)
// ldif-changes = version-spec 1*(1*SEP ldif-change-record)
// ldif-attrval-record = dn-spec SEP 1*attrval-spec
// ldif-change-record = dn-spec SEP *control changerecord
// version-spec = "version:" FILL version-number
// version-number = 1*DIGIT
// ; version-number MUST be "1" for the
// ; LDIF format described in this document.
// dn-spec = "dn:" (FILL distinguishedName /
// ":" FILL base64-distinguishedName)
// distinguishedName = SAFE-STRING
// ; a distinguished name, as defined in [3]
// base64-distinguishedName = BASE64-UTF8-STRING
// ; a distinguishedName which has been base64
// ; encoded (see note 10, below)
// rdn = SAFE-STRING
// ; a relative distinguished name, defined as
// ; <name-component> in [3]
// base64-rdn = BASE64-UTF8-STRING
// ; an rdn which has been base64 encoded (see
// ; note 10, below)
// control = "control:" FILL ldap-oid ; controlType
// 0*1(1*SPACE ("true" / "false")) ; criticality
// 0*1(value-spec) ; controlValue
// SEP
// ; (See note 9, below)
// ldap-oid = 1*DIGIT 0*1("." 1*DIGIT)
// ; An LDAPOID, as defined in [4]
// attrval-spec = AttributeDescription value-spec SEP
// value-spec = ":" ( FILL 0*1(SAFE-STRING) /
// ":" FILL (BASE64-STRING) /
// "<" FILL url)
// ; See notes 7 and 8, below
// url = <a Uniform Resource Locator,
// as defined in [6]>
// ; (See Note 6, below)
// AttributeDescription = AttributeType [";" options]
// ; Definition taken from [4]
// AttributeType = ldap-oid / (ALPHA *(attr-type-chars))
// options = option / (option ";" options)
// option = 1*opt-char
// attr-type-chars = ALPHA / DIGIT / "-"
// opt-char = attr-type-chars
// changerecord = "changetype:" FILL
// (change-add / change-delete /
// change-modify / change-moddn)
// change-add = "add" SEP 1*attrval-spec
// change-delete = "delete" SEP
// change-moddn = ("modrdn" / "moddn") SEP
// "newrdn:" ( FILL rdn /
// ":" FILL base64-rdn) SEP
// "deleteoldrdn:" FILL ("0" / "1") SEP
// 0*1("newsuperior:"
// ( FILL distinguishedName /
// ":" FILL base64-distinguishedName) SEP)
// change-modify = "modify" SEP *mod-spec
// mod-spec = ("add:" / "delete:" / "replace:")
// FILL AttributeDescription SEP
// *attrval-spec
// "-" SEP
// SPACE = %x20
// ; ASCII SP, space
// FILL = *SPACE
// SEP = (CR LF / LF)
// CR = %x0D
// ; ASCII CR, carriage return
// LF = %x0A
// ; ASCII LF, line feed
// ALPHA = %x41-5A / %x61-7A
// ; A-Z / a-z
// DIGIT = %x30-39
// ; 0-9
// UTF8-1 = %x80-BF
// UTF8-2 = %xC0-DF UTF8-1
// UTF8-3 = %xE0-EF 2UTF8-1
// UTF8-4 = %xF0-F7 3UTF8-1
// UTF8-5 = %xF8-FB 4UTF8-1
// UTF8-6 = %xFC-FD 5UTF8-1
// SAFE-CHAR = %x01-09 / %x0B-0C / %x0E-7F
// ; any value <= 127 decimal except NUL, LF,
// ; and CR
// SAFE-INIT-CHAR = %x01-09 / %x0B-0C / %x0E-1F /
// %x21-39 / %x3B / %x3D-7F
// ; any value <= 127 except NUL, LF, CR,
// ; SPACE, colon (":", ASCII 58 decimal)
// ; and less-than ("<" , ASCII 60 decimal)
// SAFE-STRING = [SAFE-INIT-CHAR *SAFE-CHAR]
// UTF8-CHAR = SAFE-CHAR / UTF8-2 / UTF8-3 /
// UTF8-4 / UTF8-5 / UTF8-6
// UTF8-STRING = *UTF8-CHAR
// BASE64-UTF8-STRING = BASE64-STRING
// ; MUST be the base64 encoding of a
// ; UTF8-STRING
// BASE64-CHAR = %x2B / %x2F / %x30-39 / %x3D / %x41-5A /
// %x61-7A
// ; +, /, 0-9, =, A-Z, and a-z
// ; as specified in [5]
// BASE64-STRING = [*(BASE64-CHAR)]
public class LdifScanner
{
private Reader ldifReader;
private char[] buffer = new char[256];
private StringBuffer ldifBuffer;
private int ldifBufferOffset;
private int pos;
public LdifScanner()
{
super();
}
public void setLdif( Reader ldifReader )
{
// this.ldif = ldif;
this.ldifReader = ldifReader;
this.pos = -1;
this.ldifBuffer = new StringBuffer();
this.ldifBufferOffset = 0;
}
char currentChar() throws EOFException
{
// check and fill buffer
try
{
int num = 0;
while ( ldifBufferOffset + ldifBuffer.length() <= pos && num > -1 )
{
num = this.ldifReader.read( buffer );
if ( num > -1 )
{
ldifBuffer.append( buffer, 0, num );
}
}
}
catch ( IOException e )
{
}
if ( 0 <= pos && pos < ldifBufferOffset + ldifBuffer.length() )
{
try
{
return ldifBuffer.charAt( pos - ldifBufferOffset );
}
catch ( RuntimeException e )
{
e.printStackTrace();
throw e;
}
}
else
{
throw new EOFException();
}
// return 0<=pos&&pos<ldif.length() ? ldif.charAt(pos) : '\u0000';
}
void addFolding( StringBuffer sb )
{
int oldPos = pos;
try
{
pos++;
char c = currentChar();
if ( c == '\n' || c == '\r' )
{
StringBuffer temp = new StringBuffer( 3 );
temp.append( c );
if ( c == '\r' )
{
pos++;
c = currentChar();
if ( c == '\n' )
{
temp.append( c );
}
else
{
pos--;
}
}
else if ( c == '\n' )
{
pos++;
c = currentChar();
if ( c == '\r' )
{
temp.append( c );
}
else
{
pos--;
}
}
pos++;
c = currentChar();
if ( c == ' ' )
{
// space after newline, continue
temp.append( c );
sb.append( temp );
}
else
{
for ( int i = 0; i < temp.length(); i++ )
{
pos--;
}
pos--;
}
}
else
{
pos--;
}
}
catch ( EOFException e )
{
// reset position
pos = oldPos;
}
}
/**
* Reads the next character from input stram if available. If read was
* possible the character is appended to the given StringBuffer and
* returned. Otherwise throws a EOFException. Additionally this method
* checks folding sequence SEP + SPACE. If any folding sequence was
* found the sequence is appended to the given StringBuffer. So it is
* possible the StringBuffer doesn't end with the read character after
* calling this method but with a folding sequence
*
* @param sb
* @return the next character if available
* @throws EOFException
*/
public char read( StringBuffer sb ) throws EOFException
{
try
{
// check EOF
// if(pos > -1) {
// currentChar();
// }
// get next char
pos++;
char c = currentChar();
sb.append( c );
// folding
addFolding( sb );
return c;
}
catch ( EOFException e )
{
pos--;
throw e;
}
}
void removeFolding( StringBuffer sb )
{
int oldPos = pos;
try
{
char c = currentChar();
pos--;
if ( c == ' ' )
{
StringBuffer temp = new StringBuffer();
temp.insert( 0, c );
c = currentChar();
pos--;
if ( c == '\n' || c == '\r' )
{
if ( c == '\r' )
{
temp.insert( 0, c );
c = currentChar();
pos--;
if ( c == '\n' )
{
temp.insert( 0, c );
}
else
{
pos++;
}
}
else if ( c == '\n' )
{
temp.insert( 0, c );
c = currentChar();
pos--;
if ( c == '\r' )
{
temp.insert( 0, c );
}
else
{
pos++;
}
}
sb.delete( sb.length() - temp.length(), sb.length() );
}
else
{
pos++;
pos++;
}
}
else
{
pos++;
}
}
catch ( EOFException e )
{
// reset position
pos = oldPos;
}
}
/**
* Inverses the previous read().
*
* @param sb
* @throws EOFException
*/
public void unread( StringBuffer sb )
{
removeFolding( sb );
if ( pos > -1 )
{
pos--;
if ( sb.length() > 0 )
{
sb.deleteCharAt( sb.length() - 1 );
}
}
}
private String getFullLine( String start )
{
String s1 = this.getWord( start );
if ( s1 != null )
{
String s2 = getContent( false );
return s2 != null ? s1 + s2 : s1;
}
else
{
return null;
}
}
private String getContent( boolean allowEmptyContent )
{
StringBuffer sb = new StringBuffer( 256 );
try
{
char c = '\u0000';
while ( c != '\n' && c != '\r' )
{
c = read( sb );
}
unread( sb );
}
catch ( EOFException e )
{
}
return sb.length() > 0 || allowEmptyContent ? sb.toString() : null;
}
private String getWord( String word )
{
StringBuffer sb = new StringBuffer();
// read
try
{
boolean matches = true;
for ( int i = 0; i < word.length(); i++ )
{
char c = read( sb );
//if ( c != word.charAt( i ) )
if ( Character.toUpperCase( c ) != Character.toUpperCase( word.charAt( i ) ) )
{
matches = false;
unread( sb );
break;
}
}
if ( matches )
{
return sb.toString();
}
}
catch ( EOFException e )
{
}
// unread
while ( sb.length() > 0 )
{
unread( sb );
}
// prevChar(sb);
return null;
}
private String getWordTillColon( String word )
{
String wordWithColon = word + ":"; //$NON-NLS-1$
String line = getWord( wordWithColon );
if ( line != null )
{
StringBuffer sb = new StringBuffer( line );
unread( sb );
return sb.toString();
}
// allow eof and sep
line = getWord( word );
if ( line != null )
{
StringBuffer sb = new StringBuffer( line );
try
{
char c = read( sb );
unread( sb );
if ( c == '\r' || c == '\n' )
{
return sb.toString();
}
else
{
while ( sb.length() > 0 )
{
unread( sb );
}
return null;
}
}
catch ( EOFException e )
{
return sb.toString();
}
}
return null;
}
private void flushBuffer()
{
if ( this.ldifBufferOffset < this.pos && this.ldifBuffer.length() > 0 )
{
int delta = Math.min( pos - this.ldifBufferOffset, this.ldifBuffer.length() );
delta--;
this.ldifBuffer.delete( 0, delta );
this.ldifBufferOffset += delta;
}
}
public LdifToken matchCleanupLine()
{
this.flushBuffer();
String line = getContent( false );
LdifToken sep = matchSep();
if ( line != null || sep != null )
{
if ( line == null )
line = ""; //$NON-NLS-1$
if ( sep != null )
line += sep.getValue();
return new LdifToken( LdifToken.UNKNOWN, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchOther()
{
this.flushBuffer();
String line = getContent( false );
if ( line != null )
{
LdifToken sep = matchSep();
if ( sep != null )
line += sep.getValue();
return new LdifToken( LdifToken.UNKNOWN, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchEOF()
{
this.flushBuffer();
StringBuffer sb = new StringBuffer( 1 );
try
{
read( sb );
unread( sb );
return null;
}
catch ( EOFException e )
{
return new LdifToken( LdifToken.EOF, "", pos + 1 ); //$NON-NLS-1$
}
}
public LdifToken matchSep()
{
this.flushBuffer();
try
{
StringBuffer sb = new StringBuffer();
char c = read( sb );
if ( c == '\n' || c == '\r' )
{
// check for two-char-linebreak
try
{
if ( c == '\r' )
{
c = read( sb );
if ( c != '\n' )
{
unread( sb );
}
}
else if ( c == '\n' )
{
c = read( sb );
if ( c != '\r' )
{
unread( sb );
}
}
}
catch ( EOFException e )
{
}
return new LdifToken( LdifToken.SEP, sb.toString(), pos - sb.length() + 1 );
}
else
{
unread( sb );
}
}
catch ( EOFException e )
{
}
return null;
}
public LdifToken matchComment()
{
this.flushBuffer();
String line = getFullLine( "#" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.COMMENT, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchVersionSpec()
{
this.flushBuffer();
String line = getWordTillColon( "version" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.VERSION_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchDnSpec()
{
this.flushBuffer();
String line = getWordTillColon( "dn" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.DN_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchControlSpec()
{
this.flushBuffer();
String line = getWordTillColon( "control" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CONTROL_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchChangeTypeSpec()
{
this.flushBuffer();
String line = getWordTillColon( "changetype" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchChangeType()
{
this.flushBuffer();
String line = getWord( "add" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_ADD, line, pos - line.length() + 1 );
}
line = getWord( "modify" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_MODIFY, line, pos - line.length() + 1 );
}
line = getWord( "delete" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_DELETE, line, pos - line.length() + 1 );
}
line = getWord( "moddn" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_MODDN, line, pos - line.length() + 1 );
}
line = getWord( "modrdn" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.CHANGETYPE_MODDN, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchCriticality()
{
this.flushBuffer();
StringBuffer sb = new StringBuffer();
String s = getWord( " " ); //$NON-NLS-1$
while ( s != null )
{
sb.append( s );
s = getWord( " " ); //$NON-NLS-1$
}
String t = getWord( "true" ); //$NON-NLS-1$
if ( t != null )
{
sb.append( t );
return new LdifToken( LdifToken.CONTROL_CRITICALITY_TRUE, sb.toString(), pos - sb.length() + 1 );
}
String f = getWord( "false" ); //$NON-NLS-1$
if ( f != null )
{
sb.append( f );
return new LdifToken( LdifToken.CONTROL_CRITICALITY_FALSE, sb.toString(), pos - sb.length() + 1 );
}
while ( sb.length() > 0 )
{
unread( sb );
}
// for(int i=0; i<sb.length(); i++) {
// unread(sb);
// }
return null;
}
public LdifToken matchNumber()
{
this.flushBuffer();
try
{
StringBuffer sb = new StringBuffer();
char c = read( sb );
if ( '0' <= c && c <= '9' )
{
try
{
while ( '0' <= c && c <= '9' )
{
c = read( sb );
}
unread( sb );
}
catch ( EOFException e )
{
}
return new LdifToken( LdifToken.NUMBER, sb.toString(), pos - sb.length() + 1 );
}
else
{
unread( sb );
}
}
catch ( EOFException e )
{
}
return null;
}
public LdifToken matchOid()
{
this.flushBuffer();
try
{
StringBuffer sb = new StringBuffer();
char c = read( sb );
if ( '0' <= c && c <= '9' )
{
try
{
while ( '0' <= c && c <= '9' || c == '.' )
{
c = read( sb );
}
unread( sb );
}
catch ( EOFException e )
{
}
return new LdifToken( LdifToken.OID, sb.toString(), pos - sb.length() + 1 );
}
else
{
unread( sb );
}
}
catch ( EOFException e )
{
}
return null;
}
public LdifToken matchAttributeDescription()
{
this.flushBuffer();
try
{
StringBuffer sb = new StringBuffer();
char c = read( sb );
if ( 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' )
{
try
{
while ( 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '.'
|| c == ';' || c == '-' || c == '_' )
{
c = read( sb );
}
unread( sb );
}
catch ( EOFException e )
{
}
return new LdifToken( LdifToken.ATTRIBUTE, sb.toString(), pos - sb.length() + 1 );
}
else
{
unread( sb );
}
}
catch ( EOFException e )
{
}
// // a-z,A-Z,0-9,.,-,;
// StringBuffer sb = new StringBuffer();
// char c = nextChar(sb);
// if('a'<=c&&c<='z' || 'A'<=c&&c<='Z' || '0'<=c&&c<='9') {
// while('a'<=c&&c<='z' || 'A'<=c&&c<='Z' || '0'<=c&&c<='9' || c=='.' ||
// c==';' || c=='-') {
// sb.append(c);
// c = nextChar(sb);
// }
// unread(sb);
//
// return new LdifToken(LdifToken.ATTRIBUTE, sb.toString(),
// pos-sb.length()+1);
// }
// else {
// unread(sb);
// }
return null;
}
/**
* Matches "add", "replace", or "delete"
*
* @return the LIDF token if matched, null if not matched
*/
public LdifToken matchModTypeSpec()
{
this.flushBuffer();
String line = getWord( "add" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODTYPE_ADD_SPEC, line, pos - line.length() + 1 );
}
line = getWord( "replace" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODTYPE_REPLACE_SPEC, line, pos - line.length() + 1 );
}
line = getWord( "delete" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODTYPE_DELETE_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchModSep()
{
this.flushBuffer();
String line = getWord( "-" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODTYPE_SEP, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchValueType()
{
this.flushBuffer();
try
{
StringBuffer sb = new StringBuffer();
char c = read( sb );
if ( c == ':' )
{
int tokenType = LdifToken.VALUE_TYPE_SAFE;
try
{
c = read( sb );
if ( c == ':' )
{
tokenType = LdifToken.VALUE_TYPE_BASE64;
}
else if ( c == '<' )
{
tokenType = LdifToken.VALUE_TYPE_URL;
}
else
{
tokenType = LdifToken.VALUE_TYPE_SAFE;
unread( sb );
}
c = read( sb );
while ( c == ' ' )
{
c = read( sb );
}
unread( sb );
}
catch ( EOFException e )
{
}
return new LdifToken( tokenType, sb.toString(), pos - sb.length() + 1 );
}
else
{
unread( sb );
}
}
catch ( EOFException e )
{
}
return null;
}
public LdifToken matchValue()
{
this.flushBuffer();
String line = getContent( true );
if ( line != null )
{
return new LdifToken( LdifToken.VALUE, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchNewrdnSpec()
{
this.flushBuffer();
String line = getWordTillColon( "newrdn" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODDN_NEWRDN_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchDeleteoldrdnSpec()
{
this.flushBuffer();
String line = getWordTillColon( "deleteoldrdn" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODDN_DELOLDRDN_SPEC, line, pos - line.length() + 1 );
}
return null;
}
public LdifToken matchNewsuperiorSpec()
{
this.flushBuffer();
String line = getWordTillColon( "newsuperior" ); //$NON-NLS-1$
if ( line != null )
{
return new LdifToken( LdifToken.MODDN_NEWSUPERIOR_SPEC, line, pos - line.length() + 1 );
}
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/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorConstants.java | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor;
/**
* Constants for the LDIF editor.
* Final reference -> class shouldn't be extended
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public final class LdifEditorConstants
{
/**
* 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 LdifEditorConstants()
{
}
/** The plug-in ID */
public static final String PLUGIN_ID = LdifEditorConstants.class.getPackage().getName();
public static final String ACTION_ID_EDIT_RECORD = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "Cmd_EditRecord_id" ); //$NON-NLS-1$
public static final String ACTION_ID_EDIT_ATTRIBUTE_DESCRIPTION = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "Cmd_EditAttributeDescription_id" ); //$NON-NLS-1$
public static final String ACTION_ID_FORMAT_LDIF_DOCUMENT =
"org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifDocumentAction"; //$NON-NLS-1$
public static final String ACTION_ID_FORMAT_LDIF_RECORD =
"org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifRecordAction"; //$NON-NLS-1$
public static final String ACTION_ID_EXECUTE_LDIF =
"org.apache.directory.studio.ldifeditor.editor.ExecuteLdifAction"; //$NON-NLS-1$
public static final String NEW_WIZARD_NEW_LDIF_FILE = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "NewWizard_NewLdifFileWizard_id" ); //$NON-NLS-1$
public static final String EDITOR_LDIF_EDITOR = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "Editor_LdifEditor_id" ); //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_FORMATTER_AUTOWRAP = "ldifEditorFormatterAutoWrap"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_FOLDING_ENABLE = "ldifEditorFoldingEnable"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDCOMMENTS = "ldifEditorFoldingInitiallyFoldComments"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDRECORDS = "ldifEditoroldingInitiallyFoldRecords"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDWRAPPEDLINES = "ldifEditorFoldingInitiallyFoldWrappedLines"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_DOUBLECLICK_USELDIFDOUBLECLICK = "ldifEditorDoubleClickUserLdifDoubleClick"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_CONTENTASSIST_INSERTSINGLEPROPOSALAUTO = "ldifEditorCodeAssistInsertSingleProposalAuto"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_CONTENTASSIST_ENABLEAUTOACTIVATION = "ldifEditorCodeAssistEnableAutoActivation"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_CONTENTASSIST_AUTOACTIVATIONDELAY = "ldifEditorCodeAssistAutoActivationDelay"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_CONTENTASSIST_SMARTINSERTATTRIBUTEINMODSPEC = "ldifEditorCodeAssistInsertAttributeInModSpec"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_OPTIONS_UPDATEIFENTRYEXISTS = "ldifEditorOptionsUpdateIfEntryExists"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_OPTIONS_CONTINUEONERROR = "ldifEditorOptionsContinueOnError"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX = "_RGB"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX = "_STYLE"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_COMMENT = "ldifEditorSyntaxComment"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_KEYWORD = "ldifEditorSyntaxKeyword"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_DN = "ldifEditorSyntaxDn"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_ATTRIBUTE = "ldifEditorSyntaxAttribute"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_VALUETYPE = "ldifEditorSyntaxValueType"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_VALUE = "ldifEditorSyntaxValue"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEADD = "ldifEditorSyntaxChangetypeAdd"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODIFY = "ldifEditorSyntaxChangetypeModify"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEDELETE = "ldifEditorSyntaxChangetypeDelete"; //$NON-NLS-1$
public static final String PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODDN = "ldifEditorSyntaxChangetypeModdn"; //$NON-NLS-1$
public static final String PREFERENCEPAGEID_LDIFEDITOR = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "PrefPage_LdifEditorPreferencePage_id" ); //$NON-NLS-1$
public static final String PREFERENCEPAGEID_LDIFEDITOR_CONTENTASSIST = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "PrefPage_LdifEditorContentAssistPreferencePage_id" ); //$NON-NLS-1$
public static final String PREFERENCEPAGEID_LDIFEDITOR_SYNTAXCOLORING = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "PrefPage_LdifEditorSyntaxColoringPreferencePage_id" ); //$NON-NLS-1$
public static final String PREFERENCEPAGEID_LDIFEDITOR_TEMPLATES = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "PrefPage_LdifEditorTemplatesPreferencePage_id" ); //$NON-NLS-1$
public static final String LDIF_FILE_TEMPLATE_ID = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "CtxType_LdifFile_id" ); //$NON-NLS-1$
public static final String LDIF_ATTR_VAL_RECORD_TEMPLATE_ID = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "CtxType_LdifAttributeValueRecord_id" ); //$NON-NLS-1$
public static final String LDIF_MODIFICATION_RECORD_TEMPLATE_ID = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "CtxType_LdifModificationRecord_id" ); //$NON-NLS-1$
public static final String LDIF_MODIFICATION_ITEM_TEMPLATE_ID = LdifEditorActivator.getDefault()
.getPluginProperties().getString( "CtxType_LdifModificationItem_id" ); //$NON-NLS-1$
public static final String LDIF_MODDN_RECORD_TEMPLATE_ID = LdifEditorActivator.getDefault().getPluginProperties()
.getString( "CtxType_LdifModdnRecord_id" ); //$NON-NLS-1$
public static final String IMG_LDIF_ADD = "resources/icons/ldif_add.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_MODIFY = "resources/icons/ldif_modify.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_DELETE = "resources/icons/ldif_delete.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_RENAME = "resources/icons/ldif_rename.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_ATTRIBUTE = "resources/icons/ldif_attribute.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_VALUE = "resources/icons/ldif_value.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_MOD_ADD = "resources/icons/ldif_mod_add.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_MOD_REPLACE = "resources/icons/ldif_mod_replace.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_MOD_DELETE = "resources/icons/ldif_mod_delete.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_COMMENT = "resources/icons/ldif_comment.gif"; //$NON-NLS-1$
public static final String IMG_LDIF_DN = "resources/icons/ldif_dn.gif"; //$NON-NLS-1$
public static final String IMG_ENTRY = "resources/icons/entry.gif"; //$NON-NLS-1$
public static final String IMG_TEMPLATE = "resources/icons/template.gif"; //$NON-NLS-1$
public static final String IMG_BROWSER_LDIFEDITOR = "resources/icons/ldifeditor.gif"; //$NON-NLS-1$
public static final String IMG_LDIFEDITOR_NEW = "resources/icons/ldifeditor_new.gif"; //$NON-NLS-1$
public static final String IMG_EXECUTE = "resources/icons/execute.gif"; //$NON-NLS-1$
public static final String LDIF_PARTITIONING = "org.apache.directory.studio.ldifeditor.LdifPartitioning"; //$NON-NLS-1$
public static final String CONTENTASSIST_ACTION = "org.apache.directory.studio.ldapbrowser.ContentAssist"; //$NON-NLS-1$
public static final String PREFERENCEPAGEID_TEXTFORMATS =
"org.apache.directory.studio.ldapbrowser.preferences.TextFormatsPreferencePage"; //$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/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorPreferencesInitializer.java | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorPreferencesInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor;
import org.apache.directory.studio.common.ui.CommonUIConstants;
import org.apache.directory.studio.common.ui.CommonUIPlugin;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
/**
* This class is used to set default preference values for the LDIF editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifEditorPreferencesInitializer extends AbstractPreferenceInitializer
{
/**
* {@inheritDoc}
*/
public void initializeDefaultPreferences()
{
IPreferenceStore store = LdifEditorActivator.getDefault().getPreferenceStore();
// LDIF Editor
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_FORMATTER_AUTOWRAP, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_FOLDING_ENABLE, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDCOMMENTS, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDRECORDS, false );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_FOLDING_INITIALLYFOLDWRAPPEDLINES, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_DOUBLECLICK_USELDIFDOUBLECLICK, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_CONTENTASSIST_INSERTSINGLEPROPOSALAUTO, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_CONTENTASSIST_ENABLEAUTOACTIVATION, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_CONTENTASSIST_AUTOACTIVATIONDELAY, 200 );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_CONTENTASSIST_SMARTINSERTATTRIBUTEINMODSPEC, true );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_OPTIONS_UPDATEIFENTRYEXISTS, false );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_OPTIONS_CONTINUEONERROR, true );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_COMMENT
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.COMMENT_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_COMMENT
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.NORMAL );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_KEYWORD
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.KEYWORD_1_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_KEYWORD
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_DN
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.DEFAULT_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_DN
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_ATTRIBUTE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.ATTRIBUTE_TYPE_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_ATTRIBUTE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUETYPE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.SEPARATOR_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUETYPE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.VALUE_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.NORMAL );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEADD
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.ADD_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEADD
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODIFY
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.MODIFY_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODIFY
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEDELETE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.DELETE_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEDELETE
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
setDefaultColor( store, LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODDN
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX,
CommonUIConstants.RENAME_COLOR );
store.setDefault( LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODDN
+ LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, SWT.BOLD );
}
private void setDefaultColor( IPreferenceStore store, String preferenceName, String colorName )
{
Color color = CommonUIPlugin.getDefault().getColor( colorName );
if ( color == null )
{
store.setDefault( preferenceName, IPreferenceStore.STRING_DEFAULT_DEFAULT );
}
else
{
PreferenceConverter.setDefault( store, preferenceName, color.getRGB() );
}
}
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorActivator.java | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/LdifEditorActivator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor;
import java.io.IOException;
import java.net.URL;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.templates.ContextTypeRegistry;
import org.eclipse.jface.text.templates.GlobalTemplateVariables;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class LdifEditorActivator extends AbstractUIPlugin
{
/** The shared instance */
private static LdifEditorActivator plugin;
/** Resource bundle */
private ResourceBundle resourceBundle;
/** The color registry */
private ColorRegistry colorRegistry;
/** The template store */
private ContributionTemplateStore ldifTemplateStore;
/** The context type registry */
private ContributionContextTypeRegistry ldifTemplateContextTypeRegistry;
/** The plugin properties */
private PropertyResourceBundle properties;
/**
* The constructor
*/
public LdifEditorActivator()
{
plugin = this;
try
{
resourceBundle = ResourceBundle.getBundle( "org.apache.directory.studio.ldifeditor.messages" ); //$NON-NLS-1$
}
catch ( MissingResourceException x )
{
resourceBundle = null;
}
}
/**
* {@inheritDoc}
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
if ( colorRegistry == null )
{
colorRegistry = new ColorRegistry( getWorkbench().getDisplay() );
}
if ( ldifTemplateContextTypeRegistry == null )
{
ldifTemplateContextTypeRegistry = new ContributionContextTypeRegistry();
ldifTemplateContextTypeRegistry.addContextType( LdifEditorConstants.LDIF_FILE_TEMPLATE_ID );
ldifTemplateContextTypeRegistry.getContextType( LdifEditorConstants.LDIF_FILE_TEMPLATE_ID ).addResolver(
new GlobalTemplateVariables.Cursor() );
ldifTemplateContextTypeRegistry.addContextType( LdifEditorConstants.LDIF_ATTR_VAL_RECORD_TEMPLATE_ID );
ldifTemplateContextTypeRegistry.getContextType( LdifEditorConstants.LDIF_ATTR_VAL_RECORD_TEMPLATE_ID )
.addResolver( new GlobalTemplateVariables.Cursor() );
ldifTemplateContextTypeRegistry.addContextType( LdifEditorConstants.LDIF_MODIFICATION_RECORD_TEMPLATE_ID );
ldifTemplateContextTypeRegistry.getContextType( LdifEditorConstants.LDIF_MODIFICATION_RECORD_TEMPLATE_ID )
.addResolver( new GlobalTemplateVariables.Cursor() );
ldifTemplateContextTypeRegistry.addContextType( LdifEditorConstants.LDIF_MODIFICATION_ITEM_TEMPLATE_ID );
ldifTemplateContextTypeRegistry.addContextType( LdifEditorConstants.LDIF_MODDN_RECORD_TEMPLATE_ID );
}
if ( ldifTemplateStore == null )
{
ldifTemplateStore = new ContributionTemplateStore( getLdifTemplateContextTypeRegistry(),
getPreferenceStore(), "templates" ); //$NON-NLS-1$
try
{
ldifTemplateStore.load();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/**
* {@inheritDoc}
*/
public void stop( BundleContext context ) throws Exception
{
plugin = null;
super.stop( context );
if ( colorRegistry != null )
{
colorRegistry = null;
}
if ( ldifTemplateContextTypeRegistry != null )
{
ldifTemplateContextTypeRegistry = null;
}
if ( ldifTemplateStore != null )
{
try
{
ldifTemplateStore.save();
}
catch ( IOException e )
{
e.printStackTrace();
}
ldifTemplateStore = null;
}
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static LdifEditorActivator getDefault()
{
return plugin;
}
/**
* 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() );
}
/**
* Use this method to get SWT images. Use the IMG_ constants from
* LdifEditorConstants for the key.
*
* @param key
* The key (relative path to the image im filesystem)
* @return The image discriptor 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
* LdifEditorConstants 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 im filesystem)
* @return The SWT Image or null
* @see LdifEditorConstants
*/
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;
}
/**
*
* @return The LDIF template context type registry
*/
public ContextTypeRegistry getLdifTemplateContextTypeRegistry()
{
return ldifTemplateContextTypeRegistry;
}
/**
*
* @return The LDIF template store
*/
public TemplateStore getLdifTemplateStore()
{
return ldifTemplateStore;
}
/**
* Gets the resource bundle.
*
* @return the resource bundle
*/
public ResourceBundle getResourceBundle()
{
return resourceBundle;
}
/**
* 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.ldifeditor", Status.OK, //$NON-NLS-1$
"Unable to get the plugin properties.", 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/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor.editor;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldifparser.model.LdifFile;
import org.eclipse.core.runtime.IAdaptable;
/**
* This interface represents the LDIF Editor.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public interface ILdifEditor extends IAdaptable
{
/**
* Gets the LDIF Model
*
* @return the LDIF Model
*/
LdifFile getLdifModel();
/**
* Gets the Connection
*
* @return the Connection
*/
IBrowserConnection getConnection();
}
| java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
apache/directory-studio | https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor.editor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants;
import org.apache.directory.studio.ldifeditor.LdifEditorConstants;
import org.apache.directory.studio.ldifeditor.editor.text.LdifExternalAnnotationModel;
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.LdifRecord;
import org.apache.directory.studio.ldifparser.parser.LdifParser;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractDocumentProvider;
/**
* This class implements the LDIF Document Provider.
* This class is used to share a LDIF Document and listen on document modifications.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifDocumentProvider extends AbstractDocumentProvider implements IDocumentListener
{
private final LdifParser ldifParser;
private final LdifDocumentSetupParticipant ldifDocumentSetupParticipant;
private LdifFile ldifModel;
/**
* Creates a new instance of LdifDocumentProvider.
*/
public LdifDocumentProvider()
{
super();
this.ldifParser = new LdifParser();
this.ldifDocumentSetupParticipant = new LdifDocumentSetupParticipant();
}
/**
* {@inheritDoc}
*/
public IDocument getDocument( Object element )
{
IDocument document = super.getDocument( element );
return document;
}
/**
* Gets the LDIF Model
*
* @return
* the LDIF Model
*/
public LdifFile getLdifModel()
{
return ldifModel;
}
/**
* {@inheritDoc}
*/
public void documentAboutToBeChanged( DocumentEvent event )
{
}
/**
* Update the LDIF Model.
*/
public void documentChanged( DocumentEvent event )
{
try
{
int changeOffset = event.getOffset();
int replacedTextLength = event.getLength();
int insertedTextLength = event.getText() != null ? event.getText().length() : 0;
IDocument document = event.getDocument();
// Region changeRegion = new Region(changeOffset,
// replacedTextLength);
Region changeRegion = new Region( changeOffset - BrowserCoreConstants.LINE_SEPARATOR.length(),
replacedTextLength + ( 2 * BrowserCoreConstants.LINE_SEPARATOR.length() ) );
// get containers to replace (from changeOffset till
// changeOffset+replacedTextLength, check end of record)
List<LdifContainer> oldContainerList = new ArrayList<LdifContainer>();
List<LdifContainer> containers = ldifModel.getContainers();
for ( int i = 0; i < containers.size(); i++ )
{
LdifContainer ldifContainer = containers.get( i );
Region containerRegion = new Region( containers.get( i ).getOffset(), containers.get( i ).getLength() );
boolean changeOffsetAtEOF = i == containers.size() - 1
&& changeOffset >= containerRegion.getOffset() + containerRegion.getLength();
if ( TextUtilities.overlaps( containerRegion, changeRegion ) || changeOffsetAtEOF )
{
// remember index
int index = i;
// add invalid containers and non-records before overlap
i--;
for ( ; i >= 0; i-- )
{
ldifContainer = containers.get( i );
if ( !ldifContainer.isValid() || !( ldifContainer instanceof LdifRecord ) )
{
oldContainerList.add( 0, ldifContainer );
}
else
{
break;
}
}
// add all overlapping containers
i = index;
for ( ; i < containers.size(); i++ )
{
ldifContainer = containers.get( i );
containerRegion = new Region( ldifContainer.getOffset(), ldifContainer.getLength() );
if ( TextUtilities.overlaps( containerRegion, changeRegion ) || changeOffsetAtEOF )
{
oldContainerList.add( ldifContainer );
}
else
{
break;
}
}
// add invalid containers and non-records after overlap
for ( ; i < containers.size(); i++ )
{
ldifContainer = containers.get( i );
if ( !ldifContainer.isValid() || !( ldifContainer instanceof LdifRecord )
|| !( oldContainerList.get( oldContainerList.size() - 1 ) instanceof LdifRecord ) )
{
oldContainerList.add( ldifContainer );
}
else
{
break;
}
}
}
}
LdifContainer[] oldContainers = ( LdifContainer[] ) oldContainerList
.toArray( new LdifContainer[oldContainerList.size()] );
int oldCount = oldContainers.length;
int oldOffset = oldCount > 0 ? oldContainers[0].getOffset() : 0;
int oldLength = oldCount > 0 ? ( oldContainers[oldContainers.length - 1].getOffset()
+ oldContainers[oldContainers.length - 1].getLength() - oldContainers[0].getOffset() ) : 0;
// get new content
int newOffset = oldOffset;
int newLength = oldLength - replacedTextLength + insertedTextLength;
String textToParse = document.get( newOffset, newLength );
// parse partion content to containers (offset=0)
LdifFile newModel = this.ldifParser.parse( textToParse );
List<LdifContainer> newContainers = newModel.getContainers();
// replace old containers with new containers
// must adjust offsets of all following containers in model
ldifModel.replace( oldContainers, newContainers );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
/**
* Creates an LDIF annotation model.
*/
protected IAnnotationModel createAnnotationModel( Object element ) throws CoreException
{
return new LdifExternalAnnotationModel();
}
/**
* Tries to read the file pointed at by <code>input</code> if it is an
* <code>IPathEditorInput</code>. If the file does not exist, <code>true</code>
* is returned.
*
* @param document the document to fill with the contents of <code>input</code>
* @param input the editor input
* @return <code>true</code> if setting the content was successful or no file exists, <code>false</code> otherwise
* @throws CoreException if reading the file fails
*/
private boolean setDocumentContent( IDocument document, IEditorInput input ) throws CoreException
{
// TODO: handle encoding
Reader reader;
try
{
String inputClassName = input.getClass().getName();
if ( input instanceof IPathEditorInput )
{
reader = new FileReader( ( ( IPathEditorInput ) input ).getPath().toFile() );
}
else if ( inputClassName.equals( "org.eclipse.ui.internal.editors.text.JavaFileEditorInput" ) //$NON-NLS-1$
|| inputClassName.equals( "org.eclipse.ui.ide.FileStoreEditorInput" ) ) //$NON-NLS-1$
// The class 'org.eclipse.ui.internal.editors.text.JavaFileEditorInput'
// is used when opening a file from the menu File > Open... in Eclipse 3.2.x
// The class 'org.eclipse.ui.ide.FileStoreEditorInput' is used when
// opening a file from the menu File > Open... in Eclipse 3.3.x
{
reader = new FileReader( new File( input.getToolTipText() ) );
}
else
{
return false;
}
}
catch ( FileNotFoundException e )
{
// return empty document and save later
return true;
}
try
{
setDocumentContent( document, reader );
return true;
}
catch ( IOException e )
{
throw new CoreException( new Status( IStatus.ERROR, LdifEditorConstants.PLUGIN_ID, IStatus.OK,
"error reading file", e ) ); //$NON-NLS-1$
}
}
/**
* Reads in document content from a reader and fills <code>document</code>
*
* @param document the document to fill
* @param reader the source
* @throws IOException if reading fails
*/
private void setDocumentContent( IDocument document, Reader reader ) throws IOException
{
Reader in = new BufferedReader( reader );
try
{
StringBuffer buffer = new StringBuffer( 512 );
char[] readBuffer = new char[512];
int n = in.read( readBuffer );
while ( n > 0 )
{
buffer.append( readBuffer, 0, n );
n = in.read( readBuffer );
}
document.set( buffer.toString() );
}
finally
{
in.close();
}
}
/**
* Set up the document: partitioning and incremental parser
*
* @param document the new document
*/
protected void setupDocument( IDocument document )
{
// setup document partitioning
ldifDocumentSetupParticipant.setup( document );
// initial parsing of whole document
this.ldifModel = this.ldifParser.parse( document.get() );
// add listener for incremental parsing
document.addDocumentListener( this );
}
/**
* Remove document listener.
*/
protected void disposeElementInfo( Object element, ElementInfo info )
{
IDocument document = info.fDocument;
document.removeDocumentListener( this );
super.disposeElementInfo( element, info );
}
/**
* {@inheritDoc}
*/
protected IDocument createDocument( Object element ) throws CoreException
{
if ( element instanceof IEditorInput )
{
IDocument document = new Document();
if ( setDocumentContent( document, ( IEditorInput ) element ) )
{
setupDocument( document );
}
return document;
}
return null;
}
/**
* {@inheritDoc}
*/
protected void doSaveDocument( IProgressMonitor monitor, Object element, IDocument document, boolean overwrite )
throws CoreException
{
File file = null;
String elementClassName = element.getClass().getName();
if ( element instanceof FileEditorInput )
// FileEditorInput class is used when the file is opened
// from a project in the workspace.
{
writeDocumentContent( document, ( ( FileEditorInput ) element ).getFile(), monitor );
return;
}
else if ( element instanceof IPathEditorInput )
{
IPathEditorInput pei = ( IPathEditorInput ) element;
IPath path = pei.getPath();
file = path.toFile();
}
else if ( elementClassName.equals( "org.eclipse.ui.internal.editors.text.JavaFileEditorInput" ) //$NON-NLS-1$
|| elementClassName.equals( "org.eclipse.ui.ide.FileStoreEditorInput" ) ) //$NON-NLS-1$
// The class 'org.eclipse.ui.internal.editors.text.JavaFileEditorInput'
// is used when opening a file from the menu File > Open... in Eclipse 3.2.x
// The class 'org.eclipse.ui.ide.FileStoreEditorInput' is used when
// opening a file from the menu File > Open... in Eclipse 3.3.x
{
file = new File( ( ( IEditorInput ) element ).getToolTipText() );
}
if ( file != null )
{
try
{
file.createNewFile();
if ( file.exists() )
{
if ( file.canWrite() )
{
Writer writer = new FileWriter( file );
writeDocumentContent( document, writer, monitor );
}
else
{
throw new CoreException( new Status( IStatus.ERROR,
"org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "file is read-only", null ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
throw new CoreException( new Status( IStatus.ERROR,
"org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "error creating file", null ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch ( IOException e )
{
throw new CoreException( new Status( IStatus.ERROR,
"org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "error when saving file", e ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
/**
* Saves the document contents to a stream.
*
* @param document the document to save
* @param file the file to save it to
* @param monitor a progress monitor to report progress
* @throws CoreException
* @throws IOException if writing fails
*/
private void writeDocumentContent( IDocument document, IFile file, IProgressMonitor monitor ) throws CoreException
{
if ( file != null )
{
file.setContents( new ByteArrayInputStream( document.get().getBytes() ), true, true, monitor );
}
}
/**
* Saves the document contents to a stream.
*
* @param document the document to save
* @param writer the stream to save it to
* @param monitor a progress monitor to report progress
* @throws IOException if writing fails
*/
private void writeDocumentContent( IDocument document, Writer writer, IProgressMonitor monitor ) throws IOException
{
Writer out = new BufferedWriter( writer );
try
{
out.write( document.get() );
}
finally
{
out.close();
}
}
/**
* {@inheritDoc}
*/
protected IRunnableContext getOperationRunner( IProgressMonitor monitor )
{
return null;
}
/**
* {@inheritDoc}
*/
public boolean isModifiable( Object element )
{
String elementClassName = element.getClass().getName();
if ( element instanceof IPathEditorInput )
{
IPathEditorInput pei = ( IPathEditorInput ) element;
File file = pei.getPath().toFile();
return file.canWrite() || !file.exists(); // Allow to edit new files
}
else if ( elementClassName.equals( "org.eclipse.ui.internal.editors.text.JavaFileEditorInput" ) //$NON-NLS-1$
|| elementClassName.equals( "org.eclipse.ui.ide.FileStoreEditorInput" ) ) //$NON-NLS-1$
// The class 'org.eclipse.ui.internal.editors.text.JavaFileEditorInput'
// is used when opening a file from the menu File > Open... in Eclipse 3.2.x
// The class 'org.eclipse.ui.ide.FileStoreEditorInput' is used when
// opening a file from the menu File > Open... in Eclipse 3.3.x
{
File file = new File( ( ( IEditorInput ) element ).getToolTipText() );
return file.canWrite() || !file.exists(); // Allow to edit new files
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean isReadOnly( Object element )
{
return !isModifiable( element );
}
/**
* {@inheritDoc}
*/
public boolean isStateValidated( Object element )
{
return true;
}
} | java | Apache-2.0 | e55b93d729a60c986fc93e52f9519f4bbdf51252 | 2026-01-05T02:32:00.866394Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.