private void checkForAdapter(Class<?> clazz, Annotation[] anns) {
   if (anns != null) {
     for (Annotation a : anns) {
       if (XmlJavaTypeAdapter.class.isAssignableFrom(a.annotationType())) {
         Type t = getTypeFromXmlAdapter((XmlJavaTypeAdapter) a);
         if (t != null) {
           addType(t);
         }
       }
     }
   }
   XmlJavaTypeAdapter xjta = clazz.getAnnotation(XmlJavaTypeAdapter.class);
   if (xjta != null) {
     Type t = getTypeFromXmlAdapter(xjta);
     if (t != null) {
       addType(t);
     }
   }
   if (clazz.getPackage() != null) {
     XmlJavaTypeAdapters adapt = clazz.getPackage().getAnnotation(XmlJavaTypeAdapters.class);
     if (adapt != null) {
       for (XmlJavaTypeAdapter a : adapt.value()) {
         globalAdapters.add(a.type());
       }
       for (XmlJavaTypeAdapter a : adapt.value()) {
         Type t = getTypeFromXmlAdapter(a);
         if (t != null) {
           addType(t);
         }
       }
     }
   }
 }
Exemple #2
1
 protected void maybeAddAncestors(Gwtc gwtc, Class<?> c) {
   addGwtcClass(gwtc, c);
   for (AncestorMode mode : gwtc.inheritanceMode()) {
     switch (mode) {
       case INHERIT_ONE_PARENT:
         Package pkg = c.getPackage();
         gwtc = pkg.getAnnotation(Gwtc.class);
         if (gwtc != null && addPackage(pkg)) {
           addGwtcPackage(gwtc, pkg, false);
         }
         break;
       case INHERIT_ALL_PARENTS:
         addAllPackages(c.getPackage());
         break;
       case INHERIT_ENCLOSING_CLASSES:
         addEnclosingClasses(c);
         break;
       case INHERIT_SUPER_CLASSES:
         addSuperclasses(c);
         break;
       default:
         X_Log.warn("Unsupported mode type", mode, "for class", c);
     }
   }
 }
