示例#1
0
  /**
   * @param request
   * @param subSystemId
   * @return
   */
  private boolean containsViewableActions(HttpServletRequest request, SubSystem ss) {
    List<WebAction> list = ss.getWebActions();
    Connection conn = null;
    try {
      UserWebImpl userWeb =
          ((UserWebImpl)
              WebUtils.getSessionContextManager(request.getSession())
                  .getActor(nds.util.WebKeys.USER));
      conn = QueryEngine.getInstance().getConnection();
      HashMap webActionEnv = new HashMap();
      webActionEnv.put("connection", conn);
      webActionEnv.put("httpservletrequest", request);
      webActionEnv.put("userweb", userWeb);

      for (int i = 0; i < list.size(); i++) {
        WebAction wa = list.get(i);
        if (wa.canDisplay(webActionEnv)) {
          return true;
        }
      }
    } catch (Throwable t) {
      logger.error("Fail to load subsystem webaction", t);
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Throwable te) {
      }
    }
    return false;
  }
示例#2
0
  /**
   * puts the value for the column aginst the column Name
   *
   * @param os
   * @param rows
   * @param oldResultSet
   * @param index
   * @param modifiedColumns
   * @param columnName
   * @throws SQLException
   * @throws IOException
   */
  public void writeUpdate(
      Writer os,
      ResultSet rows,
      ResultSet oldResultSet,
      int index,
      HashMap modifiedColumns,
      String columnName,
      ArrayList encodedCols)
      throws SQLException, IOException {
    Object newObject = rows.getObject(index);
    Object oldObject = oldResultSet.getObject(index);

    if (newObject == null) {
      write(os, "NULL", encodedCols, columnName);
      if (oldObject != null) {
        modifiedColumns.put(columnName, "NULL");
      }
    } else {
      write(os, newObject, encodedCols, columnName);
      if (oldObject != null) {
        if (!(newObject.equals(oldObject))) {
          modifiedColumns.put(columnName, newObject);
        }
      } else {
        modifiedColumns.put(columnName, newObject);
      }
    }
  }
示例#3
0
  /**
   * @param request
   * @param tableCategoryId
   * @paqram includeAction if true, will load webactions also
   * @return elements are Table or WebAction
   */
  public List getChildrenOfTableCategory(
      HttpServletRequest request, int tableCategoryId, boolean includeAction) {
    TableManager manager = TableManager.getInstance();

    WebAction action;
    ArrayList cats = new ArrayList();
    Connection conn = null;
    HashMap webActionEnv = null;
    Table table;
    UserWebImpl userWeb =
        ((UserWebImpl)
            WebUtils.getSessionContextManager(request.getSession())
                .getActor(nds.util.WebKeys.USER));

    TableCategory tc = manager.getTableCategory(tableCategoryId);
    List children = tc.children();
    ArrayList catschild = new ArrayList();
    try {
      if (includeAction) {
        conn = QueryEngine.getInstance().getConnection();
        webActionEnv = new HashMap();
        webActionEnv.put("connection", conn);
        webActionEnv.put("httpservletrequest", request);
        webActionEnv.put("userweb", userWeb);
      }
      for (int j = 0; j < children.size(); j++) {
        if (children.get(j) instanceof Table) {
          table = (Table) children.get(j);
          if (!table.isMenuObject()) {
            continue;
          }
          try {
            WebUtils.checkTableQueryPermission(table.getName(), request);
          } catch (NDSSecurityException e) {
            continue;
          }
          // table is ok for current user to list
          catschild.add(table);
        } else if (children.get(j) instanceof WebAction) {
          if (includeAction) {
            action = (WebAction) children.get(j);
            if (action.canDisplay(webActionEnv)) catschild.add(action);
          }
        } else {
          throw new NDSRuntimeException(
              "Unsupported element in TableCategory children:" + children.get(j).getClass());
        }
      }
    } catch (Throwable t) {
      logger.error("Fail to load subsystem tree", t);
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Throwable e) {
      }
    }
    return catschild;
  }
示例#4
0
 /**
  * Set Environment key to value
  *
  * @param key variable name ('#' will be vonverted to '_')
  * @param value
  */
 public void setEnvironment(String key, Object value) {
   if (key != null && key.length() > 0) {
     //	log.fine( "Scriptlet.setEnvironment " + key, value);
     if (value == null) m_ctx.remove(key);
     else m_ctx.put(convertKey(key), value);
   }
 } //  SetEnvironment
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
示例#6
0
 /**
  * Builds the HashSet which will be used to test whether the given methods can be exempted or not
  */
 void buildHashSet() {
   Class<Clob> iface = Clob.class;
   for (int i = 0; i < emd.length; i++) {
     try {
       Method m = iface.getMethod(emd[i].getMethodName(), emd[i].getParams());
       excludedMethodSet.put(m, emd[i]);
     } catch (NoSuchMethodException nsme) {
       fail("The method could not be found in the interface");
     }
   }
 }
