Пример #1
1
  private static void checkMongoClient(
      Configuration configuration, Class<?> mappedClass, String clientName, String dbName) {
    Configuration mongodbClientConfiguration =
        getMongoClientConfiguration(configuration, clientName);

    if (mongodbClientConfiguration.isEmpty()) {
      throw SeedException.createNew(MongoDbErrorCodes.UNKNOWN_CLIENT_SPECIFIED)
          .put("aggregate", mappedClass.getName())
          .put("clientName", clientName)
          .put("dbName", dbName);
    }

    boolean async = mongodbClientConfiguration.getBoolean("async", false);
    if (async) {
      throw SeedException.createNew(MorphiaErrorCodes.ERROR_ASYNC_CLIENT)
          .put("aggregate", mappedClass.getName())
          .put("clientName", clientName)
          .put("dbName", dbName);
    }

    String[] dbNames = mongodbClientConfiguration.getStringArray("databases");
    boolean found = false;
    for (String nameToCheck : dbNames) {
      if (nameToCheck.equals(resolveDatabaseAlias(mongodbClientConfiguration, dbName))) {
        found = true;
        break;
      }
    }
    if (!found) {
      throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATABASE_NAME)
          .put("aggregate", mappedClass.getName())
          .put("clientName", clientName)
          .put("dbName", dbName);
    }
  }
    @Override
    protected void generateCreateInsns(MethodVisitor mv) {
      if (this.getObjectModelMetadata().getMode() == ObjectModelMode.REFERENCE) {
        Label defaultImplLabel = new Label();
        Class<?> objectModelProxyClass =
            HibernateObjectModelFactoryProvider.this.generateObjectModelProxy(
                this.getObjectModelMetadata().getObjectModelClass());

        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.INSTANCEOF, HIBERNATE_PROXY_INTERNAL_NAME);
        mv.visitJumpInsn(Opcodes.IFEQ, defaultImplLabel);

        mv.visitTypeInsn(Opcodes.NEW, objectModelProxyClass.getName().replace('.', '/'));
        mv.visitInsn(Opcodes.DUP);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.CHECKCAST, HIBERNATE_PROXY_INTERNAL_NAME);

        mv.visitMethodInsn(
            Opcodes.INVOKESPECIAL,
            objectModelProxyClass.getName().replace('.', '/'),
            "<init>",
            '(' + ASM.getDescriptor(ObjectModelFactory.class) + HIBERNATE_PROXY_DESC + ")V",
            false);
        mv.visitInsn(Opcodes.ARETURN);

        mv.visitLabel(defaultImplLabel);
      }
      super.generateCreateInsns(mv);
    }
Пример #3
0
  /**
   * Returns an instance of the annotation MorphiaDatastore if the morphia configuration is ok.
   *
   * @param application Application
   * @param morphiaClass persistent morphia object
   * @return MorphiaDatastore
   */
  public static MorphiaDatastore getMongoDatastore(Application application, Class<?> morphiaClass) {
    Configuration morphiaEntityConfiguration =
        application.getConfiguration(morphiaClass).subset("morphia");
    if (morphiaEntityConfiguration.isEmpty()) {
      throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_CONFIGURATION)
          .put("aggregate", morphiaClass.getName());
    }

    String clientName = morphiaEntityConfiguration.getString("clientName");
    if (clientName == null) {
      throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_CLIENT)
          .put("aggregate", morphiaClass.getName());
    }

    String dbName = morphiaEntityConfiguration.getString("dbName");
    if (dbName == null) {
      throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_DATABASE)
          .put("aggregate", morphiaClass.getName())
          .put("clientName", clientName);
    }

    checkMongoClient(application.getConfiguration(), morphiaClass, clientName, dbName);

    return new MorphiaDatastoreImpl(clientName, dbName);
  }
  public SearchableCacheConfiguration(
      Class<?>[] classArray,
      Properties properties,
      EmbeddedCacheManager uninitializedCacheManager,
      ComponentRegistry cr) {
    this.providedServices = initializeProvidedServices(uninitializedCacheManager, cr);
    if (properties == null) {
      this.properties = new Properties();
    } else {
      this.properties = rescopeProperties(properties);
    }

    classes = new HashMap<String, Class<?>>();

    for (Class<?> c : classArray) {
      String classname = c.getName();
      classes.put(classname, c);
    }

    // deal with programmatic mapping:
    searchMapping = SearchMappingBuilder.getSearchMapping(this);

    // if we have a SearchMapping then we can predict at least those entities specified in the
    // mapping
    // and avoid further SearchFactory rebuilds triggered by new entity discovery during cache
    // events
    if (searchMapping != null) {
      Set<Class<?>> mappedEntities = searchMapping.getMappedEntities();
      for (Class<?> entity : mappedEntities) {
        classes.put(entity.getName(), entity);
      }
    }
  }
