/**
   * Returns the messages which ID starts with the given ID
   *
   * @param ID message ID
   * @return text and ID of the message
   */
  public synchronized Hashtable getMessagesWithId(String ID) {
    //        System.out.println("getMessagesWithId:"+ID);

    Hashtable res = new Hashtable();
    Enumeration enm = dict.keys();
    while (enm.hasMoreElements()) {
      String key = "" + enm.nextElement();
      if (key.startsWith(ID)) res.put(key, dict.get(key));
    }
    if (res.size() == 0) {
      Connection connection = null;
      try {
        connection = getMessageDBConnection();
        PreparedStatement proc =
            connection.prepareStatement("SELECT tkey,txt FROM messages_texts WHERE tkey like ?");
        proc.setString(1, ID + "%");
        ResultSet rs = proc.executeQuery();
        while (rs.next()) {
          res.put(rs.getString(1), rs.getString(2));
        }
        connection.close();
      } catch (Exception e) {
        /*not message connection*/
        e.printStackTrace();
      }
    }

    return res;
  }
Esempio n. 2
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
  /**
   * INTERNAL: Build and return the appropriate field value for the specified set of nested rows.
   * The database better be expecting an ARRAY. It looks like we can ignore inheritance here....
   */
  public Object buildFieldValueFromNestedRows(
      Vector nestedRows, String structureName, AbstractSession session) throws DatabaseException {
    Object[] fields = new Object[nestedRows.size()];
    java.sql.Connection connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
    boolean reconnected = false;

    try {
      if (connection == null) {
        ((DatabaseAccessor) session.getAccessor()).incrementCallCount(session);
        reconnected = true;
        connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
      }

      int i = 0;
      for (Enumeration stream = nestedRows.elements(); stream.hasMoreElements(); ) {
        AbstractRecord nestedRow = (AbstractRecord) stream.nextElement();
        fields[i++] = this.buildStructureFromRow(nestedRow, session, connection);
      }

      return session.getPlatform().createArray(structureName, fields, session, connection);
    } catch (java.sql.SQLException exception) {
      throw DatabaseException.sqlException(exception, session, false);
    } finally {
      if (reconnected) {
        ((DatabaseAccessor) session.getAccessor()).decrementCallCount();
      }
    }
  }
Esempio n. 4
0
    public NSArray statementsToDropPrimaryKeyConstraintsOnEntityGroups(
        NSArray entityGroups,
        EOSchemaSynchronizationModelChanges changes,
        EOSchemaGenerationOptions options) {
      if (entityGroups == null) return NSArray.EmptyArray;
      if (changes == null) changes = newChanges();

      NSMutableArray expressions = new NSMutableArray();
      for (Enumeration enumerator = entityGroups.objectEnumerator();
          enumerator.hasMoreElements(); ) {
        NSArray entities = (NSArray) enumerator.nextElement();
        EOEntity _last =
            (EOEntity)
                entities.lastObject(); // only need entity to get the table name for the group
        String nameInObjectStore =
            _nameInObjectStoreForEntityGroupWithChangeDictionary(
                entities, changes.changesForTableNamed(_last.externalName()));
        if ((nameInObjectStore != null) && (!"".equals(nameInObjectStore))) {
          expressions.addObject(
              this._expressionForString(
                  "delete from _SYS_RELATIONSHIP where source_table = '"
                      + nameInObjectStore
                      + "' or dest_table = '"
                      + nameInObjectStore
                      + "'"));
        }
      }
      return expressions.immutableClone();
    }
Esempio n. 5
0
    public void prepareUpdateExpressionWithRow(NSDictionary row, EOQualifier qualifier) {
      EOAttribute attribute;
      Object value;
      for (Enumeration enumeration = row.keyEnumerator();
          enumeration.hasMoreElements();
          addUpdateListAttribute(attribute, value)) {
        String attributeName = (String) enumeration.nextElement();
        attribute = this.entity().anyAttributeNamed(attributeName);
        if (attribute == null)
          throw new IllegalStateException(
              "prepareUpdateExpressionWithRow: row argument contains key '"
                  + attributeName
                  + "' which does not have corresponding attribute on entity '"
                  + this.entity().name()
                  + "'");
        value = row.objectForKey(attributeName);
      }

      _whereClauseString =
          EOQualifierSQLGeneration.Support._sqlStringForSQLExpression(qualifier, this);
      String tableList = tableListWithRootEntity(_rootEntityForExpression());
      _statement =
          assembleUpdateStatementWithRow(
              row, qualifier, tableList, new String(_listString), _whereClauseString);
    }
 /**
  * Returns the messages which ID starts with the given ID
  *
  * @param ID message ID
  * @return text of the message
  */
 public Vector getMessages(String ID) {
   Vector res = new Vector();
   Enumeration enm = dict.keys();
   while (enm.hasMoreElements()) {
     String key = "" + enm.nextElement();
     if (key.startsWith(ID)) {
       res.add(dict.get(key));
     }
   }
   return res;
 }
Esempio n. 7
0
 public void afficherPopo() {
   Enumeration enumPopo = tabPopoEnCours.elements();
   if (!enumPopo.hasMoreElements()) {
     System.out.println("      *    - Aucune                        *");
   }
   while (enumPopo.hasMoreElements()) {
     objet popo = (objet) enumPopo.nextElement();
     System.out.println(
         "      *    - " + popo.idObjet() + " : " + popo.duree() + " tour(s) restant(s)*");
   }
 }
Esempio n. 8
0
 public void verifTourPopo() {
   Enumeration enumPopo = tabPopoEnCours.elements();
   while (enumPopo.hasMoreElements()) {
     objet popo = (objet) enumPopo.nextElement();
     popo.decrementerTourPopo();
     System.out.println(popo.duree() + " tour(s) restants pour la potion " + popo.idObjet());
     if (popo.duree() == 0) {
       this.supprimerPopo(popo);
     }
   }
 }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Esempio n. 10
0
 public void reinitialiserTroll() {
   String idObjet;
   try {
     ResultSet rset = stmt.executeQuery("select idObjet from equipement where idTroll=" + idTroll);
     while (rset.next()) {
       idObjet = rset.getString("idObjet");
       this.desequiperObjet(idObjet);
       // int res = stmt.executeUpdate("delete from equipement where idObjet=idObjet");
     }
   } catch (SQLException E) {
     System.err.println("SQLException: " + E.getMessage());
     System.err.println("SQLState:     " + E.getSQLState());
   }
   Enumeration enumPopo = tabPopoEnCours.elements();
   while (enumPopo.hasMoreElements()) {
     objet popo = (objet) enumPopo.nextElement();
     popo.supprimerTourPopo();
     this.verifTourPopo();
   }
 }
Esempio n. 11
0
 public NSArray statementsToImplementPrimaryKeyConstraintsOnEntityGroups(
     NSArray entityGroups,
     EOSchemaSynchronizationModelChanges changes,
     EOSchemaGenerationOptions options) {
   NSArray primaryKeyExpressions =
       this.primaryKeyConstraintStatementsForEntityGroups(entityGroups);
   NSMutableArray createStatements = new NSMutableArray();
   NSMutableArray otherStatements = new NSMutableArray();
   for (Enumeration enumerator = primaryKeyExpressions.objectEnumerator();
       enumerator.hasMoreElements(); ) {
     EOSQLExpression expression = (EOSQLExpression) enumerator.nextElement();
     String statement = expression.statement();
     if (statement.startsWith("create")) {
       createStatements.addObject(expression);
     } else if (!statement.startsWith("delete from _SYS_RELATIONSHIP")) {
       otherStatements.addObject(expression);
     }
   }
   return createStatements.arrayByAddingObjectsFromArray(otherStatements);
 }
Esempio n. 12
0
 public String toString() {
   String roles_image = "";
   for (Enumeration e = myRoles.elements(); e.hasMoreElements(); ) {
     roles_image = roles_image + "/" + (String) e.nextElement();
   }
   String relations_image = "";
   for (Enumeration e = mySupportRelations.elements(); e.hasMoreElements(); ) {
     relations_image = relations_image + "/" + (SupportRelation) e.nextElement();
   }
   return "#<Organization "
       + myName
       + " "
       + myUIC
       + " "
       + myUTC
       + " "
       + mySRC
       + " "
       + mySuperior
       + " "
       + myEchelon
       + " "
       + myAgency
       + " "
       + myService
       + " "
       + myNomenclature
       + " "
       + myPrototype
       + " "
       + roles_image
       + " "
       + relations_image
       + ">";
 }
Esempio n. 13
0
  // Write <Cluster>.ini file
  // Given Hashtable mapping cluster name to Vector of plugin names
  // <Cluster>.ini File format:
  // [ Cluster ]
  // uic = <Agentname>
  // cloned = false
  // [ Plugins ]
  // plugin = <pluginname>
  // ...
  //
  private void dumpClusterInfo(Hashtable all_clusters, String path) throws IOException {
    // Dump hashtable of clusters
    for (Enumeration e = all_clusters.keys(); e.hasMoreElements(); ) {
      String cluster_name = (String) e.nextElement();
      PrintWriter cluster_file;

      try {
        if (path != null) {
          cluster_file = createPrintWriter(path + File.separator + cluster_name + ".ini");
        } else {
          cluster_file = createPrintWriter(cluster_name + ".ini");
        }

        cluster_file.println("[ Cluster ]");
        cluster_file.println("uic = " + cluster_name);
        cluster_file.println("cloned = false\n");
        cluster_file.println("[ Plugins ]");
        Vector plugins = (Vector) (all_clusters.get(cluster_name));
        for (Enumeration p = plugins.elements(); p.hasMoreElements(); ) {
          String plugin = (String) (p.nextElement());
          cluster_file.println("plugin = " + plugin);
        }
        cluster_file.close();
      } catch (IOException exc) {
        System.out.println("IOException:  " + exc);
        System.exit(-1);
      }
    }
  }
