VerifierFactoryListModel.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  *  Unless required by applicable law or agreed to in writing, software
  12.  *  distributed under the License is distributed on an "AS IS" BASIS,
  13.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  *  See the License for the specific language governing permissions and
  15.  *  limitations under the License.
  16.  */
  17. package org.apache.bcel.verifier;

  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Set;
  21. import java.util.TreeSet;

  22. import javax.swing.ListModel;
  23. import javax.swing.event.ListDataEvent;
  24. import javax.swing.event.ListDataListener;

  25. import org.apache.commons.lang3.ArrayUtils;

  26. /**
  27.  * This class implements an adapter; it implements both a Swing ListModel and a VerifierFactoryObserver.
  28.  */
  29. public class VerifierFactoryListModel implements VerifierFactoryObserver, ListModel<String> {

  30.     private final List<ListDataListener> listeners = new ArrayList<>();
  31.     private final Set<String> cache = new TreeSet<>();

  32.     public VerifierFactoryListModel() {
  33.         VerifierFactory.attach(this);
  34.         update(null); // fill cache.
  35.     }

  36.     @Override
  37.     public synchronized void addListDataListener(final ListDataListener l) {
  38.         listeners.add(l);
  39.     }

  40.     @Override
  41.     public synchronized String getElementAt(final int index) {
  42.         return cache.toArray(ArrayUtils.EMPTY_STRING_ARRAY)[index];
  43.     }

  44.     @Override
  45.     public synchronized int getSize() {
  46.         return cache.size();
  47.     }

  48.     @Override
  49.     public synchronized void removeListDataListener(final ListDataListener l) {
  50.         listeners.remove(l);
  51.     }

  52.     @Override
  53.     public synchronized void update(final String s) {
  54.         final Verifier[] verifiers = VerifierFactory.getVerifiers();
  55.         final int verifierLen = verifiers.length;
  56.         cache.clear();
  57.         for (final Verifier verifier : verifiers) {
  58.             cache.add(verifier.getClassName());
  59.         }
  60.         for (final ListDataListener listener : listeners) {
  61.             listener.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, verifierLen - 1));
  62.         }
  63.     }

  64. }