mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noel Rouvignac
18.26.2015 ca669ae54f86dbeea277280690584d9f591c7571
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
 
package org.opends.guitools.controlpanel.ui;
 
import static org.opends.messages.AdminToolMessages.*;
 
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
 
import javax.swing.JLabel;
import javax.swing.tree.TreePath;
 
import org.opends.guitools.controlpanel.datamodel.BinaryValue;
import org.opends.guitools.controlpanel.datamodel.CustomSearchResult;
import org.opends.guitools.controlpanel.datamodel.ObjectClassValue;
import org.opends.guitools.controlpanel.event.ConfigurationChangeEvent;
import org.opends.guitools.controlpanel.event.LDAPEntryChangedEvent;
import org.opends.guitools.controlpanel.event.LDAPEntryChangedListener;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
import org.opends.guitools.controlpanel.util.Utilities;
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.api.AttributeSyntax;
import org.opends.server.schema.SchemaConstants;
import org.opends.server.types.AttributeType;
import org.forgerock.opendj.ldap.ByteString;
import org.opends.server.types.Attributes;
import org.opends.server.types.Entry;
import org.opends.server.types.ObjectClass;
import org.forgerock.opendj.ldap.schema.ObjectClassType;
import org.opends.server.types.OpenDsException;
import org.opends.server.types.RDN;
import org.opends.server.types.Schema;
import org.opends.server.util.Base64;
import org.opends.server.util.ServerConstants;
 
/**
 * Abstract class containing code shared by the different LDAP entry view
 * panels (Simplified View, Attribute View and LDIF View).
 *
 */
public abstract class ViewEntryPanel extends StatusGenericPanel
{
  private static final long serialVersionUID = -1908757626234678L;
  /**
   * The read-only attributes as they appear on the schema.
   */
  protected SortedSet<String> schemaReadOnlyAttributes = new TreeSet<String>();
  /**
   * The read-only attributes in lower case.
   */
  protected SortedSet<String> schemaReadOnlyAttributesLowerCase =
    new TreeSet<String>();
  /**
   * The editable operational attributes.
   */
  protected SortedSet<String> editableOperationalAttrNames =
    new TreeSet<String>();
  private JLabel title= Utilities.createDefaultLabel();
 
  private Set<LDAPEntryChangedListener> listeners =
    new LinkedHashSet<LDAPEntryChangedListener>();
 
  /**
   * Whether the entry change events should be ignored or not.
   */
  protected boolean ignoreEntryChangeEvents;
 
  /**
   * Static boolean used to know whether only attributes with values should be
   * displayed or not.
   */
  protected static boolean displayOnlyWithAttrs = true;
 
  /**
   * {@inheritDoc}
   */
  public void okClicked()
  {
    // No ok button
  }
 
  /**
   * Returns an Entry object representing what the panel is displaying.
   * @return an Entry object representing what the panel is displaying.
   * @throws OpenDsException if the entry cannot be generated (in particular if
   * the user provided invalid data).
   */
  public abstract Entry getEntry() throws OpenDsException;
 
  /**
   * Updates the contents of the panel.
   * @param sr the search result to be used to update the panel.
   * @param isReadOnly whether the entry is read-only or not.
   * @param path the tree path associated with the entry in the tree.
   */
  public abstract void update(CustomSearchResult sr, boolean isReadOnly,
      TreePath path);
 
  /**
   * Adds a title panel to the container.
   * @param c the container where the title panel must be added.
   * @param gbc the grid bag constraints to be used.
   */
  protected void addTitlePanel(Container c, GridBagConstraints gbc)
  {
    c.add(title, gbc);
  }
 
  /**
   * Whether the schema must be checked or not.
   * @return <CODE>true</CODE> if the server is configured to check schema and
   * <CODE>false</CODE> otherwise.
   */
  protected boolean checkSchema()
  {
    return getInfo().getServerDescriptor().isSchemaEnabled();
  }
 
  /**
   * Adds an LDAP entry change listener.
   * @param listener the listener.
   */
  public void addLDAPEntryChangedListener(LDAPEntryChangedListener listener)
  {
    listeners.add(listener);
  }
 
  /**
   * Removes an LDAP entry change listener.
   * @param listener the listener.
   */
  public void removeLDAPEntryChangedListener(LDAPEntryChangedListener listener)
  {
    listeners.remove(listener);
  }
 
  /**
   * {@inheritDoc}
   */
  public boolean requiresBorder()
  {
    return true;
  }
 
