private void addControllerServlet(Class<?> klass)
     throws InstantiationException, IllegalAccessException {
   assert klass != null;
   ControllerServlet servlet = null;
   Controller controller;
   if (Controller.class.isAssignableFrom(klass)) {
     controller = controllerFactory.createController(klass.asSubclass(Controller.class));
   } else {
     SimpleControllerWrapper.checkValidSimpleControllerClass(klass);
     SimpleControllerWrapper simpleController =
         SimpleControllerWrapper.createInstance(controllerFactory.createController(klass));
     configure(simpleController);
     controller = simpleController;
   }
   URL url = klass.getAnnotation(URL.class);
   servlet = new ControllerServlet(controller);
   AllowedHttpMethods httpMethods = klass.getAnnotation(AllowedHttpMethods.class);
   if (httpMethods != null) {
     servlet.setValidHttpMethods(httpMethods.value());
   }
   ControllerServlet.AfterControllerAction action = null;
   if (klass.isAnnotationPresent(ForwardTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(ForwardTo.class).value());
   } else if (klass.isAnnotationPresent(RedirectTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(RedirectTo.class).value());
   }
   servlet.setAfterControllerAction(action);
   ServletRegistration.Dynamic dynamic = context.addServlet(klass.getSimpleName(), servlet);
   dynamic.addMapping(url.value());
 }
  private synchronized ScopeValidator getScopeValidator() throws ServerException {
    if (scopeValidator == null) {
      try {
        final String scopeValidatorClassName =
            getStringSettingValue(OAuth2ProviderService.SCOPE_PLUGIN_CLASS);
        if (isEmpty(scopeValidatorClassName)) {
          logger.message("Scope Validator class not set.");
          throw new ServerException("Scope Validator class not set.");
        }

        final Class<?> scopeValidatorClass = Class.forName(scopeValidatorClassName);

        if (Scope.class.isAssignableFrom(scopeValidatorClass)) {
          final Scope scopeClass =
              InjectorHolder.getInstance(scopeValidatorClass.asSubclass(Scope.class));
          return new LegacyScopeValidator(scopeClass);
        }

        scopeValidator =
            InjectorHolder.getInstance(scopeValidatorClass.asSubclass(ScopeValidator.class));

      } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
        throw new ServerException(e);
      }
    }
    return scopeValidator;
  }
  private ResponseTypeHandler wrap(String responseTypeName, String responseTypeHandlerClassName)
      throws UnsupportedResponseTypeException {

    if (responseTypeHandlerClassName == null || responseTypeHandlerClassName.isEmpty()) {
      logger.warning(
          "Requested a response type that is not configured. response_type=" + responseTypeName);
      throw new UnsupportedResponseTypeException("Response type is not supported");
    } else if (responseTypeHandlerClassName.equalsIgnoreCase("none")) {
      return new NoneResponseTypeHandler();
    }
    try {
      final Class<?> responseTypeHandlerClass = Class.forName(responseTypeHandlerClassName);
      if (ResponseType.class.isAssignableFrom(responseTypeHandlerClass)) {
        ResponseType responseType =
            InjectorHolder.getInstance(responseTypeHandlerClass.asSubclass(ResponseType.class));
        return new LegacyResponseTypeHandler(
            responseType, realm, getSSOCookieName(), cookieExtractor);
      }

      return InjectorHolder.getInstance(
          responseTypeHandlerClass.asSubclass(ResponseTypeHandler.class));

    } catch (ClassNotFoundException e) {
      logger.error(e.getMessage());
      throw new UnsupportedResponseTypeException("Response type is not supported");
    }
  }
Example #4
0
  public static void register(Class<? extends Event> pore) {
    checkNotNull(pore, "pore");

    Class<? extends org.spongepowered.api.event.Event> sponge = null;
    for (Constructor<?> constructor : pore.getConstructors()) {
      Class<?>[] parameters = constructor.getParameterTypes();
      if (parameters.length == 1) {
        Class<?> parameter = parameters[0];
        if (org.spongepowered.api.event.Event.class.isAssignableFrom(parameter)) {
          sponge = parameter.asSubclass(org.spongepowered.api.event.Event.class);
        }
      }
    }

    checkArgument(sponge != null, "No event constructor found in %s", pore);

    Class<?> superClass = pore.getSuperclass();
    checkState(
        !Modifier.isAbstract(superClass.getModifiers())
            && superClass.getName().startsWith("org.bukkit.event"),
        "Not a Bukkit handle event %s",
        superClass);
    Class<? extends Event> handle = superClass.asSubclass(Event.class);

    HandlerList list = SimplePluginManager.getEventListeners(handle);
    list.addAdapter(create(pore, sponge));
  }
Example #5
0
 public static Object convertArrayElements(Class<?> arrayType, Object array) {
   Class<?> src = array.getClass().getComponentType();
   Class<?> dst = arrayType.getComponentType();
   if (src == null || dst == null) throw new IllegalArgumentException("not array type");
   Wrapper sw = (src.isPrimitive() ? Wrapper.forPrimitiveType(src) : null);
   Wrapper dw = (dst.isPrimitive() ? Wrapper.forPrimitiveType(dst) : null);
   int length;
   if (sw == null) {
     Object[] a = (Object[]) array;
     length = a.length;
     if (dw == null) return Arrays.copyOf(a, length, arrayType.asSubclass(Object[].class));
     Object res = dw.makeArray(length);
     dw.copyArrayUnboxing(a, 0, res, 0, length);
     return res;
   }
   length = j86.java.lang.reflect.Array.getLength(array);
   Object[] res;
   if (dw == null) {
     res = Arrays.copyOf(NO_ARGS_ARRAY, length, arrayType.asSubclass(Object[].class));
   } else {
     res = new Object[length];
   }
   sw.copyArrayBoxing(array, 0, res, 0, length);
   if (dw == null) return res;
   Object a = dw.makeArray(length);
   dw.copyArrayUnboxing(res, 0, a, 0, length);
   return a;
 }
Example #6
0
 static {
   for (Class<?> cl : dolda.jglob.Loader.get(ResName.class).classes()) {
     String nm = cl.getAnnotation(ResName.class).value();
     if (ResCons.class.isAssignableFrom(cl)) {
       final ResCons scons;
       try {
         scons = cl.asSubclass(ResCons.class).newInstance();
       } catch (InstantiationException e) {
         throw (new Error(e));
       } catch (IllegalAccessException e) {
         throw (new Error(e));
       }
       rnames.put(
           nm,
           new ResCons2() {
             public Res.Resolver cons(Resource res, Object... args) {
               final GLState ret = scons.cons(res, args);
               return (new Res.Resolver() {
                 public void resolve(Collection<GLState> buf) {
                   if (ret != null) buf.add(ret);
                 }
               });
             }
           });
     } else if (ResCons2.class.isAssignableFrom(cl)) {
       try {
         rnames.put(nm, cl.asSubclass(ResCons2.class).newInstance());
       } catch (InstantiationException e) {
         throw (new Error(e));
       } catch (IllegalAccessException e) {
         throw (new Error(e));
       }
     } else if (GLState.class.isAssignableFrom(cl)) {
       final Constructor<? extends GLState> cons;
       try {
         cons = cl.asSubclass(GLState.class).getConstructor(Resource.class, Object[].class);
       } catch (NoSuchMethodException e) {
         throw (new Error("No proper constructor for res-consable GL state " + cl.getName(), e));
       }
       rnames.put(
           nm,
           new ResCons2() {
             public Res.Resolver cons(final Resource res, final Object... args) {
               return (new Res.Resolver() {
                 public void resolve(Collection<GLState> buf) {
                   buf.add(Utils.construct(cons, res, args));
                 }
               });
             }
           });
     } else {
       throw (new Error("Illegal material constructor class: " + cl));
     }
   }
 }
 public AbstractEJBMetaData<?, ?> toAbstractEJBMetaData() {
   if (session || statelessSession) {
     if (statelessSession) {
       return createStatelessMetaData(remoteClass.asSubclass(EJBObject.class), homeClass, home);
     }
     return createStatefulMetaData(remoteClass.asSubclass(EJBObject.class), homeClass, home);
   } else {
     return createEntityMetaData(
         remoteClass.asSubclass(EJBObject.class), homeClass, home, pkClass);
   }
 }
  public void m1(Class<?> c) {
    Class<? extends I2> x = c.asSubclass(I2.class);

    new WeakReference<Object>(x);
    new WeakReference<Class>(x);
    new WeakReference<Class<? extends I2>>(x);

    new WeakReference<Object>(c.asSubclass(I2.class));
    new WeakReference<Class>(c.asSubclass(I2.class));
    new WeakReference<Class<? extends I2>>(c.asSubclass(I2.class));
  }
Example #9
0
 private static Object getPluginImplementationViaArchaius(Class<?> pluginClass) {
   String classSimpleName = pluginClass.getSimpleName();
   // Check Archaius for plugin class.
   String propertyName = "hystrix.plugin." + classSimpleName + ".implementation";
   String implementingClass =
       DynamicPropertyFactory.getInstance().getStringProperty(propertyName, null).get();
   if (implementingClass != null) {
     try {
       Class<?> cls = Class.forName(implementingClass);
       // narrow the scope (cast) to the type we're expecting
       cls = cls.asSubclass(pluginClass);
       return cls.newInstance();
     } catch (ClassCastException e) {
       throw new RuntimeException(
           classSimpleName
               + " implementation is not an instance of "
               + classSimpleName
               + ": "
               + implementingClass);
     } catch (ClassNotFoundException e) {
       throw new RuntimeException(
           classSimpleName + " implementation class not found: " + implementingClass, e);
     } catch (InstantiationException e) {
       throw new RuntimeException(
           classSimpleName + " implementation not able to be instantiated: " + implementingClass,
           e);
     } catch (IllegalAccessException e) {
       throw new RuntimeException(
           classSimpleName + " implementation not able to be accessed: " + implementingClass, e);
     }
   } else {
     return null;
   }
 }
Example #10
0
 @Restricted(DoNotUse.class) // accessed via REST API
 public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json)
     throws Exception {
   // TODO JENKINS-31458 is there not an easier way to do this?
   JSONObject jsonO = JSONObject.fromObject(json);
   Jenkins j = Jenkins.getActiveInstance();
   Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
   StepDescriptor descriptor = (StepDescriptor) j.getDescriptor(c.asSubclass(Step.class));
   Object o;
   try {
     o = descriptor.newInstance(req, jsonO);
   } catch (RuntimeException x) { // e.g. IllegalArgumentException
     return HttpResponses.plainText(Functions.printThrowable(x));
   }
   try {
     String groovy = object2Groovy(o);
     if (descriptor.isAdvanced()) {
       String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
       groovy = "// " + warning + "\n" + groovy;
     }
     return HttpResponses.plainText(groovy);
   } catch (UnsupportedOperationException x) {
     Logger.getLogger(CpsFlowExecution.class.getName())
         .log(Level.WARNING, "failed to render " + json, x);
     return HttpResponses.plainText(x.getMessage());
   }
 }
Example #11
0
 private void activateMapRenderer(String rendererClassName) {
   Class<?> c = loadRendererClass(rendererClassName);
   if (c == null) {
     Main.error(
         tr(
             "Can''t activate map renderer class ''{0}'', because the class wasn''t found.",
             rendererClassName));
     Main.error(tr("Activating the standard map renderer instead."));
     activateDefault();
   } else if (!AbstractMapRenderer.class.isAssignableFrom(c)) {
     Main.error(
         tr(
             "Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.",
             rendererClassName, AbstractMapRenderer.class.getName()));
     Main.error(tr("Activating the standard map renderer instead."));
     activateDefault();
   } else {
     Class<? extends AbstractMapRenderer> renderer = c.asSubclass(AbstractMapRenderer.class);
     if (!isRegistered(renderer)) {
       Main.error(
           tr(
               "Can''t activate map renderer class ''{0}'', because it isn''t registered as map renderer.",
               rendererClassName));
       Main.error(tr("Activating the standard map renderer instead."));
       activateDefault();
     } else {
       activate(renderer);
     }
   }
 }
 @SuppressWarnings("unchecked")
 private void configure(SimpleControllerWrapper controller) {
   assert controller != null;
   try {
     controller.setAutoRequestAttribute(
         Boolean.parseBoolean(getParameter("carmesi.requestAttribute.autoGeneration", "true")));
     controller.setDefaultCookieMaxAge(
         Integer.parseInt(getParameter("carmesi.cookie.maxAge", "-1")));
     String jsonSerializerClassname =
         getParameter("carmesi.json.serializer", "carmesi.json.JacksonSerializer");
     Class<?> serializerKlass = Class.forName(jsonSerializerClassname);
     if (JSONSerializer.class.isAssignableFrom(serializerKlass)) {
       controller.setJSONSerializer(
           serializerKlass.asSubclass(JSONSerializer.class).newInstance());
     }
     for (Map.Entry<Class<?>, Converter<?>> entry : converterMap.entrySet()) {
       controller.addConverter(
           (Class<Object>) entry.getKey(), (Converter<Object>) entry.getValue());
     }
   } catch (ClassNotFoundException ex) {
     Logger.getLogger(CarmesiInitializer.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IllegalAccessException ex) {
     Logger.getLogger(CarmesiInitializer.class.getName()).log(Level.SEVERE, null, ex);
   } catch (InstantiationException ex) {
     Logger.getLogger(CarmesiInitializer.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
  private void loadMarshallers() {
    Set<Class<?>> marshallers =
        ScannerSingleton.getOrCreateInstance().getTypesAnnotatedWith(ClientMarshaller.class);

    for (Class<?> cls : marshallers) {
      if (Marshaller.class.isAssignableFrom(cls)) {
        try {
          Class<?> type =
              (Class<?>) Marshaller.class.getMethod("getTypeHandled").invoke(cls.newInstance());
          mappingContext.registerMarshaller(type.getName(), cls.asSubclass(Marshaller.class));

          if (cls.isAnnotationPresent(ImplementationAliases.class)) {
            for (Class<?> c : cls.getAnnotation(ImplementationAliases.class).value()) {
              mappingContext.registerMappingAlias(c, type);
            }
          }
        } catch (Throwable t) {
          throw new RuntimeException("could not instantiate marshaller class: " + cls.getName(), t);
        }
      } else {
        throw new RuntimeException(
            "class annotated with "
                + ClientMarshaller.class.getCanonicalName()
                + " does not implement "
                + Marshaller.class.getName());
      }
    }
  }
 private Class<? extends GAttrib> attrclass(Class<? extends GAttrib> cl) {
   while (true) {
     Class<?> p = cl.getSuperclass();
     if (p == GAttrib.class) return (cl);
     cl = p.asSubclass(GAttrib.class);
   }
 }
Example #15
0
  /**
   * (Compiles and) loads all custom abilities in the given directory.
   *
   * @param classDir a directory
   */
  private static void loadClasses(File classDir) {
    // Grab the class loader
    ClassLoader loader = getLoader(classDir);
    if (loader == null) return;

    for (File file : classDir.listFiles()) {
      String filename = file.getName();

      // Only load .class files.
      int dot = filename.lastIndexOf(".class");
      if (dot < 0) continue;

      // Trim off the .class extension
      String name = filename.substring(0, file.getName().lastIndexOf("."));

      try {
        // Load the class
        Class<?> cls = loader.loadClass(name);

        // Verify that it's an Ability, then register it
        if (Ability.class.isAssignableFrom(cls)) {
          register(cls.asSubclass(Ability.class), true);
        }
      } catch (Exception e) {
      }
    }
  }
 /**
  * Get the list of codecs listed in the configuration
  *
  * @param conf the configuration to look in
  * @return a list of the Configuration classes or null if the attribute was not set
  */
 public static List<Class<? extends CompressionCodec>> getCodecClasses(Configuration conf) {
   String codecsString = conf.get("io.compression.codecs");
   if (codecsString != null) {
     List<Class<? extends CompressionCodec>> result =
         new ArrayList<Class<? extends CompressionCodec>>();
     StringTokenizer codecSplit = new StringTokenizer(codecsString, ",");
     while (codecSplit.hasMoreElements()) {
       String codecSubstring = codecSplit.nextToken();
       if (codecSubstring.length() != 0) {
         try {
           Class<?> cls = conf.getClassByName(codecSubstring);
           if (!CompressionCodec.class.isAssignableFrom(cls)) {
             throw new IllegalArgumentException(
                 "Class " + codecSubstring + " is not a CompressionCodec");
           }
           result.add(cls.asSubclass(CompressionCodec.class));
         } catch (ClassNotFoundException ex) {
           throw new IllegalArgumentException(
               "Compression codec " + codecSubstring + " not found.", ex);
         }
       }
     }
     return result;
   } else {
     return null;
   }
 }
 private static <T> T getInstanceOfName(String name, ClassLoader classLoader, Class<T> type)
     throws ClassNotFoundException, InstantiationException, IllegalAccessException {
   if (name == null) {
     return null;
   }
   Class<?> klazz = getClassForName(name, classLoader);
   return klazz.asSubclass(type).newInstance();
 }
  /**
   * Creates a Resolution object that holds a client value that represents the given domain value.
   * The resolved client value will be assignable to {@code clientType}.
   */
  private Resolution resolveClientValue(Object domainValue, Type clientType) {
    if (domainValue == null) {
      return new Resolution(null);
    }

    boolean anyType = clientType == null;
    if (anyType) {
      clientType = Object.class;
    }

    Class<?> assignableTo = TypeUtils.ensureBaseType(clientType);
    ResolutionKey key = new ResolutionKey(domainValue, clientType);

    Resolution previous = resolved.get(key);
    if (previous != null && assignableTo.isInstance(previous.getClientObject())) {
      return previous;
    }

    Class<?> returnClass = service.resolveClientType(domainValue.getClass(), assignableTo, true);

    if (anyType) {
      assignableTo = returnClass;
    }

    // Pass simple values through
    if (ValueCodex.canDecode(returnClass)) {
      return makeResolution(domainValue);
    }

    // Convert entities to EntityProxies or EntityProxyIds
    boolean isProxy = BaseProxy.class.isAssignableFrom(returnClass);
    boolean isId = EntityProxyId.class.isAssignableFrom(returnClass);
    if (isProxy || isId) {
      Class<? extends BaseProxy> proxyClass = returnClass.asSubclass(BaseProxy.class);
      return resolveClientProxy(domainValue, proxyClass, key);
    }

    // Convert collections
    if (Collection.class.isAssignableFrom(returnClass)) {
      Collection<Object> accumulator;
      if (List.class.isAssignableFrom(returnClass)) {
        accumulator = new ArrayList<Object>();
      } else if (Set.class.isAssignableFrom(returnClass)) {
        accumulator = new HashSet<Object>();
      } else {
        throw new ReportableException("Unsupported collection type" + returnClass.getName());
      }

      Type elementType = TypeUtils.getSingleParameterization(Collection.class, clientType);
      for (Object o : (Collection<?>) domainValue) {
        accumulator.add(resolveClientValue(o, elementType).getClientObject());
      }
      return makeResolution(accumulator);
    }

    throw new ReportableException("Unsupported domain type " + returnClass.getCanonicalName());
  }
Example #19
0
 /**
  * Resolves a component class based on the fully qualified name of the class.
  *
  * @param qualifiedClassName the fully qualified name of the resolved class
  * @param context the design context for which the class is resolved
  * @return a component class object representing the provided class name
  */
 protected Class<? extends Component> resolveComponentClass(
     String qualifiedClassName, DesignContext context) {
   try {
     Class<?> componentClass = Class.forName(qualifiedClassName);
     return componentClass.asSubclass(Component.class);
   } catch (ClassNotFoundException e) {
     throw new DesignException("Unable to load component for design", e);
   }
 }
Example #20
0
  /**
   * Method (re)binds a service class to the registry a service class must have two public fields
   * serviceName and codebase
   *
   * @param serviceClassName the fully qualified class name to load and bind
   * @return the proxy object returned from rebindService method
   * @throws ClassNotFoundException
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws RemoteException
   * @throws AlreadyBoundException
   * @throws NoSuchFieldException
   */
  public static Remote startService(String serviceClassName)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          RemoteException, AlreadyBoundException, NoSuchFieldException {
    Class<?> aclass = Class.forName(serviceClassName);
    Class<? extends Remote> serviceClass = aclass.asSubclass(Remote.class);
    Remote obj = serviceClass.newInstance();

    String serviceName = (String) getFieldValue(serviceClass, obj, "serviceName");
    String codebase = (String) getFieldValue(serviceClass, obj, "codebase");

    return rebindService(serviceName, codebase, obj);
  }
 public <T> Collection<Class<? extends T>> getDescendants(
     Class<T> parentType, String packagePath) {
   Collection<Class<? extends T>> result = new HashSet<Class<? extends T>>();
   for (Resource classResource : resources(packagePath, ".class")) {
     String className = classResource.getClassName();
     Class<?> clazz = loadClass(className);
     if (clazz != null && !parentType.equals(clazz) && parentType.isAssignableFrom(clazz)) {
       result.add(clazz.asSubclass(parentType));
     }
   }
   return result;
 }
Example #22
0
 public static <T> Class<? extends T> defineClass(
     ClassDefinition classDefinition,
     Class<T> superType,
     Map<Long, MethodHandle> callSiteBindings,
     ClassLoader parentClassLoader) {
   Class<?> clazz =
       defineClass(
           classDefinition,
           superType,
           new DynamicClassLoader(parentClassLoader, callSiteBindings));
   return clazz.asSubclass(superType);
 }
Example #23
0
 /**
  * Sets or unsets a pairwise ordering between all factories meeting a criterion. For example in
  * the CRS framework ({@link org.geotools.referencing.FactoryFinder}), this is used for setting
  * ordering between all factories provided by two vendors, or for two authorities. If one or both
  * factories are not currently registered, or if the desired ordering is already set/unset,
  * nothing happens and false is returned.
  *
  * @param <T> The class represented by the {@code base} argument.
  * @param base The base category. Only categories {@linkplain Class#isAssignableFrom assignable}
  *     to {@code base} will be processed.
  * @param set {@code true} for setting the ordering, or {@code false} for unsetting.
  * @param service1 Filter for the preferred factory.
  * @param service2 Filter for the factory to which {@code service1} is preferred.
  * @return {@code true} if the ordering changed as a result of this call.
  */
 public <T> boolean setOrdering(
     final Class<T> base, final boolean set, final Filter service1, final Filter service2) {
   boolean done = false;
   for (final Iterator<Class<?>> categories = getCategories(); categories.hasNext(); ) {
     final Class<?> candidate = categories.next();
     if (base.isAssignableFrom(candidate)) {
       final Class<? extends T> category = candidate.asSubclass(base);
       done |= setOrUnsetOrdering(category, set, service1, service2);
     }
   }
   return done;
 }
Example #24
0
 /**
  * If a system property was setup, load the class (if not already registered) and move it in front
  * of any other factory. This is done for compatibility with legacy {@code FactoryFinder}
  * implementation.
  *
  * @param loader The class loader to use.
  * @param category The category to scan for plug-ins.
  * @param message A buffer where to write the logging message.
  * @return {@code true} if at least one factory has been registered.
  */
 private <T> boolean registerFromSystemProperty(
     final ClassLoader loader, final Class<T> category, final StringBuilder message) {
   boolean newServices = false;
   try {
     final String classname = System.getProperty(category.getName());
     if (classname != null)
       try {
         final Class<?> candidate = loader.loadClass(classname);
         if (category.isAssignableFrom(candidate)) {
           final Class<? extends T> factoryClass = candidate.asSubclass(category);
           T factory = getServiceProviderByClass(factoryClass);
           if (factory == null)
             try {
               factory = factoryClass.newInstance();
               if (registerServiceProvider(factory, category)) {
                 message.append(System.getProperty("line.separator", "\n"));
                 message.append("  ");
                 message.append(factoryClass.getName());
                 newServices = true;
               }
             } catch (IllegalAccessException exception) {
               throw new FactoryRegistryException(
                   Errors.format(ErrorKeys.CANT_CREATE_FACTORY_$1, classname), exception);
             } catch (InstantiationException exception) {
               throw new FactoryRegistryException(
                   Errors.format(ErrorKeys.CANT_CREATE_FACTORY_$1, classname), exception);
             }
           /*
            * Put this factory in front of every other factories (including the ones loaded
            * in previous class loaders, which is why we don't inline this ordering in the
            * 'register' loop). Note: if some factories were not yet registered, they will
            * not be properly ordered. Since this code exists more for compatibility reasons
            * than as a commited API, we ignore this short comming for now.
            */
           for (final Iterator<T> it = getServiceProviders(category, false); it.hasNext(); ) {
             final T other = it.next();
             if (other != factory) {
               setOrdering(category, factory, other);
             }
           }
         }
       } catch (ClassNotFoundException exception) {
         // The class has not been found, maybe because we are not using the appropriate
         // class loader. Ignore (do not thrown an exception), in order to give a chance
         // to the caller to invokes this method again with a different class loader.
       }
   } catch (SecurityException exception) {
     // We are not allowed to read property, probably
     // because we are running in an applet. Ignore...
   }
   return newServices;
 }
Example #25
0
  public static <T> Class<? extends T> getCallerClass(Class<T> type) {
    Class<?> cls = getCallerClass(2);

    if (cls != null) {
      if (type.isAssignableFrom(cls)) {
        return cls.asSubclass(type);
      } else {
        throw new JPFException(
            "caller class: " + cls.getName() + " not of type: " + type.getName());
      }
    }
    return null;
  }
  private Servlet _getServletInstance(String servletClassName) {
    try {
      Class<?> clazz = _bundle.loadClass(servletClassName);

      Class<? extends Servlet> servletClass = clazz.asSubclass(Servlet.class);

      return servletClass.newInstance();
    } catch (Exception e) {
      _logger.log(Logger.LOG_ERROR, _bundle + " unable to load servlet " + servletClassName, e);

      return null;
    }
  }
Example #27
0
  @SuppressWarnings({"unchecked", "RedundantCast"})
  private static Class<? extends InputFormat<?, ?>> getInputFormatClass(
      JobConf conf, String inputFormatName) throws ClassNotFoundException {
    // CDH uses different names for Parquet
    if ("parquet.hive.DeprecatedParquetInputFormat".equals(inputFormatName)
        || "parquet.hive.MapredParquetInputFormat".equals(inputFormatName)) {
      return MapredParquetInputFormat.class;
    }

    Class<?> clazz = conf.getClassByName(inputFormatName);
    // TODO: remove redundant cast to Object after IDEA-118533 is fixed
    return (Class<? extends InputFormat<?, ?>>) (Object) clazz.asSubclass(InputFormat.class);
  }
  private Filter _getFilterInstance(String filterClassName) {
    try {
      Class<?> clazz = _bundle.loadClass(filterClassName);

      Class<? extends Filter> filterClass = clazz.asSubclass(Filter.class);

      return filterClass.newInstance();
    } catch (Exception e) {
      _logger.log(
          Logger.LOG_ERROR, "Bundle " + _bundle + " is unable to load filter " + filterClassName);

      return null;
    }
  }
Example #29
0
  @SuppressWarnings("unchecked")
  static ToNativeConverter getToNativeConverter(
      Class javaClass, Annotation[] annotations, TypeMapper typeMapper) {
    ToNativeConverter conv = typeMapper.getToNativeConverter(javaClass);
    if (conv != null) {
      return conv;

    } else if (Enum.class.isAssignableFrom(javaClass)) {
      return EnumMapper.getInstance(javaClass.asSubclass(Enum.class));

    } else {
      return null;
    }
  }
Example #30
0
 private static final Class<? extends PlanExecutor> loadExecutorClass(String className) {
   try {
     Class<?> leClass = Class.forName(className);
     return leClass.asSubclass(PlanExecutor.class);
   } catch (ClassNotFoundException cnfe) {
     throw new RuntimeException(
         "Could not load the executor class ("
             + className
             + "). Do you have the 'stratosphere-clients' project in your dependencies?");
   } catch (Throwable t) {
     throw new RuntimeException(
         "An error occurred while loading the executor (" + className + ").", t);
   }
 }