public CircuitElementView instantiateElement(
      UUID elementUUID,
      float positionX,
      float positionY,
      CircuitElementManager elementManager,
      WireManager wireManager)
      throws InvocationTargetException, IllegalAccessException, InstantiationException,
          NoSuchMethodException {
    Class<? extends CircuitElementView> viewType = ElementTypeUUID.VIEW_MAP.get(elementUUID);
    if (viewType == null) throw new IllegalArgumentException("Missing element view UUID");

    Class<? extends CircuitElement> elementType = ElementTypeUUID.ELEMENT_MAP.get(elementUUID);
    if (elementType == null) throw new IllegalArgumentException("Missing element type UUID");

    Constructor<? extends CircuitElementView> viewConstructor;
    viewConstructor =
        viewType.getConstructor(
            Context.class, CircuitElement.class, float.class, float.class, WireManager.class);

    Constructor<? extends CircuitElement> elementConstructor;
    elementConstructor = elementType.getConstructor(CircuitElementManager.class);

    CircuitElement element = elementConstructor.newInstance(elementManager);

    return viewConstructor.newInstance(context, element, 0, 0, wireManager);
  }
  private static RetryPolicy instantiateRetryPolicy(
      String policyClassName, Object[] args, String raw) throws Exception {

    Class<?> policyClass = Class.forName(policyClassName);

    for (Constructor<?> con : policyClass.getConstructors()) {
      Class<?>[] parameterClasses = con.getParameterTypes();
      if (args.length == parameterClasses.length) {
        boolean allInts = true;
        for (Class<?> pc : parameterClasses) {
          if (!pc.equals(int.class)) {
            allInts = false;
            break;
          }
        }

        if (!allInts) {
          break;
        }

        log.debug("About to instantiate class {} with {} arguments", con.toString(), args.length);

        return (RetryPolicy) con.newInstance(args);
      }
    }

    throw new Exception(
        "Failed to identify a class matching the Astyanax Retry Policy config string \""
            + raw
            + "\"");
  }
Exemple #3
0
  protected static DeviceImpl importFromBEncodedMapStatic(DeviceManagerImpl manager, Map map)
      throws IOException {
    String impl = ImportExportUtils.importString(map, "_impl");

    if (impl.startsWith(".")) {

      impl = MY_PACKAGE + impl;
    }

    try {
      Class<DeviceImpl> cla = (Class<DeviceImpl>) Class.forName(impl);

      Constructor<DeviceImpl> cons = cla.getDeclaredConstructor(DeviceManagerImpl.class, Map.class);

      cons.setAccessible(true);

      return (cons.newInstance(manager, map));

    } catch (Throwable e) {

      Debug.out("Can't construct device for " + impl, e);

      throw (new IOException("Construction failed: " + Debug.getNestedExceptionMessage(e)));
    }
  }