Пример #5
0
  public String constructDN(final T o, final String parentDN) throws LDAPPersistException {
    final String existingDN = getEntryDN(o);
    if (existingDN != null) {
      return existingDN;
    }

    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>(1);

    for (final FieldInfo i : rdnFields) {
      final Attribute a = i.encode(o, true);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_FIELD_MISSING_VALUE.get(type.getName(), i.getField().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    for (final GetterInfo i : rdnGetters) {
      final Attribute a = i.encode(o);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_GETTER_MISSING_VALUE.get(
                type.getName(), i.getMethod().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    return constructDN(o, parentDN, attrMap);
  }
  static TypeParameterMatcher generate(Class<?> type, ClassLoader classLoader) {
    final String className = "io.netty.util.internal.__matchers__." + type.getName() + "Matcher";
    try {
      try {
        return (TypeParameterMatcher) Class.forName(className, true, classLoader).newInstance();
      } catch (Exception e) {
        // Not defined in the specified class loader.
      }

      CtClass c = classPool.getAndRename(NoOpTypeParameterMatcher.class.getName(), className);
      c.setModifiers(c.getModifiers() | Modifier.FINAL);
      c.getDeclaredMethod("match").setBody("{ return $1 instanceof " + type.getName() + "; }");
      byte[] byteCode = c.toBytecode();
      c.detach();
      Method method =
          ClassLoader.class.getDeclaredMethod(
              "defineClass", String.class, byte[].class, int.class, int.class);
      method.setAccessible(true);

      Class<?> generated =
          (Class<?>) method.invoke(classLoader, className, byteCode, 0, byteCode.length);
      logger.debug("Generated: {}", generated.getName());
      return (TypeParameterMatcher) generated.newInstance();
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #7
0
  public MethodInvoker getConstructor(Class<?> clazz, Class<?>[] parameters) {
    MethodDescriptor mDescriptor = new MethodDescriptor(clazz.getName(), clazz, parameters);
    MethodInvoker mInvoker = null;
    List<Constructor<?>> acceptableConstructors = null;
    LRUCache<MethodDescriptor, MethodInvoker> cache = cacheHolder.get();

    mInvoker = cache.get(mDescriptor);

    if (mInvoker == null) {
      acceptableConstructors = getConstructorsByLength(clazz, parameters.length);

      if (acceptableConstructors.size() == 1) {
        mInvoker = MethodInvoker.buildInvoker(acceptableConstructors.get(0), parameters);
      } else {
        mInvoker = getBestConstructor(acceptableConstructors, parameters);
      }

      if (mInvoker != null && mInvoker.getCost() != -1) {
        cache.put(mDescriptor, mInvoker);
      } else {
        String errorMessage =
            "Constructor "
                + clazz.getName()
                + "("
                + Arrays.toString(parameters)
                + ") does not exist";
        logger.log(Level.WARNING, errorMessage);
        throw new Py4JException(errorMessage);
      }
    }

    return mInvoker;
  }
  @Override
  public Statement apply(Statement statement, FrameworkMethod frameworkMethod, Object target) {

    Method method = frameworkMethod.getMethod();

    Class<?> targetClass = target.getClass();

    NewEnv newEnv = findNewEnv(method, targetClass);

    if ((newEnv == null) || (newEnv.type() == NewEnv.Type.NONE)) {
      return statement;
    }

    if (NewEnv.Type.CLASSLOADER == newEnv.type()) {
      return new RunInNewClassLoaderStatement(
          targetClass.getName(),
          getMethodKeys(targetClass, Before.class),
          method,
          getMethodKeys(targetClass, After.class));
    }

    Builder builder = new Builder();

    builder.setArguments(createArguments(method));
    builder.setBootstrapClassPath(CLASS_PATH);
    builder.setRuntimeClassPath(CLASS_PATH);

    return new RunInNewJVMStatment(
        builder.build(),
        targetClass.getName(),
        getMethodKeys(targetClass, Before.class),
        new MethodKey(method),
        getMethodKeys(targetClass, After.class));
  }
 private org.apache.hadoop.fs.FileSystem instantiateFileSystem(
     Class<? extends org.apache.hadoop.fs.FileSystem> fsClass) throws IOException {
   try {
     return fsClass.newInstance();
   } catch (ExceptionInInitializerError e) {
     throw new IOException(
         "The filesystem class '"
             + fsClass.getName()
             + "' throw an exception upon initialization.",
         e.getException());
   } catch (Throwable t) {
     String errorMessage = InstantiationUtil.checkForInstantiationError(fsClass);
     if (errorMessage != null) {
       throw new IOException(
           "The filesystem class '"
               + fsClass.getName()
               + "' cannot be instantiated: "
               + errorMessage);
     } else {
       throw new IOException(
           "An error occurred while instantiating the filesystem class '"
               + fsClass.getName()
               + "'.",
           t);
     }
   }
 }
Пример #10
0
  private void loadMessageClass(final Class<? extends MessageQueueData> messageClass) {
    final GameControllerMessage gameControllerMessage =
        messageClass.getAnnotation(GameControllerMessage.class);

    for (final GameControllerMessageType type : gameControllerMessage.value()) {
      if (messageQueueDataConstructorMap.containsKey(type)) {
        LOGGER.error(
            "{} cannot handle GameControllerMessageType {} because it is already being handled by class {}.",
            messageClass.getName(),
            type,
            messageQueueDataConstructorMap.get(type).getClass().getName());
      }

      try {
        final Constructor<? extends MessageQueueData> constructor =
            messageClass.getConstructor(ByteBuffer.class);

        LOGGER.debug(
            "Setting {} to handle GameControllerMessageType {}.", messageClass.getName(), type);
        messageQueueDataConstructorMap.put(type, constructor);

      } catch (NoSuchMethodException e) {
        LOGGER.error("{} does not have a constructor taking ByteBuffer", messageClass.getName(), e);
      }
    }
  }
Пример #11
0
  @Override
  public synchronized Collection<Event> getEventFacets() {
    if (facets == null) {
      facets = new ArrayList<Event>();

      DefaultFacets defaults = getClass().getAnnotation(DefaultFacets.class);
      if (defaults != null) {
        for (Class<? extends Event> clazz : defaults.value()) {
          Event facet;

          if (injector == null) {
            try {
              facet = clazz.newInstance();
            } catch (IllegalAccessException e) {
              throw new RuntimeException(
                  "The type " + clazz.getName() + " does not have a public, no-arg constructor", e);
            } catch (InstantiationException e) {
              throw new RuntimeException(
                  "Could not construct an instance of " + clazz.getName(), e);
            }
          } else {
            facet = injector.getInstance(clazz);
          }
          facets.add(facet);
        }
      }
    }
    return facets;
  }
  @SuppressWarnings({"unchecked"})
  public T createInstance(String managerClassName) {
    Class managerClass = ReflectionUtil.loadClass(managerClassName);
    if (managerClass == null) {
      logger.warn("Cannot load class: {}", managerClassName);
      managerClass = defaultImplClass;
    }

    if (!clazz.isAssignableFrom(managerClass)) {
      logger.warn("Cannot use as {}: {}", clazz.getName(), managerClassName);
      managerClass = defaultImplClass;
    }
    logger.debug("Using class: {}", managerClass.getName());

    T instance = (T) ReflectionUtil.newInstance(managerClass);
    if (instance == null) {
      logger.warn(
          "Cannot instanciate: {}. Fall back to default: {}.",
          managerClass.getName(),
          FieldsManager.class.getName());
      instance = (T) ReflectionUtil.newInstance(defaultImplClass);
      if (instance == null) {
        logger.error("Cannot instanciate: {}", defaultImplClass.getName());
      }
    }

    logger.debug("Installed {0}: {1}", clazz.getName(), instance);
    return instance;
  }
  @SuppressWarnings("unchecked")
  private <T> T instanciateRemoteServiceInstance(
      Class<T> remoteServiceClass, String remoteServiceRelativePath) {

    Class<?> remoteServiceImplClass =
        ModuleData.get().getRemoteServiceImplClass(remoteServiceRelativePath);

    if (remoteServiceImplClass == null) {
      throw new GwtTestConfigurationException(
          "Cannot find a RemoteService implementation class for servlet path '"
              + remoteServiceRelativePath
              + "'. Please add a <servlet> element in your test GWT configuration file (.gwt.xml)");
    } else if (!remoteServiceClass.isAssignableFrom(remoteServiceImplClass)) {
      throw new GwtTestConfigurationException(
          "The servlet class '"
              + remoteServiceImplClass.getName()
              + "' setup for path '"
              + remoteServiceRelativePath
              + "' does not implement RemoteService interface '"
              + remoteServiceClass.getName());
    } else {
      try {
        return (T) GwtReflectionUtils.instantiateClass(remoteServiceImplClass);
      } catch (Exception e) {
        throw new GwtTestConfigurationException(
            "Error during the instanciation of "
                + RemoteService.class.getSimpleName()
                + " implementation for servlet path '"
                + remoteServiceRelativePath
                + "'",
            e);
      }
    }
  }
  public static String getCreateStatement(Class<?> clazz) {
    if (null == clazz) {
      logger.info("arguments clazz null");
      System.exit(0);
    }

    DBTable dbTable = clazz.getAnnotation(DBTable.class);
    if (null == dbTable) {
      logger.info("no DBTable annotation in class {}.", clazz.getName());
      System.exit(0);
    }

    String tableName = getTableName(clazz, dbTable);

    List<String> columnDefinitions = getColumnDefinitions(clazz);

    StringBuilder createStatement = new StringBuilder("CREATE TABLE " + tableName + "(");
    for (String columnDef : columnDefinitions) {
      createStatement.append("\n  ").append(columnDef).append(",");
    }
    String schemaCreateStatement =
        createStatement.substring(0, createStatement.length() - 1) + ");";
    logger.info("Table Creation SQL for {} is:\n\n {}", clazz.getName(), schemaCreateStatement);
    return schemaCreateStatement;
  }
Пример #15
0
 private static boolean isType(JClassType type, Class<?> class1) {
   try {
     return type.getOracle().getType(class1.getName()).isAssignableFrom(type);
   } catch (NotFoundException e) {
     throw new RuntimeException("Could not find " + class1.getName(), e);
   }
 }
Пример #16
0
 public void processClass(Class klass) {
   if (this.out == null) {
     if (this.outFile.exists()) {
       this.outFile.delete();
     }
     try {
       this.out = new PrintWriter(this.outFile);
     } catch (FileNotFoundException e) {
       e.printStackTrace(System.err);
       System.exit(-1); // GRZE: special case to fail build
     }
     this.bindingName = this.ns.replaceAll("(http://)|(/$)", "").replaceAll("[./-]", "_");
     this.out.write(
         "<binding xmlns:euca=\"" + this.ns + "\" name=\"" + this.bindingName + "\">\n");
     this.out.write(
         "  <namespace uri=\"" + this.ns + "\" default=\"elements\" prefix=\"euca\"/>\n");
     this.out.flush();
   }
   if (!classNames.contains(klass.getName())) {
     classNames.add(klass.getName());
     String mapping = new RootObjectTypeBinding(klass).process();
     this.out.write(mapping);
     this.out.flush();
   } else {
     Logs.extreme().debug("Skipping duplicate class: " + klass);
   }
 }
Пример #17
0
  static {
    Class<Object> clazz;

    logger = LoggerManager.getLogger(Base64.class.getName());

    try {
      clazz = (Class<Object>) Class.forName("android.util.Base64");
      // Looking for encode( byte[] input, int flags)
      aMethod = clazz.getMethod("encode", byte[].class, Integer.TYPE);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of android.util.Base64", x);
    }

    try {
      clazz = (Class<Object>) Class.forName("org.bouncycastle.util.encoders.Base64Encoder");
      bEncoder = clazz.newInstance();
      // Looking for encode( byte[] input, int offset, int length, OutputStream output)
      bMethod =
          clazz.getMethod("encode", byte[].class, Integer.TYPE, Integer.TYPE, OutputStream.class);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of org.bouncycastle.util.encoders.Base64Encoder", x);
    }

    if (aMethod == null && bMethod == null)
      throw new IllegalStateException("No base64 encoder implementation is available.");
  }
Пример #18
0
 private void putInstance(Class<?> clazz) {
   try {
     instances.put(clazz.getName(), clazz.newInstance());
   } catch (InstantiationException | IllegalAccessException e) {
     LOGGER.error("Unable to create instance of " + clazz.getName(), e);
   }
 }
Пример #19
0
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
  @SuppressWarnings("unchecked")
  EntityTypeIdImpl(Object entityId, Object beanTypeId, Class<? extends BEAN_TYPE> beanType) {
    if (entityId == null && beanTypeId == null && beanType == null) {
      throw new IllegalArgumentException(
          "At least one of the parameters 'entityId', 'beanTypeId' or 'beanType' must not be null");
    }

    if (entityId == null) { // then beanTypeId or beanType must be != null
      if (beanTypeId == null) {
        beanTypeId = beanType.getName();
        entityId = beanType;
      } else if (beanType == null) {
        beanType = (Class<? extends BEAN_TYPE>) IBeanDto.class;
        entityId = beanTypeId;
      }
    } else { // entityId is not null
      if (beanType == null) {
        beanType = (Class<? extends BEAN_TYPE>) EntityServiceHelper.getBeanType(entityId);
        if (beanType == null) {
          beanType = (Class<? extends BEAN_TYPE>) IBeanDto.class;
        }
      }
      // from here beanType is not null
      if (beanTypeId == null) {
        beanTypeId = EntityServiceHelper.getBeanTypeId(entityId);
        if (beanTypeId == null) {
          beanTypeId = beanType.getName();
        }
      }
    }

    this.entityId = entityId;
    this.beanTypeId = beanTypeId;
    this.beanType = (Class<BEAN_TYPE>) beanType;
  }
Пример #21
0
  public static Class getClassReference(ParserContext ctx, TypeDescriptor tDescr)
      throws ClassNotFoundException {
    Class cls;
    if (ctx != null && ctx.hasImport(tDescr.className)) {
      cls = ctx.getImport(tDescr.className);
      if (tDescr.isArray()) {
        cls =
            findClass(
                null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
      }
    } else if (ctx == null && hasContextFreeImport(tDescr.className)) {
      cls = getContextFreeImport(tDescr.className);
      if (tDescr.isArray()) {
        cls =
            findClass(
                null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
      }
    } else {
      cls = createClass(tDescr.getClassName(), ctx);
      if (tDescr.isArray()) {
        cls =
            findClass(
                null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
      }
    }

    return cls;
  }
 private void processStrength(PlanningVariable planningVariableAnnotation) {
   Class<? extends Comparator> strengthComparatorClass =
       planningVariableAnnotation.strengthComparatorClass();
   if (strengthComparatorClass == PlanningVariable.NullStrengthComparator.class) {
     strengthComparatorClass = null;
   }
   Class<? extends SelectionSorterWeightFactory> strengthWeightFactoryClass =
       planningVariableAnnotation.strengthWeightFactoryClass();
   if (strengthWeightFactoryClass == PlanningVariable.NullStrengthWeightFactory.class) {
     strengthWeightFactoryClass = null;
   }
   if (strengthComparatorClass != null && strengthWeightFactoryClass != null) {
     throw new IllegalStateException(
         "The planningEntityClass ("
             + planningEntityDescriptor.getPlanningEntityClass()
             + ") property ("
             + variablePropertyAccessor.getName()
             + ") cannot have a strengthComparatorClass ("
             + strengthComparatorClass.getName()
             + ") and a strengthWeightFactoryClass ("
             + strengthWeightFactoryClass.getName()
             + ") at the same time.");
   }
   if (strengthComparatorClass != null) {
     Comparator<Object> strengthComparator =
         ConfigUtils.newInstance(this, "strengthComparatorClass", strengthComparatorClass);
     valueSorter.setStrengthComparator(strengthComparator);
   }
   if (strengthWeightFactoryClass != null) {
     SelectionSorterWeightFactory strengthWeightFactory =
         ConfigUtils.newInstance(this, "strengthWeightFactoryClass", strengthWeightFactoryClass);
     valueSorter.setStrengthWeightFactory(strengthWeightFactory);
   }
 }
Пример #23
0
  private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException {
    if (dnField != null) {
      try {
        dnField.set(o, e.getDN());
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get(
                type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }

    if (entryField != null) {
      try {
        entryField.set(o, new ReadOnlyEntry(e));
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get(
                type.getName(), entryField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }
  }
Пример #24
0
  public static void validatePassivating(Class<?> cl, Bean<?> bean, String typeName) {
    Class<?> beanClass = bean.getBeanClass();

    if (!Serializable.class.isAssignableFrom(beanClass) && false) {
      ConfigException exn =
          new ConfigException(
              L.l(
                  "{0}: {1} is an invalid {2} because it is not serializable.",
                  cl.getName(), bean, typeName));

      throw exn;
      // InjectManager.create().addDefinitionError(exn);
    }

    for (InjectionPoint ip : bean.getInjectionPoints()) {
      if (ip.isTransient() || ip.isDelegate()) continue;

      Class<?> type = getRawClass(ip.getType());

      if (type.isInterface()) continue;

      if (!Serializable.class.isAssignableFrom(type)) {
        ConfigException exn =
            new ConfigException(
                L.l(
                    "{0}: {1} is an invalid {4} because its injection point '{2}' of type {3} is not serializable.",
                    cl.getName(), bean, ip.getMember().getName(), ip.getType(), typeName));

        throw exn;
      }
    }
  }
Пример #25
0
 /**
  * Get a method by name.
  * 
  * @param c  class object
  * @param methodName  method name
  * @param argTypes  argument types
  * @return  method object, or null if it does not exist
  */
 public static Method getDeclaredMethod(Class c, String methodName, Class[] argTypes) {
     Method m;
     try {
         if (argTypes != null) {
             m = c.getMethod(methodName, argTypes);
         } else {
             m = null;
             Method[] ms = c.getDeclaredMethods();
             for (int i = 0; i < ms.length; ++i) {
                 if (ms[i].getName().equals(methodName)) {
                     m = ms[i];
                     break;
                 }
             }
             if (m == null) {
                 System.err.println("Can't find "+c.getName()+"."+methodName);
                 return null;
             }
         }
         try {
             m.setAccessible(true);
         } catch (AccessControlException _) { }
     } catch (SecurityException e1) {
         System.err.println("Cannot access "+c.getName()+"."+methodName);
         e1.printStackTrace();
         return null;
     } catch (NoSuchMethodException e1) {
         System.err.println("Can't find "+c.getName()+"."+methodName);
         e1.printStackTrace();
         return null;
     }
     return m;
 }
Пример #26
0
  /**
   * Creates and returns a new instance of Multi Layer Perceptron
   *
   * @param layersStr space separated number of neurons in layers
   * @param transferFunctionType transfer function type for neurons
   * @return instance of Multi Layer Perceptron
   */
  public static MultiLayerPerceptron createMLPerceptron(
      String layersStr,
      TransferFunctionType transferFunctionType,
      Class learningRule,
      boolean useBias,
      boolean connectIO) {
    ArrayList<Integer> layerSizes = VectorParser.parseInteger(layersStr);
    NeuronProperties neuronProperties = new NeuronProperties(transferFunctionType, useBias);
    MultiLayerPerceptron nnet = new MultiLayerPerceptron(layerSizes, neuronProperties);

    // set learning rule - TODO: use reflection here
    if (learningRule.getName().equals(BackPropagation.class.getName())) {
      nnet.setLearningRule(new BackPropagation());
    } else if (learningRule.getName().equals(MomentumBackpropagation.class.getName())) {
      nnet.setLearningRule(new MomentumBackpropagation());
    } else if (learningRule.getName().equals(DynamicBackPropagation.class.getName())) {
      nnet.setLearningRule(new DynamicBackPropagation());
    } else if (learningRule.getName().equals(ResilientPropagation.class.getName())) {
      nnet.setLearningRule(new ResilientPropagation());
    }

    // connect io
    if (connectIO) {
      nnet.connectInputsToOutputs();
    }

    return nnet;
  }
 private <T> void verifySameImplementation(
     Class<T> serviceClass, Collection<Class<? extends T>> providers) {
   boolean providersAreTheSame = false;
   Class<?> firstProvider = null;
   for (Class<?> provider : providers) {
     if (firstProvider == null) {
       // set the class to match
       firstProvider = provider;
       continue;
     }
     if (firstProvider == provider) {
       providersAreTheSame = true;
     } else {
       throw new IllegalStateException(
           "More then one implementation found for "
               + serviceClass.getName()
               + ", "
               + "please check your classpath. The found implementations are "
               + toClassString(providers));
     }
   }
   if (providersAreTheSame) {
     logger.warning(
         "More then one reference to the same implementation was found for "
             + serviceClass.getName()
             + ", please verify you classpath");
   }
 }
Пример #28
0
 private MetaClass createWithCustomLookup(Class theClass, MetaClassRegistry registry) {
   try {
     final Class customMetaClass =
         Class.forName("groovy.runtime.metaclass." + theClass.getName() + "MetaClass");
     if (DelegatingMetaClass.class.isAssignableFrom(customMetaClass)) {
       final Constructor customMetaClassConstructor =
           customMetaClass.getConstructor(MetaClass.class);
       MetaClass normalMetaClass = createNormalMetaClass(theClass, registry);
       return (MetaClass) customMetaClassConstructor.newInstance(normalMetaClass);
     } else {
       final Constructor customMetaClassConstructor =
           customMetaClass.getConstructor(MetaClassRegistry.class, Class.class);
       return (MetaClass) customMetaClassConstructor.newInstance(registry, theClass);
     }
   } catch (final ClassNotFoundException e) {
     return createNormalMetaClass(theClass, registry);
   } catch (final Exception e) {
     throw new GroovyRuntimeException(
         "Could not instantiate custom Metaclass for class: "
             + theClass.getName()
             + ". Reason: "
             + e,
         e);
   }
 }
 private Callback[] getCallbacks(Object source) {
   Class type = source.getClass();
   List fields = (List) fieldCache.get(type.getName());
   if (fields == null) {
     fields = new ArrayList();
     fieldCache.put(type.getName(), fields);
     for (int i = 0; true; ++i) {
       try {
         Field field = type.getDeclaredField(CALLBACK_MARKER + i);
         field.setAccessible(true);
         fields.add(field);
       } catch (NoSuchFieldException e) {
         break;
       }
     }
   }
   List list = new ArrayList();
   for (int i = 0; i < fields.size(); ++i) {
     try {
       Field field = (Field) fields.get(i);
       Object callback = field.get(source);
       list.add(callback);
     } catch (IllegalAccessException e) {
       throw new ObjectAccessException(
           "Access to " + type.getName() + "." + CALLBACK_MARKER + i + " not allowed");
     }
   }
   return (Callback[]) list.toArray(new Callback[list.size()]);
 }
  /**
   * This extracts and instantiates the implementation class from a {@code ClassBridge} annotation.
   *
   * @param cb the class bridge annotation
   * @param clazz the {@code Class} on which the annotation is defined on
   * @return Returns the specified {@code FieldBridge} instance
   */
  public FieldBridge extractType(ClassBridge cb, Class<?> clazz) {
    FieldBridge bridge = null;
    Class<?> bridgeType = null;

    if (cb != null) {
      bridgeType = cb.impl();
      if (bridgeType != null) {
        try {
          Object instance = bridgeType.newInstance();
          if (FieldBridge.class.isAssignableFrom(bridgeType)) {
            bridge = (FieldBridge) instance;
          } else if (org.hibernate.search.bridge.TwoWayStringBridge.class.isAssignableFrom(
              bridgeType)) {
            bridge =
                new TwoWayString2FieldBridgeAdaptor(
                    (org.hibernate.search.bridge.TwoWayStringBridge) instance);
          } else if (org.hibernate.search.bridge.StringBridge.class.isAssignableFrom(bridgeType)) {
            bridge =
                new String2FieldBridgeAdaptor((org.hibernate.search.bridge.StringBridge) instance);
          } else {
            throw LOG.noFieldBridgeInterfaceImplementedByClassBridge(bridgeType.getName());
          }
        } catch (Exception e) {
          throw LOG.cannotInstantiateClassBridgeOfType(bridgeType.getName(), clazz.getName(), e);
        }
      }
    }
    if (bridge == null) {
      throw LOG.unableToDetermineClassBridge(ClassBridge.class.getName());
    }

    populateReturnType(clazz, bridgeType, bridge);

    return bridge;
  }