コード例 #1
0
  static {
    try {
      Map<String, Method> orderedMethods = new TreeMap<String, Method>();
      for (Method m : MBeanServerConnection.class.getDeclaredMethods()) {
        orderedMethods.put(m.toGenericString(), m);
      }
      Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]);
      Map<String, Method> asynchMethods = new TreeMap<String, Method>();
      for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) {
        asynchMethods.put(asynchMethod.getName(), asynchMethod);
      }

      Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length);
      Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length);
      Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length);
      for (int i = 0; i < methods.length; i++) {
        m2k.put(methods[i], (byte) i);
        k2m.put((byte) i, methods[i]);
        Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response");
        if (asynchMethod == null)
          throw new RuntimeException(
              "Failed to find asynch handler for [" + methods[i].toGenericString() + "]",
              new Throwable());
        k2am.put((byte) i, asynchMethod);
      }
      methodToKey = Collections.unmodifiableMap(m2k);
      keyToMethod = Collections.unmodifiableMap(k2m);
      keyToAsynchMethod = Collections.unmodifiableMap(k2am);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
コード例 #2
0
 @Override
 public List<Type> extraInterfaces() {
   Type type = extractActualBoundedTypeOf(typeVariable);
   if (type instanceof BoundedType) {
     return Arrays.asList(((BoundedType) type).interfaceBounds());
   }
   if (type instanceof ParameterizedType) {
     return Collections.singletonList(type);
   }
   if (type instanceof Class) {
     return Collections.emptyList();
   }
   throw new MockitoException(
       "Cannot extract extra-interfaces from '" + typeVariable + "' : '" + type + "'");
 }
コード例 #3
0
 public Iterable<AnnotatedField> ignoredFields() {
   if (_ignoredFields == null) {
     List<AnnotatedField> l = Collections.emptyList();
     return l;
   }
   return _ignoredFields;
 }
コード例 #4
0
 /** Print info about this round. */
 private void printRoundInfo(boolean lastRound) {
   if (printRounds || verbose) {
     List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
     Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
     log.printNoteLines("x.print.rounds", number, "{" + tlc.toString(", ") + "}", ap, lastRound);
   }
 }
コード例 #5
0
    /** Run a processing round. */
    void run(boolean lastRound, boolean errorStatus) {
      printRoundInfo(lastRound);

      TaskListener taskListener = context.get(TaskListener.class);
      if (taskListener != null)
        taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));

      try {
        if (lastRound) {
          filer.setLastRound(true);
          Set<Element> emptyRootElements = Collections.emptySet(); // immutable
          RoundEnvironment renv =
              new JavacRoundEnvironment(
                  true, errorStatus, emptyRootElements, JavacProcessingEnvironment.this);
          discoveredProcs.iterator().runContributingProcs(renv);
        } else {
          discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
        }
      } finally {
        if (taskListener != null)
          taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
      }

      nMessagerErrors = messager.errorCount();
    }
コード例 #6
0
  /**
   * Method that will collect all member (non-static) fields that are either public, or have at
   * least a single annotation associated with them.
   *
   * @param collectIgnored Whether to collect list of ignored methods for later retrieval
   */
  public void resolveFields(boolean collectIgnored) {
    LinkedHashMap<String, AnnotatedField> foundFields = new LinkedHashMap<String, AnnotatedField>();
    _addFields(foundFields, _class);

    /* And last but not least: let's remove all fields that are
     * deemed to be ignorable after all annotations have been
     * properly collapsed.
     */
    Iterator<Map.Entry<String, AnnotatedField>> it = foundFields.entrySet().iterator();
    while (it.hasNext()) {
      AnnotatedField f = it.next().getValue();
      if (_annotationIntrospector.isIgnorableField(f)) {
        it.remove();
        if (collectIgnored) {
          _ignoredFields = ArrayBuilders.addToList(_ignoredFields, f);
        }
      } else {

      }
    }
    if (foundFields.isEmpty()) {
      _fields = Collections.emptyList();
    } else {
      _fields = new ArrayList<AnnotatedField>(foundFields.size());
      _fields.addAll(foundFields.values());
    }
  }
コード例 #7
0
  /**
   * Returns a Set of Strings containing the names of all available algorithms or types for the
   * specified Java cryptographic service (e.g., Signature, MessageDigest, Cipher, Mac, KeyStore).
   * Returns an empty Set if there is no provider that supports the specified service or if
   * serviceName is null. For a complete list of Java cryptographic services, please see the <a
   * href="../../../guide/security/CryptoSpec.html">Java Cryptography Architecture API Specification
   * &amp; Reference</a>. Note: the returned set is immutable.
   *
   * @param serviceName the name of the Java cryptographic service (e.g., Signature, MessageDigest,
   *     Cipher, Mac, KeyStore). Note: this parameter is case-insensitive.
   * @return a Set of Strings containing the names of all available algorithms or types for the
   *     specified Java cryptographic service or an empty set if no provider supports the specified
   *     service.
   * @since 1.4
   */
  public static Set<String> getAlgorithms(String serviceName) {

    if ((serviceName == null) || (serviceName.length() == 0) || (serviceName.endsWith("."))) {
      return Collections.EMPTY_SET;
    }

    HashSet result = new HashSet();
    Provider[] providers = Security.getProviders();

    for (int i = 0; i < providers.length; i++) {
      // Check the keys for each provider.
      for (Enumeration e = providers[i].keys(); e.hasMoreElements(); ) {
        String currentKey = ((String) e.nextElement()).toUpperCase();
        if (currentKey.startsWith(serviceName.toUpperCase())) {
          // We should skip the currentKey if it contains a
          // whitespace. The reason is: such an entry in the
          // provider property contains attributes for the
          // implementation of an algorithm. We are only interested
          // in entries which lead to the implementation
          // classes.
          if (currentKey.indexOf(" ") < 0) {
            result.add(currentKey.substring(serviceName.length() + 1));
          }
        }
      }
    }
    return Collections.unmodifiableSet(result);
  }
コード例 #8
0
ファイル: HotPotatoes.java プロジェクト: nbronson/snaptree
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
コード例 #9
0
 /**
  * Method similar to {@link #construct}, but that will NOT include information from supertypes;
  * only class itself and any direct mix-ins it may have.
  */
 public static AnnotatedClass constructWithoutSuperTypes(
     Class<?> cls, AnnotationIntrospector aintr, MixInResolver mir) {
   List<Class<?>> empty = Collections.emptyList();
   AnnotatedClass ac = new AnnotatedClass(cls, empty, aintr, mir);
   ac.resolveClassAnnotations();
   return ac;
 }
コード例 #10
0
ファイル: Query.java プロジェクト: aaberg/sql2o
  /**
   * Adds a set of parameters to this <code>Query</code> object's batch of commands and returns any
   * generated keys. <br>
   * If maxBatchRecords is more than 0, executeBatch is called upon adding that many commands to the
   * batch. This method will return any generated keys if <code>fetchGeneratedKeys</code> is set.
   * <br>
   * The current number of batched commands is accessible via the <code>getCurrentBatchRecords()
   * </code> method.
   */
  public <A> List<A> addToBatchGetKeys(Class<A> klass) {
    this.addToBatch();

    if (this.currentBatchRecords == 0) {
      return this.connection.getKeys(klass);
    } else {
      return Collections.emptyList();
    }
  }
コード例 #11
0
 /**
  * Run all remaining processors on the procStateList that have not already run this round with
  * an empty set of annotations.
  */
 public void runContributingProcs(RoundEnvironment re) {
   if (!onProcInterator) {
     Set<TypeElement> emptyTypeElements = Collections.emptySet();
     while (innerIter.hasNext()) {
       ProcessorState ps = innerIter.next();
       if (ps.contributed) callProcessor(ps.processor, emptyTypeElements, re);
     }
   }
 }
コード例 #12
0
 SelectedArgumentImpl(
     String name,
     String label,
     String description,
     String value,
     boolean mustSpecify,
     List choices) {
   super(name, label, description, value, mustSpecify);
   this.choices = Collections.unmodifiableList(new ArrayList(choices));
 }