Exemple #4
0
 public static Object[] createConstructorArguments(
     Constructor<?> c, Message m, boolean perRequest, Map<Class<?>, Object> contextValues) {
   Class<?>[] params = c.getParameterTypes();
   Annotation[][] anns = c.getParameterAnnotations();
   Type[] genericTypes = c.getGenericParameterTypes();
   @SuppressWarnings("unchecked")
   MultivaluedMap<String, String> templateValues =
       m == null ? null : (MultivaluedMap<String, String>) m.get(URITemplate.TEMPLATE_PARAMETERS);
   Object[] values = new Object[params.length];
   for (int i = 0; i < params.length; i++) {
     if (AnnotationUtils.getAnnotation(anns[i], Context.class) != null) {
       Object contextValue = contextValues != null ? contextValues.get(params[i]) : null;
       if (contextValue == null) {
         if (perRequest) {
           values[i] = JAXRSUtils.createContextValue(m, genericTypes[i], params[i]);
         } else {
           values[i] = InjectionUtils.createThreadLocalProxy(params[i]);
         }
       } else {
         values[i] = contextValue;
       }
     } else {
       // this branch won't execute for singletons given that the found constructor
       // is guaranteed to have only Context parameters, if any, for singletons
       Parameter p = ResourceUtils.getParameter(i, anns[i], params[i]);
       values[i] =
           JAXRSUtils.createHttpParameterValue(
               p, params[i], genericTypes[i], anns[i], m, templateValues, null);
     }
   }
   return values;
 }
  @SuppressWarnings("unchecked")
  private <T> T _get(Class<T> type, Set<Class<?>> seenTypes) {
    if (!seenTypes.add(type)) {
      throw new IllegalStateException("Cycle in dependencies for " + type);
    }

    Object singleton = singletons.get(type);
    if (singleton != null) {
      return (T) singleton;
    }

    try {
      Constructor<T> constructor = getConstructor(type);
      Class<?>[] parameterTypes = constructor.getParameterTypes();
      Object[] parameters = new Object[parameterTypes.length];
      for (int i = 0; i < parameterTypes.length; i++) {
        parameters[i] = _get(parameterTypes[i], seenTypes);
      }

      T instance = postProcess(constructor.newInstance(parameters));
      singletons.put(type, instance);
      return instance;
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
      throw new IllegalStateException("Unable to create instance of " + type);
    }
  }
 /**
  * Creates and returns a new Tickertape instance, or throws a TickerLinguaException if the passed
  * parameters are not valid.
  *
  * @param id A unique id (not validated).
  * @param intervalHours The interval as hours.
  * @param enabled If this ticker is to be instantiated or not.
  * @param starttime A string indicating the start time. Not yet validated.
  * @param description A description of this tickertape.
  * @param projects A non-empty list of HackystatProject instances.
  * @param services A possibly empty list of notification services. (One might use email).
  * @param tickerClass The ticker class instance.
  * @param tickerProperties A possibly empty Properties instance.
  * @throws TickerLinguaException If there is not at least one project and notification service.
  */
 public Tickertape(
     String id,
     double intervalHours,
     boolean enabled,
     String starttime,
     String description,
     List<HackystatProject> projects,
     List<NotificationService> services,
     Class<? extends Ticker> tickerClass,
     Properties tickerProperties)
     throws TickerLinguaException {
   this.id = id;
   this.intervalHours = intervalHours;
   this.enabled = enabled;
   this.starttime = starttime;
   this.description = description;
   this.projects = projects;
   if (this.projects.isEmpty()) {
     throw new TickerLinguaException("At least one project must be defined.");
   }
   this.services = services;
   try {
     Constructor<? extends Ticker> ctor = tickerClass.getConstructor();
     this.ticker = ctor.newInstance();
   } catch (Exception e) {
     throw new RuntimeException("Ticker could not be instantiated. Shouldn't ever happen!", e);
   }
   // Create the properties map.
   for (Property property : tickerProperties.getProperty()) {
     properties.put(property.getKey(), property.getValue());
   }
 }
 /** 获取指定路径的apk的资源 */
 @SuppressWarnings({"rawtypes", "unchecked"})
 public static Resources getAPKResources(String apkPath) throws Exception {
   Context context = UIUtils.getContext();
   if (null == context) {
     return null;
   }
   String PathAssetManager = "android.content.res.AssetManager";
   Class assetMagCls = Class.forName(PathAssetManager);
   Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);
   Object assetMag = assetMagCt.newInstance((Object[]) null);
   Class[] typeArgs = new Class[1];
   typeArgs[0] = String.class;
   Method assetMagAddAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs);
   Object[] valueArgs = new Object[1];
   valueArgs[0] = apkPath;
   assetMagAddAssetPathMtd.invoke(assetMag, valueArgs);
   Resources res = context.getResources();
   typeArgs = new Class[3];
   typeArgs[0] = assetMag.getClass();
   typeArgs[1] = res.getDisplayMetrics().getClass();
   typeArgs[2] = res.getConfiguration().getClass();
   Constructor resCt = Resources.class.getConstructor(typeArgs);
   valueArgs = new Object[3];
   valueArgs[0] = assetMag;
   valueArgs[1] = res.getDisplayMetrics();
   valueArgs[2] = res.getConfiguration();
   res = (Resources) resCt.newInstance(valueArgs);
   return res;
 }
  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));
  }
  @SuppressWarnings("unused")
  private static Object _invoke(
      MethodHandler methodHandler,
      Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass,
      Map<String, Serializable> context)
      throws Exception {

    if (clusterInvokeAcceptorClass != null) {
      Constructor<? extends ClusterInvokeAcceptor> constructor =
          clusterInvokeAcceptorClass.getDeclaredConstructor();

      if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
      }

      ClusterInvokeAcceptor clusterInvokeAcceptor = constructor.newInstance();

      if (!clusterInvokeAcceptor.accept(context)) {
        return null;
      }
    }

    _populateThreadLocalsFromContext(context);

    return methodHandler.invoke();
  }
  @NotNull
  public <T extends ATNState> T newState(@NotNull Class<T> nodeType, GrammarAST node) {
    Exception cause;
    try {
      Constructor<T> ctor = nodeType.getConstructor();
      T s = ctor.newInstance();
      if (currentRule == null) s.setRuleIndex(-1);
      else s.setRuleIndex(currentRule.index);
      atn.addState(s);
      return s;
    } catch (InstantiationException ex) {
      cause = ex;
    } catch (IllegalAccessException ex) {
      cause = ex;
    } catch (IllegalArgumentException ex) {
      cause = ex;
    } catch (InvocationTargetException ex) {
      cause = ex;
    } catch (NoSuchMethodException ex) {
      cause = ex;
    } catch (SecurityException ex) {
      cause = ex;
    }

    String message =
        String.format(
            "Could not create %s of type %s.", ATNState.class.getName(), nodeType.getName());
    throw new UnsupportedOperationException(message, cause);
  }
  /**
   * Constructs an instance of a property editor using the current property editor class.
   *
   * <p>If the property editor class has a public constructor that takes an Object argument then it
   * will be invoked using the bean parameter as the argument. Otherwise, the default constructor
   * will be invoked.
   *
   * @param bean the source object
   * @return a property editor instance or null if a property editor has not been defined or cannot
   *     be created
   * @since 1.5
   */
  public PropertyEditor createPropertyEditor(Object bean) {
    Object editor = null;

    Class cls = getPropertyEditorClass();
    if (cls != null) {
      Constructor ctor = null;
      if (bean != null) {
        try {
          ctor = cls.getConstructor(new Class[] {Object.class});
        } catch (Exception ex) {
          // Fall through
        }
      }
      try {
        if (ctor == null) {
          editor = cls.newInstance();
        } else {
          editor = ctor.newInstance(new Object[] {bean});
        }
      } catch (Exception ex) {
        // A serious error has occured.
        // Proably due to an invalid property editor.
        throw new RuntimeException("PropertyEditor not instantiated", ex);
      }
    }
    return (PropertyEditor) editor;
  }
 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);
   }
 }
Exemple #13
0
  private LineParser createDocDataLineReader(String line) {
    String[] header;
    String headIndicator = WriteLineDocTask.FIELDS_HEADER_INDICATOR + WriteLineDocTask.SEP;

    if (line.startsWith(headIndicator)) {
      header =
          line.substring(headIndicator.length()).split(Character.toString(WriteLineDocTask.SEP));
      skipHeaderLine = true; // mark to skip the header line when input file is reopened
    } else {
      header = WriteLineDocTask.DEFAULT_FIELDS;
    }

    // if a specific DocDataLineReader was configured, must respect it
    String docDataLineReaderClassName = getConfig().get("line.parser", null);
    if (docDataLineReaderClassName != null) {
      try {
        final Class<? extends LineParser> clazz =
            Class.forName(docDataLineReaderClassName).asSubclass(LineParser.class);
        Constructor<? extends LineParser> cnstr = clazz.getConstructor(String[].class);
        return cnstr.newInstance((Object) header);
      } catch (Exception e) {
        throw new RuntimeException("Failed to instantiate " + docDataLineReaderClassName, e);
      }
    }

    // if this the simple case,
    if (Arrays.deepEquals(header, WriteLineDocTask.DEFAULT_FIELDS)) {
      return new SimpleLineParser(header);
    }
    return new HeaderLineParser(header);
  }
  // Remove any previous entry in the given map with the given name
  // and add an entry in the given map with the given name as the key
  // and the given taglet as the value.
  private static void _register(Map tagletMap, Taglet taglet) {
    final String tagName = taglet.getName();

    if (tagletMap.containsKey(tagName)) {
      tagletMap.remove(tagName);
    }

    String javaSpecificationVersion = System.getProperty("java.specification.version");

    if (javaSpecificationVersion != null && javaSpecificationVersion.equals("1.4")) {
      tagletMap.put(taglet.getName(), taglet);
    } else {
      String legacyTagletClassName = "com.sun.tools.doclets.internal.toolkit.taglets.LegacyTaglet";

      try {
        // Use reflection so that this code will compile under jdk1.4.
        Class legacyTagletClass = Class.forName(legacyTagletClassName);
        Constructor legacyTagletConstructor =
            legacyTagletClass.getConstructor(new Class[] {Taglet.class});
        Object legacyTagletObject = legacyTagletConstructor.newInstance(new Object[] {taglet});
        tagletMap.put(tagName, legacyTagletObject);
      } catch (Throwable throwable) {
        throwable.printStackTrace();
        throw new RuntimeException(
            "Problem with the '" + legacyTagletClassName + "' class: ", throwable);
      }
    }
  }
  /**
   * Convert {@code Object} value to a value of the specified class type.
   *
   * @param value {@code Object} value to convert.
   * @param type conversion type.
   * @param <T> converted value type.
   * @return value converted to the specified class type.
   */
  public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
      // TODO: Move string value readers from server to common and utilize them here
      final Constructor constructor =
          AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
      if (constructor != null) {
        try {
          return type.cast(constructor.newInstance(value));
        } catch (Exception e) {
          // calling the constructor wasn't successful - ignore and try valueOf()
        }
      }

      final Method valueOf =
          AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
      if (valueOf != null) {
        try {
          return type.cast(valueOf.invoke(null, value));
        } catch (Exception e) {
          // calling valueOf wasn't successful
        }
      }

      // at this point we don't know what to return -> return null
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning(
            LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(
                String.valueOf(value), value.getClass().getName(), type.getName()));
      }

      return null;
    }

    return type.cast(value);
  }
Exemple #16
0
  protected boolean initInstance(
      NyARIntSize size, Class<? extends INyARRgbPixelReader> pixelReaderClass, boolean isAlloc) {
    int bufferType = getBufferType(pixelReaderClass);

    // 0:24bit, 1:32bit, 2:16bit
    int bufferSize = bufferType >> 16 & 0x3;
    bufferSize = bufferSize == 0 ? 3 : (bufferSize == 1 ? 4 : 2);

    // 1:byte[], 2:int[][], 3:short[], 4:int[], ...
    Class<?> type;
    if ((bufferType & T_BYTE1D) != 0) {
      type = byte[].class;
      this.buffer = isAlloc ? new byte[size.w * size.h * bufferSize] : null;
    } else if ((bufferType & T_INT1D) != 0) {
      type = int[].class;
      this.buffer = isAlloc ? new int[size.w * size.h] : null;
    } else {
      return false;
    }
    this.isAttachedBuffer = isAlloc;

    // Instantiate pixel reader.
    try {
      Constructor<? extends INyARRgbPixelReader> constructor =
          pixelReaderClass.getConstructor(type, NyARIntSize.class);
      this.reader = constructor.newInstance(this.buffer, size);
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Exemple #17
0
  public static void main(String[] args) throws Exception {
    System.out.println("Well, you think your EnumSingleton is really a singleton");

    System.out.println(
        "The id of the INSTANCE object is " + System.identityHashCode(EnumSingleton.INSTANCE));

    System.out.println("I will create another instance using reflection");
    Constructor<EnumSingleton> privateConstructor =
        EnumSingleton.class.getDeclaredConstructor(String.class, int.class);
    privateConstructor.setAccessible(true);
    try {
      privateConstructor.newInstance();
    } catch (IllegalArgumentException e) {
      System.out.println(
          "D'oh! An exception prevented me from creating a new instance: " + e.getMessage());
    }

    System.out.println("Hmm, I will try one more option - Serialisation");

    EnumSingleton clone = SerializationUtils.clone(EnumSingleton.INSTANCE);

    System.out.println(
        "D'oh! Even serialization did not work. id = " + System.identityHashCode(clone));

    System.out.println("I give up");
  }
 /** For internal use only. */
 private static Object makeDerivedWrapper(Element elt, String baseTypeName) {
   synchronized (DOMUtils.getDOMLock(elt)) {
     QName typeName = XArchUtils.getXSIType(elt);
     if (typeName == null) {
       return null;
     } else {
       if (!DOMUtils.hasXSIType(
           elt, "http://www.ics.uci.edu/pub/arch/xArch/changesets.xsd", baseTypeName)) {
         try {
           String packageTitle = XArchUtils.getPackageTitle(typeName.getNamespaceURI());
           String packageName = XArchUtils.getPackageName(packageTitle);
           String implName = XArchUtils.getImplName(packageName, typeName.getName());
           Class c = Class.forName(implName);
           java.lang.reflect.Constructor con = c.getConstructor(new Class[] {Element.class});
           Object o = con.newInstance(new Object[] {elt});
           return o;
         } catch (Exception e) {
           // Lots of bad things could happen, but this
           // is OK, because this is best-effort anyway.
         }
       }
       return null;
     }
   }
 }
 @SuppressWarnings("unchecked")
 private Work openEditor(String editorClassName, WorkDefinition workDefinition) {
   IJavaProject javaProject = getProject();
   if (javaProject != null) {
     try {
       ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
       ClassLoader newLoader = ProjectClassLoader.getProjectClassLoader(javaProject);
       try {
         Thread.currentThread().setContextClassLoader(newLoader);
         Class<WorkEditor> editorClass = (Class<WorkEditor>) newLoader.loadClass(editorClassName);
         Constructor<WorkEditor> constructor = editorClass.getConstructor(Shell.class);
         WorkEditor editor = constructor.newInstance(getViewer().getControl().getShell());
         editor.setWorkDefinition(workDefinition);
         WorkItemNode workItemNode = getWorkItemWrapper().getWorkItemNode();
         editor.setWork(workItemNode.getWork());
         boolean result = editor.show();
         return result ? editor.getWork() : null;
       } finally {
         Thread.currentThread().setContextClassLoader(oldLoader);
       }
     } catch (Exception e) {
       DroolsEclipsePlugin.log(e);
     }
   }
   return null;
 }
Exemple #20
0
  @Override
  public void serviceInit(Configuration conf) throws Exception {

    Constructor<?> cons;
    try {
      if (conf instanceof TajoConf) {
        this.conf = (TajoConf) conf;
      } else {
        throw new TajoInternalError("conf must be a TajoConf instance");
      }

      Class<?> storeClass = this.conf.getClass(CatalogConstants.STORE_CLASS, DerbyStore.class);

      LOG.info("Catalog Store Class: " + storeClass.getCanonicalName());
      cons = storeClass.getConstructor(new Class[] {Configuration.class});

      this.store = (CatalogStore) cons.newInstance(this.conf);

      initBuiltinFunctions(builtingFuncs);
    } catch (Throwable t) {
      LOG.error("CatalogServer initialization failed", t);
      throw new TajoInternalError(t);
    }

    super.serviceInit(conf);
  }
Exemple #21
0
  public Object exec(List arguments) throws TemplateModelException {
    int size = arguments.size();
    if (size < 1) {
      throw new TemplateModelException("Invalid number of arguments for new(class, ...) method");
    }

    Class<?> klass;
    try {
      String className = (String) arguments.get(0);
      klass = Class.forName(className);
      if (size == 1) {
        return klass.newInstance();
      }
    } catch (ReflectiveOperationException e) {
      throw new TemplateModelException("Failed to isntantiate the object", e);
    }
    arguments.remove(0);
    Object[] ar = arguments.toArray();
    size--;
    Constructor<?>[] ctors = klass.getConstructors();
    for (Constructor<?> ctor : ctors) {
      Class<?>[] params = ctor.getParameterTypes(); // this is cloning params
      if (params.length == size) { // try this one
        try {
          return ctor.newInstance(ar);
        } catch (ReflectiveOperationException e) {
          // continue
        }
      }
    }
    throw new TemplateModelException("No suitable constructor found");
  }
  private BrowserLauncher createBrowserLauncher(
      Class c, String browserStartCommand, String sessionId, SeleneseQueue queue) {
    try {
      BrowserLauncher browserLauncher;
      if (null == browserStartCommand) {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class});
        Object[] args = new Object[] {new Integer(server.getPort()), sessionId};
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      } else {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class, String.class});
        Object[] args =
            new Object[] {
              new Integer(SeleniumServer.getPortDriversShouldContact()),
              sessionId,
              browserStartCommand
            };
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      }

      if (browserLauncher instanceof SeleneseQueueAware) {
        ((SeleneseQueueAware) browserLauncher).setSeleneseQueue(queue);
      }

      return browserLauncher;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "failed to contruct launcher for "
              + browserStartCommand
              + "for"
              + e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemple #23
