Example #1
0
 public static void toString(Object value, Text t) {
   if (value == null) {
     t.append("null");
   } else {
     final Class<? extends Object> clazz = value.getClass();
     final DataType type = getDataType(clazz);
     if (type == null) {
       throw new RuntimeException("Invalid type: " + clazz.getName());
     }
     type.toMarkup(value, t);
   }
 }
Example #2
0
 public static Method functionRef(String clazz, String name) {
   try {
     Class cl = Class.forName(clazz);
     for (Method m : cl.getDeclaredMethods()) {
       if (m.getName().equals(name)) {
         return m;
       }
     }
     throw new RuntimeException("Method Not Found: " + clazz + ":" + name);
   } catch (ClassNotFoundException e) {
     throw new RuntimeException("Class Not Found: " + clazz);
   }
 }
 public ICFLibAnyObj getObjQualifier(Class qualifyingClass) {
   ICFLibAnyObj container = this;
   if (qualifyingClass != null) {
     while (container != null) {
       if (container instanceof ICFSecurityClusterObj) {
         break;
       } else if (container instanceof ICFSecurityTenantObj) {
         break;
       } else if (qualifyingClass.isInstance(container)) {
         break;
       }
       container = container.getObjScope();
     }
   } else {
     while (container != null) {
       if (container instanceof ICFSecurityClusterObj) {
         break;
       } else if (container instanceof ICFSecurityTenantObj) {
         break;
       }
       container = container.getObjScope();
     }
   }
   return (container);
 }
Example #4
0
 public OverflowException(Number n, Class<?> expectedClass) {
   super(
       "Overflow exception, "
           + n.toString()
           + " cannot be converted to: "
           + expectedClass.getSimpleName());
 }
 /**
  * Get the enum value associated with an index.
  *
  * @param clazz The type of enum to retrieve.
  * @param index The index must be between 0 and length() - 1.
  * @return The enum value at the index location
  * @throws JSONException if the key is not found or if the value cannot be converted to an enum.
  */
 public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
   E val = optEnum(clazz, index);
   if (val == null) {
     // JSONException should really take a throwable argument.
     // If it did, I would re-implement this with the Enum.valueOf
     // method and place any thrown exception in the JSONException
     throw new JSONException(
         "JSONObject["
             + JSONObject.quote(Integer.toString(index))
             + "] is not an enum of type "
             + JSONObject.quote(clazz.getSimpleName())
             + ".");
   }
   return val;
 }
 /**
  * Get the enum value associated with a key.
  *
  * @param clazz The type of enum to retrieve.
  * @param index The index must be between 0 and length() - 1.
  * @param defaultValue The default in case the value is not found
  * @return The enum value at the index location or defaultValue if the value is not found or
  *     cannot be assigned to clazz
  */
 public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
   try {
     Object val = this.opt(index);
     if (JSONObject.NULL.equals(val)) {
       return defaultValue;
     }
     if (clazz.isAssignableFrom(val.getClass())) {
       // we just checked it!
       @SuppressWarnings("unchecked")
       E myE = (E) val;
       return myE;
     }
     return Enum.valueOf(clazz, val.toString());
   } catch (IllegalArgumentException | NullPointerException e) {
     return defaultValue;
   }
 }