示例#7
0
  /**
   * Set Environment key to value
   *
   * @param key variable name ('#' will be converted to '_')
   * @param stringValue try to convert to Object
   */
  public void setEnvironment(String key, String stringValue) {
    if (key == null || key.length() == 0) return;
    //	log.fine( "Scriptlet.setEnvironment " + key, stringValue);
    if (stringValue == null) {
      m_ctx.remove(key);
      return;
    }

    //  Boolean
    if (stringValue.equals("Y")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(true));
      return;
    }
    if (stringValue.equals("N")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(false));
      return;
    }

    //  Timestamp
    Timestamp timeValue = null;
    try {
      timeValue = Timestamp.valueOf(stringValue);
      m_ctx.put(convertKey(key), timeValue);
      return;
    } catch (Exception e) {
    }

    //  Numeric
    Integer intValue = null;
    try {
      intValue = Integer.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    Double doubleValue = null;
    try {
      doubleValue = Double.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    if (doubleValue != null) {
      if (intValue != null) {
        double di = Double.parseDouble(intValue.toString());
        //  the numbers are the same -> integer
        if (Double.compare(di, doubleValue.doubleValue()) == 0) {
          m_ctx.put(convertKey(key), intValue);
          return;
        }
      }
      m_ctx.put(convertKey(key), doubleValue);
      return;
    }
    if (intValue != null) {
      m_ctx.put(convertKey(key), intValue);
      return;
    }
    m_ctx.put(convertKey(key), stringValue);
  } //  SetEnvironment
示例#8
0
  public Sql2oTest(Driver driverToRegister, String url, String user, String pass, String testName) {

    if (driverToRegister != null) {
      try {
        DriverManager.registerDriver(driverToRegister);
      } catch (SQLException e) {
        throw new RuntimeException(
            "could not register driver '" + driverToRegister.getClass().getName() + "'", e);
      }
    }

    this.sql2o = new Sql2o(url, user, pass);

    HashMap<String, String> defaultColumnMap = new HashMap<String, String>();
    defaultColumnMap.put("ID", "id");
    defaultColumnMap.put("NAME", "name");
    defaultColumnMap.put("EMAIL", "email");
    defaultColumnMap.put("TEXT", "text");
    defaultColumnMap.put("ANUMBER", "aNumber");
    defaultColumnMap.put("ALONGNUMBER", "aLongNumber");
    sql2o.setDefaultColumnMappings(defaultColumnMap);

    this.url = url;
    this.user = user;
    this.pass = pass;

    if ("HyperSQL DB test".equals(testName)) {
      sql2o.createQuery("set database sql syntax MSS true").executeUpdate();
    }
  }
  /**
   * Creates a NamedParameterStatement. Wraps a call to c.{@link
   * Connection#prepareStatement(java.lang.String) prepareStatement}.
   *
   * @param conn the database connection
   * @param sql the parameterized sql
   * @throws SQLException if the statement could not be created
   */
  public NamedParameterStatement(Connection conn, String sql) throws SQLException {
    if (nameIndexCache.containsKey(sql)) {
      nameIndexMap = nameIndexCache.get(sql);
      parsedSql = parsedSqlCache.get(sql);
    } else {
      nameIndexMap = new HashMap<String, List<Integer>>();
      parsedSql = parseNamedSql(sql, nameIndexMap);

      nameIndexCache.put(sql, nameIndexMap);
      parsedSqlCache.put(sql, parsedSql);
    }
    ps = conn.prepareStatement(parsedSql);
  }
  private void loadNewDict(String sql) {
    Debug.getAppErrLogger().debug("------------------------------------------------load:" + sql);

    HashMap htemp = new HashMap();
    Statement state = null;
    ResultSet rs_dic = null;
    try {
      if (conn != null) {
        conn.close();
        conn = null;
      }
      getConnection();
      state = conn.createStatement();
      rs_dic = state.executeQuery(sql);
      while (rs_dic.next()) {
        String text = rs_dic.getString(1);
        String value = rs_dic.getString(2);
        if (null != text && value != null) {
          htemp.put(text.trim(), value.trim());
        }
      }
      hashCache.put(sql, htemp);
      rs_dic.close();
      state.close();
    } catch (Exception e) {
      e.printStackTrace();
      Debug.getAppErrLogger().error(e);
    } finally {
      try {
        if (rs_dic != null) {
          rs_dic.close();
          rs_dic = null;
        }
        if (state != null) {
          state.close();
          state = null;
        }
      } catch (Exception e) {
        Debug.getAppErrLogger().error("Inside DictCachService::loadNewDict() - 关闭时出错!\n" + e);
      }
      close();
    }
  }
示例#11
0
 /**
  * Parses the files passed into the <CODE>setTemplateFiles</CODE> method. The data extracted from
  * the template files is returned.
  */
 public void parse() {
   setMessage("Parsing Files");
   templates.clear();
   importedFieldCount = 0;
   importedMacroCount = 0;
   File[] templateFiles = getTemplateFiles();
   resetParseCanceled();
   int totalFileSize = 0;
   for (int i = 0; i < templateFiles.length; i++)
     if (templateFiles[i].exists()) totalFileSize += (int) templateFiles[i].length();
   setProgressMaximum(totalFileSize);
   int progress = 0;
   setProgressValue(0);
   setProgressIndeterminate(false);
   for (int i = 0; i < templateFiles.length; i++) {
     String currentFilePath = templateFiles[i].getAbsolutePath();
     Timestamp modifiedDate = new Timestamp(templateFiles[i].lastModified());
     Template currentTemplate = new Template(currentFilePath, modifiedDate);
     String[] nameParts = templateFiles[i].getName().split("\\.");
     if (nameParts != null && nameParts.length > 0) currentTemplate.setID(nameParts[0]);
     templates.add(currentTemplate);
     try {
       BufferedReader iStream = new BufferedReader(new FileReader(templateFiles[i]));
       try {
         String currentLine = iStream.readLine();
         Signal currentSignal = null, archiveTag = null;
         ArchiveRequest request = null;
         ArchiveGroup group = null;
         HashMap archiveSignals = new HashMap();
         int lineNumber = 0;
         int braceCount = 0;
         while (currentLine != null) // null indicates EOF
         {
           lineNumber++;
           if (currentLine.trim().startsWith("#")) // Comments start with #
           {
             // Comments start with #. Archive information is embedded in comments.
             ArchiveGroup newGroup = parseArchiveGroupTag(currentLine, currentTemplate);
             if (newGroup != null) group = newGroup;
             else {
               ArchiveRequest newRequest =
                   parseArchiveRequestTag(currentLine, group, currentTemplate);
               if (newRequest != null) request = newRequest;
               else {
                 Signal newArchiveTag = parseArchiveTag(currentLine);
                 if (newArchiveTag != null) {
                   if (archiveTag != null) // Tag was not used in request. Use for defaults.
                   archiveSignals.put(archiveTag.getID(), archiveTag);
                   archiveTag = newArchiveTag;
                 }
               }
             }
           } else {
             Matcher macroMatcher = macroPattern.matcher(currentLine);
             if (macroMatcher.find()) {
               String macro = macroMatcher.group(1);
               if (!currentTemplate.containsMacro(macro)) {
                 importedMacroCount++;
                 currentTemplate.addMacro(macro);
               }
             }
             int linePosition = 0;
             int lineLength = currentLine.length();
             while (linePosition < lineLength) {
               int openBracePosition = currentLine.indexOf('{', linePosition);
               int closeBracePosition = currentLine.indexOf('}', linePosition);
               if (currentSignal == null || braceCount == 0) {
                 // Got no signal or the brace was never opened...
                 Matcher recordMatcher = recordPattern.matcher(currentLine);
                 if (recordMatcher.find(linePosition))
                   if (openBracePosition < 0 || recordMatcher.start() < openBracePosition) {
                     linePosition = recordMatcher.end();
                     SignalType currentSignalType = new SignalType();
                     String recordType = recordMatcher.group(1);
                     currentSignalType.setRecordType(new EpicsRecordType(recordType));
                     String signalID = recordMatcher.group(2);
                     currentSignal = new Signal(signalID);
                     currentSignal.setType(currentSignalType);
                     if (archiveTag != null)
                       archiveSignals.put(archiveTag.getID(), archiveTag); // Use as defaults.
                     archiveTag = (Signal) archiveSignals.get(signalID);
                     if (archiveTag != null) {
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                       // Must use a new instance of signal since each request has different
                       // values for type, frequency, etc.
                       if (request != null && request.getSignal(signalID) == null)
                         request.addSignal(new Signal(signalID));
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                     }
                     currentTemplate.addSignal(currentSignal);
                     archiveTag = null; // Reset so is not used twice.
                     continue; // Go back and check the line position against length.
                   }
               }
               if (braceCount == 0 && currentSignal != null && openBracePosition >= linePosition) {
                 // Got the signal, need the open brace.
                 linePosition = openBracePosition + 1;
                 braceCount++;
                 continue; // Go back and check the line position against length.
               }
               if (braceCount > 0) {
                 // Looking for fields or the close brace.
                 Matcher fieldMatcher = fieldPattern.matcher(currentLine);
                 if (fieldMatcher.find(linePosition))
                   if (closeBracePosition < 0 || fieldMatcher.start() < closeBracePosition) {
                     // Found a field...
                     linePosition = fieldMatcher.end();
                     SignalField currentField = new SignalField();
                     String currentFieldID = fieldMatcher.group(1);
                     currentField.setType(new SignalFieldType(currentFieldID));
                     currentField.setValue(fieldMatcher.group(2));
                     currentSignal.addField(currentField);
                     importedFieldCount++;
                     continue;
                   }
                 if (closeBracePosition >= 0) {
                   // Found end of current signal.
                   braceCount--;
                   linePosition = closeBracePosition + 1;
                   currentSignal = null;
                   continue;
                 }
               }
               linePosition = lineLength;
               if (isParseCanceled()) break;
             }
           }
           progress += currentLine.length() + 1;
           setProgressValue(progress);
           currentLine = iStream.readLine();
           if (isParseCanceled()) break;
         }
       } finally {
         iStream.close();
       }
     } catch (java.io.FileNotFoundException ex) {
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>Unable to open file '");
       errorMessage.append(templateFiles[i].getAbsoluteFile());
       errorMessage.append("'.</FONT></HTML>");
       addMessage(errorMessage.toString());
     } catch (java.io.IOException ex) {
       ex.printStackTrace();
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>IO Error: ");
       errorMessage.append(ex.getMessage());
       errorMessage.append("</FONT></HTML>");
       addMessage(errorMessage.toString());
     }
     if (isParseCanceled()) break;
   }
 }
示例#12
0
 static {
   dbQuotes.put(TYPE_MYSQL, "`");
 }
示例#13
0
  public void runReplicate() throws InterruptedException {
    if (verbose) log.append("Started at " + Calendar.getInstance().getTime() + "\r\n");
    Connection connectionFrom = null;
    Connection connectionTo = null;
    try {
      connectionFrom = providerI.getConnection(dbFrom);
      connectionTo = providerI.getConnection(dbTo);
      PreparedStatement preparedStatementFrom = null;
      PreparedStatement preparedStatementTo = null;
      ResultSet resultSet = null;

      for (Iterator<HashMap<String, String>> HashMapIterator = tables.iterator();
          HashMapIterator.hasNext(); ) {
        try {
          HashMap<String, String> h = HashMapIterator.next();
          String name = h.get("name");
          String name2 = h.get("name2");
          String where1 = h.get("where1");
          String where2 = h.get("where2");

          if (verbose)
            log.append("Replicating " + dbFrom + "/" + name + " to " + dbTo + "/" + name2 + "\r\n");

          preparedStatementFrom =
              connectionFrom.prepareStatement("select * from " + name + " WHERE 1=1 " + where1);
          boolean b = preparedStatementFrom.execute();
          HashMap meta = new HashMap();
          // 1. find all ids from DB1
          ArrayList db1 = new ArrayList();
          String nullMark = "____NULL";
          if (b) {
            resultSet = preparedStatementFrom.getResultSet();
            ResultSetMetaData setMetaData = resultSet.getMetaData();
            for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
              meta.put(
                  setMetaData.getColumnLabel(i).toLowerCase(), setMetaData.getColumnClassName(i));
            }
            while (resultSet.next()) {
              HashMap results = new HashMap();
              for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
                String columnName = setMetaData.getColumnLabel(i).toLowerCase();
                Object o = resultSet.getObject(i);
                if (o != null) {
                  results.put(columnName, o);
                } else {
                  results.put(columnName + nullMark, nullMark);
                }
              }
              db1.add(results);
            }
            resultSet.close();
          } else {
            log.append("Couldn't execute select from " + dbFrom + "/" + name + " /r/n");
            return;
          }

          StringBuffer allIds = new StringBuffer();
          HashMap records1 = new HashMap();
          HashMap toInsert = new HashMap();
          HashMap toUpdate = new HashMap();
          for (Iterator iterator = db1.iterator(); iterator.hasNext(); ) {
            HashMap record = (HashMap) iterator.next();
            if (allIds.length() != 0) {
              allIds.append(",");
            }
            allIds.append(record.get("id"));
            records1.put(record.get("id"), record);
          }

          toInsert.putAll(records1);

          // 2. find all ids to delete in DB2;
          if (allIds.length() > 0) {
            preparedStatementTo =
                connectionTo.prepareStatement(
                    "delete from "
                        + name2
                        + " where id not in ("
                        + allIds.toString()
                        + ")"
                        + where2);
            if (verbose)
              log.append(
                  "deleted from "
                      + dbTo
                      + "/"
                      + name2
                      + " "
                      + preparedStatementTo.executeUpdate()
                      + " records;\r\n");
          } else {
            if (verbose)
              log.append(
                  "No records in "
                      + dbFrom
                      + "/"
                      + name
                      + ", nothing to delete in "
                      + dbTo
                      + "/"
                      + name2
                      + " ;\r\n");
          }

          // 3. find all ids from DB2;
          preparedStatementTo =
              connectionTo.prepareStatement("select * from " + name2 + " WHERE 1=1 " + where2);
          b = preparedStatementTo.execute();
          HashMap meta2 = new HashMap();
          ArrayList db2 = new ArrayList();
          if (b) {
            resultSet = preparedStatementTo.getResultSet();
            ResultSetMetaData setMetaData = resultSet.getMetaData();
            for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
              meta2.put(
                  setMetaData.getColumnLabel(i).toLowerCase(), setMetaData.getColumnClassName(i));
            }
            while (resultSet.next()) {
              HashMap results = new HashMap();
              for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
                String columnName = setMetaData.getColumnLabel(i).toLowerCase();
                Object o = resultSet.getObject(i);
                if (o != null) {
                  results.put(columnName, o);
                } else {
                  results.put(columnName + nullMark, nullMark);
                }
              }
              db2.add(results);
            }
          } else {
            log.append("Couldn't execute select from " + dbTo + "/" + name2 + " /r/n");
            return;
          }

          // compare meta-data;
          {
            HashMap temp = new HashMap();
            {
              temp.putAll(meta);

              Set set = meta2.keySet();
              for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
                Object o = iteratorSet.next();
                if (meta.containsKey(o)) {
                  if (meta.get(o).equals(meta2.get(o))) {
                    temp.remove(o);
                  }
                } else {
                  log.append("ERROR: Meta data not equals! \r\n");
                  log.append(o + "\t" + temp.get(o) + " not present in table " + name + "\r\n");
                }
              }
            }
            if (!temp.isEmpty()) {
              log.append("ERROR: Meta data not equals! \r\n");
              Set set = temp.keySet();
              for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
                Object o = iteratorSet.next();
                log.append(o + "\t" + temp.get(o) + " != " + meta2.get(o) + "\r\n");
              }

              return;
            }
          }

          for (Iterator iterator = db2.iterator(); iterator.hasNext(); ) {
            HashMap db2Record = (HashMap) iterator.next();
            if (toInsert.containsKey(db2Record.get("id"))) {
              HashMap db1Record = (HashMap) toInsert.get(db2Record.get("id"));
              boolean equal = true;
              Set set = meta2.keySet();
              for (Iterator iteratorSet = set.iterator(); equal && iteratorSet.hasNext(); ) {
                String columnName2 = (String) iteratorSet.next();
                if (db2Record.containsKey(columnName2 + nullMark)
                    || db1Record.containsKey(columnName2 + nullMark)) {
                  equal =
                      db2Record.containsKey(columnName2 + nullMark)
                          && db1Record.containsKey(columnName2 + nullMark);
                } else {
                  // checking not-null;
                  equal = equalRecords(db1Record.get(columnName2), db2Record.get(columnName2));
                }
              }
              if (!equal) {
                toUpdate.put(db2Record.get("id"), toInsert.get(db2Record.get("id")));
              }
              toInsert.remove(db2Record.get("id"));
            } else {
              // this case shouldn't happen at all, since we've deleted all such records

            }
          }

          log.append(
              "Found "
                  + toUpdate.size()
                  + " to update, and "
                  + toInsert.size()
                  + " to insert.\r\n");
          int totalUpdated = 0;
          // 4. calculate all to update in DB2
          if (!toUpdate.isEmpty()) {
            Set set = toUpdate.keySet();
            for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
              StringBuffer sql = new StringBuffer();
              Object id = iteratorSet.next();
              HashMap r = (HashMap) toUpdate.get(id);
              sql.append("UPDATE " + name2 + " SET ");
              StringBuffer values = new StringBuffer();

              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (!o.equals("id")) {
                  if (values.length() != 0) {
                    values.append(",");
                  }
                  Object quote = dbQuotes.get(dbToType);
                  if (quote == null) {
                    quote = "";
                  }
                  values.append(quote).append(o).append(quote);
                  values.append(" =  ? ");
                }
              }
              values.append(" WHERE id = '" + r.get("id") + "';");
              PreparedStatement statement =
                  connectionTo.prepareStatement(sql.toString() + values.toString());
              en = meta2.keySet();
              int i = 0;
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (!o.equals("id")) {
                  i++;
                  statement.setObject(i, r.get(o));
                }
              }
              try {
                totalUpdated += statement.executeUpdate();
              } catch (SQLException e) {
                e.printStackTrace();
                log.append("Error occured: " + e + "\r\n");
              }
            }
          }
          if (verbose) log.append("Updated " + totalUpdated + " records.\r\n");

          // 4. calculate all to insert to DB2
          if (!toInsert.isEmpty()) {
            StringBuffer header = new StringBuffer();
            if (header.length() == 0) {
              header.append(" INSERT INTO " + name2 + " (");
              StringBuffer columns = new StringBuffer();
              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (columns.length() != 0) {
                  columns.append(",");
                }

                Object quote = dbQuotes.get(dbToType);
                if (quote == null) {
                  quote = "";
                }
                columns.append(quote).append(o).append(quote);
              }
              header.append(columns.toString());
              header.append(") VALUES ");
            }

            Set enumeration = toInsert.keySet();
            for (Iterator iteratorSetX = enumeration.iterator(); iteratorSetX.hasNext(); ) {
              Object id = iteratorSetX.next();
              HashMap r = (HashMap) toInsert.get(id);
              StringBuffer values = new StringBuffer();
              if (values.length() != 0) {
                values.append(",");
              }
              values.append("(");

              StringBuffer columns = new StringBuffer();
              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (columns.length() != 0) {
                  columns.append(",");
                }
                columns.append(" ? ");
              }
              values.append(columns.toString());
              values.append(");");

              PreparedStatement statement =
                  connectionTo.prepareStatement(header.toString() + values.toString());
              en = meta2.keySet();
              int i = 0;
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                i++;
                statement.setObject(i, r.get(o));
              }
              statement.execute();
            }
          }

          if (verbose) log.append("Replication finished OK.\r\n");
        } catch (Exception e) {
          log.append("Some error occured: " + e + "\r\n");
          log.append(e.getMessage() + "\r\n");
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      log.append("Error with query = " + e);
      log.append(e.getMessage());
      return;
    } finally {
      try {
        if (connectionFrom != null && !connectionFrom.isClosed()) {
          connectionFrom.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
      try {
        if (connectionTo != null && !connectionTo.isClosed()) {
          connectionTo.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (verbose) log.append("Ended at " + Calendar.getInstance().getTime());
  }
  public LoadItemVariantsBean() {
    productVariants.put("ITM11_VARIANTS_1", "ITM16_PRODUCT_VARIANTS_1");
    productVariants.put("ITM12_VARIANTS_2", "ITM17_PRODUCT_VARIANTS_2");
    productVariants.put("ITM13_VARIANTS_3", "ITM18_PRODUCT_VARIANTS_3");
    productVariants.put("ITM14_VARIANTS_4", "ITM19_PRODUCT_VARIANTS_4");
    productVariants.put("ITM15_VARIANTS_5", "ITM20_PRODUCT_VARIANTS_5");

    variantTypes.put("ITM11_VARIANTS_1", "ITM06_VARIANT_TYPES_1");
    variantTypes.put("ITM12_VARIANTS_2", "ITM07_VARIANT_TYPES_2");
    variantTypes.put("ITM13_VARIANTS_3", "ITM08_VARIANT_TYPES_3");
    variantTypes.put("ITM14_VARIANTS_4", "ITM09_VARIANT_TYPES_4");
    variantTypes.put("ITM15_VARIANTS_5", "ITM10_VARIANT_TYPES_5");

    variantTypeJoins.put("ITM11_VARIANTS_1", "VARIANT_TYPE_ITM06");
    variantTypeJoins.put("ITM12_VARIANTS_2", "VARIANT_TYPE_ITM07");
    variantTypeJoins.put("ITM13_VARIANTS_3", "VARIANT_TYPE_ITM08");
    variantTypeJoins.put("ITM14_VARIANTS_4", "VARIANT_TYPE_ITM09");
    variantTypeJoins.put("ITM15_VARIANTS_5", "VARIANT_TYPE_ITM10");

    variantCodeJoins.put("ITM11_VARIANTS_1", "VARIANT_CODE_ITM11");
    variantCodeJoins.put("ITM12_VARIANTS_2", "VARIANT_CODE_ITM12");
    variantCodeJoins.put("ITM13_VARIANTS_3", "VARIANT_CODE_ITM13");
    variantCodeJoins.put("ITM14_VARIANTS_4", "VARIANT_CODE_ITM14");
    variantCodeJoins.put("ITM15_VARIANTS_5", "VARIANT_CODE_ITM15");
  }
  /** Business logic to execute. */
  public VOListResponse loadItemVariants(GridParams pars, String serverLanguageId, String username)
      throws Throwable {

    PreparedStatement pstmt = null;

    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      String tableName = (String) pars.getOtherGridParams().get(ApplicationConsts.TABLE_NAME);
      ItemPK pk = (ItemPK) pars.getOtherGridParams().get(ApplicationConsts.ITEM_PK);
      String productVariant = (String) productVariants.get(tableName);
      String variantType = (String) variantTypes.get(tableName);
      String variantTypeJoin = (String) variantTypeJoins.get(tableName);
      String variantCodeJoin = (String) variantCodeJoins.get(tableName);

      String sql =
          "select "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".VARIANT_CODE,A.DESCRIPTION,B.DESCRIPTION, "
              + tableName
              + ".PROGRESSIVE_SYS10,"
              + variantType
              + ".PROGRESSIVE_SYS10 "
              + "from "
              + tableName
              + ","
              + variantType
              + ",SYS10_COMPANY_TRANSLATIONS A,SYS10_COMPANY_TRANSLATIONS B "
              + "where "
              + tableName
              + ".COMPANY_CODE_SYS01=? and "
              + tableName
              + ".COMPANY_CODE_SYS01="
              + variantType
              + ".COMPANY_CODE_SYS01 and "
              + tableName
              + "."
              + variantTypeJoin
              + "="
              + variantType
              + ".VARIANT_TYPE and "
              + tableName
              + ".COMPANY_CODE_SYS01=A.COMPANY_CODE_SYS01 and "
              + tableName
              + ".PROGRESSIVE_SYS10=A.PROGRESSIVE and A.LANGUAGE_CODE=? and "
              + variantType
              + ".COMPANY_CODE_SYS01=B.COMPANY_CODE_SYS01 and "
              + variantType
              + ".PROGRESSIVE_SYS10=B.PROGRESSIVE and B.LANGUAGE_CODE=? and "
              + tableName
              + ".ENABLED='Y' and "
              + variantType
              + ".ENABLED='Y' and "
              + // and not "+tableName+"."+variantTypeJoin+"=? and "+
              "not "
              + tableName
              + ".VARIANT_CODE=? "
              + "order by "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".CODE_ORDER";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("variantType", tableName + "." + variantTypeJoin);
      attribute2dbField.put("variantCode", tableName + ".VARIANT_CODE");
      attribute2dbField.put("variantDesc", "A.DESCRIPTION");
      attribute2dbField.put("variantTypeDesc", "B.DESCRIPTION");
      attribute2dbField.put("variantProgressiveSys10", tableName + ".PROGRESSIVE_SYS10");
      attribute2dbField.put("variantTypeProgressiveSys10", variantType + ".PROGRESSIVE_SYS10");

      ArrayList values = new ArrayList();
      values.add(pk.getCompanyCodeSys01ITM01());
      values.add(serverLanguageId);
      values.add(serverLanguageId);
      // values.add(ApplicationConsts.JOLLY);
      values.add(ApplicationConsts.JOLLY);

      // read from ITMxxx table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              ItemVariantVO.class,
              "Y",
              "N",
              null,
              pars,
              50,
              true);

      if (!answer.isError()) {
        java.util.List vos = ((VOListResponse) answer).getRows();
        HashMap map = new HashMap();
        ItemVariantVO vo = null;
        for (int i = 0; i < vos.size(); i++) {
          vo = (ItemVariantVO) vos.get(i);
          vo.setCompanyCodeSys01(pk.getCompanyCodeSys01ITM01());
          vo.setItemCodeItm01(pk.getItemCodeITM01());
          vo.setTableName(tableName);
          map.put(vo.getVariantType() + "." + vo.getVariantCode(), vo);
        }

        pstmt =
            conn.prepareStatement(
                "select "
                    + productVariant
                    + "."
                    + variantTypeJoin
                    + ","
                    + productVariant
                    + "."
                    + variantCodeJoin
                    + " "
                    + "from "
                    + productVariant
                    + " "
                    + "where "
                    + productVariant
                    + ".COMPANY_CODE_SYS01=? and "
                    + productVariant
                    + ".ITEM_CODE_ITM01=? and "
                    + productVariant
                    + ".ENABLED='Y' ");
        pstmt.setString(1, pk.getCompanyCodeSys01ITM01());
        pstmt.setString(2, pk.getItemCodeITM01());
        ResultSet rset = pstmt.executeQuery();

        while (rset.next()) {
          vo = (ItemVariantVO) map.get(rset.getString(1) + "." + rset.getString(2));
          if (vo != null) vo.setSelected(Boolean.TRUE);
        }
        rset.close();
        pstmt.close();
      }

      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;

    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "getItemVariants",
          "Error while fetching item variants list",
          ex);
      throw new Exception(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
示例#16
0
  /** Create data. */
  private void createData() {
    try {
      String[] categories = new String[] {"Hardware", "Software"};
      String[][] subCategories =
          new String[][] {
            {"PC", "Monitor", "Printer"},
            {"O.S.", "IDEs", "Office Appl.", "Database", "Games", "Other SW"}
          };
      String[] agents = new String[] {"Agent 1", "Agent 2", "Agent 3"};
      String[] countries = new String[] {"Italy", "France", "Germany", "Other"};
      String[][] zones =
          new String[][] {
            {"North Italy", "Center Italy", "South Italy"},
            {"Paris", "Outside Paris"},
            {"East", "West"},
            {"Iberica Peninsula", "U.K. & Ireland", "Be.Ne.Lux.", "East Europe"}
          };
      HashMap items = new HashMap();
      items.put("PC", new String[] {"Dell", "HP"});
      items.put("Monitor", new String[] {"LG", "Sony", "Philips"});
      items.put("Printer", new String[] {"HP", "Epson"});
      items.put("O.S.", new String[] {"Windows", "Linux", "Mac"});
      items.put("IDEs", new String[] {"JBuilder", "IBM RAD", "MS Visual Studio .NET"});
      items.put("Office Appl.", new String[] {"MS Office 2007", "Open Office"});
      items.put("Database", new String[] {"Oracle", "MS SQLServer", "Sybase", "IBM DB2"});
      items.put("Games", new String[] {"Need4Speed", "Fifa"});
      items.put("Other SW", new String[] {"Norton AV", "Photoshop"});

      FileOutputStream out = new FileOutputStream("orders.txt");
      String line = null;
      int i = 0;
      Calendar cal = Calendar.getInstance();
      cal.set(cal.YEAR, 2007);
      cal.set(cal.MONTH, 0);
      cal.set(cal.DAY_OF_MONTH, 1);
      cal.set(cal.HOUR_OF_DAY, 0);
      cal.set(cal.MINUTE, 0);
      cal.set(cal.SECOND, 0);
      cal.set(cal.MILLISECOND, 0);
      long t = cal.getTimeInMillis();
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      String date = null;
      int maxRows = 2000000;
      String[] ii = null;
      String[] sub = null;
      String[] z = null;
      do {
        date = sdf.format(new java.util.Date(t));
        for (int k1 = 0; k1 < categories.length; k1++) {
          sub = subCategories[k1];
          for (int k2 = 0; k2 < sub.length; k2++) {
            if (i >= maxRows) break;
            for (int k3 = 0; k3 < countries.length; k3++) {
              z = zones[k3];
              for (int k4 = 0; k4 < z.length; k4++)
                for (int k5 = 0; k5 < agents.length; k5++) {
                  if (i >= maxRows) break;
                  ii = (String[]) items.get(sub[k2]);
                  for (int k6 = 0; k6 < ii.length; k6++) {
                    if (i >= maxRows) break;

                    line =
                        date
                            + ";"
                            + categories[k1]
                            + ";"
                            + sub[k2]
                            + ";"
                            + countries[k3]
                            + ";"
                            + z[k4]
                            + ";"
                            + agents[k5]
                            + ";"
                            + ii[k6]
                            + ";"
                            + new BigDecimal(Math.random() * 10)
                                .setScale(0, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + new BigDecimal(Math.random() * 1000)
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + "\n";
                    out.write(line.getBytes());
                    out.flush();
                    i++;
                  }
                }
            }
          }
        }
        t += 86400000;
      } while (i < maxRows);
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  /**
   * Method to go though the HDFS filesystem in a DFS to find all files
   *
   * <p>fs:FileSystem object from HDFS minDate: Oldest date for files to be backed up maxDate:Newest
   * date for files to be backed up p:Path in HDFS to look for files pathList:Will be filled with
   * all files in p hmTimestamps: hashmap of timestamps for later sorting
   */
  public void checkDir(
      FileSystem fs,
      long minDate,
      long maxDate,
      Path p,
      ArrayList<Path> pathList,
      HashMap<Path, Long> hmTimestamps) {
    long tmpDate;
    FileStatus[] fStat;

    try {
      String sPath = p.toUri().getPath();

      // If this is a directory
      if (fs.getFileStatus(p).isDir()) {
        // ignore certain directories
        if ("dfstmp".equals(p.getName())
            || "tmp".equals(p.getName())
            || "jobtracker".equals(p.getName())
            || sPath.startsWith("/mapred")
            || "ops".equals(p.getName())
            || p.getName().startsWith("_distcp_logs")) {
          return;
        }

        // dump the mkdir and chmod commands for this
        // directory -- skip root directory only
        {
          FileStatus stat = fs.getFileStatus(p);

          if (!sPath.equals("/")) {
            m_wrMkdirs.println("hadoop fs -mkdir " + sPath);
          }

          m_wrChmods.println(
              "hadoop fs -chown " + stat.getOwner() + ":" + stat.getGroup() + " " + sPath);

          Short sh = new Short(stat.getPermission().toShort());
          m_wrChmods.println(
              "hadoop fs -chmod " + Long.toOctalString(sh.longValue()) + " " + sPath);
        }

        fStat = fs.listStatus(p);

        // Do a recursive call to all elements
        for (int i = 0; i < fStat.length; i++) {
          checkDir(fs, minDate, maxDate, fStat[i].getPath(), pathList, hmTimestamps);
        }
      } else {
        // If not a directory then we've found a file

        // ignore crc files
        if (p.getName().endsWith(".crc")) {
          return;
        }

        // ignore other files
        if (sPath.startsWith("/user/oozie/etl/workflows/")) {
          return;
        }

        // try to get the table name from the path. There are
        // various types of tables, from those replicated from
        // another database to regular hive tables to
        // partitioned hive tables.  We use table names to
        // both exclude some from the backup, and for the rest
        // to dump out the schema and partition name.
        if (m_ignoreTables != null && m_ignoreTables.doIgnoreFile(sPath)) {
          m_nIgnoredTables++;

          if (m_nIgnoredTables < 5) {
            System.out.println("Skipping ignore-table file: " + sPath);
          } else if (m_nIgnoredTables == 5) {
            System.out.println("(...not showing other skipped tables...)");
          }
          return;
        }

        FileStatus stat = fs.getFileStatus(p);

        tmpDate = stat.getModificationTime() / 1000;

        // store the chmods/chowns for all files
        m_wrChmods.println(
            "hadoop fs -chown " + stat.getOwner() + ":" + stat.getGroup() + " " + sPath);

        m_wrChmods.println("hadoop fs -chmod " + stat.getPermission().toShort() + " " + sPath);

        // check dates.  is it too young?
        if (tmpDate < minDate) {
          return;
        }

        // is the file too recent?
        if (tmpDate > maxDate) {
          // System.out.println("file too recent: " + sPath);
          return;
        }

        // file timestamp is ok
        pathList.add(p);

        hmTimestamps.put(p, new Long(tmpDate));

        // store info about total bytes neeed to backup
        m_nTotalBytes += fs.getContentSummary(p).getLength();
      }
    } catch (IOException e) {
      System.err.println("ERROR: could not open " + p + ": " + e);

      // System.exit(1) ;
    }
  }
示例#18
0
  static {
    conversionTypes = new HashMap<String, String>();
    conversionTypes.put(DBConstants.DataTypes.CHAR, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.STRING, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.QUERY_STRING, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.VARCHAR, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.NVARCHAR, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.TEXT, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.NUMERIC, "java.math.BigDecimal");
    conversionTypes.put(DBConstants.DataTypes.DECIMAL, "java.math.BigDecimal");
    conversionTypes.put(DBConstants.DataTypes.MONEY, "java.math.BigDecimal");
    conversionTypes.put(DBConstants.DataTypes.SMALLMONEY, "java.math.BigDecimal");
    conversionTypes.put(DBConstants.DataTypes.BIT, "boolean");
    conversionTypes.put(DBConstants.DataTypes.BOOLEAN, "boolean");
    conversionTypes.put(DBConstants.DataTypes.TINYINT, "byte");
    conversionTypes.put(DBConstants.DataTypes.SMALLINT, "short");
    conversionTypes.put(DBConstants.DataTypes.INTEGER, "int");
    conversionTypes.put(DBConstants.DataTypes.BIGINT, "long");
    conversionTypes.put(DBConstants.DataTypes.REAL, "float");
    conversionTypes.put(DBConstants.DataTypes.FLOAT, "double");
    conversionTypes.put(DBConstants.DataTypes.DOUBLE, "double");
    conversionTypes.put(DBConstants.DataTypes.BINARY, "base64Binary"); /* byte[] */
    conversionTypes.put(DBConstants.DataTypes.VARBINARY, "base64Binary"); /* byte[] */
    conversionTypes.put(DBConstants.DataTypes.LONG_VARBINARY, "base64Binary"); /* byte [] */
    conversionTypes.put(DBConstants.DataTypes.IMAGE, "base64Binary"); /* byte[] */
    conversionTypes.put(DBConstants.DataTypes.DATE, "java.sql.Date");
    conversionTypes.put(DBConstants.DataTypes.TIME, "java.sql.Time");
    conversionTypes.put(DBConstants.DataTypes.TIMESTAMP, "java.sql.Timestamp");
    conversionTypes.put(DBConstants.DataTypes.ANYURI, "java.net.URI");
    conversionTypes.put(DBConstants.DataTypes.STRUCT, "java.sql.Struct");

    conversionTypes.put(DBConstants.DataTypes.VARINT, "java.math.BigInteger");
    conversionTypes.put(DBConstants.DataTypes.UUID, "java.lang.String");
    conversionTypes.put(DBConstants.DataTypes.INETADDRESS, "java.lang.String");

    xsdSqlTypeMap = new HashMap<String, String>();
    xsdSqlTypeMap.put("string", DBConstants.DataTypes.STRING);
    xsdSqlTypeMap.put("boolean", DBConstants.DataTypes.BOOLEAN);
    xsdSqlTypeMap.put("int", DBConstants.DataTypes.INTEGER);
    xsdSqlTypeMap.put("integer", DBConstants.DataTypes.INTEGER);
    xsdSqlTypeMap.put("long", DBConstants.DataTypes.LONG);
    xsdSqlTypeMap.put("float", DBConstants.DataTypes.FLOAT);
    xsdSqlTypeMap.put("double", DBConstants.DataTypes.DOUBLE);
    xsdSqlTypeMap.put("decimal", DBConstants.DataTypes.DECIMAL);
    xsdSqlTypeMap.put("dateTime", DBConstants.DataTypes.TIMESTAMP);
    xsdSqlTypeMap.put("time", DBConstants.DataTypes.TIME);
    xsdSqlTypeMap.put("date", DBConstants.DataTypes.DATE);
    xsdSqlTypeMap.put("base64Binary", DBConstants.DataTypes.BINARY);
    xsdSqlTypeMap.put("binary", DBConstants.DataTypes.BINARY);
  }
示例#19
0
  /**
   * Return table categories and table that user has view permission
   *
   * @param request
   * @param subSystemId
   * @return never null, elements are List, containing 2 elements: 1)when first element is
   *     nds.schema.TableCategory, then second will be java.util.List (nds.schema.Table or
   *     nds.schema.WebAction) 2) when first element is nds.schema.WebAction, then second is null
   */
  public List getTableCategories(
      HttpServletRequest request, int subSystemId, boolean includeActions) {
    // Create categories and their tables in hashtable
    TableManager manager = TableManager.getInstance();
    // Iterator tables = manager.getAllTables().iterator();
    // Hashtable categories = new Hashtable(50,20); // key:Integer(category id), values :List of
    // table
    SubSystem ss;
    Integer tableCategoryId;
    Table table;
    WebAction action;
    ArrayList cats = new ArrayList();
    Connection conn = null;
    HashMap webActionEnv = null;
    try {
      UserWebImpl userWeb =
          ((UserWebImpl)
              WebUtils.getSessionContextManager(request.getSession())
                  .getActor(nds.util.WebKeys.USER));
      if (includeActions) {
        conn = QueryEngine.getInstance().getConnection();
        webActionEnv = new HashMap();
        webActionEnv.put("connection", conn);
        webActionEnv.put("httpservletrequest", request);
        webActionEnv.put("userweb", userWeb);
      }
      List categories = manager.getSubSystem(subSystemId).children();
      for (int i = 0; i < categories.size(); i++) {
        Object o = categories.get(i); // TableCategory or WebAction
        if (o instanceof TableCategory) {
          TableCategory tc = (TableCategory) o;
          List children = tc.children();
          ArrayList catschild = new ArrayList();
          for (int j = 0; j < children.size(); j++) {
            if (children.get(j) instanceof Table) {
              table = (Table) children.get(j);
              if (!table.isMenuObject()) {
                continue;
              }
              try {
                WebUtils.checkTableQueryPermission(table.getName(), request);
              } catch (NDSSecurityException e) {
                continue;
              }
              // table is ok for current user to list
              catschild.add(table);
            } else if (children.get(j) instanceof WebAction) {
              if (includeActions) {
                action = (WebAction) children.get(j);
                if (action.canDisplay(webActionEnv)) catschild.add(action);
              }
            } else {
              throw new NDSRuntimeException(
                  "Unsupported element in TableCategory children:" + children.get(j).getClass());
            }
          }
          if (catschild.size() > 0) {
            // show this category
            ArrayList row = new ArrayList();
            row.add(tc);
            row.add(catschild);
            cats.add(row);
          }
        } else if (o instanceof WebAction) {
          if (includeActions && ((WebAction) o).canDisplay(webActionEnv)) {
            ArrayList row = new ArrayList();
            row.add(o);
            row.add(Collections.EMPTY_LIST);
            cats.add(row);
          }
        } else {
          throw new NDSException(
              "Unexpected class in subsystem (id=" + subSystemId + "), class is " + o.getClass());
        }
      }
    } catch (Throwable t) {
      logger.error("Fail to load subsystem tree", t);
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Throwable e) {
      }
    }

    return cats;
  }
示例#20
0
  /**
   * menu action
   *
   * @throws Exception cyl
   * @param request
   * @param tableCategoryId desgin menu list
   * @paqram includeAction if true, will load webactions also
   * @return elements are Table or WebAction and menu list
   */
  public List getChildrenOfTableCategorybymenu(
      HttpServletRequest request, int tableCategoryId, boolean includeAction) throws Exception {
    TableManager manager = TableManager.getInstance();

    WebAction action;
    ArrayList cats = new ArrayList();
    List children = new ArrayList();
    Connection conn = null;
    HashMap webActionEnv = null;
    Table table;
    List al =
        QueryEngine.getInstance()
            .doQueryList(
                "select e.id,e.name from ad_table g,AD_ACCORDION e where g.AD_ACCORDION_id=e.id and g.ad_tablecategory_id="
                    + tableCategoryId
                    + " group by e.id,e.name,e.orderno order by e.orderno asc");
    UserWebImpl userWeb =
        ((UserWebImpl)
            WebUtils.getSessionContextManager(request.getSession())
                .getActor(nds.util.WebKeys.USER));
    TableCategory tc = manager.getTableCategory(tableCategoryId);
    if (tc != null) children = tc.children();

    // ArrayList prow= new ArrayList();
    if (al.size() > 0) {
      for (int i = 0; i < al.size(); i++) {
        List als = (List) al.get(i);
        int ACCORDION = Tools.getInt(als.get(0), -1);
        logger.debug("ACCORDION~~~~~~~~~~" + String.valueOf(ACCORDION));
        ArrayList catschild = new ArrayList();
        String ACCORDION_name = (String) als.get(1);
        try {
          if (includeAction) {
            conn = QueryEngine.getInstance().getConnection();
            webActionEnv = new HashMap();
            webActionEnv.put("connection", conn);
            webActionEnv.put("httpservletrequest", request);
            webActionEnv.put("userweb", userWeb);
          }
          for (int j = 0; j < children.size(); j++) {
            if (children.get(j) instanceof Table) {
              table = (Table) children.get(j);
              // logger.debug("getAccordid~~~~~~~~~~"+String.valueOf(table.getAccordid()));
              if (!table.isMenuObject()) {
                continue;
              } else if (ACCORDION != table.getAccordid()) {
                // logger.debug(String.valueOf(ACCORDION)+"!="+String.valueOf(table.getAccordid()));
                continue;
              }
              try {
                WebUtils.checkTableQueryPermission(table.getName(), request);
              } catch (NDSSecurityException e) {
                continue;
              }
              // table is ok for current user to list
              logger.debug(String.valueOf(ACCORDION) + "&&" + String.valueOf(table.getAccordid()));
              catschild.add(table);
            } else if (children.get(j) instanceof WebAction) {
              if (includeAction) {
                action = (WebAction) children.get(j);
                if (action.canDisplay(webActionEnv) && (action.getAcordionId() == ACCORDION)) {
                  logger.debug("add action" + String.valueOf(ACCORDION));
                  //				        			System.out.print("add action"+String.valueOf(ACCORDION));
                  //				        			System.out.print("action name"+String.valueOf(action.getName()));
                  //				        			System.out.print("ACCORDION name"+String.valueOf(ACCORDION));
                  //				        			System.out.print("action
                  // name"+String.valueOf(action.getAcordionId()));
                  catschild.add(action);
                }
              }
            } else {
              throw new NDSRuntimeException(
                  "Unsupported element in TableCategory children:" + children.get(j).getClass());
            }
          }
        } catch (Throwable t) {
          logger.error("Fail to load subsystem tree", t);
        } finally {
          try {
            if (conn != null) conn.close();
          } catch (Throwable e) {
          }
        }
        if (catschild.size() > 0) {
          // show this category
          ArrayList row = new ArrayList();
          row.add(ACCORDION_name);
          row.add(catschild);
          cats.add(row);
        }
      }
      return cats;
    } else {
      ArrayList catschild1 = new ArrayList();
      try {
        if (includeAction) {
          conn = QueryEngine.getInstance().getConnection();
          webActionEnv = new HashMap();
          webActionEnv.put("connection", conn);
          webActionEnv.put("httpservletrequest", request);
          webActionEnv.put("userweb", userWeb);
        }
        for (int j = 0; j < children.size(); j++) {
          if (children.get(j) instanceof Table) {
            table = (Table) children.get(j);
            if (!table.isMenuObject()) {
              continue;
            }
            try {
              WebUtils.checkTableQueryPermission(table.getName(), request);
            } catch (NDSSecurityException e) {
              continue;
            }
            // table is ok for current user to list
            catschild1.add(table);
          } else if (children.get(j) instanceof WebAction) {
            if (includeAction) {
              action = (WebAction) children.get(j);
              if (action.canDisplay(webActionEnv)) catschild1.add(action);
            }
          } else {
            throw new NDSRuntimeException(
                "Unsupported element in TableCategory children:" + children.get(j).getClass());
          }
        }
      } catch (Throwable t) {
        logger.error("Fail to load subsystem tree", t);
      } finally {
        try {
          if (conn != null) conn.close();
        } catch (Throwable e) {
        }
      }
      if (catschild1.size() > 0) {
        // show this category
        ArrayList row = new ArrayList();
        row.add(tc.getName());
        row.add(catschild1);
        cats.add(row);
      }
    }
    return cats;
  }
示例#21
0
  /** Business logic to execute. */
  public VOListResponse updateCharges(
      ArrayList oldVOs,
      ArrayList newVOs,
      String serverLanguageId,
      String username,
      ArrayList customizedFields)
      throws Throwable {
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      ChargeVO oldVO = null;
      ChargeVO newVO = null;
      Response res = null;

      for (int i = 0; i < oldVOs.size(); i++) {
        oldVO = (ChargeVO) oldVOs.get(i);
        newVO = (ChargeVO) newVOs.get(i);

        // update SYS10 table...
        TranslationUtils.updateTranslation(
            oldVO.getDescriptionSYS10(),
            newVO.getDescriptionSYS10(),
            newVO.getProgressiveSys10SAL06(),
            serverLanguageId,
            conn);

        HashSet pkAttrs = new HashSet();
        pkAttrs.add("companyCodeSys01SAL06");
        pkAttrs.add("chargeCodeSAL06");

        HashMap attr2dbFields = new HashMap();
        attr2dbFields.put("companyCodeSys01SAL06", "COMPANY_CODE_SYS01");
        attr2dbFields.put("chargeCodeSAL06", "CHARGE_CODE");
        attr2dbFields.put("progressiveSys10SAL06", "PROGRESSIVE_SYS10");
        attr2dbFields.put("valueSAL06", "VALUE");
        attr2dbFields.put("percSAL06", "PERC");
        attr2dbFields.put("vatCodeReg01SAL06", "VAT_CODE_REG01");
        attr2dbFields.put("currencyCodeReg03SAL06", "CURRENCY_CODE_REG03");

        res =
            new CustomizeQueryUtil()
                .updateTable(
                    conn,
                    new UserSessionParameters(username),
                    pkAttrs,
                    oldVO,
                    newVO,
                    "SAL06_CHARGES",
                    attr2dbFields,
                    "Y",
                    "N",
                    null,
                    true,
                    customizedFields);
        if (res.isError()) {
          throw new Exception(res.getErrorMessage());
        }
      }

      return new VOListResponse(newVOs, false, newVOs.size());
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while updating existing charges",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      Response responseVO =
          bean.insertItem(
              conn,
              (JournalHeaderVO) inputPar,
              userSessionPars,
              request,
              response,
              userSession,
              context);
      if (responseVO.isError()) {
        conn.rollback();
        return responseVO;
      }

      if (inputPar instanceof JournalHeaderWithVatVO) {
        JournalHeaderWithVatVO vo = (JournalHeaderWithVatVO) inputPar;

        // insert vat rows in the specified vat register...
        Response regRes =
            vatRegisterAction.insertVatRows(
                conn, vo.getVats(), userSessionPars, request, response, userSession, context);
        if (regRes.isError()) {
          conn.rollback();
          return regRes;
        }

        // retrieve payment instalments...
        Response payRes =
            payAction.executeCommand(
                new LookupValidationParams(vo.getPaymentCodeREG10(), new HashMap()),
                userSessionPars,
                request,
                response,
                userSession,
                context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        PaymentVO payVO = (PaymentVO) ((VOListResponse) payRes).getRows().get(0);
        GridParams gridParams = new GridParams();
        gridParams
            .getOtherGridParams()
            .put(ApplicationConsts.PAYMENT_CODE_REG10, vo.getPaymentCodeREG10());
        payRes =
            paysAction.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        java.util.List rows = ((VOListResponse) payRes).getRows();

        // create expirations in DOC19 ONLY if:
        // - there are more than one instalment OR
        // - there is only one instalment and this instalment has more than 0 instalment days
        if (rows.size() > 1
            || (rows.size() == 1
                && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() > 0)) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          PaymentInstalmentVO inVO = null;
          pstmt =
              conn.prepareStatement(
                  "insert into DOC19_EXPIRATIONS(COMPANY_CODE_SYS01,DOC_TYPE,DOC_YEAR,DOC_NUMBER,DOC_SEQUENCE,PROGRESSIVE,DOC_DATE,EXPIRATION_DATE,NAME_1,NAME_2,VALUE,PAYED,DESCRIPTION,CUSTOMER_SUPPLIER_CODE,PROGRESSIVE_REG04,CURRENCY_CODE_REG03) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
          long startTime = vo.getItemDateACC05().getTime(); // item date...
          if (payVO.getStartDayREG10().equals(ApplicationConsts.START_DAY_END_MONTH)) {
            Calendar cal = Calendar.getInstance();
            if (cal.get(cal.MONTH) == 10
                || cal.get(cal.MONTH) == 3
                || cal.get(cal.MONTH) == 5
                || cal.get(cal.MONTH) == 8) cal.set(cal.DAY_OF_MONTH, 30);
            else if (cal.get(cal.MONTH) == 1) {
              if (cal.get(cal.YEAR) % 4 == 0) cal.set(cal.DAY_OF_MONTH, 29);
              else cal.set(cal.DAY_OF_MONTH, 28);
            } else cal.set(cal.DAY_OF_MONTH, 31);
            startTime = cal.getTime().getTime();
          }
          BigDecimal amount = null;

          for (int i = 0; i < rows.size(); i++) {
            inVO = (PaymentInstalmentVO) rows.get(i);
            pstmt.setString(1, vo.getCompanyCodeSys01ACC05());
            pstmt.setString(2, vo.getDocTypeDOC19());
            pstmt.setBigDecimal(3, vo.getItemYearACC05());
            pstmt.setBigDecimal(4, null);
            pstmt.setBigDecimal(5, vo.getDocSequenceDOC19());
            pstmt.setBigDecimal(
                6,
                ProgressiveUtils.getConsecutiveProgressive(
                    "DOC19_EXPIRATIONS", "PROGRESSIVE", conn));
            pstmt.setDate(7, vo.getItemDateACC05());
            pstmt.setDate(
                8,
                new java.sql.Date(
                    startTime
                        + inVO.getInstalmentDaysREG17().longValue()
                            * 86400
                            * 1000)); // expiration date
            pstmt.setString(9, vo.getName_1REG04());
            pstmt.setString(10, vo.getName_2REG04());
            amount =
                vo.getTotalValue()
                    .multiply(inVO.getPercentageREG17())
                    .divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP)
                    .setScale(vo.getTotalValue().scale(), BigDecimal.ROUND_HALF_UP); // value

            pstmt.setBigDecimal(11, amount);
            pstmt.setString(12, "N");

            if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE))
              pstmt.setString(
                  13,
                  resources.getResource("sale generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            else
              pstmt.setString(
                  13,
                  resources.getResource("purchase generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            pstmt.setString(14, vo.getCustomerCodeSAL07());
            pstmt.setBigDecimal(15, vo.getProgressiveREG04());
            pstmt.setString(16, vo.getCurrencyCodeREG01());
            pstmt.execute();
          }
          pstmt.close();
        }

        // create an item registration for proceeds, according to expiration settings (e.g. retail
        // selling):
        // there must be only one instalment and this instalment has 0 instalment days
        if (rows.size() == 1
            && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() == 0) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          HashMap map = new HashMap();
          map.put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01ACC05());
          map.put(ApplicationConsts.PARAM_CODE, ApplicationConsts.CASE_ACCOUNT);
          Response res =
              userParamAction.executeCommand(
                  map, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          String caseAccountCode = ((VOResponse) res).getVo().toString();

          JournalHeaderVO jhVO = new JournalHeaderVO();
          jhVO.setCompanyCodeSys01ACC05(vo.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jhVO.setDescriptionACC05(
                resources.getResource("sale generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("customer")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_INVOICE_PROCEEDS);
          } else {
            jhVO.setDescriptionACC05(
                resources.getResource("purchase generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("supplier")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_PURCHASE_INVOICE_PAYED);
          }

          jhVO.setItemDateACC05(new java.sql.Date(System.currentTimeMillis()));
          jhVO.setItemYearACC05(new BigDecimal(Calendar.getInstance().get(Calendar.YEAR)));

          JournalRowVO jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setAccountCodeAcc02ACC06(vo.getCreditAccountCodeAcc02SAL07());
            jrVO.setAccountCodeACC06(vo.getCustomerCodeSAL07());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_CUSTOMER);
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setAccountCodeAcc02ACC06(vo.getDebitAccountCodeAcc02PUR01());
            jrVO.setAccountCodeACC06(vo.getSupplierCodePUR01());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_SUPPLIER);
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);

          jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          jrVO.setAccountCodeAcc02ACC06(caseAccountCode);
          jrVO.setAccountCodeACC06(caseAccountCode);
          jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_ACCOUNT);
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);
          Response proceedsRes =
              bean.insertItem(conn, jhVO, userSessionPars, request, response, userSession, context);
          if (proceedsRes.isError()) {
            conn.rollback();
            return proceedsRes;
          }
        }
      }

      Response answer = responseVO;

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting a new item in the journal",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }