public void main(IWContext iwc) throws Exception {
    ELUtil.getInstance().autowire(this);

    String val = iwc.getParameter("submitBtn");
    if (!StringUtil.isEmpty(val)) {
      dao.createDish(
          iwc.getParameter("dishName"),
          iwc.getParameter("dishDescription"),
          iwc.getParameter("dishPrice"));
    }

    Layer container = new Layer(); // 	<div>
    add(container);

    IWResourceBundle iwrb = getResourceBundle(iwc);

    Form form = new Form();
    container.add(form);

    createField(form, "Dish", "dish_name", new TextInput("dishName"), iwrb);
    createField(form, "Description", "description", new TextArea("dishDescription"), iwrb);
    createField(form, "Price", "price", new TextInput("dishPrice"), iwrb);

    SubmitButton submitBtn =
        new SubmitButton("submitBtn", iwrb.getLocalizedString("submit", "Submit"));
    form.add(submitBtn);
  }
  @Override
  public void handleRSSRequest(RSSRequest rssRequest) throws IOException {
    String feedParentFolder = null;
    String feedFile = null;
    String category = getCategory(rssRequest.getExtraUri());
    String extraURI = rssRequest.getExtraUri();
    if (extraURI == null) {
      extraURI = CoreConstants.EMPTY;
    }
    if ((!extraURI.endsWith(CoreConstants.SLASH)) && (extraURI.length() != 0)) {
      extraURI = extraURI.concat(CoreConstants.SLASH);
    }

    List<String> categories = new ArrayList<String>();
    List<String> articles = new ArrayList<String>();
    if (category != null) categories.add(category);

    IWContext iwc = getIWContext(rssRequest);
    String language = iwc.getLocale().getLanguage();

    if (StringUtil.isEmpty(extraURI)) {
      feedParentFolder = ARTICLE_RSS;
      feedFile = "all_".concat(language).concat(".xml");
    } else if (category != null) {
      feedParentFolder =
          ARTICLE_RSS.concat("category/").concat(category).concat(CoreConstants.SLASH);
      feedFile = "feed_.".concat(language).concat(".xml");
    } else {
      //	Have page URI
      feedParentFolder = ARTICLE_RSS.concat("page/").concat(extraURI);
      feedFile = "feed_".concat(language).concat(".xml");
      categories = getCategoriesByURI(extraURI, iwc);
      if (ListUtil.isEmpty(categories)) {
        articles = getArticlesByURI(extraURI, iwc);
      }
    }

    String realURI = CoreConstants.WEBDAV_SERVLET_URI + feedParentFolder + feedFile;
    if (rssFileURIsCacheList.contains(feedFile)) {
      try {
        this.dispatch(realURI, rssRequest);
      } catch (ServletException e) {
        LOGGER.log(Level.WARNING, "Error dispatching: " + realURI, e);
      }
    } else {
      //	Generate RSS and store and the dispatch to it and add a listener to that directory
      try {
        // todo code the 3 different cases (see description)
        searchForArticles(rssRequest, feedParentFolder, feedFile, categories, articles, extraURI);
        rssFileURIsCacheList.add(feedFile);

        this.dispatch(realURI, rssRequest);
      } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error while searching or dispatching: " + realURI, e);
        throw new IOException(e.getMessage());
      }
    }
  }
 public void onSlideChange(IWContentEvent contentEvent) {
   //	On a file change this code checks if RSS file already exists and if so updates it
   // (overwrites) with a new folder list
   String uri = contentEvent.getContentEvent().getUri();
   //	Only do it for articles (whenever something changes in the articles folder)
   if (!StringUtil.isEmpty(uri) && uri.indexOf("/cms/article/") > -1) {
     // TODO don't remove cache on comments change, just check the URI for comments RSS.
     getrssFileURIsCacheList().clear();
   }
 }
  public void addBundle(String bundleIdentifier, IWBundle bundle) {
    if (StringUtil.isEmpty(bundleIdentifier) || bundle == null) {
      return;
    }

    if (bundles.get(bundleIdentifier) != null) {
      return;
    }

    BundleLocalizationMap localizationMap = new BundleLocalizationMap(bundle);
    bundles.put(bundleIdentifier, localizationMap);
  }
 public String getEnabledCategories(IWContext iwc) {
   StringBuffer categories = new StringBuffer(CategoryBean.CATEGORY_DELIMETER);
   CategoryBean categoryBean = CategoryBean.getInstance();
   String selectedCategory = null;
   for (ContentCategory category : categoryBean.getCategories()) {
     selectedCategory = iwc.getParameter(getCategoryKey(category));
     if (!StringUtil.isEmpty(selectedCategory)
         && selectedCategory.equals(Boolean.TRUE.toString())) {
       categories.append(category.getId()).append(CategoryBean.CATEGORY_DELIMETER);
     }
   }
   return categories.toString();
 }
  protected List<User> getUsersHavingHandlerRole() {
    String roleKey = getHandlerRoleKey();
    if (StringUtil.isEmpty(roleKey)) {
      return null;
    }

    IWApplicationContext iwac = IWMainApplication.getDefaultIWApplicationContext();
    AccessController accessControler =
        IWMainApplication.getDefaultIWMainApplication().getAccessController();
    Collection<Group> groupsWithRole = accessControler.getAllGroupsForRoleKey(roleKey, iwac);
    if (ListUtil.isEmpty(groupsWithRole)) {
      return null;
    }

    UserBusiness userBusiness = getUserBusiness();
    if (userBusiness == null) {
      return null;
    }

    List<User> users = new ArrayList<User>();
    for (Group group : groupsWithRole) {
      if (group instanceof User) {
        User user = (User) group;
        if (!users.contains(user)) {
          users.add(user);
        }
      } else {
        Collection<User> usersInGroup = null;
        try {
          usersInGroup = userBusiness.getUsersInGroup(group);
        } catch (Exception e) {
          LOGGER.log(Level.WARNING, "Error getting users in group: " + group, e);
        }
        if (!ListUtil.isEmpty(usersInGroup)) {
          for (User user : usersInGroup) {
            if (!users.contains(user)) {
              users.add(user);
            }
          }
        }
      }
    }

    return users;
  }
  @Override
  protected boolean authenticate(Principal principal, Credentials credentials)
      throws FailedLoginException, RepositoryException {
    String userId = getUserID(credentials);
    if (StringUtil.isEmpty(userId)) {
      return super.authenticate(principal, credentials);
    }

    if (userId.equals(getAdminId())) {
      return true; //	Administrator user has all rights
    }

    if (credentials instanceof SimpleCredentials) {
      credentials = new SimpleCredentials(userId, ((SimpleCredentials) credentials).getPassword());
    }

    return super.authenticate(principal, credentials);
  }
  protected List<String> getEmails(Collection<User> users) {
    if (ListUtil.isEmpty(users)) {
      return null;
    }

    UserBusiness userBusiness = getUserBusiness();
    if (userBusiness == null) {
      return null;
    }

    List<String> emails = new ArrayList<String>(users.size());
    for (User user : users) {
      Email email = getEmail(user);
      String emailAddress = email == null ? null : email.getEmailAddress();
      if (!StringUtil.isEmpty(emailAddress) && !emails.contains(emailAddress)) {
        emails.add(emailAddress);
      }
    }

    return emails;
  }
  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());
  }
  /**
   * Creates {@link org.w3.dom.Document} with structure
   * <\tableRow><\ColumName>Value<\/ColumName><\/tableRow>. ColumnName's are parsed from {@link
   * com.idega.util.text.TableRecord#getItems()}.
   *
   * @param list {@link Collection} of {@link com.idega.util.text.TableRecord}.
   * @return {@link org.w3.dom.Document} or null if error happen.
   */
  public static Document createTableDocument(Collection<TableRecord> list) {
    if (ListUtil.isEmpty(list)) {
      return null;
    }

    DocumentBuilder documentBuilder = null;
    try {
      documentBuilder = XmlUtil.getDocumentBuilder();
    } catch (ParserConfigurationException e) {
      LOGGER.log(Level.WARNING, "Unable to create table document.", e);
      return null;
    }

    if (documentBuilder == null) {
      return null;
    }

    Document document = documentBuilder.newDocument();
    if (document == null) {
      return null;
    }

    Element localeElement = document.createElement(items);
    if (localeElement == null) {
      return null;
    }

    for (TableRecord tableRecord : list) {
      Element itemElem = document.createElement(tableRow);
      if (itemElem == null) {
        continue;
      }

      Map<String, String> data = tableRecord.getItems();
      if (MapUtil.isEmpty(data)) {
        continue;
      }

      for (Iterator<Map.Entry<String, String>> iter = data.entrySet().iterator();
          iter.hasNext(); ) {
        Map.Entry<String, String> entry = iter.next();
        if (entry == null) {
          continue;
        }

        String key = entry.getKey();
        String value = entry.getValue();
        if (StringUtil.isEmpty(key) || StringUtil.isEmpty(value)) {
          continue;
        }

        Element itemValueElem = document.createElement(key);
        if (itemValueElem == null) {
          continue;
        }

        itemValueElem.setTextContent(value);
        itemElem.appendChild(itemValueElem);
      }

      Document documentOfItemNode = localeElement.getOwnerDocument();
      if (documentOfItemNode == null) {
        continue;
      }

      Node itemNode = documentOfItemNode.importNode(itemElem, true);
      if (itemNode == null) {
        continue;
      }

      localeElement.appendChild(itemNode);
    }

    document.appendChild(localeElement);
    return document;
  }
  @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);
      }
    }
  }