0
 /**
  * 创建Dao对象
  *
  * @param clazz Dao类型
  * @param sourceType 数据源类型
  * @param dbType 数据库类型
  * @return
  * @throws Exception
  */
 private Object createDao(Class<?> clazz, SourceType sourceType, DbType dbType) throws Exception {
   Constructor<?> constructor =
       (Constructor<?>) clazz.getConstructor(SourceType.class, DbType.class);
   Object obj = constructor.newInstance(sourceType, dbType);
   daoContainer.put(clazz, obj);
   return obj;
 }
Exemple #24
0
 public static void create() throws Exception {
   ObjectType type = ObjectType.get(getControllerClass());
   notFoundIfNull(type);
   Constructor<?> constructor = type.entityClass.getDeclaredConstructor();
   constructor.setAccessible(true);
   Model object = (Model) constructor.newInstance();
   Binder.bindBean(params.getRootParamNode(), "object", object);
   validation.valid(object);
   if (validation.hasErrors()) {
     renderArgs.put("error", play.i18n.Messages.get("crud.hasErrors"));
     try {
       render(request.controller.replace(".", "/") + "/blank.html", type, object);
     } catch (TemplateNotFoundException e) {
       render("CRUD/blank.html", type, object);
     }
   }
   object._save();
   flash.success(play.i18n.Messages.get("crud.created", type.modelName));
   if (params.get("_save") != null) {
     redirect(request.controller + ".list");
   }
   if (params.get("_saveAndAddAnother") != null) {
     redirect(request.controller + ".blank");
   }
   redirect(request.controller + ".show", object._key());
 }
