Ejemplo n.º 1
1
  @SuppressWarnings({"fallthrough"})
  private static Permission getPermission(String type, String name, String actions)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          NoSuchMethodException, InvocationTargetException {
    Class<?> clazz = Class.forName(type);
    int nArgs = actions != null ? 2 : name != null ? 1 : 0;

    switch (nArgs) {
      case 0:
        try {
          return (Permission) clazz.getConstructor().newInstance();
        } catch (NoSuchMethodException e) {
        }

      case 1:
        try {
          return (Permission) clazz.getConstructor(ARGS_NAME).newInstance(name);
        } catch (NoSuchMethodException e) {
        }

      case 2:
        return (Permission) clazz.getConstructor(ARGS_NAME_ACTIONS).newInstance(name, actions);
    }

    assert false;
    return null;
  }
 public static void main(String[] args) {
   if (args.length < 1) {
     print(usage);
     System.exit(0);
   }
   int lines = 0;
   try {
     Class<?> c = Class.forName(args[0]);
     Method[] methods = c.getMethods();
     Constructor[] ctors = c.getConstructors();
     if (args.length == 1) {
       for (Method method : methods) print(p.matcher(method.toString()).replaceAll(""));
       for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll(""));
       lines = methods.length + ctors.length;
     } else {
       for (Method method : methods)
         if (method.toString().indexOf(args[1]) != -1) {
           print(p.matcher(method.toString()).replaceAll(""));
           lines++;
         }
       for (Constructor ctor : ctors)
         if (ctor.toString().indexOf(args[1]) != -1) {
           print(p.matcher(ctor.toString()).replaceAll(""));
           lines++;
         }
     }
   } catch (ClassNotFoundException e) {
     print("No such class: " + e);
   }
 }
Ejemplo n.º 3
0
 private void guessClassReference(TypedValues list, String name) {
   try {
     Class<?> type = Class.forName(fixPotentialArrayName(name));
     list.add(new TypedValue(type.getClass(), type));
   } catch (ClassNotFoundException y) {
     _logger.fine(name + " looked like a class reference but is not");
   }
 }
Ejemplo n.º 4
0
  private void injectProperty(
      Object bean, Class<?> type, Object property, String alias, TypedValueGroup arguments)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    NoSuchMethodException nsme = null;

    if (arguments != null && arguments.size() > 0) {
      Object[] props = new Object[arguments.size() + 1];
      props[0] = property;
      Class<?>[] types = new Class<?>[arguments.size() + 1];
      types[0] = type;

      arguments.reset();
      while (arguments.load(props, 1)) {
        try {
          addSetProperty(bean, types, alias, props);
          return;
        } catch (NoSuchMethodException x) {
          // not a problem
          nsme = x;
        }
      }
    } else {
      try {
        addSetProperty(bean, new Class<?>[] {type}, alias, property);
        return;
      } catch (NoSuchMethodException x) {
        // not a problem
        nsme = x;
      }
    }

    // now try the super classes
    Class<?>[] interfaces = type.getInterfaces();
    for (Class<?> face : interfaces) {
      try {
        injectProperty(bean, face, property, alias, arguments);
        return;
      } catch (NoSuchMethodException x) {
        continue;
      }
    }
    Class<?> supertype = type.getSuperclass();
    if (supertype != null) {
      injectProperty(bean, supertype, property, alias, arguments);
    } else {
      throw nsme;
    }
  }
Ejemplo n.º 5
0
 public String toString() {
   return "type="
       + type.getSimpleName()
       + ",data="
       + data.getClass().getSimpleName()
       + ':'
       + data;
 }
Ejemplo n.º 6
0
  static <T> T set(Class<T> interf, Object value) {
    Properties p = new Properties();
    Method ms[] = interf.getMethods();

    for (Method m : ms) {
      p.put(m.getName(), value);
    }
    return Configurable.createConfigurable(interf, (Map<Object, Object>) p);
  }
Ejemplo n.º 7
0
 public void close() {
   if (jusl) {
     try {
       // Call java.util.ServiceLoader.reload
       Method reloadMethod = loaderClass.getMethod("reload");
       reloadMethod.invoke(loader);
     } catch (Exception e) {; // Ignore problems during a call to reload.
     }
   }
 }
