private DropdownMenu getDropDownOfQueries(String key, IWContext iwc)
     throws RemoteException, FinderException {
   SortedMap sortedMap = new TreeMap(new StringAlphabeticalComparator(iwc.getCurrentLocale()));
   DropdownMenu drp = new DropdownMenu(key);
   Iterator iterator = getQueryService(iwc).getQueries(iwc).iterator();
   while (iterator.hasNext()) {
     EntityRepresentation userQuery = (EntityRepresentation) iterator.next();
     String name = (String) userQuery.getColumnValue(QueryRepresentation.NAME_KEY);
     String id = userQuery.getPrimaryKey().toString();
     if (sortedMap.containsKey(name)) {
       // usually the items have different names therefore we implement
       // a very simple solution
       name += " (1)";
     }
     sortedMap.put(name, id);
   }
   Iterator sortedIterator = sortedMap.entrySet().iterator();
   while (sortedIterator.hasNext()) {
     Map.Entry entry = (Map.Entry) sortedIterator.next();
     String id = (String) entry.getValue();
     String name = (String) entry.getKey();
     drp.addMenuElement(id, name);
   }
   return drp;
 }
 public String getDisplayForResultingObject(Object value, IWContext iwc) {
   Locale locale = iwc.getCurrentLocale();
   if (value != null) {
     return TextSoap.findAndCut(
         (new IWTimestamp((java.sql.Date) value)).getLocaleDate(locale), "GMT");
   } else {
     return null;
   }
 }
  protected Locale getCurrentLocale() {
    IWContext iwc = CoreUtil.getIWContext();
    Locale locale = iwc == null ? null : iwc.getCurrentLocale();

    if (locale == null) {
      locale = IWMainApplication.getDefaultIWMainApplication().getDefaultLocale();
    }

    return locale == null ? Locale.ENGLISH : locale;
  }
 private String getLocalizedTimestamp(IWContext iwc, IWTimestamp timestamp) {
   if (timestamp == null) {
     return null;
   }
   IWCalendar cal = new IWCalendar(iwc.getCurrentLocale(), timestamp);
   if (cal != null) {
     return cal.getLocaleDate(IWCalendar.SHORT);
   } else {
     return null;
   }
 }
  public Collection<SearchResult> getArticleSearchResults(
      String folder, List<String> categories, IWContext iwc) {
    if (folder == null) {
      return null;
    }
    if (iwc == null) {
      iwc = IWContext.getInstance();
      if (iwc == null) {
        return null;
      }
    }

    IWTimestamp oldest = null;

    if (this.numberOfDaysDisplayed > 0) {
      oldest = IWTimestamp.RightNow();
      oldest.addDays(-this.numberOfDaysDisplayed);
    }

    IWSlideSession session = null;
    try {
      session = (IWSlideSession) IBOLookup.getSessionInstance(iwc, IWSlideSession.class);
    } catch (IBOLookupException e) {
      e.printStackTrace();
      return null;
    }
    String webDavUri = null;
    try {
      webDavUri = session.getWebdavServerURI();
    } catch (RemoteException e) {
      e.printStackTrace();
    }
    if (webDavUri != null) {
      if (folder.startsWith(webDavUri)) {
        folder = folder.substring(webDavUri.length());
      }
      if (folder.startsWith(CoreConstants.SLASH)) {
        folder = folder.substring(1);
      }
    }
    SearchRequest articleSearch = null;
    try {
      articleSearch = getSearchRequest(folder, iwc.getCurrentLocale(), oldest, categories);
    } catch (SearchException e) {
      e.printStackTrace();
      return null;
    }
    ContentSearch searchBusiness = new ContentSearch(iwc.getIWMainApplication());
    searchBusiness.setToUseRootAccessForSearch(true);
    searchBusiness.setToUseDescendingOrder(true);
    Search search = searchBusiness.createSearch(articleSearch);
    return search.getSearchResults();
  }
  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);
    }
  }
  private String getFeed(
      String title, String feedFileName, Collection entries, RSSRequest rssRequest, IWContext iwc) {
    if (rssFileURIsCacheList.contains(feedFileName))
      return PATH_TO_FEED_PARENT_FOLDER + feedFileName;
    Date now = new Date();
    RSSBusiness rss = null;
    try {
      rss = IBOLookup.getServiceInstance(iwc, RSSBusiness.class);
    } catch (IBOLookupException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    String serverName = iwc.getServerURL();
    serverName = serverName.substring(0, serverName.length() - 1);
    SyndFeed feed = null;

    feed =
        rss.createNewFeed(
            title,
            serverName,
            FEED_DESCRIPTION,
            "atom_1.0",
            iwc.getCurrentLocale().toString(),
            new Timestamp(now.getTime()));

    if (entries != null) feed.setEntries(getFeedEntries(entries));

    try {
      String feedContent = rss.convertFeedToAtomXMLString(feed);
      IWSlideService service = this.getIWSlideService(rssRequest);
      service.uploadFileAndCreateFoldersFromStringAsRoot(
          PATH_TO_FEED_PARENT_FOLDER,
          feedFileName,
          feedContent,
          RSSAbstractProducer.RSS_CONTENT_TYPE,
          true);
      rssFileURIsCacheList.add(feedFileName);
    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return PATH_TO_FEED_PARENT_FOLDER + feedFileName;
  }
  private void addLocalized(IWContext iwc) {
    Locale locale = iwc.getCurrentLocale();
    DateFormatSymbols symbols = new DateFormatSymbols(locale);
    IWBundle iwb = this.getBundle(iwc);
    IWResourceBundle iwrb = iwb.getResourceBundle(iwc);
    String[] monthStrings;

    if (this.showNullValue) {
      if (this.inShort) {
        this.dayString = iwrb.getLocalizedString(DAY_KEY_S, "D");
        this.monthString = iwrb.getLocalizedString(MONTH_KEY_S, "M");
        this.yearString = iwrb.getLocalizedString(YEAR_KEY_S, "Y");
      } else {
        this.dayString = iwrb.getLocalizedString(DAY_KEY, "Day");
        this.monthString = iwrb.getLocalizedString(MONTH_KEY, "Month");
        this.yearString = iwrb.getLocalizedString(YEAR_KEY, "Year");
      }
      this.theDay.setMenuElementDisplayString("00", this.dayString);
      this.theMonth.setMenuElementDisplayString("00", this.monthString);

      if (this.showYear) {
        this.theYear.setMenuElementDisplayString("YY", this.yearString);
      }
    }
    if (this.inShort) {
      monthStrings = symbols.getShortMonths();
    } else {
      monthStrings = symbols.getMonths();
    }

    for (int i = 1; i <= 12; i++) {
      String value = Integer.toString(i);

      if (i < 10) {
        value = "0" + value;
      }

      this.theMonth.setMenuElementDisplayString(value, monthStrings[i - 1]);
    }
  }
  public String getUserNameDWR(String personalID, String localeStr) {
    try {
      if (personalID != null && !personalID.trim().equals("")) {
        UserHome uHome = (UserHome) IDOLookup.getHome(User.class);
        User user = uHome.findByPersonalID(personalID);
        return user.getName();
      } else {
        return "";
      }
    } catch (IDOLookupException e) {
      e.printStackTrace();
    } catch (FinderException e) {
    }

    try {
      IWContext iwc = IWContext.getInstance();
      Locale locale = iwc.getCurrentLocale();
      IWResourceBundle iwrb = getBundle().getResourceBundle(locale);
      return iwrb.getLocalizedString("landsmot.user_not_found", "User not found");
    } catch (UnavailableIWContext e) {
      return "User not found";
    }
  }
  public void main(IWContext iwc) throws Exception {
    // TODO eiki cache countries
    // some caching made by aron
    super.main(iwc);
    // System.out.println( "country dropdown main start "+
    // com.idega.util.IWTimestamp.RightNow().toString());
    List localeCountries = Arrays.asList(Locale.getISOCountries());

    // List locales = Arrays.asList( java.util.Locale.getAvailableLocales());
    // List locales = ICLocaleBusiness.listOfAllLocalesJAVA();
    Locale currentLocale = iwc.getCurrentLocale();

    // Iterator iter = locales.iterator();
    Iterator iter = localeCountries.iterator();

    Country country = null;
    String countryDisplayName = null;
    Map countries = new HashMap();
    String lang = currentLocale.getISO3Language();
    Locale locale;
    List smallCountries = new Vector();
    // CountryHome countryHome = getAddressBusiness(iwc).getCountryHome();
    while (iter.hasNext()) {
      // Locale locale = (Locale) iter.next();

      String ISOCountry = (String) iter.next();
      try {
        locale = new Locale(lang, ISOCountry);

        countryDisplayName = locale.getDisplayCountry(currentLocale);
        // country = countryHome.findByIsoAbbreviation(locale.getCountry());
        country = getCountryByISO(locale.getCountry());

        if (countryDisplayName != null
            && country != null
            && !countries.containsKey(country.getPrimaryKey())) {
          countries.put(country.getPrimaryKey(), country); // cache
          SmallCountry sCountry =
              new SmallCountry(
                  (Integer) country.getPrimaryKey(), countryDisplayName, ISOCountry, currentLocale);
          smallCountries.add(sCountry);
          // addMenuElement(((Integer)country.getPrimaryKey()).intValue(),countryDisplayName);
        }
      } catch (Exception e1) {
        // e1.printStackTrace();
      }
    }
    Collections.sort(smallCountries);

    for (Iterator iterator = smallCountries.iterator(); iterator.hasNext(); ) {
      SmallCountry sCountry = (SmallCountry) iterator.next();
      // we dont want the ISO code into the list
      if (!sCountry.name.equalsIgnoreCase(sCountry.code)) {
        addMenuElement(sCountry.getID().intValue(), sCountry.getName());
      }
    }

    try {
      if (!StringUtil.isEmpty(this.selectedCountryName)) {
        this.selectedCountry =
            getAddressBusiness(iwc).getCountryHome().findByCountryName(this.selectedCountryName);
      }
      // we must ensure no external selected country is set
      else if (this.selectedCountry == null && !StringUtil.isEmpty(currentLocale.getCountry())) {
        this.selectedCountry =
            getAddressBusiness(iwc)
                .getCountryHome()
                .findByIsoAbbreviation(currentLocale.getCountry());
      }
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (EJBException e) {
      e.printStackTrace();
    } catch (FinderException e) {
      e.printStackTrace();
    }

    if (this.selectedCountry != null) {
      setSelectedElement(((Integer) this.selectedCountry.getPrimaryKey()).intValue());
    }
    // System.out.println( "country dropdown main end "+
    // com.idega.util.IWTimestamp.RightNow().toString());
  }
  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;
  }
  @SuppressWarnings("unchecked")
  public void searchForArticles(
      RSSRequest rssRequest,
      String feedParentPath,
      String feedFileName,
      List<String> categories,
      List<String> articles,
      String extraURI) {

    IWContext iwc = getIWContext(rssRequest);
    boolean getAllArticles = false;

    if (StringUtil.isEmpty(extraURI)) {
      getAllArticles = true;
    }

    String serverName = iwc.getServerURL();
    serverName = serverName.substring(0, serverName.length() - 1);

    Collection<SearchResult> results = getArticleSearchResults(PATH, categories, iwc);
    if (ListUtil.isEmpty(results)) {
      LOGGER.warning("No results found in: " + PATH + " by the categories: " + categories);
      return;
    }

    List<String> urisToArticles = new ArrayList<String>();
    for (SearchResult result : results) {
      urisToArticles.add(result.getSearchResultURI());
    }

    if (!ListUtil.isEmpty(articles)) {
      if (ListUtil.isEmpty(categories)) {
        urisToArticles = articles;
      } else {
        urisToArticles.addAll(articles);
      }
    }

    if (!ListUtil.isEmpty(articles) && ListUtil.isEmpty(categories)) urisToArticles = articles;

    RSSBusiness rss = null;
    SyndFeed articleFeed = null;
    long time = System.currentTimeMillis();
    try {
      rss = IBOLookup.getServiceInstance(iwc, RSSBusiness.class);
    } catch (IBOLookupException e) {
      LOGGER.log(Level.WARNING, "Error getting " + RSSBusiness.class, e);
    }

    String description = CoreConstants.EMPTY;
    String title = CoreConstants.EMPTY;
    if (ListUtil.isEmpty(results) && !getAllArticles) {
      description = "No articles found. Empty feed";
    } else {
      description =
          "Article feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com";

      BuilderService bservice = null;
      String pageKey = null;
      try {
        if (!StringUtil.isEmpty(extraURI)) {
          bservice = BuilderServiceFactory.getBuilderService(iwc);
          pageKey = bservice.getExistingPageKeyByURI(CoreConstants.SLASH + extraURI);
          ICPage icpage = bservice.getICPage(pageKey);
          title = icpage.getName();
        }
      } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error getting page name from: " + extraURI, e);
      }

      String lang = iwc.getCurrentLocale().getLanguage();
      SyndFeed allArticles =
          rss.createNewFeed(title, serverName, description, "atom_1.0", lang, new Timestamp(time));

      List<SyndEntry> allEntries = new ArrayList<SyndEntry>();
      for (int i = 0; i < urisToArticles.size(); i++) {
        String articleURL =
            serverName
                .concat(urisToArticles.get(i))
                .concat(CoreConstants.SLASH)
                .concat(lang)
                .concat(".xml");
        articleFeed = rss.getFeed(articleURL);
        if (articleFeed != null) allEntries.addAll(articleFeed.getEntries());
      }

      allArticles.setEntries(allEntries);
      String allArticlesContent = null;
      try {
        allArticlesContent = rss.convertFeedToAtomXMLString(allArticles);
      } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error converting to Atom from: " + allArticles, e);
      }

      try {
        IWSlideService service = this.getIWSlideService(rssRequest);
        service.uploadFileAndCreateFoldersFromStringAsRoot(
            feedParentPath,
            feedFileName,
            allArticlesContent,
            RSSAbstractProducer.RSS_CONTENT_TYPE,
            true);
      } catch (RemoteException e) {
        LOGGER.log(
            Level.WARNING,
            "Error uploading to: " + feedParentPath + feedFileName + " file: " + allArticlesContent,
            e);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see is.idega.idegaweb.member.presentation.UserEditor#presentateUserRelations(com.idega.presentation.IWContext)
   */
  protected void presentUserRelations(IWContext iwc) throws RemoteException {
    Table relationsTable = new Table();
    relationsTable.setCellspacing(4);
    relationsTable.setWidth(Table.HUNDRED_PERCENT);
    int row = 1;

    if (user != null) {
      addSeperator(iwrb.getLocalizedString("mbe.user_relations", "User relations"));
      CommuneFamilyService familyService = getFamilyService(iwc);

      // parent handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.parents", "Parents")), 1, row++);
      Collection parents = null;
      try {
        parents = familyService.getParentsFor(user);
        if (parents != null && !parents.isEmpty()) {
          for (Iterator iter = parents.iterator(); iter.hasNext(); ) {
            User parent = (User) iter.next();
            relationsTable.add(getRelatedUserLink(parent), 1, row);
            relationsTable.add(
                PersonalIDFormatter.format(parent.getPersonalID(), iwc.getCurrentLocale()),
                2,
                row++);
          }
        }
      } catch (Exception e1) {
      }
      row++;

      // partner handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.spouse", "Spouse")), 1, row++);
      User partner = null;
      try {
        partner = familyService.getSpouseFor(this.user);
      } catch (NoSpouseFound e) {
      } catch (Exception e) {
      }
      if (partner != null) {
        relationsTable.add(getRelatedUserLink(partner), 1, row);
        relationsTable.add(
            PersonalIDFormatter.format(partner.getPersonalID(), iwc.getCurrentLocale()), 2, row++);
      }
      row++;

      // cohabitant handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.cohabitant", "Cohabitant")), 1, row++);
      User cohabitant = null;
      try {
        cohabitant = familyService.getCohabitantFor(this.user);
      } catch (NoCohabitantFound e) {
      }
      if (cohabitant != null) {
        relationsTable.add(getRelatedUserLink(cohabitant), 1, row);
        relationsTable.add(
            PersonalIDFormatter.format(cohabitant.getPersonalID(), iwc.getCurrentLocale()),
            2,
            row++);
      }
      row++;

      // biological children handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.parential_children", "Parential children")),
          1,
          row++);
      Collection children = null;
      Collection custodianChildren = null;
      Text star = new Text(" *");
      star.setStyleClass(STYLENAME_HEADER);
      try {
        children = familyService.getChildrenFor(user);
        custodianChildren = familyService.getChildrenInCustodyOf(user);
        if (custodianChildren != null && !custodianChildren.isEmpty()) {
          for (Iterator iter = custodianChildren.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 1, row);
            if (children != null && !children.contains(child)) {
              relationsTable.add(star, 1, row);
            }
            relationsTable.add(
                PersonalIDFormatter.format(child.getPersonalID(), iwc.getCurrentLocale()),
                2,
                row++);
            row++;
          }
        }
      } catch (Exception e2) {
      }
    }
    relationsTable.setWidth(1, "300");
    row++;

    Text infoText =
        new Text(
            iwrb.getLocalizedString(
                "person_is_only_custodian", "* Not child, person is only custodian"));
    infoText.setStyleClass(STYLENAME_TEXT);
    relationsTable.add(infoText, 1, row++);
    row++;

    relationsTable.setAlignment(2, row, Table.HORIZONTAL_ALIGN_RIGHT);
    relationsTable.add(getEditButton(iwc, ACTION_EDIT_RELATIONS), 2, row);

    addToMainPart(relationsTable);
  }