Example #7
0
  // event handling
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btnok) {
      PreparedStatement pstm;
      ResultSet rs;
      String sql;
      // if no entries has been made and hit ok button throw an error
      // you can do this step using try clause as well
      if ((tf1.getText().equals("") && (tf2.getText().equals("")))) {
        lblmsg.setText("Enter your details ");
        lblmsg.setForeground(Color.magenta);
      } else {

        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection connect = DriverManager.getConnection("jdbc:odbc:student_base");
          System.out.println("Connected to the database");
          pstm = connect.prepareStatement("insert into student_base values(?,?)");
          pstm.setString(1, tf1.getText());
          pstm.setString(2, tf2.getText());
          // execute method to execute the query
          pstm.executeUpdate();
          lblmsg.setText("Details have been added to database");

          // closing the prepared statement  and connection object
          pstm.close();
          connect.close();
        } catch (SQLException sqe) {
          System.out.println("SQl error");
        } catch (ClassNotFoundException cnf) {
          System.out.println("Class not found error");
        }
      }
    }
    // upon clickin button addnew , your textfield will be empty to enternext record
    if (e.getSource() == btnaddnew) {
      tf1.setText("");
      tf2.setText("");
    }

    if (e.getSource() == btnexit) {
      System.exit(1);
    }
  }
Example #8
0
  /**
   * @param methodName getter method
   * @param clazz value object class
   * @return attribute name related to the specified getter method
   */
  private String getAttributeName(String methodName, Class classType) {
    String attributeName = null;
    if (methodName.startsWith("is"))
      attributeName =
          methodName.substring(2, 3).toLowerCase()
              + (methodName.length() > 3 ? methodName.substring(3) : "");
    else
      attributeName =
          methodName.substring(3, 4).toLowerCase()
              + (methodName.length() > 4 ? methodName.substring(4) : "");

    // an attribute name "Xxxx" becomes "xxxx" and this is not correct!
    try {
      Class c = classType;
      boolean attributeFound = false;
      while (!c.equals(Object.class)) {
        try {
          c.getDeclaredField(attributeName);
          attributeFound = true;
          break;
        } catch (Throwable ex2) {
          c = c.getSuperclass();
        }
      }
      if (!attributeFound) {
        // now trying to find an attribute having the first character in upper case (e.g. "Xxxx")
        String name = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
        c = classType;
        while (!c.equals(Object.class)) {
          try {
            c.getDeclaredField(name);
            attributeFound = true;
            break;
          } catch (Throwable ex2) {
            c = c.getSuperclass();
          }
        }
        if (attributeFound) attributeName = name;
      }
    } catch (Throwable ex1) {
    }

    return attributeName;
  }
 public void init() throws Exception {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   con = DriverManager.getConnection("jdbc:odbc:metaquery", "", "");
   con.setAutoCommit(true);
 }
Example #10
0
 TypeMismatchException(Class<? extends Object> got, Class<?> expected) {
   super("Cannot convert " + got.getSimpleName() + " to  " + expected.getSimpleName());
 }