Esempio n. 14
0
  // Generate files for given node
  // Given Hashtable mapping node_name to Vector of cluster names
  // <Node>.ini File format:
  // [ Clusters ]
  // cluster = <clustername>
  // ...
  private void dumpNodeInfo(Hashtable all_nodes, String path) throws IOException {
    PrintWriter node_file;
    // Iterate over hashtable of nodes and write <Node>.ini file for each
    for (Enumeration e = all_nodes.keys(); e.hasMoreElements(); ) {
      String node_name = (String) (e.nextElement());

      try {
        if (path != null) {
          node_file = createPrintWriter(path + File.separator + node_name + ".ini");
        } else {
          node_file = createPrintWriter(node_name + ".ini");
        }
        node_file.println("[ Clusters ]");
        Vector clusters = (Vector) all_nodes.get(node_name);
        for (Enumeration c = clusters.elements(); c.hasMoreElements(); ) {
          String cluster_name = (String) (c.nextElement());
          node_file.println("cluster = " + cluster_name);
        }
        node_file.close();
      } catch (IOException exc) {
        System.out.println("IOException:  " + exc);
        System.exit(-1);
      }
    }
  }
Esempio n. 15
0
  protected String[] listJarResources(URL dirURL, FilenameFilter filter)
      throws IOException, URISyntaxException {
    String[] files = new String[0];
    String spec = dirURL.getFile();
    int seperator = spec.indexOf("!/");

    if (seperator == -1) {
      return files;
    }

    URL jarFileURL = new URL(spec.substring(0, seperator));
    Set<String> filesSet = new HashSet<>();

    try (JarFile jarFile = new JarFile(jarFileURL.toURI().getPath())) {
      Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        if (entry.isDirectory()) {
          continue;
        }

        String entryName = entry.getName();

        if (entryName.indexOf(schemaPath) > -1 && filter.accept(null, entryName)) {
          filesSet.add(entryName);
        }
      }
    }

    if (!filesSet.isEmpty()) {
      files = new String[filesSet.size()];
      files = filesSet.toArray(files);
    }

    return files;
  }
Esempio n. 16
0
    public void prepareInsertExpressionWithRow(NSDictionary row) {
      EOAttribute attribute;
      Object value;
      for (Enumeration enumeration = row.keyEnumerator();
          enumeration.hasMoreElements();
          this.addInsertListAttribute(attribute, value)) {
        String attributeName = (String) enumeration.nextElement();
        attribute = this.entity().anyAttributeNamed(attributeName);
        if (attribute == null)
          throw new IllegalStateException(
              "prepareInsertExpressionWithRow: row argument contains key '"
                  + attributeName
                  + "' which does not have corresponding attribute on entity '"
                  + this.entity().name()
                  + "'");
        value = row.objectForKey(attributeName);
      }

      String tableList = tableListWithRootEntity(_rootEntityForExpression());
      _statement =
          this.assembleInsertStatementWithRow(
              row, tableList, new String(_listString), new String(_valueListString));
    }
Esempio n. 17
0
  /**
   * Location where you can add commandline properties to the connection The Super class will call
   * this function before creating the connection
   *
   * @param cmdLine command line operations
   * @see CommandLine
   */
  public void addMoreProps(CommandLine cmdLine) {
    Enumeration extras = cmdLine._extraArgs.elements();
    Enumeration options = cmdLine._extraOptions.elements();
    while (extras.hasMoreElements()) {

      String option = (String) extras.nextElement();
      String value = (String) options.nextElement();
      String loaderURL = null;
      error("Extra options= " + option + " " + value + "\n");

      if (option.equals(_extraCmdOption) && loaderURL == null) {
        loaderURL = value;
        Properties props = (Properties) _cmdline._props.clone();
        _loader = _sybDriver.getClassLoader(loaderURL, props);
        if (_loader == null) {
          error("Could not get a CLASS_LOADER");
          break;
        }
        _cmdline._props.put("CLASS_LOADER", _loader);
        _gotClassLoader = true;
        break;
      }
    }
  }
Esempio n. 18
0
  // Print <Cluster>-prototype-ini.dat file
  // File format:
  // [Prototype] CombatOrganization|CivilanOrganization
  // [UniqueId] "UTC/CombatOrg"
  // [UIC] "UIC/<OrganizationName>
  // [Relationship]
  // Superior  <Superior> ""
  // Support   <Supported> <Role>
  // [TypeIdentificationPG]
  // TypeIdentification String "UTC/RTOrg"
  // Nomenclature String <Nomenclature>
  // AlternateTypeIdentification String "SRC/<SRC>"
  // [ClusterPG]
  // MessageAddress String <OrganizationName>
  // [OrganizationPG]
  // Roles Collection<Role> <Role>
  // [MilitaryOrgPG]
  // UIC String <UIC>
  // Echelon String <Echelon>
  // UTC String <UTC>
  // SRC String <SRC>
  //
  private void dumpOrganizationInfo(Hashtable all_organizations, String path) throws IOException {

    Hashtable supportedOrgRoles = null;

    for (Enumeration e = all_organizations.keys(); e.hasMoreElements(); ) {
      supportedOrgRoles = new Hashtable();
      String org_name = (String) e.nextElement();
      OrganizationData org_data = (OrganizationData) all_organizations.get(org_name);
      PrintWriter org_file;

      try {
        if (path != null) {
          org_file = createPrintWriter(path + File.separator + org_name + "-prototype-ini.dat");
        } else {
          org_file = createPrintWriter(org_name + "-prototype-ini.dat");
        }
        org_file.println(
            "[Prototype] "
                + (org_data.isCivilan() ? "CivilianOrganization" : "MilitaryOrganization"));
        org_file.println("\n[UniqueId] " + '"' + "UTC/CombatOrg" + '"');
        org_file.println("\n[UIC] " + '"' + "UIC/" + org_name + '"');

        // Write out Superior/Support Relationships
        org_file.println("\n[Relationship]");
        if (org_data.mySuperior != null) {
          org_file.println("Superior " + '"' + org_data.mySuperior + '"' + " " + '"' + '"');
        }

        for (Enumeration rels = org_data.mySupportRelations.elements(); rels.hasMoreElements(); ) {
          SupportRelation suprel = (SupportRelation) rels.nextElement();

          if (!supportedOrgRoles.containsKey(suprel.mySupportedOrganization)) {
            supportedOrgRoles.put(suprel.mySupportedOrganization, suprel.myRole);
          } else {
            String role = (String) supportedOrgRoles.get(suprel.mySupportedOrganization);
            role = role + ", " + suprel.myRole;
            supportedOrgRoles.put(suprel.mySupportedOrganization, role);
          }
        }

        for (Enumeration roles = supportedOrgRoles.keys(); roles.hasMoreElements(); ) {
          String supportedOrg = (String) roles.nextElement();
          String role = (String) supportedOrgRoles.get(supportedOrg);
          org_file.println("Supporting " + '"' + supportedOrg + '"' + " " + '"' + role + '"');
        }

        // Print TypeIdentificationPG fields
        org_file.println("\n[TypeIdentificationPG]");
        org_file.println("TypeIdentification String " + '"' + "UTC/RTOrg" + '"');
        org_file.println("Nomenclature String " + '"' + org_data.myNomenclature + '"');
        org_file.println(
            "AlternateTypeIdentification String " + '"' + "SRC/" + org_data.mySRC + '"');

        // Print ClusterPG info
        org_file.println("\n[ClusterPG]");
        org_file.println("MessageAddress String " + '"' + org_name + '"');

        // Print OrganizationPG (Roles) info
        org_file.println("\n[OrganizationPG]");
        org_file.print("Roles Collection<Role> " + '"');
        boolean is_first = true;
        for (Enumeration roles = org_data.myRoles.elements(); roles.hasMoreElements(); ) {
          String role = (String) roles.nextElement();
          if (!is_first) {
            org_file.print(", ");
          }
          org_file.print(role);
          is_first = false;
        }
        org_file.println('"');

        // Print MilitaryOrgPG info
        org_file.println("\n[MilitaryOrgPG]");
        org_file.println("UIC String " + '"' + org_data.myUIC + '"');
        if (org_data.myEchelon.intValue() != -1) {
          org_file.println("Echelon String " + '"' + org_data.myEchelon.intValue() + '"');
        } else {
          org_file.println("Echelon String " + '"' + '"');
        }
        org_file.println("UTC String " + '"' + org_data.myUTC + '"');
        org_file.println("SRC String " + '"' + org_data.mySRC + '"');
        if (org_data.myIsReserve == true) {
          org_file.println("IsReserve       boolean     true");
        } else {
          org_file.println("IsReserve       boolean     false");
        }

        // Print HomeLocationPG info under Military Org PG
        org_file.println(
            "HomeLocation     GeolocLocation   "
                + "\"GeolocCode="
                + org_data.myHomeGeoLoc
                + ", InstallationTypeCode="
                + org_data.myHomeInstallCode
                + ", CountryStateCode="
                + org_data.myHomeCSCode
                + ", CountryStateName="
                + org_data.myHomeCSName
                + ", IcaoCode="
                + org_data.myHomeICAOCode
                + ", Name="
                + org_data.myHomeLocation
                + ", Latitude=Latitude "
                + org_data.myHomeLatitude
                + "degrees, Longitude=Longitude "
                + org_data.myHomeLongitude
                + "degrees\"");

        /*
        // Print AssignmentPG info
        org_file.println("\n[AssignmentPG]");
        org_file.println("GeolocCode            String    "+'"'+org_data.myAssignedGeoLoc+'"');
        org_file.println("InstallationTypeCode  String    "+'"'+org_data.myAssignedInstallCode+'"');
        org_file.println("CountryStateCode      String    "+'"'+org_data.myAssignedCSCode+'"');
        org_file.println("CountryStateName      String    "+'"'+org_data.myAssignedCSName+'"');
        org_file.println("IcaoCode              String    "+'"'+org_data.myAssignedICAOCode+'"');
        */
        // Print CSSCapabilities info
        if (org_data.myCSSCapabilities != null) {
          is_first = true;
          org_file.println("\n[CSSCapabilityPG]");
          org_file.print("Capabilities Collection<CSSCapability> " + '"');
          for (Enumeration eCap = org_data.myCSSCapabilities.elements(); eCap.hasMoreElements(); ) {
            CSSCapabilities cssCap = (CSSCapabilities) eCap.nextElement();
            if (!is_first) {
              org_file.print(", ");
            }
            org_file.print(cssCap.capability);
            org_file.print(" " + cssCap.qty);
            if (!cssCap.period.equals("")) {
              org_file.print(" Duration=" + cssCap.period);
            }
            is_first = false;
          }
          org_file.println('"');
        }

        org_file.close();
      } catch (IOException exc) {
        System.out.println("IOException:  " + exc);
        System.exit(-1);
      }
    }
  }
Esempio n. 19
0
  /**
   * Sets the TabularData to the AaplicationTable
   *
   * @param data The TabularData to be set to the AaplicationTable
   */
  public void setAlarmTable(TabularData data) throws Exception {
    AgentException ae = null;

    for (Enumeration e = data.enumerate(); e.hasMoreElements(); ) {
      Object[] index = (Object[]) e.nextElement();
      CompositeData comp = data.getRow(index);

      if (table != null)
        entry =
            (AlarmEntry)
                Utilities.getEntryFromCompositeData(table, comp, indexNames, instrClassName);
      else if (vec != null)
        entry =
            (AlarmEntry) Utilities.getEntryFromCompositeData(vec, comp, indexNames, instrClassName);

      if (comp.getOperationType().equals(CompositeData.CREATED)) { // create new entry

        if (entry != null)
          throw new AgentException("Row already exist", CommonUtils.ROWCREATIONFAILED); // no i18n
        entry = new AlarmEntry();

        if (table != null) table.put(index, entry);
        else if (vec != null) vec.addElement(entry);
        for (Enumeration ce = comp.enumerate(); ce.hasMoreElements(); ) {
          String key = (String) ce.nextElement();
          try {
            Utilities.setField(entry, instrClassName, key, comp.getDataItem(key));
          } catch (AgentException aexp) {
            ae = aexp;
          }
        }
      } else if (comp.getOperationType().equals(CompositeData.DELETED)) {

        if (table != null) {
          for (Enumeration en = table.keys(); en.hasMoreElements(); ) {
            Object keyObject = en.nextElement();
            if (entry.equals(table.get(keyObject))) table.remove(keyObject);
          }
        } else if (vec != null)
          if (!vec.removeElement(entry))
            throw new AgentException("Invalid Index", CommonUtils.INVALIDINDEX); // no i18n
        data.deleteRow(index);
      } else if (comp.getOperationType().equals(CompositeData.MODIFIED)) {

        for (Enumeration ce = comp.enumerate(); ce.hasMoreElements(); ) {
          String key = (String) ce.nextElement();
          if (!comp.isModified(key)) continue;
          try {

            Utilities.setField(entry, instrClassName, key, comp.getDataItem(key));
          } catch (AgentException aexp) {
            ae = aexp;
          }
        }
      }

      comp.setOperationType(CompositeData.NOCHANGES);
    }

    if (ae != null) throw ae;
  }
  /**
   * Check if components required by specified products are available.
   *
   * @param products list of ProdOrderProductVO objects
   * @params compAltComps collection of <component item code,HashSet of alternative component item
   *     codes>; filled by this method (and given back by reference)
   * @return VOListResponse of ProdOrderComponentVO objects
   */
  public final Response checkComponentsAvailability(
      Connection conn,
      Hashtable compAltComps,
      ArrayList products,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
    try {

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

      if (products.size() == 0) {
        return new VOListResponse(new ArrayList(), false, 0);
      }

      // fill in comps hashtable with the collection of required components...
      ItemPK pk = null;
      ProdOrderProductVO prodVO = null;
      ArrayList components = null;
      MaterialVO compVO = null;
      Response res = null;
      ProdOrderComponentVO componentVO = null;
      Hashtable comps =
          new Hashtable(); // collection of <component item code,ProdOrderComponentVO object>
      for (int i = 0; i < products.size(); i++) {
        // retrieve bill of materials for each product...
        prodVO = (ProdOrderProductVO) products.get(i);
        pk = new ItemPK(prodVO.getCompanyCodeSys01DOC23(), prodVO.getItemCodeItm01DOC23());
        res =
            bean.getBillOfMaterials(
                conn, pk, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          return res;
        }

        // extract components only (leaf nodes)...
        components =
            getComponents(
                (DefaultMutableTreeNode) ((TreeModel) ((VOResponse) res).getVo()).getRoot());
        for (int j = 0; j < components.size(); j++) {
          compVO = (MaterialVO) components.get(j);
          componentVO = (ProdOrderComponentVO) comps.get(compVO.getItemCodeItm01ITM03());
          if (componentVO == null) {
            componentVO = new ProdOrderComponentVO();
            comps.put(compVO.getItemCodeItm01ITM03(), componentVO);
            componentVO.setAvailableQty(new BigDecimal(0));
            componentVO.setCompanyCodeSys01DOC24(compVO.getCompanyCodeSys01ITM03());
            componentVO.setDescriptionSYS10(compVO.getDescriptionSYS10());
            componentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
            componentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
            componentVO.setItemCodeItm01DOC24(compVO.getItemCodeItm01ITM03());
            componentVO.setMinSellingQtyUmCodeReg02ITM01(compVO.getMinSellingQtyUmCodeReg02ITM01());
            componentVO.setQtyDOC24(new BigDecimal(0));
          }
          componentVO.setQtyDOC24(
              componentVO.getQtyDOC24().add(compVO.getQtyITM03().multiply(prodVO.getQtyDOC23())));
        }
      }

      // check components availability in the specified warehouse...
      Enumeration en = comps.keys();
      GridParams gridParams = new GridParams();
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.COMPANY_CODE_SYS01, prodVO.getCompanyCodeSys01DOC23());
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.WAREHOUSE_CODE, prodVO.getWarehouseCodeWar01DOC22());
      gridParams.getOtherGridParams().put(ApplicationConsts.LOAD_ALL, Boolean.TRUE);
      ItemAvailabilityVO availVO = null;
      BigDecimal availability, altAvailability, delta;
      String itemCode = null;
      ArrayList list, availList;
      AltComponentVO altVO = null;
      ArrayList alternativeComps = new ArrayList();
      ArrayList compsToRemove = new ArrayList();
      ProdOrderComponentVO altComponentVO = null;
      HashSet altCodes = null; // list of alternative component item codes...
      BigDecimal altQty = null;
      while (en.hasMoreElements()) {
        itemCode = en.nextElement().toString();
        componentVO = (ProdOrderComponentVO) comps.get(itemCode);

        gridParams
            .getOtherGridParams()
            .put(
                ApplicationConsts.ITEM_PK, new ItemPK(prodVO.getCompanyCodeSys01DOC23(), itemCode));
        res =
            avail.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (res.isError()) return res;

        availList = ((VOListResponse) res).getRows();
        componentVO.setAvailabilities(availList);
        availability = new BigDecimal(0);
        for (int i = 0; i < availList.size(); i++) {
          availVO = (ItemAvailabilityVO) availList.get(i);
          availability = availability.add(availVO.getAvailableQtyWAR03());
        }
        componentVO.setAvailableQty(availability);

        if (componentVO.getQtyDOC24().doubleValue() > componentVO.getAvailableQty().doubleValue()) {
          // check if there exist some alternative component...
          res =
              altComps.executeCommand(
                  gridParams, userSessionPars, request, response, userSession, context);
          if (res.isError()) return res;
          list = ((VOListResponse) res).getRows();
          for (int i = 0; i < list.size(); i++) {
            altVO = (AltComponentVO) list.get(i);
            gridParams
                .getOtherGridParams()
                .put(
                    ApplicationConsts.ITEM_PK,
                    new ItemPK(prodVO.getCompanyCodeSys01DOC23(), altVO.getItemCodeItm01ITM04()));
            res =
                avail.executeCommand(
                    gridParams, userSessionPars, request, response, userSession, context);
            if (res.isError()) return res;
            availList = ((VOListResponse) res).getRows();
            altAvailability = new BigDecimal(0);
            for (int j = 0; j < availList.size(); j++) {
              availVO = (ItemAvailabilityVO) availList.get(j);
              altAvailability = altAvailability.add(availVO.getAvailableQtyWAR03());
            }
            if (altAvailability.doubleValue() > 0) {
              altComponentVO = new ProdOrderComponentVO();
              altComponentVO.setAvailabilities(availList);
              altComponentVO.setAvailableQty(altAvailability);
              altComponentVO.setCompanyCodeSys01DOC24(altVO.getCompanyCodeSys01ITM04());
              altComponentVO.setDescriptionSYS10(altVO.getDescriptionSYS10());
              altComponentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
              altComponentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
              altComponentVO.setItemCodeItm01DOC24(altVO.getItemCodeItm01ITM04());
              altComponentVO.setMinSellingQtyUmCodeReg02ITM01(
                  altVO.getMinSellingQtyUmCodeReg02ITM01());
              altQty =
                  conv.convertQty(
                      altVO.getMinSellingQtyUmCodeReg02ITM01(),
                      componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                      altAvailability,
                      userSessionPars,
                      request,
                      response,
                      userSession,
                      context);
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue()
                  > altQty.doubleValue()) {
                delta = altQty;
                altComponentVO.setQtyDOC24(altAvailability);
              } else {
                delta = componentVO.getQtyDOC24();
                altComponentVO.setQtyDOC24(
                    conv.convertQty(
                        componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                        altVO.getMinSellingQtyUmCodeReg02ITM01(),
                        delta,
                        userSessionPars,
                        request,
                        response,
                        userSession,
                        context));
              }
              componentVO.setQtyDOC24(componentVO.getQtyDOC24().subtract(delta));
              alternativeComps.add(altComponentVO);

              altCodes = (HashSet) compAltComps.get(itemCode);
              if (altCodes == null) {
                altCodes = new HashSet();
                compAltComps.put(itemCode, altCodes);
              }
              altCodes.add(altVO.getItemCodeItm01ITM04());

              if (componentVO.getQtyDOC24().doubleValue() == 0) {
                compsToRemove.add(componentVO);
                break;
              }
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue() == 0) break;
            }
          }
        }
      }

      list = new ArrayList(comps.values());
      list.addAll(alternativeComps);
      list.removeAll(compsToRemove);
      return new VOListResponse(list, false, list.size());
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "checkComponentsAvailability",
          "Error while retrieving components availability for the specified production order",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
Esempio n. 21
0
  /** INTERNAL: Conform the result if specified. */
  protected Object conformResult(
      Object result,
      UnitOfWorkImpl unitOfWork,
      AbstractRecord arguments,
      boolean buildDirectlyFromRows) {
    if (getSelectionCriteria() != null) {
      ExpressionBuilder builder = getSelectionCriteria().getBuilder();
      builder.setSession(unitOfWork.getRootSession(null));
      builder.setQueryClass(getReferenceClass());
    }

    // If the query is redirected then the collection returned might no longer
    // correspond to the original container policy.  CR#2342-S.M.
    ContainerPolicy cp;
    if (getRedirector() != null) {
      cp = ContainerPolicy.buildPolicyFor(result.getClass());
    } else {
      cp = getContainerPolicy();
    }

    // This code is now a great deal different...  For one, registration is done
    // as part of conforming.  Also, this should only be called if one actually
    // is conforming.
    // First scan the UnitOfWork for conforming instances.
    // This will walk through the entire cache of registered objects.
    // Let p be objects from result not in the cache.
    // Let c be objects from cache.
    // Presently p intersect c = empty set, but later p subset c.
    // By checking cache now doesConform will be called p fewer times.
    Map indexedInterimResult =
        unitOfWork.scanForConformingInstances(
            getSelectionCriteria(), getReferenceClass(), arguments, this);

    Cursor cursor = null;
    // In the case of cursors just conform/register the initially read collection.
    if (cp.isCursorPolicy()) {
      cursor = (Cursor) result;
      cp = ContainerPolicy.buildPolicyFor(ClassConstants.Vector_class);
      // In nested UnitOfWork session might have been session of the parent.
      cursor.setSession(unitOfWork);
      result = cursor.getObjectCollection();
      // for later incremental conforming...
      cursor.setInitiallyConformingIndex(indexedInterimResult);
      cursor.setSelectionCriteriaClone(getSelectionCriteria());
      cursor.setTranslationRow(arguments);
    }

    // Now conform the result from the database.
    // Remove any deleted or changed objects that no longer conform.
    // Deletes will only work for simple queries, queries with or's or anyof's may not return
    // correct results when untriggered indirection is in the model.
    Vector fromDatabase = null;

    // When building directly from rows, one of the performance benefits
    // is that we no longer have to wrap and then unwrap the originals.
    // result is just a vector, not a container of wrapped originals.
    if (buildDirectlyFromRows) {
      Vector rows = (Vector) result;
      fromDatabase = new Vector(rows.size());
      for (int i = 0; i < rows.size(); i++) {
        Object object = rows.elementAt(i);
        // null is placed in the row collection for 1-m joining to filter duplicate rows.
        if (object != null) {
          Object clone =
              conformIndividualResult(
                  object,
                  unitOfWork,
                  arguments,
                  getSelectionCriteria(),
                  indexedInterimResult,
                  buildDirectlyFromRows);
          if (clone != null) {
            fromDatabase.addElement(clone);
          }
        }
      }
    } else {
      fromDatabase = new Vector(cp.sizeFor(result));
      AbstractSession sessionToUse = unitOfWork.getParent();
      for (Object iter = cp.iteratorFor(result); cp.hasNext(iter); ) {
        Object object = cp.next(iter, sessionToUse);
        Object clone =
            conformIndividualResult(
                object,
                unitOfWork,
                arguments,
                getSelectionCriteria(),
                indexedInterimResult,
                buildDirectlyFromRows);
        if (clone != null) {
          fromDatabase.addElement(clone);
        }
      }
    }

    // Now add the unwrapped conforming instances into an appropriate container.
    // Wrapping is done automatically.
    // Make sure a vector of exactly the right size is returned.
    Object conformedResult =
        cp.containerInstance(indexedInterimResult.size() + fromDatabase.size());
    Object eachClone;
    for (Iterator enumtr = indexedInterimResult.values().iterator(); enumtr.hasNext(); ) {
      eachClone = enumtr.next();
      cp.addInto(eachClone, conformedResult, unitOfWork);
    }
    for (Enumeration enumtr = fromDatabase.elements(); enumtr.hasMoreElements(); ) {
      eachClone = enumtr.nextElement();
      cp.addInto(eachClone, conformedResult, unitOfWork);
    }

    if (cursor != null) {
      cursor.setObjectCollection((Vector) conformedResult);

      // For nested UOW must copy all in object collection to
      // initiallyConformingIndex, as some of these could have been from
      // the parent UnitOfWork.
      if (unitOfWork.isNestedUnitOfWork()) {
        for (Enumeration enumtr = cursor.getObjectCollection().elements();
            enumtr.hasMoreElements(); ) {
          Object clone = enumtr.nextElement();
          indexedInterimResult.put(clone, clone);
        }
      }
      return cursor;
    } else {
      return conformedResult;
    }
  }
Esempio n. 22
0
    public NSArray primaryKeyConstraintStatementsForEntityGroup(NSArray entityGroup) {
      if (entityGroup == null) return NSArray.EmptyArray;

      NSMutableDictionary columnNameDictionary = new NSMutableDictionary();
      NSMutableArray primaryKeyConstraintExpressions = new NSMutableArray();

      for (Enumeration enumerator = entityGroup.objectEnumerator();
          enumerator.hasMoreElements(); ) {
        EOEntity entity = (EOEntity) enumerator.nextElement();
        String tableName = entity.externalName();
        NSArray primaryKeyAttributes = entity.primaryKeyAttributes();
        boolean singlePrimaryKey = primaryKeyAttributes.count() == 1;
        if ((tableName != null) && (!"".equals(tableName)) && (primaryKeyAttributes.count() > 0)) {
          NSArray expressions = super.primaryKeyConstraintStatementsForEntityGroup(entityGroup);
          if ((expressions != null) && (expressions.count() > 0))
            primaryKeyConstraintExpressions.addObjectsFromArray(expressions);
          for (Enumeration attributeEnumerator = primaryKeyAttributes.objectEnumerator();
              attributeEnumerator.hasMoreElements(); ) {
            String columnName = ((EOAttribute) attributeEnumerator.nextElement()).columnName();
            columnNameDictionary.setObjectForKey(
                columnName, entity.externalName() + "." + columnName);
            EOSQLExpression expression =
                this._expressionForString(
                    "create "
                        + (singlePrimaryKey ? "unique" : "")
                        + " index "
                        + entity.externalName()
                        + " "
                        + columnName);
            if (expression != null) primaryKeyConstraintExpressions.addObject(expression);
          }
        }
      }

      for (Enumeration enumerator = entityGroup.objectEnumerator();
          enumerator.hasMoreElements(); ) {
        EOEntity entity = (EOEntity) enumerator.nextElement();
        String tableName = entity.externalName();
        if ((tableName != null) && (!"".equals(tableName))) {
          for (Enumeration relationshipEnumerator = entity.relationships().objectEnumerator();
              relationshipEnumerator.hasMoreElements(); ) {
            EORelationship relationship = (EORelationship) relationshipEnumerator.nextElement();
            if (!relationship.isFlattened()) {
              NSArray destinationAttributes = relationship.destinationAttributes();

              // First exclude all the destination entity primary keys
              for (Enumeration attributeEnumerator =
                      relationship.destinationEntity().primaryKeyAttributes().objectEnumerator();
                  attributeEnumerator.hasMoreElements(); ) {
                EOAttribute attribute = (EOAttribute) attributeEnumerator.nextElement();
                columnNameDictionary.setObjectForKey(
                    attribute.columnName(),
                    relationship.destinationEntity().externalName() + "." + attribute.columnName());
              }
              // Then deal with our end of things
              for (Enumeration attributeEnumerator =
                      relationship.sourceAttributes().objectEnumerator();
                  attributeEnumerator.hasMoreElements(); ) {
                EOAttribute attribute = (EOAttribute) attributeEnumerator.nextElement();
                if ((!this.isSinglePrimaryKeyAttribute(attribute))
                    && (columnNameDictionary.objectForKey(tableName + "." + attribute.columnName())
                        != null)) {
                  columnNameDictionary.setObjectForKey(
                      attribute.columnName(), tableName + "." + attribute.columnName());
                  EOSQLExpression expression =
                      this._expressionForString(
                          "create index " + tableName + " " + attribute.columnName());
                  if (expression != null) primaryKeyConstraintExpressions.addObject(expression);
                }
              }
              // Then deal with the other side
              if (entity.model() == relationship.destinationEntity().model()) {
                for (Enumeration attributeEnumerator =
                        relationship.destinationAttributes().objectEnumerator();
                    attributeEnumerator.hasMoreElements(); ) {
                  EOAttribute attribute = (EOAttribute) attributeEnumerator.nextElement();
                  String destinationTableName = relationship.destinationEntity().externalName();
                  if ((destinationTableName != null) && (!"".equals(destinationTableName))) {
                    if ((!this.isSinglePrimaryKeyAttribute(attribute))
                        && (columnNameDictionary.objectForKey(
                                destinationTableName + "." + attribute.columnName())
                            != null)) {
                      columnNameDictionary.setObjectForKey(
                          attribute.columnName(),
                          destinationTableName + "." + attribute.columnName());
                      EOSQLExpression expression =
                          this._expressionForString(
                              "create index "
                                  + destinationTableName
                                  + " "
                                  + attribute.columnName());
                      if (expression != null) primaryKeyConstraintExpressions.addObject(expression);
                    }
                    if ((!relationship.isCompound())
                        && (relationship.sourceAttributes().count() == 1)
                        && (relationship.destinationAttributes().count() == 1)) {
                      String semantics;
                      switch (relationship.joinSemantic()) {
                        case EORelationship.FullOuterJoin: // '\001'
                        case EORelationship.LeftOuterJoin: // '\002'
                        case EORelationship.RightOuterJoin: // '\003'
                          semantics = "*";
                          break;

                        default:
                          semantics = "=";
                          break;
                      }
                      String sourceColumn =
                          ((EOAttribute) relationship.sourceAttributes().objectAtIndex(0))
                              .columnName();
                      String destinationColumn =
                          ((EOAttribute) relationship.destinationAttributes().objectAtIndex(0))
                              .columnName();
                      EOSQLExpression expression =
                          this._expressionForString(
                              "delete from _SYS_RELATIONSHIP where relationshipName = '"
                                  + relationship.name()
                                  + "' and source_table = '"
                                  + tableName
                                  + "' ");
                      if (expression != null) primaryKeyConstraintExpressions.addObject(expression);
                      expression =
                          this._expressionForString(
                              "insert into _SYS_RELATIONSHIP (relationshipName, source_table, source_column, dest_table, dest_column, operator, one_to_many) values ('"
                                  + relationship.name()
                                  + "','"
                                  + tableName
                                  + "','"
                                  + sourceColumn
                                  + "','"
                                  + destinationTableName
                                  + "','"
                                  + destinationColumn
                                  + "','"
                                  + semantics
                                  + "',"
                                  + (relationship.isToMany() ? 1 : 0)
                                  + ")");
                      if (expression != null) primaryKeyConstraintExpressions.addObject(expression);
                    }
                  }
                }
              }
            }
          }
        }
      }
      return primaryKeyConstraintExpressions.immutableClone();
    }