コード例 #13
0
ファイル: Dom.java プロジェクト: hk2-project/hk2
 /*package*/ void fillAttributes(XMLStreamReader in) {
   for (int i = in.getAttributeCount() - 1; i >= 0; i--) {
     String n = in.getAttributeLocalName(i);
     if (model.attributes.containsKey(n)) {
       if (attributes == null) attributes = new HashMap<String, String>();
       attributes.put(n, in.getAttributeValue(i));
     }
   }
   if (attributes == null) attributes = Collections.emptyMap();
 }
コード例 #14
0
 public <T> Enumerator<T> executeQuery(Queryable<T> queryable) {
   try {
     OptiqStatement statement = (OptiqStatement) createStatement();
     OptiqPrepare.PrepareResult<T> enumerable = statement.prepare(queryable);
     final DataContext dataContext = createDataContext(Collections.emptyList());
     return enumerable.enumerator(dataContext);
   } catch (SQLException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #15
0
ファイル: Macro.java プロジェクト: bramk/bnd
  public String _sort(String args[]) {
    verifyCommand(args, _sortHelp, null, 2, Integer.MAX_VALUE);

    List<String> result = new ArrayList<String>();
    for (int i = 1; i < args.length; i++) {
      Processor.split(args[i], result);
    }
    Collections.sort(result);
    return Processor.join(result);
  }
コード例 #16
0
 private Set<String> initPlatformAnnotations() {
   Set<String> platformAnnotations = new HashSet<String>();
   platformAnnotations.add("java.lang.Deprecated");
   platformAnnotations.add("java.lang.Override");
   platformAnnotations.add("java.lang.SuppressWarnings");
   platformAnnotations.add("java.lang.annotation.Documented");
   platformAnnotations.add("java.lang.annotation.Inherited");
   platformAnnotations.add("java.lang.annotation.Retention");
   platformAnnotations.add("java.lang.annotation.Target");
   return Collections.unmodifiableSet(platformAnnotations);
 }
コード例 #17
0
ファイル: ProxyClient.java プロジェクト: summerpulse/openjdk7
 private Object getAttribute(ObjectName objName, String attrName)
     throws MBeanException, InstanceNotFoundException, AttributeNotFoundException,
         ReflectionException, IOException {
   final NameValueMap values = getCachedAttributes(objName, Collections.singleton(attrName));
   Object value = values.get(attrName);
   if (value != null || values.containsKey(attrName)) {
     return value;
   }
   // Not in cache, presumably because it was omitted from the
   // getAttributes result because of an exception.  Following
   // call will probably provoke the same exception.
   return conn.getAttribute(objName, attrName);
 }
コード例 #18
0
 static {
   FILE_UTILS = FileUtils.getFileUtils();
   AntClassLoader.pathMap = Collections.synchronizedMap(new HashMap<String, String>());
   AntClassLoader.subClassToLoad = null;
   CONSTRUCTOR_ARGS = new Class[] {ClassLoader.class, Project.class, Path.class, Boolean.TYPE};
   if (JavaEnvUtils.isAtLeastJavaVersion("1.5")) {
     try {
       AntClassLoader.subClassToLoad =
           Class.forName("org.apache.tools.ant.loader.AntClassLoader5");
     } catch (ClassNotFoundException ex) {
     }
   }
 }
コード例 #19
0
 /**
  * Construct a new EnumConstantsBuilder.
  *
  * @param configuration the current configuration of the doclet.
  * @param classDoc the class whoses members are being documented.
  * @param writer the doclet specific writer.
  */
 public static EnumConstantBuilder getInstance(
     Configuration configuration, ClassDoc classDoc, EnumConstantWriter writer) {
   EnumConstantBuilder builder = new EnumConstantBuilder(configuration);
   builder.classDoc = classDoc;
   builder.writer = writer;
   builder.visibleMemberMap =
       new VisibleMemberMap(classDoc, VisibleMemberMap.ENUM_CONSTANTS, configuration.nodeprecated);
   builder.enumConstants =
       new ArrayList<ProgramElementDoc>(builder.visibleMemberMap.getMembersFor(classDoc));
   if (configuration.getMemberComparator() != null) {
     Collections.sort(builder.enumConstants, configuration.getMemberComparator());
   }
   return builder;
 }
コード例 #20
0
 /**
  * Construct a new FieldBuilder.
  *
  * @param configuration the current configuration of the doclet.
  * @param classDoc the class whoses members are being documented.
  * @param writer the doclet specific writer.
  */
 public static FieldBuilder getInstance(
     Configuration configuration, ClassDoc classDoc, FieldWriter writer) {
   FieldBuilder builder = new FieldBuilder(configuration);
   builder.classDoc = classDoc;
   builder.writer = writer;
   builder.visibleMemberMap =
       new VisibleMemberMap(classDoc, VisibleMemberMap.FIELDS, configuration.nodeprecated);
   builder.fields =
       new ArrayList<ProgramElementDoc>(
           builder.visibleMemberMap.getLeafClassMembers(configuration));
   if (configuration.getMemberComparator() != null) {
     Collections.sort(builder.fields, configuration.getMemberComparator());
   }
   return builder;
 }
コード例 #21
0
  /**
   * Returns an empty processor iterator if no processors are on the relevant path, otherwise if
   * processors are present, logs an error. Called when a service loader is unavailable for some
   * reason, either because a service loader class cannot be found or because a security policy
   * prevents class loaders from being created.
   *
   * @param key The resource key to use to log an error message
   * @param e If non-null, pass this exception to Abort
   */
  private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
      StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
      Iterable<? extends File> workingPath =
          fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
              ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
              : standardFileManager.getLocation(CLASS_PATH);

      if (needClassLoader(options.get(PROCESSOR), workingPath)) handleException(key, e);

    } else {
      handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
  }
コード例 #22
0
  private Map<String, String> initProcessorOptions(Context context) {
    Options options = Options.instance(context);
    Set<String> keySet = options.keySet();
    Map<String, String> tempOptions = new LinkedHashMap<String, String>();

    for (String key : keySet) {
      if (key.startsWith("-A") && key.length() > 2) {
        int sepIndex = key.indexOf('=');
        String candidateKey = null;
        String candidateValue = null;

        if (sepIndex == -1) candidateKey = key.substring(2);
        else if (sepIndex >= 3) {
          candidateKey = key.substring(2, sepIndex);
          candidateValue = (sepIndex < key.length() - 1) ? key.substring(sepIndex + 1) : null;
        }
        tempOptions.put(candidateKey, candidateValue);
      }
    }

    return Collections.unmodifiableMap(tempOptions);
  }
コード例 #23
0
  static {
    try {
      CON_PROXY_CTOR = createProxyConstructor(ProxyConnection.class);

      Class[] argClasses = new Class[0];
      RS_CLOSE_METHOD = ResultSet.class.getMethod("close", argClasses);
      STMT_CLOSE_METHOD = Statement.class.getMethod("close", argClasses);

      CLOSE_ARGS = new Object[0];

      OBJECT_METHODS =
          Collections.unmodifiableSet(new HashSet(Arrays.asList(Object.class.getMethods())));
    } catch (Exception e) {
      // e.printStackTrace();
      logger.log(
          MLevel.SEVERE,
          "An Exception occurred in static initializer of" + C3P0PooledConnection.class.getName(),
          e);
      throw new InternalError(
          "Something is very wrong, or this is a pre 1.3 JVM."
              + "We cannot set up dynamic proxies and/or methods!");
    }
  }
コード例 #24
0
ファイル: TypeBindings.java プロジェクト: twoi/jackson
  protected void _resolve() {
    _resolveBindings(_contextClass);

    // finally: may have root level type info too
    if (_contextType != null) {
      int count = _contextType.containedTypeCount();
      if (count > 0) {
        if (_bindings == null) {
          _bindings = new LinkedHashMap<String, JavaType>();
        }
        for (int i = 0; i < count; ++i) {
          String name = _contextType.containedTypeName(i);
          JavaType type = _contextType.containedType(i);
          _bindings.put(name, type);
        }
      }
    }

    // nothing bound? mark with empty map to prevent further calls
    if (_bindings == null) {
      _bindings = Collections.emptyMap();
    }
  }
コード例 #25
0
  List<ObjectClassDefinition> constructObjectClasses(final OIDAllocator a)
      throws LDAPPersistException {
    final LinkedHashMap<String, ObjectClassDefinition> ocMap =
        new LinkedHashMap<String, ObjectClassDefinition>(1 + auxiliaryClasses.length);

    if (superclassHandler != null) {
      for (final ObjectClassDefinition d : superclassHandler.constructObjectClasses(a)) {
        ocMap.put(toLowerCase(d.getNameOrOID()), d);
      }
    }

    final String lowerStructuralClass = toLowerCase(structuralClass);
    if (!ocMap.containsKey(lowerStructuralClass)) {
      if (superclassHandler == null) {
        ocMap.put(
            lowerStructuralClass,
            constructObjectClass(structuralClass, "top", ObjectClassType.STRUCTURAL, a));
      } else {
        ocMap.put(
            lowerStructuralClass,
            constructObjectClass(
                structuralClass,
                superclassHandler.getStructuralClass(),
                ObjectClassType.STRUCTURAL,
                a));
      }
    }

    for (final String s : auxiliaryClasses) {
      final String lowerName = toLowerCase(s);
      if (!ocMap.containsKey(lowerName)) {
        ocMap.put(lowerName, constructObjectClass(s, "top", ObjectClassType.AUXILIARY, a));
      }
    }

    return Collections.unmodifiableList(new ArrayList<ObjectClassDefinition>(ocMap.values()));
  }
コード例 #26
0
  List<Modification> getModifications(
      final T o, final boolean deleteNullValues, final String... attributes)
      throws LDAPPersistException {
    final ReadOnlyEntry originalEntry;
    if (entryField != null) {
      originalEntry = getEntry(o);
    } else {
      originalEntry = null;
    }
    if (originalEntry != null) {
      try {
        final T decodedOrig = decode(originalEntry);
        final Entry reEncodedOriginal = encode(decodedOrig, originalEntry.getParentDNString());

        final Entry newEntry = encode(o, originalEntry.getParentDNString());
        final List<Modification> mods =
            Entry.diff(reEncodedOriginal, newEntry, true, false, attributes);
        if (!deleteNullValues) {
          final Iterator<Modification> iterator = mods.iterator();
          while (iterator.hasNext()) {
            final Modification m = iterator.next();
            if (m.getRawValues().length == 0) {
              iterator.remove();
            }
          }
        }

        HashSet<String> stripAttrs = null;
        for (final FieldInfo i : fieldMap.values()) {
          if (!i.includeInModify()) {
            if (stripAttrs == null) {
              stripAttrs = new HashSet<String>(10);
            }
            stripAttrs.add(toLowerCase(i.getAttributeName()));
          }
        }

        for (final GetterInfo i : getterMap.values()) {
          if (!i.includeInModify()) {
            if (stripAttrs == null) {
              stripAttrs = new HashSet<String>(10);
            }
            stripAttrs.add(toLowerCase(i.getAttributeName()));
          }
        }

        if (stripAttrs != null) {
          final Iterator<Modification> iterator = mods.iterator();
          while (iterator.hasNext()) {
            final Modification m = iterator.next();
            if (stripAttrs.contains(toLowerCase(m.getAttributeName()))) {
              iterator.remove();
            }
          }
        }

        return mods;
      } catch (final Exception e) {
        debugException(e);
      } finally {
        setDNAndEntryFields(o, originalEntry);
      }
    }

    final HashSet<String> attrSet;
    if ((attributes == null) || (attributes.length == 0)) {
      attrSet = null;
    } else {
      attrSet = new HashSet<String>(attributes.length);
      for (final String s : attributes) {
        attrSet.add(toLowerCase(s));
      }
    }

    final ArrayList<Modification> mods = new ArrayList<Modification>(5);

    for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) {
      final String attrName = toLowerCase(e.getKey());
      if ((attrSet != null) && (!attrSet.contains(attrName))) {
        continue;
      }

      final FieldInfo i = e.getValue();
      if (!i.includeInModify()) {
        continue;
      }

      final Attribute a = i.encode(o, false);
      if (a == null) {
        if (!deleteNullValues) {
          continue;
        }

        if ((originalEntry != null) && (!originalEntry.hasAttribute(attrName))) {
          continue;
        }

        mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName()));
        continue;
      }

      if (originalEntry != null) {
        final Attribute originalAttr = originalEntry.getAttribute(attrName);
        if ((originalAttr != null) && originalAttr.equals(a)) {
          continue;
        }
      }

      mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName(), a.getRawValues()));
    }

    for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) {
      final String attrName = toLowerCase(e.getKey());
      if ((attrSet != null) && (!attrSet.contains(attrName))) {
        continue;
      }

      final GetterInfo i = e.getValue();
      if (!i.includeInModify()) {
        continue;
      }

      final Attribute a = i.encode(o);
      if (a == null) {
        if (!deleteNullValues) {
          continue;
        }

        if ((originalEntry != null) && (!originalEntry.hasAttribute(attrName))) {
          continue;
        }

        mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName()));
        continue;
      }

      if (originalEntry != null) {
        final Attribute originalAttr = originalEntry.getAttribute(attrName);
        if ((originalAttr != null) && originalAttr.equals(a)) {
          continue;
        }
      }

      mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName(), a.getRawValues()));
    }

    if (superclassHandler != null) {
      final List<Modification> superMods =
          superclassHandler.getModifications(o, deleteNullValues, attributes);
      final ArrayList<Modification> modsToAdd = new ArrayList<Modification>(superMods.size());
      for (final Modification sm : superMods) {
        boolean add = true;
        for (final Modification m : mods) {
          if (m.getAttributeName().equalsIgnoreCase(sm.getAttributeName())) {
            add = false;
            break;
          }
        }
        if (add) {
          modsToAdd.add(sm);
        }
      }
      mods.addAll(modsToAdd);
    }

    return Collections.unmodifiableList(mods);
  }
