View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.verifier;
20  
21  import java.util.ArrayList;
22  import java.util.List;
23  import java.util.Set;
24  import java.util.TreeSet;
25  
26  import javax.swing.ListModel;
27  import javax.swing.event.ListDataEvent;
28  import javax.swing.event.ListDataListener;
29  
30  import org.apache.commons.lang3.ArrayUtils;
31  
32  /**
33   * This class implements an adapter; it implements both a Swing ListModel and a VerifierFactoryObserver.
34   */
35  public class VerifierFactoryListModel implements VerifierFactoryObserver, ListModel<String> {
36  
37      private final List<ListDataListener> listeners = new ArrayList<>();
38      private final Set<String> cache = new TreeSet<>();
39  
40      /**
41       * Constructs a VerifierFactoryListModel.
42       */
43      public VerifierFactoryListModel() {
44          VerifierFactory.attach(this);
45          update(null); // fill cache.
46      }
47  
48      @Override
49      public synchronized void addListDataListener(final ListDataListener l) {
50          listeners.add(l);
51      }
52  
53      @Override
54      public synchronized String getElementAt(final int index) {
55          return cache.toArray(ArrayUtils.EMPTY_STRING_ARRAY)[index];
56      }
57  
58      @Override
59      public synchronized int getSize() {
60          return cache.size();
61      }
62  
63      @Override
64      public synchronized void removeListDataListener(final ListDataListener l) {
65          listeners.remove(l);
66      }
67  
68      @Override
69      public synchronized void update(final String s) {
70          final Verifier[] verifiers = VerifierFactory.getVerifiers();
71          final int verifierLen = verifiers.length;
72          cache.clear();
73          for (final Verifier verifier : verifiers) {
74              cache.add(verifier.getClassName());
75          }
76          for (final ListDataListener listener : listeners) {
77              listener.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, verifierLen - 1));
78          }
79      }
80  
81  }