Ejemplo n.º 8
0
    ServiceIterator(ClassLoader classLoader, Log log) {
      String loadMethodName;

      this.log = log;
      try {
        try {
          loaderClass = Class.forName("java.util.ServiceLoader");
          loadMethodName = "load";
          jusl = true;
        } catch (ClassNotFoundException cnfe) {
          try {
            loaderClass = Class.forName("sun.misc.Service");
            loadMethodName = "providers";
            jusl = false;
          } catch (ClassNotFoundException cnfe2) {
            // Fail softly if a loader is not actually needed.
            this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
            return;
          }
        }

        // java.util.ServiceLoader.load or sun.misc.Service.providers
        Method loadMethod = loaderClass.getMethod(loadMethodName, Class.class, ClassLoader.class);

        Object result = loadMethod.invoke(null, Processor.class, classLoader);

        // For java.util.ServiceLoader, we have to call another
        // method to get the iterator.
        if (jusl) {
          loader = result; // Store ServiceLoader to call reload later
          Method m = loaderClass.getMethod("iterator");
          result = m.invoke(result); // serviceLoader.iterator();
        }

        // The result should now be an iterator.
        this.iterator = (Iterator<?>) result;
      } catch (Throwable t) {
        log.error("proc.service.problem");
        throw new Abort(t);
      }
    }
 public void init(SeqClassifierFlags flags, TokenizerFactory<IN> tokenizerFactory) {
   if (flags.tokenFactory == null)
     tokenFactory = (CoreTokenFactory<IN>) new CoreLabelTokenFactory();
   else {
     try {
       this.tokenFactory = (CoreTokenFactory<IN>) Class.forName(flags.tokenFactory).newInstance();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
   init(flags, tokenizerFactory, tokenFactory);
 }
Ejemplo n.º 10
0
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int num = Integer.parseInt(br.readLine().trim());
    Object o;

    // Solution starts here
    if (num < 1 || num > Math.pow(2, 30)) throw new Exception();
    Solution ob = new Solution();
    Class<?> c = Class.forName("Solution$Private");
    Constructor<?> constructor = c.getDeclaredConstructor(Solution.class);
    constructor.setAccessible(true);
    o = constructor.newInstance(ob);
    Method m = c.getDeclaredMethod("powerof2", new Class[] {int.class});
    m.setAccessible(true);
    String ans = (String) m.invoke(o, num);
    System.out.println(num + " is " + ans);
    // ends here

    System.out.println(
        "An instance of class: " + o.getClass().getSimpleName() + " has been created");
  } // end of main
Ejemplo n.º 11
0
 public static File locationOf(Class clazz) {
   String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
   path = path.contains("!") ? path.substring(0, path.lastIndexOf('!')) : path;
   if (!path.isEmpty() && path.charAt(0) == '/') {
     path = "file:" + path;
   }
   try {
     return getRelativeFile(new File(new URL(path).toURI()), currentDir);
   } catch (Exception e) {
     Log.severe("", e);
     return getRelativeFile(new File(path), currentDir);
   }
 }
Ejemplo n.º 12
0
    public Writer getErrorReport(
        Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException {
      final Writer logMsg = new StringWriter();
      final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg);
      Writer msg = tee;

      LinkedList<Throwable> stack = getStack();
      String ticket = new Date().toString();

      Map<String, String> props;
      try {
        props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage");
      } catch (javax.naming.NamingException ne) {
        props = Collections.emptyMap();
        log.info(ne);
      }

      if (request != null) {
        {
          msg.append("Headers\n----------\n");
          // request properties
          for (Object name : Collections.list(request.getHeaderNames())) {
            msg.append(
                escape.transform(
                    name + ": " + escape.transform(request.getHeader((String) name)) + "\n"));
          }
        }
        {
          msg.append("\nAttributes\n----------\n");
          Pattern p = requestIgnore;
          if (p == null && props.get("request_ignore") != null) {
            p = Pattern.compile(props.get("request_ignore"));
          }
          for (Object name : Collections.list(request.getAttributeNames())) {
            if (p == null || !p.matcher((String) name).matches()) {
              msg.append(
                  escape.transform(name + ": " + request.getAttribute((String) name) + "\n"));
            }
          }
        }
        if (Boolean.TRUE.equals(showSession)
            || (showSession == null && !"false".equals(props.get("show_session")))) {
          HttpSession ses = request.getSession(false);
          if (ses != null) {
            msg.append("\nSession\n----------\n");
            Pattern p = sessionIgnore;
            if (p == null && props.get("session_ignore") != null) {
              p = Pattern.compile(props.get("session_ignore"));
            }
            for (Object name : Collections.list(ses.getAttributeNames())) {
              if (p == null || !p.matcher((String) name).matches()) {
                msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n"));
              }
            }
          }
        }
      }
      msg.append("\n");
      msg.append("Misc. properties\n----------\n");

      if (request != null) {
        msg.append("method: ").append(escape.transform(request.getMethod())).append("\n");
        msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n");
        msg.append("requesturl: ")
            .append(escape.transform(request.getRequestURL().toString()))
            .append("\n");
      }
      if (Boolean.TRUE.equals(showMMBaseVersion)
          || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) {
        msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n");
      }
      msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n");

      if (request != null) {
        msg.append("Parameters\n----------\n");
        // request parameters
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String name = (String) en.nextElement();
          msg.append(name)
              .append(": ")
              .append(escape.transform(request.getParameter(name)))
              .append("\n");
        }
      }
      msg.append("\nException ")
          .append(ticket)
          .append("\n----------\n\n")
          .append(
              exception != null
                  ? (escape.transform(exception.getClass().getName()))
                  : "NO EXCEPTION")
          .append(": ");

      int wroteCauses = 0;
      while (!stack.isEmpty()) {

        Throwable t = stack.removeFirst();
        // add stack stacktraces
        if (t != null) {
          if (stack.isEmpty()) { // write last message always
            msg = tee;
          }
          String message = t.getMessage();
          if (msg != tee) {
            to.append("\n=== skipped(see log)  : ")
                .append(escape.transform(t.getClass().getName()))
                .append(": ")
                .append(message)
                .append("\n");
          }

          msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message));
          StackTraceElement[] stackTrace = t.getStackTrace();
          for (StackTraceElement e : stackTrace) {
            msg.append("\n        at ").append(escape.transform(e.toString()));
          }
          if (!stack.isEmpty()) {
            msg.append("\n-------caused:\n");
          }
          wroteCauses++;
          if (wroteCauses >= MAX_CAUSES) {
            msg = logMsg;
          }
        }
      }
      // write errors to  log
      if (status == 500) {
        try {
          if (props.get("to") != null && props.get("to").length() > 0) {
            javax.naming.Context initCtx = new javax.naming.InitialContext();
            javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
            Object mailSession = envCtx.lookup("mail/Session");
            Class sessionClass = Class.forName("javax.mail.Session");
            Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType");
            Class messageClass = Class.forName("javax.mail.internet.MimeMessage");
            Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession);
            messageClass
                .getMethod("addRecipients", recipientTypeClass, String.class)
                .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to"));
            messageClass.getMethod("setSubject", String.class).invoke(mail, ticket);
            mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString());
            Class.forName("javax.mail.Transport")
                .getMethod("send", Class.forName("javax.mail.Message"))
                .invoke(null, mail);
            tee.append("\nmailed to (").append(String.valueOf(props)).append(")");
          }

        } catch (Exception nnfe) {
          tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")");
          if (log.isDebugEnabled()) {
            log.debug(nnfe.getMessage(), nnfe);
          }
        }
        log.error("TICKET " + ticket + ":\n" + logMsg);
      }
      return to;
    }
Ejemplo n.º 13
0
  @SuppressWarnings("unchecked")
  static Object bindInternal(
      String name,
      Class clazz,
      Type type,
      Annotation[] annotations,
      Map<String, String[]> params,
      String suffix,
      String[] profiles) {
    try {
      Logger.trace("bindInternal: name [" + name + "] suffix [" + suffix + "]");

      String[] value = params.get(name + suffix);
      Logger.trace("bindInternal: value [" + value + "]");
      Logger.trace("bindInternal: profile [" + Utils.join(profiles, ",") + "]");
      // Let see if we have a BindAs annotation and a separator. If so, we need to split the values
      // Look up for the BindAs annotation. Extract the profile if there is any.
      // TODO: Move me somewhere else?
      if (annotations != null) {
        for (Annotation annotation : annotations) {
          if ((clazz.isArray() || Collection.class.isAssignableFrom(clazz))
              && value != null
              && value.length > 0
              && annotation.annotationType().equals(As.class)) {
            As as = ((As) annotation);
            final String separator = as.value()[0];
            value = value[0].split(separator);
          }
          if (annotation.annotationType().equals(NoBinding.class)) {
            NoBinding bind = ((NoBinding) annotation);
            String[] localUnbindProfiles = bind.value();
            Logger.trace(
                "bindInternal: localUnbindProfiles [" + Utils.join(localUnbindProfiles, ",") + "]");

            if (localUnbindProfiles != null && contains(profiles, localUnbindProfiles)) {
              return NO_BINDING;
            }
          }
        }
      }

      // Arrays types
      // The array condition is not so nice... We should find another way of doing this....
      if (clazz.isArray()
          && (clazz != byte[].class
              && clazz != byte[][].class
              && clazz != File[].class
              && clazz != Upload[].class)) {
        if (value == null) {
          value = params.get(name + suffix + "[]");
        }
        if (value == null) {
          return MISSING;
        }
        Object r = Array.newInstance(clazz.getComponentType(), value.length);
        for (int i = 0; i <= value.length; i++) {
          try {
            Array.set(r, i, directBind(name, annotations, value[i], clazz.getComponentType()));
          } catch (Exception e) {
            // ?? One item was bad
          }
        }
        return r;
      }
      // Enums
      if (Enum.class.isAssignableFrom(clazz)) {
        if (value == null || value.length == 0) {
          return MISSING;
        } else if (StringUtils.isEmpty(value[0])) {
          return null;
        }
        return Enum.valueOf(clazz, value[0]);
      }
      // Map
      if (Map.class.isAssignableFrom(clazz)) {
        Class keyClass = String.class;
        Class valueClass = String.class;
        if (type instanceof ParameterizedType) {
          keyClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
          valueClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
        }

        // Special case Map<String, String>
        // Multivalues composite params are binded to a Map<String, String>
        // see http://play.lighthouseapp.com/projects/57987/tickets/443
        if (keyClass == String.class && valueClass == String.class && isComposite(name, params)) {
          Map<String, String> stringMap = Utils.filterParams(params, name);
          if (stringMap.size() > 0) return stringMap;
        }

        // Search for all params
        Map<Object, Object> r = new HashMap<Object, Object>();
        for (String param : params.keySet()) {
          Pattern p = Pattern.compile("^" + name + suffix + "\\[([^\\]]+)\\](.*)$");
          Matcher m = p.matcher(param);
          if (m.matches()) {
            String key = m.group(1);
            value = params.get(param);
            Map<String, String[]> tP = new HashMap<String, String[]>();
            tP.put("key", new String[] {key});
            Object oKey = bindInternal("key", keyClass, keyClass, annotations, tP, "", value);
            if (oKey != MISSING) {
              if (isComposite(name + suffix + "[" + key + "]", params)) {
                BeanWrapper beanWrapper = getBeanWrapper(valueClass);
                Object oValue =
                    beanWrapper.bind(
                        "", type, params, name + suffix + "[" + key + "]", annotations);
                r.put(oKey, oValue);
              } else {
                tP = new HashMap<String, String[]>();
                tP.put("value", params.get(name + suffix + "[" + key + "]"));
                Object oValue =
                    bindInternal("value", valueClass, valueClass, annotations, tP, "", value);
                if (oValue != MISSING) {
                  r.put(oKey, oValue);
                } else {
                  r.put(oKey, null);
                }
              }
            }
          }
        }
        return r;
      }
      // Collections types
      if (Collection.class.isAssignableFrom(clazz)) {
        if (clazz.isInterface()) {
          if (clazz.equals(List.class)) {
            clazz = ArrayList.class;
          }
          if (clazz.equals(Set.class)) {
            clazz = HashSet.class;
          }
          if (clazz.equals(SortedSet.class)) {
            clazz = TreeSet.class;
          }
        }
        Collection r = (Collection) clazz.newInstance();
        Class componentClass = String.class;
        if (type instanceof ParameterizedType) {
          componentClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
        // Create a an array of the component class
        if (value != null) {
          Object customArray = Array.newInstance(componentClass, value.length);
          // custom types
          for (Class<?> c : supportedTypes.keySet()) {
            if (c.isAssignableFrom(customArray.getClass())) {
              Object[] ar =
                  (Object[])
                      supportedTypes
                          .get(c)
                          .bind("value", annotations, name, customArray.getClass(), null);
              List l = Arrays.asList(ar);
              if (clazz.equals(HashSet.class)) {
                return new HashSet(l);
              } else if (clazz.equals(TreeSet.class)) {
                return new TreeSet(l);
              }
              return l;
            }
          }
        }
        if (value == null) {
          value = params.get(name + suffix + "[]");
          if (value == null && r instanceof List) {
            for (String param : params.keySet()) {
              Pattern p = Pattern.compile("^" + escape(name + suffix) + "\\[([0-9]+)\\](.*)$");
              Matcher m = p.matcher(param);
              if (m.matches()) {
                int key = Integer.parseInt(m.group(1));
                while (((List<?>) r).size() <= key) {
                  ((List<?>) r).add(null);
                }
                if (isComposite(name + suffix + "[" + key + "]", params)) {
                  BeanWrapper beanWrapper = getBeanWrapper(componentClass);
                  Object oValue =
                      beanWrapper.bind(
                          "", type, params, name + suffix + "[" + key + "]", annotations);
                  ((List) r).set(key, oValue);
                } else {
                  Map<String, String[]> tP = new HashMap<String, String[]>();
                  tP.put("value", params.get(name + suffix + "[" + key + "]"));
                  Object oValue =
                      bindInternal(
                          "value", componentClass, componentClass, annotations, tP, "", value);
                  if (oValue != MISSING) {
                    ((List) r).set(key, oValue);
                  }
                }
              }
            }
            return r.isEmpty() ? MISSING : r;
          }
        }
        if (value == null) {
          return MISSING;
        }
        for (String v : value) {
          try {
            r.add(directBind(name, annotations, v, componentClass));
          } catch (Exception e) {
            // ?? One item was bad
            Logger.debug(e, "error:");
          }
        }
        return r;
      }

      // Assume a Bean if isComposite
      Logger.trace(
          "bindInternal: class ["
              + clazz
              + "] name ["
              + name
              + "] annotation ["
              + Utils.join(annotations, " ")
              + "] isComposite ["
              + isComposite(name + suffix, params)
              + "]");
      if (isComposite(name + suffix, params)) {
        BeanWrapper beanWrapper = getBeanWrapper(clazz);
        return beanWrapper.bind(name, type, params, suffix, annotations);
      }

      // Simple types
      if (value == null || value.length == 0) {
        return MISSING;
      }

      return directBind(name, annotations, value[0], clazz, type);
    } catch (Exception e) {
      Validation.addError(name + suffix, "validation.invalid");
      return MISSING;
    }
  }
Ejemplo n.º 14
0
  @SuppressWarnings("unchecked")
  public static Object directBind(
      String name, Annotation[] annotations, String value, Class<?> clazz, Type type)
      throws Exception {
    Logger.trace(
        "directBind: value ["
            + value
            + "] annotation ["
            + Utils.join(annotations, " ")
            + "] Class ["
            + clazz
            + "]");

    boolean nullOrEmpty = value == null || value.trim().length() == 0;

    if (annotations != null) {
      for (Annotation annotation : annotations) {
        if (annotation.annotationType().equals(As.class)) {
          Class<? extends TypeBinder<?>> toInstanciate = ((As) annotation).binder();
          if (!(toInstanciate.equals(As.DEFAULT.class))) {
            // Instantiate the binder
            TypeBinder<?> myInstance = toInstanciate.newInstance();
            return myInstance.bind(name, annotations, value, clazz, type);
          }
        }
      }
    }

    // custom types
    for (Class<?> c : supportedTypes.keySet()) {
      Logger.trace("directBind: value [" + value + "] c [" + c + "] Class [" + clazz + "]");
      if (c.isAssignableFrom(clazz)) {
        Logger.trace("directBind: isAssignableFrom is true");
        return supportedTypes.get(c).bind(name, annotations, value, clazz, type);
      }
    }

    // application custom types
    for (Class<TypeBinder<?>> c : Play.classloader.getAssignableClasses(TypeBinder.class)) {
      if (c.isAnnotationPresent(Global.class)) {
        Class<?> forType =
            (Class) ((ParameterizedType) c.getGenericInterfaces()[0]).getActualTypeArguments()[0];
        if (forType.isAssignableFrom(clazz)) {
          return c.newInstance().bind(name, annotations, value, clazz, type);
        }
      }
    }

    // raw String
    if (clazz.equals(String.class)) {
      return value;
    }

    // Enums
    if (Enum.class.isAssignableFrom(clazz)) {
      if (nullOrEmpty) {
        return null;
      }
      return Enum.valueOf((Class<Enum>) clazz, value);
    }

    // int or Integer binding
    if (clazz.getName().equals("int") || clazz.equals(Integer.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? 0 : null;
      }

      return Integer.parseInt(value.contains(".") ? value.substring(0, value.indexOf(".")) : value);
    }

    // long or Long binding
    if (clazz.getName().equals("long") || clazz.equals(Long.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? 0l : null;
      }

      return Long.parseLong(value.contains(".") ? value.substring(0, value.indexOf(".")) : value);
    }

    // byte or Byte binding
    if (clazz.getName().equals("byte") || clazz.equals(Byte.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? (byte) 0 : null;
      }

      return Byte.parseByte(value.contains(".") ? value.substring(0, value.indexOf(".")) : value);
    }

    // short or Short binding
    if (clazz.getName().equals("short") || clazz.equals(Short.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? (short) 0 : null;
      }

      return Short.parseShort(value.contains(".") ? value.substring(0, value.indexOf(".")) : value);
    }

    // float or Float binding
    if (clazz.getName().equals("float") || clazz.equals(Float.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? 0f : null;
      }

      return Float.parseFloat(value);
    }

    // double or Double binding
    if (clazz.getName().equals("double") || clazz.equals(Double.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? 0d : null;
      }

      return Double.parseDouble(value);
    }

    // BigDecimal binding
    if (clazz.equals(BigDecimal.class)) {
      if (nullOrEmpty) {
        return null;
      }

      return new BigDecimal(value);
    }

    // boolean or Boolean binding
    if (clazz.getName().equals("boolean") || clazz.equals(Boolean.class)) {
      if (nullOrEmpty) {
        return clazz.isPrimitive() ? false : null;
      }

      if (value.equals("1")
          || value.toLowerCase().equals("on")
          || value.toLowerCase().equals("yes")) {
        return true;
      }

      return Boolean.parseBoolean(value);
    }

    return null;
  }
Ejemplo n.º 15
0
  public static Object bind(
      String name,
      Class<?> clazz,
      Type type,
      Annotation[] annotations,
      Map<String, String[]> params,
      Object o,
      Method method,
      int parameterIndex) {
    Logger.trace("bind: name [" + name + "] annotation [" + Utils.join(annotations, " ") + "] ");

    Object result = null;
    // Let a chance to plugins to bind this object
    for (PlayPlugin plugin : Play.plugins) {
      result = plugin.bind(name, clazz, type, annotations, params);
      if (result != null) {
        return result;
      }
    }
    String[] profiles = null;
    if (annotations != null) {
      for (Annotation annotation : annotations) {
        if (annotation.annotationType().equals(As.class)) {
          As as = ((As) annotation);
          profiles = as.value();
        }
        if (annotation.annotationType().equals(NoBinding.class)) {
          NoBinding bind = ((NoBinding) annotation);
          profiles = bind.value();
        }
      }
    }
    result = bindInternal(name, clazz, type, annotations, params, "", profiles);

    if (result == MISSING) {
      // Try the scala default
      if (o != null && parameterIndex > 0) {
        try {
          Method defaultMethod =
              method
                  .getDeclaringClass()
                  .getDeclaredMethod(method.getName() + "$default$" + parameterIndex);
          return defaultMethod.invoke(o);
        } catch (NoSuchMethodException e) {
          //
        } catch (Exception e) {
          throw new UnexpectedException(e);
        }
      }
      if (clazz.equals(boolean.class)) {
        return false;
      }
      if (clazz.equals(int.class)) {
        return 0;
      }
      if (clazz.equals(long.class)) {
        return 0;
      }
      if (clazz.equals(double.class)) {
        return 0;
      }
      if (clazz.equals(short.class)) {
        return 0;
      }
      if (clazz.equals(byte.class)) {
        return 0;
      }
      if (clazz.equals(char.class)) {
        return ' ';
      }
      return null;
    }
    return result;
  }
  public void actionPerformed(ActionEvent ae) {
    os = a.getText();
    Pattern pat = Pattern.compile("[ .]");
    String ms[] = pat.split(os), v; // Get whole String from Text area in tokens form

    Pattern pat1 = Pattern.compile("[ ]");
    String ms1[] = pat1.split(os); // for string aaray

    int hcode[] = {100, 102, 220, 110, 111},
        ecode[] = new int[20],
        j,
        p = 0; // p for check entry & hcode=Hindi lang.code  ecode=English lang. code
    ResultSet rs;
    b.setText("");
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection con =
          DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "student");
      Statement stmt = con.createStatement();
      for (i = 0; i <= ms.length; i++) {
        v = "'" + ms[i] + "'";
        p = 0;
        if (p == 0) {
          rs = stmt.executeQuery("select hnoun from noun where enoun=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 100;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hhv from hv where ehv=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 111;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hneg from neg where eneg=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 220;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hverb from verb where everb=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 110;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hpre from pre where epre=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 140;
          }
        }
        if (p == 0) {
          rs = stmt.executeQuery("select hpro from pro where epro=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 102;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hart from art where eart=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 123;
          }
        }
      }

      con.close();

    } catch (Exception e) {
      System.out.println(e);
    }

    for (i = 0; i < 5; i++) {
      for (j = 0; j < ms.length; j++) {
        if (hcode[i] == ecode[j]) {
          b.append(ms1[j] + " "); // print to hindi code wise
        }
      }
    }
  }
Ejemplo n.º 17
0
 /**
  * Assembles a bean from an XML stream.
  *
  * @param <T> the expected object type
  * @param stream the XML input stream
  * @param type the expected object type
  * @return an object assembled from this XML stream
  * @throws SAXException if the internal SAX parser fails
  * @throws IOException if any IO errors occur
  */
 public <T> T build(InputStream stream, Class<T> type) throws SAXException, IOException {
   _parser.parse(stream, this);
   return type.cast(getBean());
 }
Ejemplo n.º 18
0
 /**
  * Assembles a bean from an XML file.
  *
  * @param <T> the expected object type
  * @param file the path to the XML file
  * @param type the expected object type
  * @return an object assembled from this XML file
  * @throws SAXException if the internal SAX parser fails
  * @throws IOException if any IO errors occur
  */
 public <T> T build(String file, Class<T> type) throws SAXException, IOException {
   _parser.parse(new File(file), this);
   return type.cast(getBean());
 }
Ejemplo n.º 19
0
  /** Receive notification of the start of an element. */
  @Override
  public void startElement(String uri, String l, String q, Attributes a) {
    /*
     * 1. Load a class that matches the element name.
     * 2. If no class found, assume the element maps to a String.
     * 3. Otherwise, construct a new object of the class with element attributes.
     */
    _logger.fine(
        S.fine(_logger)
            ? "Consider element " + l + "\n             uri " + uri + "\n               q " + q
            : null);
    ElementInfo info = new ElementInfo();

    // Record java packages defined on this element as xmlns
    for (int i = 0; i < a.getLength(); ++i) {
      _logger.fine(
          S.fine(_logger)
              ? "            attr "
                  + a.getQName(i)
                  + "="
                  + a.getValue(i)
                  + "\n                 "
                  + a.getQName(i)
                  + ":"
                  + a.getURI(i)
              : null);
      if (a.getQName(i).startsWith("xmlns:") && a.getValue(i).startsWith("java://")) {
        info.pkgs.put(a.getQName(i).substring(6), a.getValue(i).substring(7));
      }
    }

    // Resolve the package name of this element, which could be empty (default package)
    int colon = q.indexOf(':');
    if (colon > 0) {
      String xmlns = q.substring(0, colon);
      // is it defined right here?
      info.jpkg = info.pkgs.get(xmlns);
      // find a matching namespace from ancesters
      if (info.jpkg == null && !_stack.isEmpty()) {
        for (int i = _stack.size() - 1; i >= 0; --i) {
          info.jpkg = _stack.get(i).pkgs.get(xmlns);
          if (info.jpkg != null) {
            break;
          }
        }
      }
    } else if (isPrimitiveType(q)) {
      info.jpkg = "java.lang";
    } else if (!_stack.isEmpty()) {
      info.jpkg = _stack.get(_stack.size() - 1).jpkg;
    } else {
      info.jpkg = _jpkg;
    }

    _logger.fine("to create element with package = " + info.jpkg);
    try {
      info.name =
          (info.jpkg != null) ? info.jpkg + '.' + Strings.toCamelCase(l) : Strings.toCamelCase(l);
      try {
        if (info.name.endsWith("...")) {
          // Array construction
          info.type = Class.forName(info.name.substring(0, info.name.length() - 3));
          info.data = new ArrayList<Object>();
        } else {
          // Non-array construction
          int size = a.getLength();
          TypedValueGroup arguments = new TypedValueGroup();
          for (int i = 0; i < size; ++i) {
            if (!a.getQName(i).startsWith("xmlns:") && !a.getQName(i).equals("xmlns")) {
              arguments.add(guessUntypedValue(a.getQName(i), a.getValue(i)));
            }
          }
          arguments.complete();
          _logger.fine(S.fine(_logger) ? "arguments=" + arguments : null);

          if (arguments.size() > 0) {
            if (arguments.size() == 1 && "java.lang".equals(info.jpkg)) {
              info.inst.put(
                  "@as",
                  Strings.toCamelCase(
                      arguments.get(0).name, '-', false)); // respect original spelling
              info.data = arguments.get(0).get(0).data;
              info.type = arguments.get(0).get(0).type;
            } else {
              Exception last = null;
              Object[] args = new Object[arguments.size()];
              while (arguments.load(args, 0)) {
                try {
                  _logger.fine(
                      S.fine(_logger)
                          ? "to create " + info.name + " with args: " + args.length + args(args)
                          : null);
                  info.data = _factory.create(info.name, args);
                  info.type = info.data.getClass();
                  break;
                } catch (InvocationTargetException x) {
                  throw x;
                } catch (Exception x) {
                  last = x;
                  _logger.fine(
                      "failure in creating " + info.name + ": probing for other constructors");
                }
              }

              if (info.data == null) {
                throw last;
              }
            }
          } else {
            _logger.fine("Create " + info.name + " with the default constructor");
            info.data = _factory.create(info.name);
            info.type = info.data.getClass();
          }
        }
      } catch (ClassNotFoundException x) {
        // no class by the element name is found, assumed String
        if (!_lenient) {
          throw new BeanAssemblyException("No class associated with element " + q);
        } else {
          _logger.log(Level.WARNING, "can't find class " + info.name, x);
        }
      }
      _stack.add(info);
      // _logger.fine(">>ElementInfo: " + info.type.getName() + " in " + info);
      // all other exceptions indicate mismatches between the beans and the XML schema
    } catch (Exception x) {
      if (!_lenient) {
        throw new BeanAssemblyException("Failed to assemble bean from element " + q, x);
      } else {
        _logger.log(Level.SEVERE, "can't create object for this element", x);
      }
    }
  }
Ejemplo n.º 20
0
  private TypedValues guessUntypedValue(String name, String value) {
    TypedValues list = new TypedValues(name);

    if (value.startsWith("java:")) { // possible java static reference
      int dot;
      if (value.equals("java:null")) {
        list.add(new TypedValue(Object.class, null));
      } else if (value.charAt(5) == '$') { // reference to a local object (assemble @id)
        ElementInfo element = _local.get(value.substring(6));
        if (element != null) {
          list.add(new TypedValue(element.type, element.data));
        }
      } else if ((dot = value.lastIndexOf('.')) > 5) {
        try {
          // public static refernce? (don't override access control)
          _logger.fine("public static refernce? " + value);
          Object object =
              Class.forName(value.substring(5, dot)).getField(value.substring(dot + 1)).get(null);
          Class<?> type = object.getClass();
          list.add(new TypedValue(type, object));
          // automatic upscaling to larger types
          if (type == Byte.class) {
            object = new Short(((Byte) object).byteValue());
            list.add(new TypedValue(Short.class, object));
            type = Short.class;
          }
          if (type == Short.class) {
            object = new Integer(((Short) object).shortValue());
            list.add(new TypedValue(Integer.class, object));
            type = Integer.class;
          }
          if (type == Integer.class) {
            object = new Long(((Integer) object).intValue());
            list.add(new TypedValue(Long.class, object));
            type = Long.class;
          }
          if (type == Long.class) {
            object = new Float(((Long) object).longValue());
            list.add(new TypedValue(Float.class, object));
            type = Float.class;
          }
          if (type == Float.class) {
            object = new Double(((Float) object).floatValue());
            list.add(new TypedValue(Double.class, object));
          }
        } catch (Exception x) {
          _logger.fine(value + " looked like a static reference but is not: " + x.getMessage());
          // class reference?
          guessClassReference(list, value.substring(5));
        }
      } else { // no '.' at all
        // class reference?
        guessClassReference(list, value.substring(5));
      }
    } else if (value.equals("true")) {
      list.add(new TypedValue(Boolean.class, Boolean.TRUE));
    } else if (value.equals("false")) {
      list.add(new TypedValue(Boolean.class, Boolean.FALSE));
    } else {
      // numbers? multiple possibilities
      try {
        list.add(new TypedValue(Integer.class, Integer.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Long.class, Long.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Float.class, Float.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Double.class, Double.valueOf(value)));
      } catch (Exception x) {
      }
    }

    // always try String as the last resort
    list.add(new TypedValue(String.class, value));

    return list;
  }