  /**
   * Returns the DN of the entry that the user is editing (it might differ
   * from the DN of the entry in the tree if the user modified the DN).
   * @return the DN of the entry that the user is editing.
   */
  protected abstract String getDisplayedDN();
 
  /**
   * Notifies the entry changed listeners that the entry changed.
   *
   */
  protected void notifyListeners()
  {
    if (ignoreEntryChangeEvents)
    {
      return;
    }
    // TODO: With big entries this is pretty slow.  Until there is a fix, try
    // simply to update the dn
    Entry entry = null;
    String dn = getDisplayedDN();
    if ((dn != null) && !dn.equals(title.getText()))
    {
      title.setText(dn);
    }
    /*
    Entry entry;
    try
    {
      entry = getEntry();
      String dn = entry.getDN().toString();
      if (!dn.equals(title.getText()))
      {
        title.setText(dn);
      }
    }
    catch (OpenDsException de)
    {
      entry = null;
    }
    catch (Throwable t)
    {
      entry = null;
      logger.warn(LocalizableMessage.raw("Unexpected error: "+t, t));
    }
    */
    LDAPEntryChangedEvent ev = new LDAPEntryChangedEvent(this, entry);
    for (LDAPEntryChangedListener listener : listeners)
    {
      listener.entryChanged(ev);
    }
  }
 
  /**
   * Updates the title panel with the provided entry.
   * @param sr the search result.
   * @param path the path to the node of the entry selected in the tree.  Used
   * to display the same icon as in the tree.
   */
  protected void updateTitle(CustomSearchResult sr, TreePath path)
  {
    String dn = sr.getDN();
    if ((dn != null) && (dn.length() > 0))
    {
      title.setText(sr.getDN());
    }
    else if (path != null)
    {
      BasicNode node = (BasicNode)path.getLastPathComponent();
      title.setText(node.getDisplayName());
    }
 
    if (path != null)
    {
      BasicNode node = (BasicNode)path.getLastPathComponent();
      title.setIcon(node.getIcon());
    }
    else
    {
      title.setIcon(null);
    }
 
    List<Object> ocs =
      sr.getAttributeValues(ServerConstants.OBJECTCLASS_ATTRIBUTE_TYPE_NAME);
    Schema schema = getInfo().getServerDescriptor().getSchema();
    if (!ocs.isEmpty() && (schema != null))
    {
      ObjectClassValue ocDesc = getObjectClassDescriptor(ocs, schema);
      StringBuilder sb = new StringBuilder();
      sb.append("<html>");
      if (ocDesc.getStructural() != null)
      {
        sb.append(INFO_CTRL_OBJECTCLASS_DESCRIPTOR.get(ocDesc.getStructural()));
      }
      if (ocDesc.getAuxiliary().size() > 0)
      {
        if (sb.length() > 0)
        {
          sb.append("<br>");
        }
        sb.append(INFO_CTRL_AUXILIARY_OBJECTCLASS_DESCRIPTOR.get(
            Utilities.getStringFromCollection(ocDesc.getAuxiliary(), ", ")));
      }
      title.setToolTipText(sb.toString());
    }
    else
    {
      title.setToolTipText(null);
    }
  }
 
  /**
   * Returns an object class value representing all the object class values of
   * the entry.
   * @param ocValues the list of object class values.
   * @param schema the schema.
   * @return an object class value representing all the object class values of
   * the entry.
   */
  protected ObjectClassValue getObjectClassDescriptor(List<Object> ocValues,
      Schema schema)
  {
    ObjectClass structuralObjectClass = null;
    SortedSet<String> auxiliaryClasses = new TreeSet<String>();
    for (Object o : ocValues)
    {
      ObjectClass objectClass =
        schema.getObjectClass(((String)o).toLowerCase());
      if (objectClass != null)
      {
        if (objectClass.getObjectClassType() == ObjectClassType.STRUCTURAL)
        {
          if (structuralObjectClass == null)
          {
            structuralObjectClass = objectClass;
          }
          else
          {
            if (objectClass.isDescendantOf(structuralObjectClass))
            {
              structuralObjectClass = objectClass;
            }
          }
        }
        else
        {
          String name = objectClass.getNameOrOID();
          if (!name.equals(SchemaConstants.TOP_OBJECTCLASS_NAME))
          {
            auxiliaryClasses.add(objectClass.getNameOrOID());
          }
        }
      }
    }
    String structural = structuralObjectClass != null ?
        structuralObjectClass.getNameOrOID() : null;
    return new ObjectClassValue(structural, auxiliaryClasses);
  }
 