Exemple #3
1
 /**
  * 获取版本号
  *
  * @param clazz
  * @param defaultVersion
  * @return
  */
 public static String getVersion(Class clazz, String defaultVersion) {
   try {
     // 首先查找MANIFEST.MF规范中的版本号
     String version = clazz.getPackage().getImplementationVersion();
     if (version == null || version.length() == 0) {
       version = clazz.getPackage().getSpecificationVersion();
     }
     if (version == null || version.length() == 0) {
       // 如果MANIFEST.MF规范中没有版本号,基于jar包名获取版本号
       String file = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
       if (file != null && file.length() > 0 && file.endsWith(".jar")) {
         Matcher matcher = VERSION_PATTERN.matcher(file);
         while (matcher.find() && matcher.groupCount() > 0) {
           version = matcher.group(1);
         }
       }
     }
     // 返回版本号,如果为空返回缺省版本号
     return version == null || version.length() == 0 ? defaultVersion : version;
   } catch (Throwable e) { // 防御性容错
     // 忽略异常,返回缺省版本号
     logger.error(e.getMessage(), e);
     return defaultVersion;
   }
 }
  protected static ClassLoadingMetaData createMetaData(
      PredeterminedManagedObjectAttachments deployment,
      String name,
      Version version,
      boolean useVersionOnPackages,
      Class<?>... packages) {
    MockClassLoadingMetaData classLoadingMetaData = new MockClassLoadingMetaData(name, version);

    classLoadingMetaData.setPaths(packages);

    CapabilitiesMetaData capabilities = classLoadingMetaData.getCapabilities();
    Capability capability = classLoadingMetaDataFactory.createModule(name, version);
    capabilities.addCapability(capability);

    if (packages != null) {
      for (Class<?> pkg : packages) {
        if (useVersionOnPackages)
          capability =
              classLoadingMetaDataFactory.createPackage(pkg.getPackage().getName(), version);
        else capability = classLoadingMetaDataFactory.createPackage(pkg.getPackage().getName());
        capabilities.addCapability(capability);
      }
    }

    classLoadingMetaData.setCapabilities(capabilities);
    return classLoadingMetaData;
  }
  @Test
  public void testPOJO() throws Exception {
    log.info("*** testPOJO ***");

    for (int i = 0; i < 10; i++) {
      Person person = makePerson();
      person.setLastName("smith" + i);
      registrar.createPerson(person);
    }
    // the objects returned will be fully loaded, but...
    Collection<Person> people = registrar.getPeopleByNameHydrated("joe", "%");
    assertEquals("unexpected number of managed people", 10, people.size());

    // the collection class requires hibernate to be in the path
    Class<?> clazz = people.iterator().next().getAddresses().getClass();
    log.debug("collection class=" + clazz);
    assertTrue("unexpected collection class", clazz.getPackage().getName().contains("hibernate"));

    // now get a graph of objects that contain pure POJO classes. The
    // server will create fresh POJOs for DTOs and pass information from
    // the business object POJO to the data transfer object POJO.
    people = registrar.getPeopleByNameCleaned("joe", "%");
    assertEquals("unexpected number of clean people", 10, people.size());
    for (Person p : people) {
      p.getAddresses().iterator().next().getZip();
    }

    // the POJOs are cleansed of their hibernate types
    clazz = people.iterator().next().getAddresses().getClass();
    log.debug("collection class=" + clazz);
    assertFalse("unexpected collection class", clazz.getPackage().getName().contains("hibernate"));
  }
  private void mountFiles(String path, Class<?> clazz) {
    try {
      List<Resource> list = new ArrayList<>();
      String packagePath = clazz.getPackage().getName().replace('.', '/');

      PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      Resource[] res = resolver.getResources("classpath:" + packagePath + "/*.png");
      if (res != null) {
        list.addAll(Arrays.asList(res));
      }
      res = resolver.getResources("classpath:" + packagePath + "/*.gif");
      if (res != null) {
        list.addAll(Arrays.asList(res));
      }

      for (Resource resource : list) {
        URI uri = resource.getURI();
        File file = new File(uri.toString());
        mountResource(
            path + "/" + file.getName(), new SharedResourceReference(clazz, file.getName()));
      }
    } catch (Exception ex) {
      LoggingUtils.logUnexpectedException(LOGGER, "Couldn't mount files", ex);
    }
  }
 @SuppressWarnings("rawtypes")
 public String getVersionInformation(Class clazz) {
   // The following two lines read from the MANIFEST.MF
   String implTitle = clazz.getPackage().getImplementationTitle();
   String implVersion = clazz.getPackage().getImplementationVersion();
   if (implVersion != null) {
     // If we're in a .jar file, then we can return the version information
     // from the .jar file.
     return implTitle + " " + implVersion; // $NON-NLS-1$
   } else {
     // We're not in a .jar file - try to find the version file and
     // read the version information from that.
     try {
       ResourceBundle bundle = ResourceBundle.getBundle("version"); // $NON-NLS-1$
       StringBuffer buff = new StringBuffer();
       buff.append(bundle.getString("impl.title"))
           .append(' ')
           .append(bundle.getString("release.major.number"))
           .append('.')
           .append(
               bundle.getString(
                   "release.minor.number")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
       buff.append('.')
           .append(bundle.getString("release.milestone.number"))
           .append('.')
           .append(bundle.getString("release.build.number"))
           .append(" (class)"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
       return buff.toString();
     } catch (Exception ex) {
       return "Pentaho BI Platform - No Version Information Available"; //$NON-NLS-1$
     }
   }
 }
 /**
  * Creates a new {@link MetricName} without a scope.
  *
  * @param klass the {@link Class} to which the {@link Metric} belongs
  * @param name the name of the {@link Metric}
  * @param scope the scope of the {@link Metric}
  */
 public MetricName(Class<?> klass, String name, String scope) {
   this(
       klass.getPackage() == null ? "" : klass.getPackage().getName(),
       klass.getSimpleName().replaceAll("\\$$", ""),
       name,
       scope);
 }
 private String getFunctionMessBundle(Class clazz) {
   String functionMessBundle = "jasperreports_messages";
   if (clazz.getPackage() != null) {
     functionMessBundle =
         clazz.getPackage().getName() + ".jasperreports_messages"; // FIXMEFUNCT use constant
   }
   return functionMessBundle;
 }
Exemple #10
0
  @SuppressWarnings("unchecked")
  public static <T> T coerceClassic(Class<T> clz, Object value) {

    if (clz == null || value == null) {
      return null;
    }

    if (clz == value.getClass()) {
      return (T) value;
    }

    if (clz == Typ.string || clz == Typ.chars) {
      return (T) value.toString();
    } else if (clz == Typ.integer || clz == Typ.intgr) {
      Integer i = toInt(value);
      return (T) i;
    } else if (clz == Typ.longWrapper || clz == Typ.lng) {
      Long l = toLong(value);
      return (T) l;
    } else if (clz == Typ.doubleWrapper || clz == Typ.dbl) {
      Double i = toDouble(value);
      return (T) i;
    } else if (clz == Typ.date) {
      return (T) toDate(value);
    } else if (clz == Typ.bigInteger) {
      return (T) toBigInteger(value);
    } else if (clz == Typ.bigDecimal) {
      return (T) toBigDecimal(value);
    } else if (clz == Typ.calendar) {
      return (T) toCalendar(toDate(value));
    } else if (clz == Typ.floatWrapper || clz == Typ.flt) {
      Float i = toFloat(value);
      return (T) i;
    } else if (clz == Typ.stringArray) {
      die("Need to fix this");
      return null;
    } else if (clz == Typ.bool || clz == Typ.bln) {
      Boolean b = toBoolean(value);
      return (T) b;
    } else if (Typ.isMap(clz)) {
      return (T) toMap(value);
    } else if (clz.isArray()) {
      return toPrimitiveArrayIfPossible(clz, value);
    } else if (Typ.isCollection(clz)) {
      return toCollection(clz, value);
    } else if (clz.getPackage() != null
        && !clz.getPackage().getName().startsWith("java")
        && Typ.isMap(value.getClass())
        && Typ.doesMapHaveKeyTypeString(value)) {
      return (T) MapObjectConversion.fromMap((Map<String, Object>) value);
    } else if (clz.isEnum()) {
      return (T) toEnum((Class<? extends Enum>) clz, value);

    } else {
      return null;
    }
  }
  public static Set<Class<?>> findModels() {

    if (modelCache != null) {
      return new HashSet<Class<?>>(modelCache.values());
    }

    modelCache = new MapMaker().makeMap();
    repoCache = new MapMaker().makeMap();

    synchronized (modelCache) {
      log.info("Searching for model classes...");

      register(Model.class);

      ClassFinder<Model> finder =
          MetaScanner.findSubTypesOf(Model.class)
              .having(Entity.class)
              .having(Embeddable.class)
              .having(MappedSuperclass.class);

      for (String pkg : includes) {
        finder = finder.within(pkg);
      }

      for (Class<?> klass : finder.any().find()) {
        if (modelCache.containsKey(klass.getName())
            || excludes.contains(klass.getPackage().getName())) {
          continue;
        }
        register(klass);
      }
      log.info("Total found: {}", modelCache.size());
    }

    synchronized (repoCache) {
      log.info("Searching for repository classes...");

      ClassFinder<?> finder = MetaScanner.findSubTypesOf(JpaRepository.class);

      for (String pkg : includes) {
        finder = finder.within(pkg);
      }

      for (Class<?> klass : finder.any().find()) {
        if (repoCache.containsKey(klass.getName())
            || excludes.contains(klass.getPackage().getName())) {
          continue;
        }
        repoCache.put(klass.getName(), klass);
        repoNames.put(klass.getSimpleName(), klass.getName());
      }
      log.info("Total found: {}", repoCache.size());
    }
    return new HashSet<Class<?>>(modelCache.values());
  }
Exemple #12
0
 @Override
 public String shorten(Class<?> cls) {
   if (cls.getEnclosingClass() != null) {
     return shorten(cls.getEnclosingClass()) + "." + cls.getSimpleName();
   } else if (cls.getPackage() != null) {
     return getPrefixForTopLevelClass(cls.getPackage().getName(), cls.getSimpleName())
         + cls.getSimpleName();
   } else {
     return cls.getSimpleName();
   }
 }
Exemple #13
0
  public static <T> Class getObjectFactory(CamelContext camelContext, Class<T> type) {
    if (camelContext == null) {
      return null;
    }

    if (type.getPackage() != null) {
      String objectFactoryClassName = type.getPackage().getName() + ".ObjectFactory";
      return camelContext.getClassResolver().resolveClass(objectFactoryClassName);
    }
    return null;
  }
Exemple #14
0
 /**
  * Perform access checks on a member of a class. This API is derived from the public domain code
  * in the JSR 166 reference implementation.
  *
  * @param caller the class requesting access to the member
  * @param declarer the declaring class of the member
  * @param ignored unknown parameter; always null
  * @param modifiers the modifiers on the member
  * @return true if access is granted, false otherwise
  */
 public static void ensureMemberAccess(
     Class caller, Class declarer, MustBeNull ignored, int modifiers) {
   // Same class, always ok.
   if (caller == declarer) return;
   // Public access is ok.
   if ((modifiers & Modifier.PUBLIC) != 0) return;
   // Protected access and request comes from
   // a subclass of the declarer -- ok.
   if ((modifiers & Modifier.PROTECTED) != 0 && declarer.isAssignableFrom(caller)) return;
   // Package-private access, or protected access,
   // and the packages are the same --ok.
   if ((modifiers & Modifier.PRIVATE) == 0 && caller.getPackage() == declarer.getPackage()) return;
   // Otherwise, no.
   throw new IllegalAccessError();
 }
 public static String getVersion(Class<?> cls, String defaultVersion) {
   try {
     // 首先查找MANIFEST.MF规范中的版本号
     String version = cls.getPackage().getImplementationVersion();
     if (version == null || version.length() == 0) {
       version = cls.getPackage().getSpecificationVersion();
     }
     if (version == null || version.length() == 0) {
       // 如果规范中没有版本号,基于jar包名获取版本号
       CodeSource codeSource = cls.getProtectionDomain().getCodeSource();
       if (codeSource == null) {
         LOGGER.info(
             "No codeSource for class "
                 + cls.getName()
                 + " when getVersion, use default version "
                 + defaultVersion);
       } else {
         String file = codeSource.getLocation().getFile();
         if (file != null && file.length() > 0 && file.endsWith(".jar")) {
           file = file.substring(0, file.length() - 4);
           int i = file.lastIndexOf('/');
           if (i >= 0) {
             file = file.substring(i + 1);
           }
           i = file.indexOf("-");
           if (i >= 0) {
             file = file.substring(i + 1);
           }
           while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
             i = file.indexOf("-");
             if (i >= 0) {
               file = file.substring(i + 1);
             } else {
               break;
             }
           }
           version = file;
         }
       }
     }
     // 返回版本号,如果为空返回缺省版本号
     return version == null || version.length() == 0 ? defaultVersion : version;
   } catch (Throwable e) { // 防御性容错
     // 忽略异常,返回缺省版本号
     LOGGER.error("return default version, ignore exception " + e.getMessage(), e);
     return defaultVersion;
   }
 }
Exemple #16
0
  /**
   * Returns the correct implementation instance for the interface <code>type</code>. For convention
   * the implentation is named <code>InterfaceName + Impl</code>.
   *
   * @param type The interface type
   * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise
   * @throws MalformedModelException is the interface or the implementation are not well formed
   *     (they don't respect the conventions).
   * @throws ModelRuntimeException is any error occurs during the instantiation
   */
  protected ModelProxy createInstance(Class type) {
    Class backClass;
    if (implementations.containsKey(type)) backClass = implementations.get(type);
    else {
      /* type never seen */

      try {
        Package pkg = type.getPackage();
        String pkgN = pkg == null ? "" : pkg.getName();

        backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix());

      } catch (Exception e) {
        backClass = ModelProxy.class;
      }

      Validator.validateModel(type, backClass);

      initFieldsTypes(type);
      implementations.put(type, backClass);
    }

    ModelProxy impl = null;
    try {
      impl = (ModelProxy) backClass.newInstance();
    } catch (Exception e) {
      throw new ModelRuntimeException(e.getMessage());
    }

    return impl;
  }