Example #11
0
  /**
   * Type converts values to other classes. For example an Integer can be converted to a Long.
   *
   * @param <T> Data Type.
   * @param value The value to be converted.
   * @param to The class to be converted to. Must be one of the Java types corresponding to the
   *     DataTypes.
   * @return The converted value.
   * @throws TypeMismatchException Thrown desired class is incompatible with the source class.
   * @throws OverflowException Thrown only on narrowing value conversions, e.g from a BigInteger to
   *     an Integer.
   */
  @Nullable
  public static <T> T convert(Object value, Class<?> to)
      throws TypeMismatchException, OverflowException {
    final Object result;

    if (value == null || value.getClass() == to) {
      result = value;
    } else {
      final Class<?> from = value.getClass();
      try {
        if (from == Integer.class) { // Integer -> ...
          if (to == Long.class) {
            result = new Long(((Number) value).longValue());
          } else if (to == BigInteger.class) {
            result = BigInteger.valueOf(((Number) value).intValue());
          } else if (to == Float.class) {
            result = new Float(((Number) value).floatValue());
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            // Use intValue() to avoid precision errors
            result = new BigDecimal(((Number) value).intValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Long.class) { // Long -> ...
          if (to == Integer.class) {
            final long l = ((Long) value).longValue();
            if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) l);
          } else if (to == BigInteger.class) {
            result = BigInteger.valueOf(((Number) value).longValue());
          } else if (to == Float.class) {
            result = new Float(((Number) value).floatValue());
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            // Use longValue() to avoid precision errors
            result = new BigDecimal(((Number) value).longValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == BigInteger.class) { // BigInteger -> ...
          final BigInteger bi = (BigInteger) value;
          if (to == Integer.class) {
            result = new Integer(bi.intValueExact());
          } else if (to == Long.class) {
            result = new Long(bi.longValueExact());
          } else if (to == Float.class) {
            final float f1 = bi.floatValue();
            if (f1 == Float.NEGATIVE_INFINITY || f1 == Float.POSITIVE_INFINITY) {
              throw new OverflowException(bi, to);
            }
            result = new Float(f1);
          } else if (to == Double.class) {
            final double d = bi.doubleValue();
            if (d == Double.NEGATIVE_INFINITY || d == Double.POSITIVE_INFINITY) {
              throw new OverflowException(bi, to);
            }
            result = new Double(d);
          } else if (to == BigDecimal.class) {
            result = new BigDecimal(bi);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Float.class) { // Float -> ...
          final float fl = ((Float) value).floatValue();
          if (to == Integer.class) {
            if (fl < Integer.MIN_VALUE || fl > Integer.MAX_VALUE | fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) fl);
          } else if (to == Long.class) {
            if (fl < Long.MIN_VALUE || fl > Long.MAX_VALUE | fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Long((long) fl);
          } else if (to == BigInteger.class) {
            if (fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            final BigDecimal bd = BigDecimal.valueOf(fl);
            result = bd.toBigInteger();
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            result = BigDecimal.valueOf(fl);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Double.class) { // Double -> ...
          final double d = ((Double) value).doubleValue();
          if (to == Integer.class) {
            if (d < Integer.MIN_VALUE || d > Integer.MAX_VALUE || d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) d);
          } else if (to == Long.class) { // OK
            if (d < Long.MIN_VALUE || d > Long.MAX_VALUE || d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Long((int) d);
          } else if (to == BigInteger.class) { // OK
            if (d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            final BigDecimal bd = BigDecimal.valueOf(d);
            result = bd.toBigInteger();
          } else if (to == Float.class) { // OK
            if (d < -Float.MAX_VALUE || d > Float.MAX_VALUE) {
              throw new OverflowException((Number) value, to);
            }
            result = new Float((float) d);
          } else if (to == BigDecimal.class) { // OK
            result = BigDecimal.valueOf(d);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == BigDecimal.class) { // BigDecimal -> ...
          final BigDecimal bd = (BigDecimal) value;
          if (to == Integer.class) { // OK
            result = new Integer(bd.intValueExact());
          } else if (to == Long.class) { // OK
            result = new Long(bd.longValueExact());
          } else if (to == BigInteger.class) { // OK
            // BigDecimal modulus
            final BigDecimal remainder = bd.remainder(BigDecimal.ONE);
            if (!remainder.equals(BigDecimal.ZERO)) {
              throw new OverflowException(bd, to);
            }
            result = bd.toBigInteger();
          } else if (to == Float.class) { // OK
            if (bd.compareTo(BigDecimal_MIN_FLOAT) < 0 || bd.compareTo(BigDecimal_MAX_FLOAT) > 0) {
              throw new OverflowException(bd, to);
            }
            result = new Float(bd.floatValue());
          } else if (to == Double.class) { // OK
            if (bd.compareTo(BigDecimal_MIN_DOUBLE) < 0
                || bd.compareTo(BigDecimal_MAX_DOUBLE) > 0) {
              throw new OverflowException(bd, to);
            }
            result = new Double(bd.doubleValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else {
          throw new UnexpectedException("convert: " + from.getName());
        }
      } catch (final ArithmeticException e) {
        // Thrown by intValueExact() etc.
        throw new OverflowException((Number) value, to);
      }
    }

    @SuppressWarnings("unchecked")
    final T t = (T) result;
    return t;
  }
  public Design() throws Exception {
    super.setBackground(Color.BLACK);
    this.setTitle("");
    con = getContentPane();
    con.setLayout(null);
    dim = tk.getDefaultToolkit().getScreenSize();
    this.setTitle("Customer Peer Login");

    l1 = new JLabel(new ImageIcon("plain.jpg"));
    l1.setBounds(0, 0, 400, 400);
    con.add(l1);
    l1.setBorder(BorderFactory.createEtchedBorder(5, Color.black, Color.black));

    title = new JLabel("CUSTOMER PEER LOGIN ");
    title.setFont(new Font("Bookman Old Style", Font.ROMAN_BASELINE, 20));
    title.setForeground(Color.red);
    title.setBounds(80, 30, 300, 30);
    l1.add(title);

    l4 = new JLabel("CMACHINE NAME");
    l4.setFont(new Font("Bookman Old Style", Font.BOLD, 16));
    l4.setForeground(Color.BLUE);
    l4.setBounds(70, 100, 160, 20);
    //	l4.setBorder(BorderFactory.createEtchedBorder(5,Color.green,Color.green));

    l1.add(l4);
    jtf2 = new JTextField();
    jtf2.setBounds(250, 100, 100, 20);
    jtf2.setBorder(BorderFactory.createEtchedBorder(5, Color.green, Color.green));

    l1.add(jtf2);

    l2 = new JLabel("CUSER LOGIN");
    l2.setFont(new Font("Bookman Old Style", Font.BOLD, 16));
    l2.setForeground(Color.blue);
    l2.setBounds(70, 150, 120, 20);
    l1.add(l2);

    jtf1 = new JTextField();
    jtf1.setBounds(250, 150, 100, 20);
    jtf1.setBorder(BorderFactory.createEtchedBorder(5, Color.green, Color.green));

    l1.add(jtf1);

    l3 = new JLabel("CPASSWORD");
    l3.setFont(new Font("Bookman Old Style", Font.BOLD, 16));
    l3.setForeground(Color.blue);
    l3.setBounds(70, 200, 120, 20);
    l1.add(l3);

    jptf1 = new JPasswordField();
    jptf1.setBounds(250, 200, 100, 20);
    jptf1.setBorder(BorderFactory.createEtchedBorder(5, Color.green, Color.green));

    l1.add(jptf1);

    JLabel l4 = new JLabel("DAgent");
    l4.setFont(new Font("Bookman Old Style", Font.BOLD, 16));
    l4.setForeground(Color.blue);
    l4.setBounds(70, 250, 120, 20);
    l1.add(l4);

    box = new JComboBox();
    box.setBounds(250, 250, 100, 20);
    box.setBorder(BorderFactory.createEtchedBorder(5, Color.green, Color.green));
    l1.add(box);

    b2 = new JButton("Register");
    b2.setBounds(50, 300, 100, 20);
    l1.add(b2);
    b2.setBorder(BorderFactory.createEtchedBorder(10, Color.BLUE, Color.BLUE));

    b3 = new JButton("Login");
    b3.setBounds(150, 300, 100, 20);
    b3.setBorder(BorderFactory.createEtchedBorder(10, Color.BLUE, Color.BLUE));
    l1.add(b3);

    b1 = new JButton("Cancel");
    b1.setBounds(250, 300, 100, 20);
    b1.setBorder(BorderFactory.createEtchedBorder(10, Color.BLUE, Color.BLUE));

    l1.add(b1);

    b1.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent we) {

            dispose();
          }
        });

    try {

      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      conn = DriverManager.getConnection("jdbc:odbc:agent");

    } catch (Exception exp) {

    }

    try {
      Statement satem = conn.createStatement();
      ResultSet rsatem = satem.executeQuery("select * from Dagent");
      while (rsatem.next()) {
        String namem = rsatem.getString("uname");
        box.addItem(namem);
      }

    } catch (Exception expo1) {

    }

    b2.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent we) {

            String username = jtf1.getText().trim();
            String password = jptf1.getText().trim();
            String mechine = jtf2.getText().trim();
            String dname = box.getSelectedItem().toString();
            int porte = 0;

            try {
              Statement sate = conn.createStatement();
              ResultSet rsate =
                  sate.executeQuery("select * from Dagent where uname='" + dname + "'");
              if (rsate.next()) {
                servermachine = rsate.getString("umechine");
                porte = rsate.getInt("ulistport");
                System.out.println(servermachine);
              }
              System.out.println(servermachine);

            } catch (Exception exp) {
              exp.printStackTrace();
            }

            try {
              packet p = new packet();
              p.setaction("Creg");
              p.setCuser(username);
              p.setCpass(password);
              p.setCmname(mechine);
              p.setCDpeer(dname);
              Socket soc = new Socket(servermachine, porte);
              ObjectOutputStream out = new ObjectOutputStream(soc.getOutputStream());
              out.writeObject(p);
              ObjectInputStream in = new ObjectInputStream(soc.getInputStream());
              packet rpac = (packet) in.readObject();
              if (rpac.getaction().equals("ok")) {

                JOptionPane.showMessageDialog(null, "Sucessfully Registered");

                jtf2.setText("");
                jtf1.setText("");
                jptf1.setText("");

              } else {

                JOptionPane.showMessageDialog(null, "Already Registered");
                jtf2.setText("");
                jtf1.setText("");
                jptf1.setText("");
              }

            } catch (Exception exp) {
            }
          }
        });

    b3.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent we) {

            String username = jtf1.getText().trim();
            String password = jptf1.getText().trim();
            String mechine = jtf2.getText().trim();
            String Dname = box.getSelectedItem().toString();

            int porte = 0;

            try {
              Statement sate = conn.createStatement();
              ResultSet rsate =
                  sate.executeQuery("select * from Dagent where uname='" + Dname + "'");
              if (rsate.next()) {
                servermachine = rsate.getString("umechine");
                porte = rsate.getInt("ulistport");
                System.out.println(servermachine);
              }
              System.out.println(servermachine);

            } catch (Exception exp) {

            }

            try {

              packet p1 = new packet();
              p1.setaction("clogin");
              p1.setCuser(username);
              p1.setCpass(password);
              p1.setCmname(mechine);
              p1.setCDpeer(Dname);
              Socket soc1 = new Socket(servermachine, porte);
              ObjectOutputStream out1 = new ObjectOutputStream(soc1.getOutputStream());
              out1.writeObject(p1);
              ObjectInputStream in1 = new ObjectInputStream(soc1.getInputStream());
              packet rpac1 = (packet) in1.readObject();
              if (rpac1.getaction().equals("ok")) {
                int port1 = 0;
                try {

                  int portm = rpac1.getCport();
                  System.out.println("XXXXXXX" + portm);
                  //	JOptionPane.showMessageDialog(null,"Sucessfully Started");

                  new Listen(portm);
                  new process(username, portm);
                  dispose();
                } catch (Exception exp) {
                }
              } else {
                JOptionPane.showMessageDialog(
                    null, "Enter valid username and password", "Server reply", 2);
                jtf1.setText("");
                jtf2.setText("");
                jptf1.setText("");
              }

            } catch (Exception exp) {
            }
          }
        });

    setSize(400, 400);
    show();
    setLocation(150, 100);
    setResizable(false);
  }
Example #13
0
  /**
   * Analyze class fields and fill in "voSetterMethods","voGetterMethods","indexes",reverseIndexes"
   * attributes.
   *
   * @param prefix e.g. "attrx.attry."
   * @param parentMethods getter methods of parent v.o.
   * @param classType class to analyze
   */
  private void analyzeClassFields(String prefix, Method[] parentMethods, Class classType) {
    try {
      if (prefix.split("\\.").length > ClientSettings.MAX_NR_OF_LOOPS_IN_ANALYZE_VO) return;

      // retrieve all getter and setter methods defined in the specified value object...
      String attributeName = null;
      Method[] methods = classType.getMethods();
      String aName = null;
      for (int i = 0; i < methods.length; i++) {
        attributeName = methods[i].getName();

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && ValueObject.class.isAssignableFrom(methods[i].getReturnType())) {
          aName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          analyzeClassFields(prefix + aName + ".", newparentMethods, methods[i].getReturnType());
        }

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(String.class)
                || methods[i].getReturnType().equals(Long.class)
                || methods[i].getReturnType().equals(Long.TYPE)
                || methods[i].getReturnType().equals(Float.class)
                || methods[i].getReturnType().equals(Float.TYPE)
                || methods[i].getReturnType().equals(Short.class)
                || methods[i].getReturnType().equals(Short.TYPE)
                || methods[i].getReturnType().equals(Double.class)
                || methods[i].getReturnType().equals(Double.TYPE)
                || methods[i].getReturnType().equals(BigDecimal.class)
                || methods[i].getReturnType().equals(java.util.Date.class)
                || methods[i].getReturnType().equals(java.sql.Date.class)
                || methods[i].getReturnType().equals(java.sql.Timestamp.class)
                || methods[i].getReturnType().equals(Integer.class)
                || methods[i].getReturnType().equals(Integer.TYPE)
                || methods[i].getReturnType().equals(Character.class)
                || methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class)
                || methods[i].getReturnType().equals(ImageIcon.class)
                || methods[i].getReturnType().equals(Icon.class)
                || methods[i].getReturnType().equals(byte[].class)
                || methods[i].getReturnType().equals(Object.class)
                || ValueObject.class.isAssignableFrom(methods[i].getReturnType()))) {
          attributeName = getAttributeName(attributeName, classType);
          //          try {
          //            if
          // (classType.getMethod("set"+attributeName.substring(0,1).toUpperCase()+attributeName.substring(1),new Class[]{methods[i].getReturnType()})!=null)
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
          //          } catch (NoSuchMethodException ex) {
          //          }
        } else if (attributeName.startsWith("is")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class))) {
          attributeName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
        } else if (attributeName.startsWith("set") && methods[i].getParameterTypes().length == 1) {
          attributeName = getAttributeName(attributeName, classType);
          try {
            if (classType.getMethod(
                    "get"
                        + attributeName.substring(0, 1).toUpperCase()
                        + attributeName.substring(1),
                    new Class[0])
                != null) {
              Method[] newparentMethods = new Method[parentMethods.length + 1];
              System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
              newparentMethods[parentMethods.length] = methods[i];
              voSetterMethods.put(prefix + attributeName, newparentMethods);
            }
          } catch (NoSuchMethodException ex) {
            try {
              if (classType.getMethod(
                      "is"
                          + attributeName.substring(0, 1).toUpperCase()
                          + attributeName.substring(1),
                      new Class[0])
                  != null) {
                Method[] newparentMethods = new Method[parentMethods.length + 1];
                System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
                newparentMethods[parentMethods.length] = methods[i];
                voSetterMethods.put(prefix + attributeName, newparentMethods);
              }
            } catch (NoSuchMethodException exx) {
            }
          }
        }
      }

      // fill in indexes with the colProperties indexes first; after them, it will be added the
      // other indexes (of attributes not mapped with grid column...)
      HashSet alreadyAdded = new HashSet();
      int i = 0;
      for (i = 0; i < colProperties.length; i++) {
        indexes.put(new Integer(i), colProperties[i].getColumnName());
        reverseIndexes.put(colProperties[i].getColumnName(), new Integer(i));
        alreadyAdded.add(colProperties[i].getColumnName());
      }
      Enumeration en = voGetterMethods.keys();
      while (en.hasMoreElements()) {
        attributeName = en.nextElement().toString();
        if (!alreadyAdded.contains(attributeName)) {
          indexes.put(new Integer(i), attributeName);
          reverseIndexes.put(attributeName, new Integer(i));
          i++;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #14
0
  /**
   * @param obj ValueObject where updating the value for the specified attribute (identified by
   *     colunm index)
   * @param attributeName attribute name
   * @param value new Object to set onto ValueObject
   */
  public final void setField(ValueObject obj, String attributeName, Object value) {
    try {
      Method[] getter = ((Method[]) voGetterMethods.get(attributeName));
      Method[] setter = ((Method[]) voSetterMethods.get(attributeName));
      if (getter == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No getter method for attribute name '" + attributeName + "'.",
            null);
      if (setter == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No setter method for attribute name '" + attributeName + "'.",
            null);

      if (value != null
          && (value instanceof Number || !value.equals("") && value instanceof String)) {
        if (!getter[getter.length - 1].getReturnType().equals(value.getClass())) {
          Class attrType = getter[getter.length - 1].getReturnType();
          if (attrType.equals(Integer.class) || attrType.equals(Integer.TYPE))
            value = new Integer(Double.valueOf(value.toString()).intValue());
          else if (attrType.equals(Double.class) || attrType.equals(Double.TYPE))
            value = new Double(value.toString());
          else if (attrType.equals(BigDecimal.class)) value = new BigDecimal(value.toString());
          else if (attrType.equals(Long.class) || attrType.equals(Long.TYPE))
            value = new Long(Double.valueOf(value.toString()).longValue());
          else if (attrType.equals(Short.class) || attrType.equals(Short.TYPE))
            value = new Short(Double.valueOf(value.toString()).shortValue());
          else if (attrType.equals(Float.class) || attrType.equals(Float.TYPE))
            value = new Float(Double.valueOf(value.toString()).floatValue());
        }
      } else if (value != null && value.equals("")) {
        if (!getter[getter.length - 1].getReturnType().equals(value.getClass())) value = null;
      }
      // test date compatibility...
      if (value != null && value.getClass().equals(java.util.Date.class)) {
        if (setter[setter.length - 1].getParameterTypes()[0].equals(java.sql.Date.class))
          value = new java.sql.Date(((java.util.Date) value).getTime());
        else if (setter[setter.length - 1].getParameterTypes()[0].equals(java.sql.Timestamp.class))
          value = new java.sql.Timestamp(((java.util.Date) value).getTime());
      }

      // retrieve inner v.o.: if not present then maybe create it, according to "createInnerVO"
      // property...
      Method[] m = (Method[]) voGetterMethods.get(attributeName);
      if (m == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No getter method for attribute name '" + attributeName + "'.",
            null);
      Object oldObj = obj;
      String auxAttr;
      for (int i = 0; i < m.length - 1; i++) {
        oldObj = obj;
        obj = (ValueObject) m[i].invoke(oldObj, new Object[0]);
        if (obj == null) {
          if (grids.getGridControl() == null || !grids.getGridControl().isCreateInnerVO()) return;
          else {
            obj = (ValueObject) m[i].getReturnType().newInstance();
            String[] attrs = attributeName.split("\\.");

            auxAttr = "";
            for (int k = 0; k <= i; k++) auxAttr += attrs[k] + ".";
            auxAttr = auxAttr.substring(0, auxAttr.length() - 1);
            Method aux = ((Method[]) voSetterMethods.get(auxAttr))[i];
            aux.invoke(oldObj, new Object[] {obj});
          }
        }
      }

      // avoid to set null for primitive types!
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Long.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Long(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Integer.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Integer(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Short.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Short((short) 0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Float.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Float(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Double.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Double(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Boolean.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {Boolean.FALSE});
      else setter[setter.length - 1].invoke(obj, new Object[] {value});
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }