Ejemplo n.º 1
0
 public static boolean download(
     URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) {
   File fFile = new File(new File(file).getParentFile().getPath());
   if (!fFile.exists()) fFile.mkdirs();
   boolean downloaded = true;
   BufferedInputStream in = null;
   FileOutputStream out = null;
   BufferedOutputStream bout = null;
   try {
     int count;
     int totalCount = 0;
     byte data[] = new byte[BUFFER];
     in = new BufferedInputStream(url.openStream());
     out = new FileOutputStream(file);
     bout = new BufferedOutputStream(out);
     while ((count = in.read(data, 0, BUFFER)) != -1) {
       bout.write(data, 0, count);
       totalCount += count;
       if (updater != null) updater.update(prefix + totalCount, totalFilesize);
     }
   } catch (Exception e) {
     e.printStackTrace();
     Utils.logger.log(Level.SEVERE, "Download error!");
     downloaded = false;
   } finally {
     try {
       close(in);
       close(bout);
       close(out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return downloaded;
 }
Ejemplo n.º 2
0
 // User defined finders/Buscadores definidos por el usuario
 public static Size findById(int id) throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     try {
       return (Size) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "Size"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     Size r = (Size) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "Size"));
     }
     return r;
   }
 }
Ejemplo n.º 3
0
  /**
   * @param obj ValueObject related to the current row
   * @param colIndex TableModel column index
   * @return Object contained into the TableModel at the specified column and ValueObject
   */
  public final Object getField(ValueObject obj, int colIndex) {
    try {
      Method[] m = (Method[]) voGetterMethods.get(getFieldName(colIndex));
      if (m == null)
        Logger.error(
            this.getClass().getName(),
            "getField",
            "No getter method for index "
                + colIndex
                + " and attribute name '"
                + getFieldName(colIndex)
                + "'.",
            null);

      for (int i = 0; i < m.length - 1; i++) {
        obj = (ValueObject) m[i].invoke(obj, new Object[0]);
        if (obj == null) {
          if (grids.getGridControl() == null || !grids.getGridControl().isCreateInnerVO())
            return null;
          else obj = (ValueObject) m[i].getReturnType().newInstance();
        }
      }

      return m[m.length - 1].invoke(obj, new Object[0]);
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 4
0
 // User defined finders/Buscadores definidos por el usuario
 public static FilterBySubfamily findBy() throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager().createQuery("from FilterBySubfamily as o");
     try {
       return (FilterBySubfamily) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "FilterBySubfamily"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession().createQuery("from FilterBySubfamily as o");
     FilterBySubfamily r = (FilterBySubfamily) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "FilterBySubfamily"));
     }
     return r;
   }
 }
Ejemplo n.º 5
0
  public String getRangeDescription() {
    try {
      org.openxava.test.calculators.RangeDescriptionCalculator rangeDescriptionCalculator =
          (org.openxava.test.calculators.RangeDescriptionCalculator)
              getMetaModel()
                  .getMetaProperty("rangeDescription")
                  .getMetaCalculator()
                  .createCalculator();

      rangeDescriptionCalculator.setSubfamilyNumberFrom(getSubfamily().getNumber());

      rangeDescriptionCalculator.setSubfamilyNumberTo(getSubfamilyTo().getNumber());
      return (String) rangeDescriptionCalculator.calculate();
    } catch (NullPointerException ex) {
      // Usually for multilevel property access with null references
      return null;
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(
          XavaResources.getString(
              "generator.calculate_value_error",
              "RangeDescription",
              "FilterBySubfamily",
              ex.getLocalizedMessage()));
    }
  }
Ejemplo n.º 6
0
  public static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      Object objref = ctx.lookup(JNDI_NAME);

      SavingsAccountHome home =
          (SavingsAccountHome) PortableRemoteObject.narrow(objref, SavingsAccountHome.class);

      BigDecimal zeroAmount = new BigDecimal("0.00");
      SavingsAccount John = home.create("100", "John", "Smith", zeroAmount);

      System.out.println("Account Name: " + John.getFirstName());
      System.out.println("Credit: 88.50");

      John.credit(new BigDecimal("88.50"));
      System.out.println("Debit: 20.25");

      John.debit(new BigDecimal("20.25"));
      BigDecimal balance = John.getBalance();
      System.out.println("Balance = " + balance);
      // John.remove();
      System.exit(0);
    } catch (InsufficientBalanceException ex) {
      System.err.println("Caught an InsufficientBalanceException: " + ex.getMessage());
    } catch (Exception ex) {
      System.err.println("Caught an exception.");
      ex.printStackTrace();
    }
  }