Exemple #25
0
  public static Constructor<?> findResourceConstructor(Class<?> resourceClass, boolean perRequest) {
    List<Constructor<?>> cs = new LinkedList<Constructor<?>>();
    for (Constructor<?> c : resourceClass.getConstructors()) {
      Class<?>[] params = c.getParameterTypes();
      Annotation[][] anns = c.getParameterAnnotations();
      boolean match = true;
      for (int i = 0; i < params.length; i++) {
        if (!perRequest) {
          if (AnnotationUtils.getAnnotation(anns[i], Context.class) == null) {
            match = false;
            break;
          }
        } else if (!AnnotationUtils.isValidParamAnnotations(anns[i])) {
          match = false;
          break;
        }
      }
      if (match) {
        cs.add(c);
      }
    }
    Collections.sort(
        cs,
        new Comparator<Constructor<?>>() {

          public int compare(Constructor<?> c1, Constructor<?> c2) {
            int p1 = c1.getParameterTypes().length;
            int p2 = c2.getParameterTypes().length;
            return p1 > p2 ? -1 : p1 < p2 ? 1 : 0;
          }
        });
    return cs.size() == 0 ? null : cs.get(0);
  }
Exemple #26
0
  public static JTFCommand generateCommandObject(String rawCommand) throws Exception {
    if (rawCommand == null) {
      throw new JTFException("rawCommand should not be null");
    }

    String[] tokens = rawCommand.split("\\s+");

    // JTFCommand command = (JTFCommand)
    // Class.forName("com.sandisk.zsjtf.command." +
    // tokens[0]).newInstance();
    // command.setArgs(parse(tokens));

    Class<?> clazz = Class.forName("com.sandisk.zsjtf.command." + tokens[0]);

    //		Properties initargs = parse(tokens);

    Constructor<?> constructor = clazz.getConstructor(String.class);

    JTFCommand command = (JTFCommand) constructor.newInstance(rawCommand);

    //		if(command.getClass().equals(ZSOpenContainer.class)){
    //			ContainerProperty containerProps = ContainerProperty
    //					.getDefaultProperty();
    //
    //			ZSOpenContainer zsOpenContainer = (ZSOpenContainer)command;
    //
    //			zsOpenContainer.setContainerProperty(containerProps);
    //			return zsOpenContainer;
    //		}
    //

    return command;
  }
  private void postNext() throws HibernateException, SQLException {
    this.hasNext = rs.next();
    if (!hasNext) {
      log.debug("exhausted results");
      close();
    } else {
      log.debug("retrieving next results");
      if (single) {
        nextResult = types[0].nullSafeGet(rs, names[0], sess, null);
      } else {
        Object[] nextResults = new Object[types.length];
        for (int i = 0; i < types.length; i++) {
          nextResults[i] = types[i].nullSafeGet(rs, names[i], sess, null);
        }
        nextResult = nextResults;
      }

      if (holderConstructor != null) {
        try {
          if (nextResult == null || !nextResult.getClass().isArray()) {
            nextResult = holderConstructor.newInstance(new Object[] {nextResult});
          } else {
            nextResult = holderConstructor.newInstance((Object[]) nextResult);
          }
        } catch (Exception e) {
          throw new QueryException(
              "Could not instantiate: " + holderConstructor.getDeclaringClass(), e);
        }
      }
    }
  }
  @Test
  public void chanson() throws Throwable {
    checkConstructor(chanson, String.class, String.class, temps);

    collector.checkThat(constructor.newInstance("", "", null), instanceOf(chanson));
    collector.checkThat(constructor.newInstance("a", "a", null), instanceOf(chanson));
  }
  protected WebDriver createInstanceOf(String className) {
    try {
      DesiredCapabilities capabilities = createCommonCapabilities();
      capabilities.setJavascriptEnabled(true);
      capabilities.setCapability(TAKES_SCREENSHOT, true);
      capabilities.setCapability(ACCEPT_SSL_CERTS, true);
      capabilities.setCapability(SUPPORTS_ALERTS, true);
      if (isPhantomjs()) {
        capabilities.setCapability(
            "phantomjs.cli.args", // PhantomJSDriverService.PHANTOMJS_CLI_ARGS ==
                                  // "phantomjs.cli.args"
            new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
      }

      Class<?> clazz = Class.forName(className);
      if (WebDriverProvider.class.isAssignableFrom(clazz)) {
        return ((WebDriverProvider) clazz.newInstance()).createDriver(capabilities);
      } else {
        Constructor<?> constructor = Class.forName(className).getConstructor(Capabilities.class);
        return (WebDriver) constructor.newInstance(capabilities);
      }
    } catch (InvocationTargetException e) {
      throw runtime(e.getTargetException());
    } catch (Exception invalidClassName) {
      throw new IllegalArgumentException(invalidClassName);
    }
  }
        @Override
        public int compare(Constructor<?> o1, Constructor<?> o2) {
          int p1 = o1.getParameterTypes().length;
          int p2 = o2.getParameterTypes().length;

          return (p1 < p2) ? 1 : ((p1 == p2) ? 0 : -1);
        }