private Locale getLocale(IWContext iwc) {
    Locale l = null;
    if (localeIdentity == null) {
      l = iwc.getCurrentLocale();
    } else {
      l = ICLocaleBusiness.getLocaleFromLocaleString(localeIdentity);
    }

    if (l == null) {
      l = Locale.ENGLISH;
    }

    return l;
  }
  private void init(IWContext iwc) {
    this.bundle = getBundle(iwc);
    this.iwrb = this.bundle.getResourceBundle(iwc);
    this.iwc = iwc;
    setAutoCreate(false);
    if (iwc.isParameterSet(this.prmClrCache)) {
      clearCache(iwc);
    }
    this._currentLocale = iwc.getCurrentLocale();
    this._currentLocaleId = ICLocaleBusiness.getLocaleId(this._currentLocale);
    this._hasEditPermission = this.hasEditPermission();
    if (iwc.isInPreviewMode()) {
      this._hasEditPermission = false;
    }
    IWBundle coreBundle = iwc.getIWMainApplication().getCoreBundle();
    this.iCreate = coreBundle.getImage("shared/create.gif");
    this.iDelete = coreBundle.getImage("shared/delete.gif");
    this.iEdit = coreBundle.getImage("shared/edit.gif");
    this.iDetach = coreBundle.getImage("shared/detach.gif");
    try {
      this.layout = (AbstractProductCatalogLayout) this._layoutClass.newInstance();
    } catch (IllegalAccessException iae) {
      iae.printStackTrace(System.err);
    } catch (InstantiationException ie) {
      ie.printStackTrace(System.err);
    }
    try {
      String sCurrentPage = iwc.getParameter(ProductCatalog._VIEW_PAGE);
      String sOrderBy = iwc.getParameter(ProductCatalog._ORDER_BY);
      if (sCurrentPage != null) {
        this.currentPage = Integer.parseInt(sCurrentPage);
      }
      if (sOrderBy != null) {
        this.orderBy = Integer.parseInt(sOrderBy);
      }
    } catch (NumberFormatException n) {
    }

    this.expandedCategories = new Vector();
    String selCat = iwc.getParameter(CATEGORY_ID);

    if (selCat != null) {
      this._selectedCategoryID = Integer.parseInt(selCat);
      addCategoryAsExpanded(selCat);
    }
  }
  @Override
  public void present(IWContext iwc) throws Exception {
    this.iwrb = getResourceBundle(iwc);
    this.iwb = getBundle(iwc);

    List<ICLocale> locales = ICLocaleBusiness.listOfLocales();

    String action = iwc.getParameter(PARAMETER_ACTION);
    if (ACTION_CREATE.equals(action)) {
      getCategoryCreationForm(iwc, null, locales);
    } else if (ACTION_EDIT.equals(action)) {
      ApplicationCategory category =
          getApplicationBusiness(iwc)
              .getApplicationCategoryHome()
              .findByPrimaryKey(Integer.parseInt(iwc.getParameter("id")));
      getCategoryCreationForm(iwc, category, locales);
    } else if (ACTION_SAVE.equals(action)) {
      String id = iwc.getParameter("id");
      String name = iwc.getParameter("name");
      String desc = iwc.getParameter("desc");
      String priority = iwc.getParameter("priority");

      if (name != null && !name.trim().equals("")) {
        ApplicationCategory cat = null;
        if (id != null) {
          try {
            cat =
                getApplicationBusiness(iwc)
                    .getApplicationCategoryHome()
                    .findByPrimaryKey(new Integer(iwc.getParameter("id")));
          } catch (FinderException f) {
            f.printStackTrace();
          }
        } else {
          cat = getApplicationBusiness(iwc).getApplicationCategoryHome().create();
        }

        cat.setName(name);
        cat.setDescription(desc);
        if (priority != null && !priority.equals("")) {
          cat.setPriority(new Integer(priority));
        }
        cat.store();

        for (Iterator<ICLocale> it = locales.iterator(); it.hasNext(); ) {
          ICLocale locale = it.next();
          String locName = iwc.getParameter(locale.getName() + "_locale");

          if (locName != null && !locName.equals("")) {
            LocalizedText locText = cat.getLocalizedText(locale.getLocaleID());
            boolean newText = false;
            if (locText == null) {
              locText = getLocalizedTextHome().create();
              newText = true;
            }

            locText.setLocaleId(locale.getLocaleID());
            locText.setBody(locName);

            locText.store();

            if (newText) {
              cat.addLocalizedName(locText);
            }
          }
        }

        IWCacheManager.getInstance(iwc.getIWMainApplication())
            .invalidateCache(ApplicationCategoryViewer.CACHE_KEY);
        IWCacheManager.getInstance(iwc.getIWMainApplication())
            .invalidateCache(ApplicationFavorites.CACHE_KEY);
      }
      listExisting(iwc);
    } else if (ACTION_CATEGORY_UP.equals(action)) {
      String id = iwc.getParameter("id");

      ApplicationCategory cat = null;
      if (id != null) {
        try {
          cat =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPrimaryKey(new Integer(id));
        } catch (FinderException f) {
          f.printStackTrace();
        }
      }
      Integer priority = cat.getPriority();
      ApplicationCategory upperCat = null;
      if (priority != null) {
        try {
          upperCat =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPriority(priority.intValue() - 1);
          upperCat.setPriority(-1);
          upperCat.store();
        } catch (FinderException f) {
          f.printStackTrace();
        }
        cat.setPriority(priority.intValue() - 1);
      }

      cat.store();

      if (upperCat != null) {
        upperCat.setPriority(priority.intValue());
        upperCat.store();
      }

      clearApplicationCategoryViewerCache(iwc);

      listExisting(iwc);
    } else if (ACTION_CATEGORY_DOWN.equals(action)) {
      String id = iwc.getParameter("id");

      ApplicationCategory cat = null;
      if (id != null) {
        try {
          cat =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPrimaryKey(new Integer(id));
        } catch (FinderException f) {
          f.printStackTrace();
        }
      }
      Integer priority = cat.getPriority();
      ApplicationCategory lowerCat = null;
      if (priority != null) {
        try {
          lowerCat =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPriority(priority.intValue() + 1);
          lowerCat.setPriority(-1);
          lowerCat.store();
        } catch (FinderException f) {
          f.printStackTrace();
        }
        cat.setPriority(priority.intValue() + 1);
      }

      cat.store();

      if (lowerCat != null) {
        lowerCat.setPriority(priority.intValue());
        lowerCat.store();
      }

      clearApplicationCategoryViewerCache(iwc);

      listExisting(iwc);
    } else if (ACTION_APP_UP.equals(action)) {
      String appId = iwc.getParameter("app_id");
      String id = iwc.getParameter("id");

      Application app = null;
      ApplicationCategory category = null;
      if (appId != null) {
        try {
          app =
              getApplicationBusiness(iwc).getApplicationHome().findByPrimaryKey(new Integer(appId));
        } catch (FinderException f) {
          f.printStackTrace();
        }
      }
      Integer priority = app.getPriority();
      Application upperApp = null;
      if (priority != null) {
        try {
          category =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPrimaryKey(new Integer(id));

          upperApp =
              getApplicationBusiness(iwc)
                  .getApplicationHome()
                  .findByCategoryAndPriority(category, priority.intValue() - 1);
          upperApp.setPriority(-1);
          upperApp.store();
        } catch (FinderException f) {
          f.printStackTrace();
        }
        app.setPriority(priority.intValue() - 1);
      }

      app.store();

      if (upperApp != null) {
        upperApp.setPriority(priority.intValue());
        upperApp.store();
      }

      clearApplicationCategoryViewerCache(iwc);

      getCategoryCreationForm(iwc, category, locales);
    } else if (ACTION_APP_DOWN.equals(action)) {
      String appId = iwc.getParameter("app_id");
      String id = iwc.getParameter("id");

      Application app = null;
      ApplicationCategory category = null;
      if (appId != null) {
        try {
          app =
              getApplicationBusiness(iwc).getApplicationHome().findByPrimaryKey(new Integer(appId));
        } catch (FinderException f) {
          f.printStackTrace();
        }
      }
      Integer priority = app.getPriority();
      Application lowerApp = null;
      if (priority != null) {
        try {
          category =
              getApplicationBusiness(iwc)
                  .getApplicationCategoryHome()
                  .findByPrimaryKey(new Integer(id));

          lowerApp =
              getApplicationBusiness(iwc)
                  .getApplicationHome()
                  .findByCategoryAndPriority(category, priority.intValue() + 1);
          lowerApp.setPriority(-1);
          lowerApp.store();
        } catch (FinderException f) {
          f.printStackTrace();
        }
        app.setPriority(priority.intValue() + 1);
      }

      app.store();

      if (lowerApp != null) {
        lowerApp.setPriority(priority.intValue());
        lowerApp.store();
      }

      clearApplicationCategoryViewerCache(iwc);

      getCategoryCreationForm(iwc, category, locales);
    } else if (ACTION_DELETE.equals(action)) {
      try {
        ApplicationCategory cat =
            getApplicationBusiness(iwc)
                .getApplicationCategoryHome()
                .findByPrimaryKey(new Integer(iwc.getParameter("id")));
        cat.remove();
      } catch (FinderException f) {
        f.printStackTrace();
      }
      listExisting(iwc);
    } else if (ACTION_LIST.equals(action)) {
      listExisting(iwc);
    } else {
      listExisting(iwc);
    }
  }
  public PresentationObject getCatalog(
      ProductCatalog productCatalog, IWContext iwc, List productCategories)
      throws RemoteException, FinderException {
    this.localeID = iwc.getCurrentLocaleId();
    this.locale = iwc.getCurrentLocale();
    this.defaultLocale = iwc.getIWMainApplication().getSettings().getDefaultLocale();
    this.defaultLocaleID = ICLocaleBusiness.getLocaleId(this.defaultLocale);

    Table table = new Table();
    table.setWidth("100%");
    table.setCellspacing(1);
    table.setCellpadding(2);

    Collection products = productCatalog.getProducts(productCategories);
    Iterator iter = products.iterator();
    Iterator catIter = productCategories.iterator();

    int row = 1;
    int column = 1;
    int imageColumn = 1;

    Hashtable metaDataTypes = new Hashtable();

    table.add(
        productCatalog.getHeader(
            productCatalog.iwrb.getLocalizedString("product.product", "Product")),
        column++,
        row);
    List metadataKeys = new Vector();
    String[] metadata = new String[10 + column];

    while (catIter.hasNext()) {
      ICCategory element = (ICCategory) catIter.next();
      metaDataTypes.putAll(
          getCategoryService(iwc).getInheritedMetaDataTypes(element.getMetaDataTypes(), element));
    }

    if (!metaDataTypes.isEmpty()) {
      Set set = metaDataTypes.keySet();
      Iterator setIter = set.iterator();
      while (setIter.hasNext()) {
        String key = setIter.next().toString();
        if (!metadataKeys.contains(key)) {
          metadataKeys.add(key);
          metadata[column] = key;
          table.add(
              productCatalog.getHeader(productCatalog.iwrb.getLocalizedString(METADATA + key, key)),
              column++,
              row);
        }
      }
    }
    imageColumn = column;
    table.add(
        productCatalog.getHeader(
            productCatalog.iwrb.getLocalizedString("product.images", "Images")),
        column++,
        row);
    table.setRowColor(row, productCatalog.getHeaderBackgroundColor());

    Product product;
    String key;
    String meta;
    Locale localeInUse;
    int localeIDinUse;
    while (iter.hasNext()) {
      ++row;
      product = (Product) iter.next();

      if (null == product.getProductName(this.localeID, null)) {
        localeInUse = this.defaultLocale;
        localeIDinUse = this.defaultLocaleID;
      } else {
        localeInUse = this.locale;
        localeIDinUse = this.localeID;
      }

      if (productCatalog.hasEditPermission()) {
        table.add(productCatalog.getProductEditorLink(product), 1, row);
      }
      table.add(
          productCatalog.getNamePresentationObject(
              product, product.getProductName(localeIDinUse), false),
          1,
          row);
      for (int i = 0; i < metadata.length; i++) {
        key = metadata[i];
        if (key != null) {
          meta = product.getMetaData(METADATA + key + "_" + localeInUse.toString());
          if (meta != null) {
            table.add(productCatalog.getText(meta), i, row);
          }
        }
      }

      // Collection coll = getEditorBusiness(iwc).getFiles(product);
      Collection coll;
      try {
        coll = product.getICFile();
        Iterator images = coll.iterator();
        Image image;
        int counter = 0;
        while (images.hasNext()) {
          ++counter;
          try {
            image =
                new Image(
                    new Integer(((ICFile) images.next()).getPrimaryKey().toString()).intValue());
            Window window = new Window(image);

            Link link = new Link(productCatalog.getText(Integer.toString(counter)));

            if (productCatalog._iconPhoto != null) {
              link = new Link(productCatalog._iconPhoto);
            }

            link.setWindow(window);

            table.add(link, imageColumn, row);
            table.add(productCatalog.getText(Text.NON_BREAKING_SPACE), imageColumn, row);
          } catch (Exception e) {
            e.printStackTrace(System.err);
          }
        }
      } catch (IDORelationshipException e1) {
        e1.printStackTrace();
      }

      table.setRowColor(row, productCatalog.getBackgroundColor());
    }

    return table;
  }
  /**
   * this method creates the form for creating new categories as well as editing the properties of
   * existing ones, plus it allows to see all the applications within this category and change their
   * display ordering
   *
   * @throws RemoteException
   */
  private void getCategoryCreationForm(
      IWContext iwc, ApplicationCategory cat, List<ICLocale> locales) throws RemoteException {
    if (cat != null) {
      getApplicationBusiness(iwc).checkApplicationPriorityConstraint(cat);
    }

    Form form = new Form();
    form.setID("applicationCategoryCreator");
    form.setStyleClass("adminForm");

    TextInput tName = new TextInput("name");
    TextArea tDesc = new TextArea("desc");

    if (cat != null) {
      tName.setContent(cat.getName());
      tDesc.setContent(cat.getDescription());
      form.addParameter("id", cat.getPrimaryKey().toString());
    }

    Layer layer = new Layer(Layer.DIV);
    layer.setStyleClass("formSection");
    form.add(layer);

    Layer formItem = new Layer(Layer.DIV);
    formItem.setStyleClass("formItem");
    Label label = new Label(this.iwrb.getLocalizedString("default_name", "Default name"), tName);
    formItem.add(label);
    formItem.add(tName);
    layer.add(formItem);

    formItem = new Layer(Layer.DIV);
    formItem.setStyleClass("formItem");
    label =
        new Label(
            this.iwrb.getLocalizedString("default_description", "Default description"), tDesc);
    formItem.add(label);
    formItem.add(tDesc);
    layer.add(formItem);

    for (Iterator<ICLocale> it = locales.iterator(); it.hasNext(); ) {
      ICLocale locale = it.next();
      Locale javaLocale = ICLocaleBusiness.getLocaleFromLocaleString(locale.getLocale());

      TextInput locInput = new TextInput(locale.getName() + "_locale");
      if (cat != null) {
        LocalizedText text = cat.getLocalizedText(locale.getLocaleID());
        locInput.setValue(text == null ? "" : text.getBody());
      }
      formItem = new Layer(Layer.DIV);
      formItem.setStyleClass("formItem");
      label = new Label(javaLocale.getDisplayLanguage(), locInput);
      formItem.add(label);
      formItem.add(locInput);
      layer.add(formItem);
    }

    List apps = null;
    if (cat != null) {
      try {
        apps =
            new ArrayList(
                getApplicationBusiness(iwc)
                    .getApplicationHome()
                    .findAllByCategoryOrderedByPriority(cat));
      } catch (FinderException f) {
        f.printStackTrace();
      }
    }

    if (apps != null && !apps.isEmpty()) {
      Table2 table = new Table2();
      table.setWidth("100%");
      table.setCellpadding(0);
      table.setCellspacing(0);
      table.setStyleClass("ruler");
      table.setStyleClass("adminTable");

      TableRowGroup group = table.createHeaderRowGroup();
      TableRow row = group.createRow();
      TableCell2 cell = row.createHeaderCell();
      cell.setStyleClass("firstColumn");
      cell.setStyleClass("application");
      cell.add(new Text(this.iwrb.getLocalizedString("application", "Application")));

      cell = row.createHeaderCell();
      cell.setStyleClass("description");
      cell.add(new Text(this.iwrb.getLocalizedString("priority", "Priority")));

      group = table.createBodyRowGroup();
      int iRow = 1;

      Iterator iter = apps.iterator();

      while (iter.hasNext()) {
        Application app = (Application) iter.next();

        row = table.createRow();

        if (iRow % 2 == 0) {
          row.setStyleClass("evenRow");
        } else {
          row.setStyleClass("oddRow");
        }

        cell = row.createCell();
        cell.setStyleClass("firstColumn");
        cell.setStyleClass("application");
        cell.add(new Text(app.getName()));

        cell = row.createCell();
        cell.setStyleClass("description");
        cell.setStyleClass("lastColumn");

        Link up =
            new Link(
                this.iwb.getImage("previous.png", this.iwrb.getLocalizedString("previous", "Up")));
        up.addParameter(PARAMETER_ACTION, ACTION_APP_UP);
        up.addParameter("app_id", app.getPrimaryKey().toString());
        up.addParameter("id", cat.getPrimaryKey().toString());
        up.setStyleClass("flippedImageLink");
        cell.add(up);

        if (iRow <= 1) {
          up.setStyleAttribute("visibility", "hidden");
        }

        Link down =
            new Link(this.iwb.getImage("next.png", this.iwrb.getLocalizedString("next", "Down")));
        down.addParameter(PARAMETER_ACTION, ACTION_APP_DOWN);
        down.addParameter("app_id", app.getPrimaryKey().toString());
        down.addParameter("id", cat.getPrimaryKey().toString());
        down.setStyleClass("flippedImageLink");
        cell.add(down);

        if (iRow >= apps.size()) {
          down.setStyleAttribute("visibility", "hidden");
        }

        iRow++;
      }

      Layer clearLayer = new Layer(Layer.DIV);
      clearLayer.setStyleClass("Clear");
      layer.add(clearLayer);

      form.add(table);
    }

    Layer buttonLayer = new Layer(Layer.DIV);
    buttonLayer.setStyleClass("buttonLayer");
    form.add(buttonLayer);

    SubmitButton back =
        new SubmitButton(this.iwrb.getLocalizedString("back", "Back"), PARAMETER_ACTION, "list");
    buttonLayer.add(back);

    SubmitButton save =
        new SubmitButton(this.iwrb.getLocalizedString("save", "Save"), PARAMETER_ACTION, "save");
    buttonLayer.add(save);

    add(form);
  }