コード例 #27
0
  @SuppressWarnings("unchecked")
  LDAPObjectHandler(final Class<T> type) throws LDAPPersistException {
    this.type = type;

    final Class<? super T> superclassType = type.getSuperclass();
    if (superclassType == null) {
      superclassHandler = null;
    } else {
      final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class);
      if (superclassAnnotation == null) {
        superclassHandler = null;
      } else {
        superclassHandler = new LDAPObjectHandler(superclassType);
      }
    }

    final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>();
    final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>();
    final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>();

    ldapObject = type.getAnnotation(LDAPObject.class);
    if (ldapObject == null) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName()));
    }

    final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10);

    final String oc = ldapObject.structuralClass();
    if (oc.length() == 0) {
      structuralClass = getUnqualifiedClassName(type);
    } else {
      structuralClass = oc;
    }

    final StringBuilder invalidReason = new StringBuilder();
    if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) {
      objectClasses.put(toLowerCase(structuralClass), structuralClass);
    } else {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get(
              type.getName(), structuralClass, invalidReason.toString()));
    }

    auxiliaryClasses = ldapObject.auxiliaryClass();
    for (final String auxiliaryClass : auxiliaryClasses) {
      if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) {
        objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get(
                type.getName(), auxiliaryClass, invalidReason.toString()));
      }
    }

    superiorClasses = ldapObject.superiorClass();
    for (final String superiorClass : superiorClasses) {
      if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) {
        objectClasses.put(toLowerCase(superiorClass), superiorClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get(
                type.getName(), superiorClass, invalidReason.toString()));
      }
    }

    if (superclassHandler != null) {
      for (final String s : superclassHandler.objectClassAttribute.getValues()) {
        objectClasses.put(toLowerCase(s), s);
      }
    }

    objectClassAttribute = new Attribute("objectClass", objectClasses.values());

    final String parentDNStr = ldapObject.defaultParentDN();
    try {
      defaultParentDN = new DN(parentDNStr);
    } catch (LDAPException le) {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get(
              type.getName(), parentDNStr, le.getMessage()),
          le);
    }

    final String postDecodeMethodName = ldapObject.postDecodeMethod();
    if (postDecodeMethodName.length() > 0) {
      try {
        postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName);
        postDecodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get(
                type.getName(), postDecodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postDecodeMethod = null;
    }

    final String postEncodeMethodName = ldapObject.postEncodeMethod();
    if (postEncodeMethodName.length() > 0) {
      try {
        postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class);
        postEncodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get(
                type.getName(), postEncodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postEncodeMethod = null;
    }

    try {
      constructor = type.getDeclaredConstructor();
      constructor.setAccessible(true);
    } catch (Exception e) {
      debugException(e);
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e);
    }

    Field tmpDNField = null;
    Field tmpEntryField = null;
    final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>();
    for (final Field f : type.getDeclaredFields()) {
      final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class);
      final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class);
      final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class);

      if (fieldAnnotation != null) {
        f.setAccessible(true);

        final FieldInfo fieldInfo = new FieldInfo(f, type);
        final String attrName = toLowerCase(fieldInfo.getAttributeName());
        if (fields.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName()));
        } else {
          fields.put(attrName, fieldInfo);
        }

        switch (fieldInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterFields.add(fieldInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterFields.add(fieldInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterFields.add(fieldInfo);
            break;
          case EXCLUDED:
          default:
            break;
        }

        if (fieldInfo.includeInRDN()) {
          tmpRDNFields.add(fieldInfo);
        }
      }

      if (dnFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPDNField", f.getName()));
        }

        if (tmpDNField != null) {
          throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(String.class)) {
          tmpDNField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }

      if (entryFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPEntryField", f.getName()));
        }

        if (tmpEntryField != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(ReadOnlyEntry.class)) {
          tmpEntryField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }
    }

    dnField = tmpDNField;
    entryField = tmpEntryField;
    requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields);
    alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields);
    conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields);
    rdnFields = Collections.unmodifiableList(tmpRDNFields);

    final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>();
    for (final Method m : type.getDeclaredMethods()) {
      final LDAPGetter getter = m.getAnnotation(LDAPGetter.class);
      final LDAPSetter setter = m.getAnnotation(LDAPSetter.class);

      if (getter != null) {
        m.setAccessible(true);

        if (setter != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get(
                  type.getName(), "LDAPGetter", "LDAPSetter", m.getName()));
        }

        final GetterInfo methodInfo = new GetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || getters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          getters.put(attrName, methodInfo);
        }

        switch (methodInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterGetters.add(methodInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterGetters.add(methodInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterGetters.add(methodInfo);
            break;
          case EXCLUDED:
          default:
            // No action required.
            break;
        }

        if (methodInfo.includeInRDN()) {
          tmpRDNGetters.add(methodInfo);
        }
      }

      if (setter != null) {
        m.setAccessible(true);

        final SetterInfo methodInfo = new SetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || setters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          setters.put(attrName, methodInfo);
        }
      }
    }

    requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters);
    alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters);
    conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters);

    rdnGetters = Collections.unmodifiableList(tmpRDNGetters);
    if (rdnFields.isEmpty() && rdnGetters.isEmpty()) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName()));
    }

    fieldMap = Collections.unmodifiableMap(fields);
    getterMap = Collections.unmodifiableMap(getters);
    setterMap = Collections.unmodifiableMap(setters);

    final TreeSet<String> attrSet = new TreeSet<String>();
    final TreeSet<String> lazySet = new TreeSet<String>();
    if (ldapObject.requestAllAttributes()) {
      attrSet.add("*");
      attrSet.add("+");
    } else {
      for (final FieldInfo i : fields.values()) {
        if (i.lazilyLoad()) {
          lazySet.add(i.getAttributeName());
        } else {
          attrSet.add(i.getAttributeName());
        }
      }

      for (final SetterInfo i : setters.values()) {
        attrSet.add(i.getAttributeName());
      }
    }
    attributesToRequest = new String[attrSet.size()];
    attrSet.toArray(attributesToRequest);

    lazilyLoadedAttributes = new String[lazySet.size()];
    lazySet.toArray(lazilyLoadedAttributes);
  }
コード例 #28
0
 /** @return Returns extra interfaces <strong>if relevant</strong>, otherwise empty List. */
 public List<Type> extraInterfaces() {
   return Collections.emptyList();
 }
コード例 #29
0
 public List<AnnotatedMethod> getStaticMethods() {
   if (_creatorMethods == null) {
     return Collections.emptyList();
   }
   return _creatorMethods;
 }
コード例 #30
0
 public List<AnnotatedConstructor> getConstructors() {
   if (_constructors == null) {
     return Collections.emptyList();
   }
   return _constructors;
 }