Ejemplo n.º 7
0
 /**
  * @param colIndex TableModel column index
  * @return TableCellEditor for the specified column
  */
 public final TableCellEditor getCellEditor(int colIndex) {
   try {
     return colProperties[colIndex].getCellEditor(tableContainer, grids);
   } catch (Exception ex) {
     ex.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 8
0
 private static void setStream(String in, String out) {
   try {
     System.setIn(new BufferedInputStream(new FileInputStream(in)));
     System.setOut(new PrintStream(out));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 9
0
 public static JSONObject readJSONUrlFile(String url) {
   try {
     return readJSONUrlFile(new URL(url));
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 10
0
 private void receiveEGTable() {
   int nBytes = (nBits - 1) / 8 + 1;
   try {
     for (int j = 0; j < nCols; j++)
       EGTable[j] = Utils.readBigInteger(nBytes * Wire.labelBitLength, ois);
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Ejemplo n.º 11
0
 public static JSONObject readJSONUrlFile(URL url) {
   try {
     JSONParser tmp = new JSONParser();
     Object o = tmp.parse(new InputStreamReader(url.openStream()));
     if (!(o instanceof JSONObject)) return null;
     else return (JSONObject) o;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 12
0
 public static JSONObject readJSONFile(String filename) {
   try {
     JSONParser tmp = new JSONParser();
     Object o = tmp.parse(new InputStreamReader(new FileInputStream(filename)));
     if (!(o instanceof JSONObject)) return null;
     else return (JSONObject) o;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 13
0
  private void init() {
    try {
      receiveParams();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    EGTable = new BigInteger[nCols];
    outputLabels = new BigInteger[nBits];
  }
Ejemplo n.º 14
0
 private void receiveEGTable_EXT() {
   int nBytes = (nBits - 1) / 8 + 1;
   try {
     for (int j = 0; j < nCols; j++) {
       boolean temp = ois.readBoolean();
       if (temp) EGTable[j] = Utils.readBigInteger(nBytes * Wire.labelBitLength, ois);
       else EGTable[j] = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Ejemplo n.º 15
0
 public static void close(Object o) {
   try {
     if (o == null) return;
     if (o instanceof InputStream) {
       ((InputStream) o).close();
     } else if (o instanceof OutputStream) {
       ((OutputStream) o).flush();
       ((OutputStream) o).close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 16
0
 public void run() {
   // long time = System.currentTimeMillis();
   try {
     br = new BufferedReader(new FileReader(new File("cell.in")));
     out = new PrintWriter("cell.out");
     solve();
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(111);
   }
   // System.err.println(System.currentTimeMillis() - time);
   out.close();
 }
Ejemplo n.º 17
0
 private org.openxava.converters.IConverter getNameConverter() {
   if (nameConverter == null) {
     try {
       nameConverter =
           (org.openxava.converters.IConverter) getMetaModel().getMapping().getConverter("name");
     } catch (Exception ex) {
       ex.printStackTrace();
       throw new RuntimeException(
           XavaResources.getString("generator.create_converter_error", "name"));
     }
   }
   return nameConverter;
 }
Ejemplo n.º 18
0
 public static String loadStringFromFile(String filename) {
   String line = "";
   File file = new File(filename);
   if (!file.exists()) return line;
   try {
     BufferedReader reader = new BufferedReader(new FileReader(file));
     line = reader.readLine();
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return line;
 }
Ejemplo n.º 19
0
 public static boolean saveStringToFile(String filename, String data) {
   BufferedWriter writer = null;
   try {
     writer = new BufferedWriter(new FileWriter(filename));
     writer.write(data);
     writer.close();
   } catch (Exception e) {
     e.printStackTrace();
     if (writer != null)
       try {
         writer.close();
       } catch (Exception ee) {
       }
     return false;
   }
   return true;
 }
Ejemplo n.º 20
0
 /**
  * @param colIndex TableModel column index
  * @return column type
  */
 public final Class getFieldClass(int colIndex) {
   try {
     Method[] m = (Method[]) voGetterMethods.get(getFieldName(colIndex));
     if (m == null)
       Logger.error(
           this.getClass().getName(),
           "getField",
           "No getter method for index "
               + colIndex
               + " and attribute name '"
               + getFieldName(colIndex)
               + "'.",
           null);
     return m[m.length - 1].getReturnType();
   } catch (Exception ex) {
     ex.printStackTrace();
     return String.class;
   }
 }
Ejemplo n.º 21
0
    public void diff(int id, String small, String large) {
      try {
        Scanner sm = new Scanner(new File(small));
        Scanner lg = new Scanner(new File(large));
        int line = 0;
        while (sm.hasNextLine() && lg.hasNextLine()) {
          String s = sm.nextLine();
          String l = lg.nextLine();
          if (!s.equals(l)) {
            System.out.println(line + ">" + s);
            System.out.println(line + "<" + l);
          }
          line++;
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  public SupplierDetailFrame(final SupplierController controller) {
    try {
      jbInit();
      setSize(750, 550);
      setMinimumSize(new Dimension(750, 550));

      supplierPanel.setFormController(controller);
      supplierPanel.setInsertButton(insertButton);
      supplierPanel.setEditButton(editButton);
      supplierPanel.setReloadButton(reloadButton);
      supplierPanel.setDeleteButton(deleteButton);
      supplierPanel.setSaveButton(saveButton);
      supplierPanel.setFunctionId("PUR01");
      organizationPanel.setFunctionId("PUR01");

      // link the parent grid to the current Form...
      HashSet pk = new HashSet();
      pk.add("companyCodeSys01REG04");
      pk.add("progressiveREG04");
      supplierPanel.linkGrid(
          controller.getGridFrame().getGrid(), pk, true, true, true, navigatorBar);

      // banks lookup...
      bankDataLocator.setGridMethodName("loadBanks");
      bankDataLocator.setValidationMethodName("validateBankCode");
      controlBank.setLookupController(bankController);
      controlBank.setControllerMethodName("getBanksList");
      bankController.setLookupDataLocator(bankDataLocator);
      bankController.setFrameTitle("banks");
      bankController.setLookupValueObjectClassName("org.jallinone.registers.bank.java.BankVO");
      bankController.addLookup2ParentLink("bankCodeREG12", "bankCodeReg12PUR01");
      bankController.addLookup2ParentLink("descriptionREG12", "descriptionREG12");
      bankController.setAllColumnVisible(false);
      bankController.setVisibleColumn("bankCodeREG12", true);
      bankController.setVisibleColumn("descriptionREG12", true);
      bankController.setPreferredWidthColumn("descriptionREG12", 200);
      new CustomizedColumns(new BigDecimal(232), bankController);

      // payments lookup...
      payDataLocator.setGridMethodName("loadPayments");
      payDataLocator.setValidationMethodName("validatePaymentCode");
      controlPayment.setLookupController(payController);
      controlPayment.setControllerMethodName("getPaymentsList");
      payController.setLookupDataLocator(payDataLocator);
      payController.setFrameTitle("payments");
      payController.setLookupValueObjectClassName(
          "org.jallinone.registers.payments.java.PaymentVO");
      payController.addLookup2ParentLink("paymentCodeREG10", "paymentCodeReg10PUR01");
      payController.addLookup2ParentLink("descriptionSYS10", "paymentDescriptionSYS10");
      payController.setAllColumnVisible(false);
      payController.setVisibleColumn("paymentCodeREG10", true);
      payController.setVisibleColumn("descriptionSYS10", true);
      payController.setPreferredWidthColumn("descriptionSYS10", 200);
      new CustomizedColumns(new BigDecimal(212), payController);
      payController.addLookupListener(
          new LookupListener() {

            public void beforeLookupAction(
                org.openswing.swing.message.receive.java.ValueObject parentVO) {
              DetailSupplierVO vo = (DetailSupplierVO) parentVO;
              payDataLocator
                  .getLookupValidationParameters()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01REG04());
              payDataLocator
                  .getLookupFrameParams()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01REG04());
            }

            public void codeChanged(
                org.openswing.swing.message.receive.java.ValueObject parentVO,
                Collection parentChangedAttributes) {}

            public void codeValidated(boolean validated) {}

            public void forceValidate() {}
          });

      // items lookup...
      itemDataLocator.setGridMethodName("loadItems");
      itemDataLocator.setValidationMethodName("validateItemCode");
      colItemCode.setLookupController(itemController);
      colItemCode.setControllerMethodName("getItemsList");
      itemController.setLookupDataLocator(itemDataLocator);
      itemController.setFrameTitle("items");
      itemController.setLookupValueObjectClassName("org.jallinone.items.java.GridItemVO");
      itemController.addLookup2ParentLink("companyCodeSys01ITM01", "companyCodeSys01PUR02");
      itemController.addLookup2ParentLink("itemCodeITM01", "itemCodeItm01PUR02");
      itemController.addLookup2ParentLink("descriptionSYS10", "descriptionSYS10");
      itemController.setAllColumnVisible(false);
      itemController.setVisibleColumn("itemCodeITM01", true);
      itemController.setVisibleColumn("descriptionSYS10", true);
      itemController.setPreferredWidthColumn("descriptionSYS10", 200);
      new CustomizedColumns(ApplicationConsts.ID_ITEMS_GRID, itemController);
      itemController.addLookupListener(
          new LookupListener() {

            public void codeValidated(boolean validated) {}

            public void codeChanged(ValueObject parentVO, Collection parentChangedAttributes) {
              GridItemVO vo = (GridItemVO) itemController.getLookupVO();
              if (vo.getItemCodeITM01() != null) {
                SupplierItemVO supplierVO = (SupplierItemVO) parentVO;
                supplierVO.setSupplierItemCodePUR02(vo.getItemCodeITM01());
              }
            }

            public void beforeLookupAction(ValueObject parentVO) {}

            public void forceValidate() {}
          });

      // purchase um lookup...
      umDataLocator.setGridMethodName("loadMeasures");
      umDataLocator.setValidationMethodName("validateMeasureCode");
      colUmCode.setLookupController(umController);
      colUmCode.setControllerMethodName("getMeasureUnitsList");
      umController.setLookupDataLocator(umDataLocator);
      umController.setFrameTitle("measures");
      umController.setLookupValueObjectClassName("org.jallinone.registers.measure.java.MeasureVO");
      umController.addLookup2ParentLink("umCodeREG02", "umCodeReg02PUR02");
      umController.addLookup2ParentLink("decimalsREG02", "decimalsREG02");
      umController.setAllColumnVisible(false);
      umController.setVisibleColumn("umCodeREG02", true);
      umController.setVisibleColumn("decimalsREG02", true);
      new CustomizedColumns(ApplicationConsts.ID_UM_GRID, umController);
      umController.addLookupListener(
          new LookupListener() {

            public void codeValidated(boolean validated) {}

            public void codeChanged(ValueObject parentVO, Collection parentChangedAttributes) {
              MeasureVO vo = (MeasureVO) umController.getLookupVO();
              if (vo.getUmCodeREG02() != null) {
                colMinQty.setDecimals(vo.getDecimalsREG02().intValue());
                colMultipleQty.setDecimals(vo.getDecimalsREG02().intValue());
                SupplierItemVO supplierVO = (SupplierItemVO) parentVO;
                if (supplierVO.getMinPurchaseQtyPUR02() != null)
                  supplierVO.setMinPurchaseQtyPUR02(
                      supplierVO
                          .getMinPurchaseQtyPUR02()
                          .setScale(vo.getDecimalsREG02().intValue(), BigDecimal.ROUND_HALF_UP));
                if (supplierVO.getMultipleQtyPUR02() != null)
                  supplierVO.setMultipleQtyPUR02(
                      supplierVO
                          .getMultipleQtyPUR02()
                          .setScale(vo.getDecimalsREG02().intValue(), BigDecimal.ROUND_HALF_UP));
              }
            }

            public void beforeLookupAction(ValueObject parentVO) {}

            public void forceValidate() {}
          });

      itemsGrid.setController(new SupplierItemsController(this));
      itemsGrid.setGridDataLocator(itemsGridDataLocator);
      itemsGridDataLocator.setServerMethodName("loadSupplierItems");

      treePanel.addHierarTreeListener(
          new HierarTreeListener() {

            public void loadDataCompleted(boolean error) {
              if (treePanel.getTree().getRowCount() > 0) treePanel.getTree().setSelectionRow(0);
              if (treePanel.getTree().getSelectionPath() != null)
                controller.leftClick(
                    (DefaultMutableTreeNode)
                        treePanel.getTree().getSelectionPath().getLastPathComponent());
            }
          });

      treePanel.setTreeController(controller);
      treePanel.setFunctionId("PUR01");

      init();

      itemsGrid.enableDrag(ApplicationConsts.ID_SUPPLIER_ITEMS_GRID.toString());

      // debit account code lookup...
      controlDebitsCode.setLookupController(debitController);
      controlDebitsCode.setControllerMethodName("getAccounts");
      debitController.setLookupDataLocator(debitDataLocator);
      debitDataLocator.setGridMethodName("loadAccounts");
      debitDataLocator.setValidationMethodName("validateAccountCode");
      debitController.setFrameTitle("accounts");
      debitController.setAllowTreeLeafSelectionOnly(false);
      debitController.setLookupValueObjectClassName(
          "org.jallinone.accounting.accounts.java.AccountVO");
      debitController.addLookup2ParentLink("accountCodeACC02", "debitAccountCodeAcc02PUR01");
      debitController.addLookup2ParentLink("descriptionSYS10", "debitAccountDescrPUR01");
      debitController.setFramePreferedSize(new Dimension(400, 400));
      debitController.setAllColumnVisible(false);
      debitController.setVisibleColumn("accountCodeACC02", true);
      debitController.setVisibleColumn("descriptionSYS10", true);
      debitController.setFilterableColumn("accountCodeACC02", true);
      debitController.setFilterableColumn("descriptionSYS10", true);
      debitController.setSortedColumn("accountCodeACC02", "ASC", 1);
      debitController.setSortableColumn("accountCodeACC02", true);
      debitController.setSortableColumn("descriptionSYS10", true);
      debitController.setPreferredWidthColumn("accountCodeACC02", 100);
      debitController.setPreferredWidthColumn("descriptionSYS10", 290);
      debitController.addLookupListener(
          new LookupListener() {

            public void codeValidated(boolean validated) {}

            public void codeChanged(ValueObject parentVO, Collection parentChangedAttributes) {}

            public void beforeLookupAction(ValueObject parentVO) {
              debitDataLocator
                  .getLookupFrameParams()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, controlCompanyCode.getValue());
              debitDataLocator
                  .getLookupValidationParameters()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, controlCompanyCode.getValue());
            }

            public void forceValidate() {}
          });

      // costs account code lookup...
      controlCostsCode.setLookupController(costsController);
      controlCostsCode.setControllerMethodName("getAccounts");
      costsController.setLookupDataLocator(costsDataLocator);
      costsDataLocator.setGridMethodName("loadAccounts");
      costsDataLocator.setValidationMethodName("validateAccountCode");
      costsController.setFrameTitle("accounts");
      costsController.setAllowTreeLeafSelectionOnly(false);
      costsController.setLookupValueObjectClassName(
          "org.jallinone.accounting.accounts.java.AccountVO");
      costsController.addLookup2ParentLink("accountCodeACC02", "costsAccountCodeAcc02PUR01");
      costsController.addLookup2ParentLink("descriptionSYS10", "costsAccountDescrPUR01");
      costsController.setFramePreferedSize(new Dimension(400, 400));
      costsController.setAllColumnVisible(false);
      costsController.setVisibleColumn("accountCodeACC02", true);
      costsController.setVisibleColumn("descriptionSYS10", true);
      costsController.setFilterableColumn("accountCodeACC02", true);
      costsController.setFilterableColumn("descriptionSYS10", true);
      costsController.setSortedColumn("accountCodeACC02", "ASC", 1);
      costsController.setSortableColumn("accountCodeACC02", true);
      costsController.setSortableColumn("descriptionSYS10", true);
      costsController.setPreferredWidthColumn("accountCodeACC02", 100);
      costsController.setPreferredWidthColumn("descriptionSYS10", 290);
      costsController.addLookupListener(
          new LookupListener() {

            public void codeValidated(boolean validated) {}

            public void codeChanged(ValueObject parentVO, Collection parentChangedAttributes) {}

            public void beforeLookupAction(ValueObject parentVO) {
              costsDataLocator
                  .getLookupFrameParams()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, controlCompanyCode.getValue());
              costsDataLocator
                  .getLookupValidationParameters()
                  .put(ApplicationConsts.COMPANY_CODE_SYS01, controlCompanyCode.getValue());
            }

            public void forceValidate() {}
          });

      CustomizedControls customizedControls =
          new CustomizedControls(tabbedPane, supplierPanel, ApplicationConsts.ID_SUPPLIER_GRID);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 23
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();
    }
  }
    public void runTest() throws Throwable {
      boolean pass = true;

      out.println("### framework test bundle :STARTLVL100A start");

      try {
        buA = Util.installBundle(bc, "bundleSLA_test-1.0.0.jar");
        sl.setBundleStartLevel(buA, baseLevel + 10);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      buB = null;
      try {
        buB = Util.installBundle(bc, "bundleSLB_test-1.0.0.jar");
        sl.setBundleStartLevel(buB, baseLevel + 30);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      buC = null;
      try {
        buC = Util.installBundle(bc, "bundleSLC_test_api-1.0.0.jar");
        sl.setBundleStartLevel(buC, baseLevel + 20);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buA.start();
        assertTrue("BundleA should not be ACTIVE", buA.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buB.start();
        assertTrue("BundleB should not be ACTIVE", buB.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buC.start();
        assertTrue("BundleC should not be ACTIVE", buC.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      syncBListen.clearEvents();

      sl.setStartLevel(baseLevel + 30);

      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STARTED, buA),
                new BundleEvent(BundleEvent.STARTED, buC),
                new BundleEvent(BundleEvent.STARTED, buB)
              });
      assertTrue("Bundle A, C, B should start", pass);

      buD = null;
      try {
        buD = Util.installBundle(bc, "bundleSLD_test-1.0.0.jar");
        sl.setBundleStartLevel(buD, baseLevel + 15);
        buD.start();
        assertTrue("BundleD should be ACTIVE", buD.getState() == Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("start level test bundle " + e + " :STARTLVL100A:FAIL");
      }

      syncBListen.clearEvents();

      Util.updateBundle(bc, buC, "bundleSLC_test_api-1.0.0.jar");

      // Check BundleEvent stop/start C
      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STOPPED, buC),
                new BundleEvent(BundleEvent.STARTED, buC),
              });
      assertTrue("Bundle C should stop and start", pass);

      syncBListen.clearEvents();

      pa.refreshPackages(new Bundle[] {buA, buB, buC, buD});

      // Check BundleEvent stop order B, C, D, A
      // Check BundleEvent start order A, D, C, B
      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STOPPED, buB),
                new BundleEvent(BundleEvent.STOPPED, buC),
                new BundleEvent(BundleEvent.STOPPED, buD),
                new BundleEvent(BundleEvent.STOPPED, buA),
                new BundleEvent(BundleEvent.STARTED, buA),
                new BundleEvent(BundleEvent.STARTED, buD),
                new BundleEvent(BundleEvent.STARTED, buC),
                new BundleEvent(BundleEvent.STARTED, buB)
              });
      assertTrue("Bundle B, C, D, A should stop and start in reverse", pass);

      buA.uninstall();
      buA = null;
      buB.uninstall();
      buB = null;
      buC.uninstall();
      buC = null;
      buD.uninstall();
      buD = null;

      out.println("### start level test bundle :STARTLVL100A:PASS");
    }
Ejemplo n.º 25
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();
    }
  }