Exemple #17
0
  /**
   * Loads a design for the given root component.
   *
   * <p>This methods assumes that the component class (or a super class) has been marked with an
   * {@link DesignRoot} annotation and will either use the value from the annotation to locate the
   * design file, or will fall back to using a design with the same same as the annotated class file
   * (with an .html extension)
   *
   * <p>Any {@link Component} type fields in the root component which are not assigned (i.e. are
   * null) are mapped to corresponding components in the design. Matching is done based on field
   * name in the component class and id/local id/caption in the design file.
   *
   * <p>The type of the root component must match the root element in the design
   *
   * @param rootComponent The root component of the layout
   * @return The design context used in the load operation
   * @throws DesignException If the design could not be loaded
   */
  public static DesignContext read(Component rootComponent) throws DesignException {
    // Try to find an @DesignRoot annotation on the class or any parent
    // class
    Class<? extends Component> annotatedClass =
        findClassWithAnnotation(rootComponent.getClass(), DesignRoot.class);
    if (annotatedClass == null) {
      throw new IllegalArgumentException(
          "The class "
              + rootComponent.getClass().getName()
              + " or any of its superclasses do not have an @DesignRoot annotation");
    }

    DesignRoot designAnnotation = annotatedClass.getAnnotation(DesignRoot.class);
    String filename = designAnnotation.value();
    if (filename.equals("")) {
      // No value, assume the html file is named as the class
      filename = annotatedClass.getSimpleName() + ".html";
    }

    InputStream stream = annotatedClass.getResourceAsStream(filename);
    if (stream == null) {
      throw new DesignException(
          "Unable to find design file "
              + filename
              + " in "
              + annotatedClass.getPackage().getName());
    }

    Document doc = parse(stream);
    DesignContext context = designToComponentTree(doc, rootComponent, annotatedClass);

    return context;
  }
 private List<String> dependenciesOf(Package source) {
   List<String> result = new ArrayList<>();
   if (source.isAnnotationPresent(DependsUpon.class))
     for (Class<?> target : source.getAnnotation(DependsUpon.class).packagesOf())
       result.add(target.getPackage().getName());
   return result;
 }
 /**
  * Cenverte o objeto informado para uma String que representa o XML do objeto.
  *
  * @param <T> Tipo generico que informa a classe
  * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de
  *     JAXB.
  * @param schemaLocation {@link URL} do schema.
  * @return
  * @throws JAXBException
  */
 @SuppressWarnings("unchecked")
 public static <T> String marshal(T object, URL schemaLocation) throws JAXBException {
   Class<T> objClass = (Class<T>) object.getClass();
   JAXBContext context = JAXBContext.newInstance(objClass);
   Marshaller marshaller = context.createMarshaller();
   StringWriter sWriter = new StringWriter();
   XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class);
   if (xmlSchema != null && xmlSchema.namespace() != null) {
     XmlType xmlType = objClass.getAnnotation(XmlType.class);
     if (xmlType != null && xmlType.name() != null) {
       QName qName = new QName(xmlSchema.namespace(), xmlType.name());
       JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object);
       if (schemaLocation != null) {
         SchemaFactory schemaFactory =
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         try {
           Schema schema = schemaFactory.newSchema(schemaLocation);
           marshaller.setSchema(schema);
         } catch (SAXException e) {
           e.printStackTrace();
         }
       }
       marshaller.marshal(elem, sWriter);
       return sWriter.toString();
     } else {
       throw new JAXBException("The xmlType could not be identified in class annotation");
     }
   } else {
     throw new JAXBException("The namespace could not be identified from package-info class");
   }
 }
 Runtime(
     boolean hasFastStructs,
     boolean hasJNA,
     boolean hasBitFields,
     Class<?> callbackClass,
     Class<?> pointerClass,
     Class<?> memoryClass,
     Class<?> structClass,
     Class<?> unionClass,
     Class<?> structIOClass,
     Class<?> arrayClass,
     Class<?> libraryClass,
     Class<? extends Annotation> someAnnotationClass,
     String runtimeFilesListFileName) {
   this.hasFastStructs = hasFastStructs;
   this.hasBitFields = hasBitFields;
   this.hasJNA = hasJNA;
   this.callbackClass = callbackClass;
   this.pointerClass = pointerClass;
   this.memoryClass = memoryClass;
   this.structClass = structClass;
   this.libraryClass = libraryClass;
   this.unionClass = unionClass;
   this.structIOClass = structIOClass;
   this.arrayClass = arrayClass;
   this.runtimeFilesListFileName = runtimeFilesListFileName;
   annotationPackage =
       someAnnotationClass == null ? null : someAnnotationClass.getPackage().getName();
 }
 /**
  * When this method is inherited by every test it will make sure that all of the tested classes
  * are in the same package as {@link com.mcdermottroe.exemplar.Constants} which is in the root
  * package.
  *
  * @see com.mcdermottroe.exemplar.Constants
  */
 public void testCorrectPackage() {
   if (testedClass != null) {
     assertTrue(
         "Checking tested class package is rooted in the base package.",
         testedClass.getPackage().getName().startsWith(PACKAGE));
   }
 }
  public String doGetClassMethods() throws Exception {
    StringBuffer document = new StringBuffer();
    try {
      Class cls = null;
      if (className == null || className.equals("$templateLogic"))
        cls = BasicTemplateController.class;
      else if (className.equals("$componentLogic")) cls = ComponentLogic.class;
      else cls = Class.forName(className);

      if (cls == null) return out("<methods class=\"null\" package=\"null\"/>");

      document.append(
          "<methods class=" + q(cls.getName()) + " package=" + q(cls.getPackage().getName()) + ">");
      Method m[] = cls.getDeclaredMethods();
      for (int i = 0; i < m.length; i++) {
        Method method = m[i];
        if (Modifier.isPublic(method.getModifiers())) {
          document.append(createMethodElement(method));
        }
      }
      document.append("</methods>");
    } catch (Throwable e) {
      System.err.println(e);
      return out("<methods class=\"null\" package=\"null\"/>");
    }

    return out(document.toString());
  }
  /**
   * Gets an system property value.
   *
   * @param parameterName the Name or the parameter.
   * @return String value or null if not found
   */
  protected String getSystemProperty(String parameterName) {
    String val = null;

    String pkgName;
    final Package pkg = systemPropertyBaseClass.getPackage();
    if (pkg != null) {
      pkgName = pkg.getName();
    } else {
      final String className = systemPropertyBaseClass.getName();
      int index = className.lastIndexOf('.');
      if (index >= 0) {
        pkgName = className.substring(0, index);
      } else {
        pkgName = null;
      }
    }
    if (pkgName == null) {
      pkgName = "";
    } else {
      pkgName += '.';
    }
    val = System.getProperty(pkgName + parameterName);
    if (val != null) {
      return val;
    }

    // Try lowercased system properties
    val = System.getProperty(pkgName + parameterName.toLowerCase());
    return val;
  }
  private void removeDuplicateCommands(MinecraftServer server) {
    if (server.getCommandManager() instanceof CommandHandler) {
      try {
        Set<String> commandNames = new HashSet<String>();
        Set<String> toRemoveNames = new HashSet<String>();
        CommandHandler cmdMng = (CommandHandler) server.getCommandManager();

        for (Object cmdObj : cmdMng.commandSet) {
          ICommand cmd = (ICommand) cmdObj;
          if (!commandNames.add(cmd.getCommandName())) {
            OutputHandler.debug("Duplicate command found! Name:" + cmd.getCommandName());
            toRemoveNames.add(cmd.getCommandName());
          }
        }
        Set toRemove = new HashSet();
        for (Object cmdObj : cmdMng.commandSet) {
          ICommand cmd = (ICommand) cmdObj;
          if (toRemoveNames.contains(cmd.getCommandName())) {
            Class<?> cmdClass = cmd.getClass();
            if (!cmdClass.getPackage().getName().contains("ForgeEssentials")) {
              OutputHandler.debug(
                  "Removing command '"
                      + cmd.getCommandName()
                      + "' from class: "
                      + cmdClass.getName());
              toRemove.add(cmd.getCommandName());
            }
          }
        }
        cmdMng.commandSet.removeAll(toRemove);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemple #25
0
 private Object findAncestor(Class<?> clazz) {
   // First check enclosing classes
   Class<?> c = clazz.getDeclaringClass();
   while (c != null) {
     if (c.isAnnotationPresent(Gwtc.class)) {
       return c;
     }
     c = c.getDeclaringClass();
   }
   Package p = clazz.getPackage();
   if (p.getAnnotation(Gwtc.class) != null) {
     return p;
   }
   Object o = findAncestor(p);
   if (o == null) {
     c = clazz.getSuperclass();
     while (c != null) {
       if (c.isAnnotationPresent(Gwtc.class)) {
         return c;
       }
       c = c.getSuperclass();
     }
   }
   return o;
 }
  public ClassMeta getClassInfo(Class<?> cls) {
    final Package pkg = cls.getPackage();

    URL loadedFrom = null;

    try {
      loadedFrom = cls.getProtectionDomain().getCodeSource().getLocation();
    } catch (Throwable t) {
      Log.warn(t, "Failed to get source for %s", cls);
    }

    final API apiAnnotation = pkg.getAnnotation(API.class);
    final ApiInfo apiInfo = apiAnnotation != null ? new ApiInfo(apiAnnotation) : null;

    Map<File, Set<String>> mods = Maps.newHashMap();
    for (ModCandidate candidate : table.getCandidatesFor(pkg.getName())) {
      if (!candidate.getClassList().contains(cls.getName().replace('.', '/'))) continue;

      final File candidateFile = candidate.getModContainer();

      Set<String> modIds = Sets.newHashSet();
      mods.put(candidateFile, modIds);
      for (ModContainer mod : candidate.getContainedMods()) modIds.add(mod.getModId());
    }

    return new ClassMeta(cls, loadedFrom, apiInfo, mods);
  }
 public boolean isNonTerminal(Class clazz) {
   Package pack = clazz.getPackage();
   if (pack == null) { // z.B. bei int[]
     return false;
   }
   return patternListFilter.filter(pack.getName());
 }
  /**
   * Get the {@link JAXBContext} from an existing {@link Class} object. If the class's owning
   * package is a valid JAXB package, this method redirects to {@link #getFromCache(Package)}
   * otherwise a new JAXB context is created and NOT cached.
   *
   * @param aClass The class for which the JAXB context is to be created. May not be <code>null
   *     </code>.
   * @param aClassLoader Class loader to use. May be <code>null</code> in which case the default
   *     class loader is used.
   * @return Never <code>null</code>.
   */
  @Nonnull
  public JAXBContext getFromCache(
      @Nonnull final Class<?> aClass, @Nullable final ClassLoader aClassLoader) {
    ValueEnforcer.notNull(aClass, "Class");

    final Package aPackage = aClass.getPackage();
    if (aPackage.getAnnotation(XmlSchema.class) != null) {
      // Redirect to cached version
      return getFromCache(aPackage, aClassLoader);
    }

    // E.g. an internal class - try anyway!
    if (GlobalDebug.isDebugMode())
      s_aLogger.info("Creating JAXB context for class " + aClass.getName());

    if (aClassLoader != null)
      s_aLogger.warn(
          "Package "
              + aPackage.getName()
              + " does not seem to be JAXB generated. Therefore a new JAXBContext is created and the provided ClassLoader is ignored!");

    try {
      return JAXBContext.newInstance(aClass);
    } catch (final JAXBException ex) {
      final String sMsg = "Failed to create JAXB context for class '" + aClass.getName() + "'";
      s_aLogger.error(sMsg + ": " + ex.getMessage());
      throw new IllegalArgumentException(sMsg, ex);
    }
  }
  public static void main(String args[]) throws Exception {
    if (args.length >= 2) {
      String className = args[0];
      String infoNeeded = args[1];
      String message = "";
      Class clazz = null;

      try {
        clazz = Class.forName(className);
      } catch (Exception e) {
        System.out.println("class not found: '" + className + "'");
        return;
      }

      if ("ImplementationVersion".equals(infoNeeded)) {
        final Package aPackage = clazz.getPackage();
        if (aPackage != null) {
          System.out.print(aPackage.getImplementationVersion());
          return;
        } else {
          System.out.println("package for class '" + className + "' not found!");
          return;
        }
      } else {
        throw new Exception(infoNeeded + " not supported");
      }
    } else {
      throw new Exception("Usage: PackageInfo class-name info-required");
    }
  }
  protected AegisType createUserType(TypeClassInfo info) {
    try {
      AegisType type = info.getAegisTypeClass().newInstance();

      QName name = info.getTypeName();
      if (name == null) {
        // We do not want to use the java.lang.whatever schema type.
        // If the @ annotation or XML file didn't specify a schema type,
        // but the natural type has a schema type mapping, we use that rather
        // than create nonsense.
        Class<?> typeClass = TypeUtil.getTypeRelatedClass(info.getType());
        if (typeClass.getPackage().getName().startsWith("java")) {
          name = tm.getTypeQName(typeClass);
        }
        // if it's still null, we'll take our lumps, but probably end up with
        // an invalid schema.
        if (name == null) {
          name = createQName(typeClass);
        }
      }

      type.setSchemaType(name);
      type.setTypeClass(info.getType());
      type.setTypeMapping(getTypeMapping());

      return type;
    } catch (InstantiationException e) {
      throw new DatabindingException(
          "Couldn't instantiate type classs " + info.getAegisTypeClass().getName(), e);
    } catch (IllegalAccessException e) {
      throw new DatabindingException(
          "Couldn't access type classs " + info.getAegisTypeClass().getName(), e);
    }
  }