  /**
   * Adds the values in the RDN to the entry definition.
   * @param entry the entry to be updated.
   */
  protected void addValuesInRDN(Entry entry)
  {
//  Add the values in the RDN if  they are not there
    RDN rdn = entry.getName().rdn();
    for (int i=0; i<rdn.getNumValues(); i++)
    {
      String attrName = rdn.getAttributeName(i);
      ByteString value = rdn.getAttributeValue(i);
      List<org.opends.server.types.Attribute> attrs =
        entry.getAttribute(attrName.toLowerCase());
      boolean done = false;
      if (attrs != null)
      {
        for (org.opends.server.types.Attribute attr : attrs)
        {
          if (attr.getNameWithOptions().equals(attrName))
          {
            ArrayList<ByteString> newValues = new ArrayList<ByteString>();
            Iterator<ByteString> it = attr.iterator();
            while (it.hasNext())
            {
              newValues.add(it.next());
            }
            newValues.add(value);
            entry.addAttribute(attr, newValues);
            done = true;
            break;
          }
        }
      }
      if (!done)
      {
        org.opends.server.types.Attribute attr =
          Attributes.create(rdn.getAttributeType(i), value);
        ArrayList<ByteString> newValues = new ArrayList<ByteString>();
        newValues.add(value);
        entry.addAttribute(attr, newValues);
      }
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public LocalizableMessage getTitle()
  {
    return INFO_CTRL_PANEL_EDIT_LDAP_ENTRY_TITLE.get();
  }
 
  /**
   * {@inheritDoc}
   */
  public void configurationChanged(ConfigurationChangeEvent ev)
  {
    Schema schema = ev.getNewDescriptor().getSchema();
    if (schema != null && schemaReadOnlyAttributes.isEmpty())
    {
      schemaReadOnlyAttributes.clear();
      schemaReadOnlyAttributesLowerCase.clear();
      for (AttributeType attr : schema.getAttributeTypes().values())
      {
        if (attr.isNoUserModification())
        {
          String attrName = attr.getNameOrOID();
          schemaReadOnlyAttributes.add(attrName);
          schemaReadOnlyAttributesLowerCase.add(attrName.toLowerCase());
        }
        else if (attr.isOperational())
        {
          editableOperationalAttrNames.add(attr.getNameOrOID());
        }
      }
    }
  }
 
  /**
   * Appends the LDIF lines corresponding to the different values of an
   * attribute to the provided StringBuilder.
   * @param sb the StringBuilder that must be updated.
   * @param attrName the attribute name.
   * @param values the attribute values.
   */
  protected void appendLDIFLines(StringBuilder sb, String attrName,
      List<Object> values)
  {
    for (Object value : values)
    {
      appendLDIFLine(sb, attrName, value);
    }
  }
 
  /**
   * Appends the LDIF line corresponding to the value of an
   * attribute to the provided StringBuilder.
   * @param sb the StringBuilder that must be updated.
   * @param attrName the attribute name.
   * @param value the attribute value.
   */
  protected void appendLDIFLine(StringBuilder sb, String attrName, Object value)
  {
    if (value instanceof ObjectClassValue)
    {
      ObjectClassValue ocValue = (ObjectClassValue)value;
      if (ocValue.getStructural() != null)
      {
        sb.append("\n");
        sb.append(attrName).append(": ").append(ocValue.getStructural());
        Schema schema = getInfo().getServerDescriptor().getSchema();
        if (schema != null)
        {
          ObjectClass oc =
            schema.getObjectClass(ocValue.getStructural().toLowerCase());
          if (oc != null)
          {
            Set<String> names = getObjectClassSuperiorValues(oc);
            for (String name : names)
            {
              sb.append("\n");
              sb.append(attrName).append(": ").append(name);
            }
          }
        }
      }
      for (String v : ocValue.getAuxiliary())
      {
        sb.append("\n");
        sb.append(attrName).append(": ").append(v);
      }
    }
    else if (value instanceof byte[])
    {
      if (((byte[])value).length > 0)
      {
        sb.append("\n");
        sb.append(attrName).append(":: ").append(Base64.encode((byte[])value));
      }
    }
    else if (value instanceof BinaryValue)
    {
      sb.append("\n");
      sb.append(attrName).append(":: ").append(((BinaryValue)value).getBase64());
    }
    else if (String.valueOf(value).trim().length() > 0)
    {
      sb.append("\n");
      sb.append(attrName).append(": ").append(value);
    }
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided attribute name has binary syntax
   * and <CODE>false</CODE> otherwise.
   * @param attrName the attribute name.
   * @return <CODE>true</CODE> if the provided attribute name has binary syntax
   * and <CODE>false</CODE> otherwise.
   */
  protected boolean isBinary(String attrName)
  {
    Schema schema = getInfo().getServerDescriptor().getSchema();
    return Utilities.hasBinarySyntax(attrName, schema);
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided attribute name has password
   * syntax and <CODE>false</CODE> otherwise.
   * @param attrName the attribute name.
   * @return <CODE>true</CODE> if the provided attribute name has password
   * syntax and <CODE>false</CODE> otherwise.
   */
  protected boolean isPassword(String attrName)
  {
    Schema schema = getInfo().getServerDescriptor().getSchema();
    return Utilities.hasPasswordSyntax(attrName, schema);
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided attribute name has certificate
   * syntax and <CODE>false</CODE> otherwise.
   * @param attrName the attribute name.
   * @param schema the schema.
   * @return <CODE>true</CODE> if the provided attribute name has certificate
   * syntax and <CODE>false</CODE> otherwise.
   */
  protected boolean hasCertificateSyntax(String attrName, Schema schema)
  {
    boolean isCertificate = false;
    // Check all the attributes that we consider binaries.
    if (schema != null)
    {
      AttributeType attr = schema.getAttributeType(
          Utilities.getAttributeNameWithoutOptions(attrName).toLowerCase());
      if (attr != null)
      {
        AttributeSyntax<?> syntax = attr.getSyntax();
        if (syntax != null)
        {
          isCertificate = syntax.getOID().equals(
              SchemaConstants.SYNTAX_CERTIFICATE_OID);
        }
      }
    }
    return isCertificate;
  }
 
  /**
   * Gets the values associated with a given attribute.  The values are the
   * ones displayed in the panel.
   * @param attrName the attribute name.
   * @return the values associated with a given attribute.
   */
  protected abstract List<Object> getValues(String attrName);
 
  /**
   * Sets the values displayed in the panel for a given attribute in the
   * provided search result.
   * @param sr the search result to be updated.
   * @param attrName the attribute name.
   */
  protected void setValues(CustomSearchResult sr, String attrName)
  {
    List<Object> values = getValues(attrName);
    List<Object> valuesToSet = new ArrayList<Object>();
    for (Object value : values)
    {
      if (value instanceof ObjectClassValue)
      {
        ObjectClassValue ocValue = (ObjectClassValue)value;
        if (ocValue.getStructural() != null)
        {
          valuesToSet.add(ocValue.getStructural());
        }
        valuesToSet.addAll(ocValue.getAuxiliary());
      }
      else if (value instanceof byte[])
      {
        valuesToSet.add(value);
      }
      else if (value instanceof BinaryValue)
      {
        try
        {
          valuesToSet.add(((BinaryValue)value).getBytes());
        }
        catch (ParseException pe)
        {
         throw new RuntimeException("Unexpected error: "+pe, pe);
        }
      }
      else
      {
        if (String.valueOf(value).trim().length() > 0)
        {
          valuesToSet.add(String.valueOf(value));
        }
      }
    }
    if (valuesToSet.size() > 0)
    {
      sr.set(attrName, valuesToSet);
    }
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided attribute name is an editable
   * attribute and <CODE>false</CODE> otherwise.
   * @param attrName the attribute name.
   * @param schema the schema.
   * @return <CODE>true</CODE> if the provided attribute name is an editable
   * attribute and <CODE>false</CODE> otherwise.
   */
  public static boolean isEditable(String attrName, Schema schema)
  {
    boolean isEditable = false;
    attrName = Utilities.getAttributeNameWithoutOptions(attrName);
    if (schema != null)
    {
      AttributeType attrType = schema.getAttributeType(attrName.toLowerCase());
      if (attrType != null)
      {
        isEditable = !attrType.isNoUserModification();
      }
    }
    return isEditable;
  }
 
  /**
   * Returns the list of superior object classes (to top) for a given object
   * class.
   * @param oc the object class.
   * @return the set of superior object classes for a given object classes.
   */
  protected Set<String> getObjectClassSuperiorValues(
      ObjectClass oc)
  {
    Set<String> names = new LinkedHashSet<String>();
    Set<ObjectClass> parents = oc.getSuperiorClasses();
    if (parents != null && !parents.isEmpty())
    {
      for (ObjectClass parent : parents)
      {
        names.add(parent.getNameOrOID());
        names.addAll(getObjectClassSuperiorValues(parent));
      }
    }
    return names;
  }
}