@Test
  public void removeForumFromForumWidget() {
    DraftForum forum = new DraftForum();
    forum.setName("name");
    persistance.putItem(forum);

    Site site = new Site();
    site.getSitePaymentSettings().setUserId(-1);
    site.setTitle("f");
    site.getThemeId().setTemplateDirectory("f");
    site.getThemeId().setThemeCss("f");
    site.setSubDomain("f");
    persistance.putSite(site);

    Page page = TestUtil.createPage(site);
    PageManager pageVersion = new PageManager(page);

    WidgetItem widgetForum = new WidgetItem();
    widgetForum.setDraftItem(forum);
    persistance.putWidget(widgetForum);
    pageVersion.addWidget(widgetForum);

    persistance.removeDraftItem(forum);

    Assert.assertNull(persistance.getDraftItem(forum.getId()));
    Assert.assertNotNull(widgetForum.getDraftItem());
  }
  @SynchronizeByAllEntity(entityClass = Site.class)
  @RemoteMethod
  public String execute(final Integer targetSiteId) throws IOException, ServletException {
    userSitesUrl = configStorage.get().getUserSitesUrl();

    final UserManager userManager = new UsersManager().getLogined();

    if (targetSiteId != null) {
      targetSite = userManager.getRight().getSiteRight().getSiteForEdit(targetSiteId).getSite();
      targetSites = Arrays.asList(targetSite);
    } else {
      targetSites =
          persistance.getSites(userManager.getUserId(), SiteAccessLevel.getUserAccessLevels());
      Collections.sort(targetSites, new SiteByTitleComparator());
    }

    sites = new ArrayList<Site>();
    for (final Site site : persistance.getAllSites()) {
      if (site.getType() == SiteType.COMMON
          && site.getSitePaymentSettings().getSiteStatus() == SiteStatus.ACTIVE) {
        sites.add(site);
      }
    }
    Collections.sort(sites, new SiteByTitleComparator());
    return executePage("/site/showRequestContent.jsp");
  }
  @Test
  public void testGetSortedFilledFormsFromSession() {
    User user = TestUtil.createUserAndLogin("aa");

    Site site1 = TestUtil.createSite("title1", "url1");
    TestUtil.createUserOnSiteRightActive(user, site1, SiteAccessLevel.ADMINISTRATOR);

    List<DraftFormItem> items = TestUtil.createDefaultFormItemsForGallery();
    final DraftCustomForm customForm = TestUtil.createCustomForm(site1.getSiteId(), "form1", items);
    DraftGallery gallery =
        TestUtil.createGallery(site1.getSiteId(), "galleryName1", "commentsNotes1", customForm);
    gallery.setRows(1);
    gallery.setColumns(5);

    // ---------------------------------------------filled
    // forms---------------------------------------------
    List<FilledForm> filledForms = new ArrayList<FilledForm>();
    for (int i = 0; i < 30; i++) {
      final List<FilledFormItem> filledFormItems = new ArrayList<FilledFormItem>();
      for (DraftFormItem formItem : items) {
        FilledFormItem filledFormItem =
            TestUtil.createFilledFormItem(
                formItem.getFormItemId(), formItem.getFormItemName(), formItem.getItemName() + i);
        filledFormItems.add(filledFormItem);
      }
      filledForms.add(TestUtil.createFilledFormByFormId(customForm.getFormId(), filledFormItems));
    }
    // ---------------------------------------------filled
    // forms---------------------------------------------

    gallery.setFirstSortItemId(items.get(0).getFormItemId());
    gallery.setSecondSortItemId(items.get(1).getFormItemId());

    gallery.setFirstSortType(GallerySortOrder.ASCENDING);
    gallery.setSecondSortType(GallerySortOrder.DESCENDING);

    Assert.assertNull(filledFormsInSession.get(gallery, null));
    filledFormsInSession.set(gallery, filledForms, null);
    List<Integer> filledFormsIds = filledFormsInSession.get(gallery, null);
    Assert.assertNotNull(filledFormsIds);
    Assert.assertEquals(30, filledFormsIds.size());

    Assert.assertNull(filledFormsInSession.get(null, null));
    Assert.assertNull(filledFormsInSession.get(new DraftGallery(), null));

    Assert.assertEquals(filledForms.get(0).getFilledFormId(), ((int) filledFormsIds.get(0)));
    Assert.assertEquals(filledForms.get(1).getFilledFormId(), ((int) filledFormsIds.get(1)));
    Assert.assertEquals(filledForms.get(2).getFilledFormId(), ((int) filledFormsIds.get(2)));

    Assert.assertEquals(
        5,
        filledFormsInSession
            .reduceSortedItems(filledFormsIds, (gallery.getRows() * gallery.getColumns()), 3)
            .size());
  }
 @RemoteMethod
 public UpdateMenuItemResponse execute(final Integer menuId) throws Exception {
   final UpdateMenuItemResponse response = new UpdateMenuItemResponse();
   final DraftMenu menu = persistance.getMenuById(menuId);
   if (menu == null) {
     logger.warning(
         "Can`t create default structure for menu with id = " + menuId + ". Menu not found.");
     return response;
   }
   final Site site = persistance.getSite(menu.getSiteId());
   if (site == null) {
     logger.warning(
         "Can`t create default structure for menu with id = "
             + menuId
             + ". Site not found. Site id "
             + "in this menu = "
             + menu.getSiteId());
     return response;
   }
   final DraftMenu defaultMenu = site.getMenu();
   if (defaultMenu == null) {
     logger.warning(
         "Can`t create default structure for menu with id = "
             + menuId
             + ". Default menu not found"
             + " for site with id = "
             + menu.getSiteId());
     return response;
   }
   ServiceLocator.getPersistanceTransaction()
       .execute(
           new Runnable() {
             public void run() {
               MenuItemsManager.restoreDefaultStructure(defaultMenu, menu);
             }
           });
   final MenuPagesHtmlTextCreator pagesHtmlTextCreator =
       new MenuPagesHtmlTextCreator(
           menu, new MenuPageCheckSometimes(menu), SiteShowOption.getDraftOption());
   response.setTreeHtml(pagesHtmlTextCreator.getHtml());
   if (!menu.getMenuItems().isEmpty()) {
     final int selectedMenuItemId = menu.getMenuItems().get(0).getId();
     response.setInfoAboutSelectedItem(new GetInfoAboutItemService().execute(selectedMenuItemId));
     response.setSelectedMenuItemId(selectedMenuItemId);
   }
   return response;
 }
  /**
   * @param widgetId - selected widget id
   * @param force - if this parameter true login show always. If false login show only if visitor
   *     not logined.
   * @return - html with login controls
   * @throws IOException
   * @throws ServletException
   */
  @RemoteMethod
  @SynchronizeByMethodParameter(entityClass = Widget.class)
  public String execute(final int widgetId, final boolean force)
      throws IOException, ServletException {
    this.widgetId = widgetId;
    widget = persistance.getWidget(widgetId);
    if (widget == null) {
      throw new WidgetNotFoundException("Cannot find widget by id " + widgetId);
    }
    final Cookie[] cookies = getContext().getHttpServletRequest().getCookies();
    final Site site = widget.getSite();
    if (cookies != null) {
      final Cookie crypted = ActionUtil.findCookie(cookies, "sh_cpt" + site.getSiteId());
      final Cookie visitorId = ActionUtil.findCookie(cookies, "sh_vid" + site.getSiteId());
      if (crypted != null && visitorId != null && !force) {
        // Getting our user from cookie
        user = persistance.getUserById(Integer.parseInt(visitorId.getValue()));

        // Check for rights.
        if (user == null
            || persistance.getUserOnSiteRightByUserAndSiteId(user.getUserId(), site.getSiteId())
                == null) {
          return executePage("/site/render/widgetLogin.jsp");
        }

        // Checking if user md5(login + password) matches the same form cookie
        if (MD5.crypt(user.getEmail() + user.getPassword()).equals(crypted.getValue())) {
          // If so - login our user
          new UsersManager().login(user.getUserId());
        }
      }
    }

    user = new UsersManager().getLoginedUser();
    if (user != null && !force) {
      final boolean isVisitorLogined =
          user != null && new UserRightManager(user).toSite(site) != null;

      if (isVisitorLogined) {
        return executePage("/site/render/visitorLogined.jsp");
      } else {
        return executePage("/site/render/widgetLogin.jsp");
      }
    }
    return executePage("/site/render/widgetLogin.jsp");
  }
  @Test
  public void getForumsByUserId() {
    User user = new User();
    user.setPassword("1");
    user.setEmail("a");
    user.setRegistrationDate(new Date());
    persistance.putUser(user);

    Site site = new Site();
    site.getSitePaymentSettings().setUserId(-1);
    site.setSubDomain("$");
    site.getThemeId().setTemplateDirectory("f");
    site.getThemeId().setThemeCss("G");
    site.setTitle("F");
    persistance.putSite(site);

    UserOnSiteRight userOnUserRight = new UserOnSiteRight();
    userOnUserRight.setActive(true);
    userOnUserRight.setSiteAccessType(SiteAccessLevel.ADMINISTRATOR);
    user.addUserOnSiteRight(userOnUserRight);
    site.addUserOnSiteRight(userOnUserRight);
    persistance.putUserOnSiteRight(userOnUserRight);

    DraftForum forum = new DraftForum();
    forum.setSiteId(site.getSiteId());
    forum.setName("name");
    persistance.putItem(forum);

    List<DraftItem> userForums =
        persistance.getDraftItemsByUserId(user.getUserId(), ItemType.FORUM);
    Assert.assertEquals(forum, userForums.get(0));
  }
  @Test
  public void putSiteOnForumRight() {
    DraftForum forum = new DraftForum();
    forum.setName("aa");
    persistance.putItem(forum);

    Site site = new Site();
    site.getSitePaymentSettings().setUserId(-1);
    site.setTitle("f");
    site.setSubDomain("g");
    site.getThemeId().setTemplateDirectory("f");
    site.getThemeId().setThemeCss("f");
    persistance.putSite(site);

    SiteOnItem siteOnForumRight = new SiteOnItem();
    siteOnForumRight.getId().setItem(forum);
    siteOnForumRight.getId().setSite(site);
    persistance.putSiteOnItem(siteOnForumRight);
  }
  @Test(expected = ContactUsNameNotUniqueException.class)
  public void executeWithNotUniqueName() throws ServletException, IOException {
    final Site site = TestUtil.createSite();
    TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR);
    PageManager pageVersion = TestUtil.createPageVersionAndPage(site);

    WidgetItem widget = TestUtil.createWidgetItem();
    widget.setPosition(0);
    persistance.putWidget(widget);
    pageVersion.addWidget(widget);

    DraftContactUs contactUs = new DraftContactUs();
    contactUs.setShowDescription(true);
    contactUs.setEmail("[email protected]");
    contactUs.setDescription("header");
    contactUs.setName("name2");
    contactUs.setSiteId(site.getSiteId());
    ServiceLocator.getPersistance().putContactUs(contactUs);

    DraftContactUs contactUs2 = new DraftContactUs();
    contactUs2.setShowDescription(true);
    contactUs2.setEmail("[email protected]");
    contactUs2.setDescription("header2");
    contactUs2.setName("name");
    contactUs2.setSiteId(site.getSiteId());
    ServiceLocator.getPersistance().putContactUs(contactUs2);

    widget.setDraftItem(contactUs);

    final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest();
    request.setContactUsName("name");
    request.setContactUsId(contactUs.getId());
    request.setDisplayHeader(true);
    request.setEmail("[email protected]");
    request.setHeader("header");
    request.setWidgetId(widget.getWidgetId());
    final List<DraftFormItem> formItems =
        TestUtil.createFormItems(FormItemName.FIRST_NAME, FormItemName.REGISTRATION_EMAIL);
    request.setFormItems(formItems);

    service.execute(request);
  }
  @Test
  public void getForumsByUserIdWithoutActive() {
    User user = new User();
    user.setPassword("1");
    user.setEmail("a");
    user.setRegistrationDate(new Date());
    persistance.putUser(user);

    Site site = new Site();
    site.getSitePaymentSettings().setUserId(-1);
    site.setSubDomain("$");
    site.getThemeId().setTemplateDirectory("f");
    site.getThemeId().setThemeCss("G");
    site.setTitle("F");
    persistance.putSite(site);

    DraftForum forum = new DraftForum();
    forum.setSiteId(site.getSiteId());
    forum.setName("name");
    persistance.putItem(forum);

    List<DraftItem> userForums =
        persistance.getDraftItemsByUserId(user.getUserId(), ItemType.FORUM);
    Assert.assertEquals(0, userForums.size());
  }
 @Test
 public void testExecute_WithActiveUserAndCreatedChildSite() throws Exception {
   final Date activationDate = new Date();
   User user = TestUtil.createUser();
   user.setActiveted(activationDate);
   Site parentSite = TestUtil.createSite();
   DraftChildSiteRegistration registration = TestUtil.createChildSiteRegistration(parentSite);
   ChildSiteSettings settings = TestUtil.createChildSiteSettings(registration, parentSite);
   Site childSite = TestUtil.createSite();
   settings.setSite(childSite);
   settings.setUserId(user.getUserId());
   settings.setConfirmCode("confirm");
   settings.setCreatedDate(new Date());
   settings.setAccessLevel(SiteAccessLevel.ADMINISTRATOR);
   action.setSettingsId(settings.getChildSiteSettingsId());
   action.setConfirmCode("confirm");
   ResolutionMock resolutionMock = (ResolutionMock) action.show();
   Assert.assertEquals(SiteEditPageAction.class, resolutionMock.getRedirectByAction());
   Assert.assertEquals("siteId", resolutionMock.getRedirectByActionParameters()[0].getName());
   Assert.assertEquals(
       childSite.getSiteId(), resolutionMock.getRedirectByActionParameters()[0].getValue());
 }
  @SynchronizeByMethodParameter(entityClass = Site.class)
  @RemoteMethod
  public String sort(
      final int siteId,
      final StatisticsSortType sortType,
      final boolean desc,
      final StatisticsTimePeriodType timePeriod,
      final Integer pageNumber)
      throws IOException, ServletException {
    final UserManager userManager = new UsersManager().getLogined();
    final Site site = userManager.getRight().getSiteRight().getSiteForView(siteId).getSite();

    final List<Page> sitePages = PagesWithoutSystem.get(site.getPages());
    sessionStorage.setStatisticsTimePeriodTypeInServiceForPage(this, timePeriod);

    final Paginator paginator =
        statisticsPageSort.sort(sitePages, sortType, desc, timePeriod, pageNumber);

    getContext().getHttpServletRequest().setAttribute("paginator", paginator);
    getContext().getHttpServletRequest().setAttribute("trafficPagesSortType", sortType);
    getContext().getHttpServletRequest().setAttribute("descending", desc);
    return executePage("/site/traffic/trafficPagesList.jsp");
  }
  @Test
  public void getFormFiltersByUserId_and_getFormFilterByNameAndUserId() {
    User user = new User();
    user.setPassword("1");
    user.setEmail("a");
    user.setRegistrationDate(new Date());
    persistance.putUser(user);

    Site site = new Site();
    site.getSitePaymentSettings().setUserId(-1);
    site.setSubDomain("$");
    site.getThemeId().setTemplateDirectory("f");
    site.getThemeId().setThemeCss("G");
    site.setTitle("F");
    persistance.putSite(site);

    UserOnSiteRight userOnUserRight = new UserOnSiteRight();
    userOnUserRight.setActive(true);
    userOnUserRight.setSiteAccessType(SiteAccessLevel.ADMINISTRATOR);
    user.addUserOnSiteRight(userOnUserRight);
    site.addUserOnSiteRight(userOnUserRight);
    persistance.putUserOnSiteRight(userOnUserRight);

    DraftForm form = new DraftCustomForm();
    form.setSiteId(site.getSiteId());
    form.setName("name");
    persistance.putItem(form);

    DraftFormFilter filter = new DraftFormFilter();
    filter.setForm(form);
    String filterName = "filter name " + System.currentTimeMillis();
    filter.setName(filterName);
    persistance.putFormFilter(filter);

    List<DraftFormFilter> userFitlers = persistance.getFormFiltersByUserId(user.getUserId());
    Assert.assertEquals(filter, userFitlers.get(0));

    DraftFormFilter namedUserFilter =
        persistance.getFormFilterByNameAndUserId(filterName, user.getUserId());
    Assert.assertEquals(filter, namedUserFilter);
  }
 public static void execute() {
   for (final Site site : ServiceLocator.getPersistance().getSitesWithNotEmptyIncomeSettings()) {
     if (site.getIncomeSettings() != null && site.getIncomeSettings().getSum() > 0) {
       final PayPalPaymentRequest request = new PayPalPaymentRequest();
       request.setEmail(site.getIncomeSettings().getPaypalAddress());
       request.setSum(site.getIncomeSettings().getSum());
       request.setNote(StringUtil.getEmptyOrString(site.getIncomeSettings().getPaymentDetails()));
       request.setSiteId(site.getId());
       try {
         // Here should be default PayPal because we must send money from our system to child
         // site`s owner,
         // which decided to use our payment system instead of their own one.
         ((PayPal) PaymentSystem.newInstance(PaymentMethod.PAYPAL))
             .massPayment(Arrays.asList(request), PaymentReason.AUTO_PAYMENT);
         new SiteManager(site).clearIncomeSettings();
       } catch (Exception exception) {
         Logger.getLogger(IncomeSettingsOwnerMoneySender.class.getName())
             .log(Level.SEVERE, "Can`t send money for parent site.", exception);
       }
     }
   }
 }
  @Test
  public void testExecute_WithFirstState() throws Exception {
    ServiceLocator.getConfigStorage().get().setUserSitesUrl("web-deva.com");
    User user = TestUtil.createUser();
    user.setActiveted(null);
    Site parentSite = TestUtil.createSite();
    DraftChildSiteRegistration registration = TestUtil.createChildSiteRegistration(parentSite);
    ChildSiteSettings settings = TestUtil.createChildSiteSettings(registration, parentSite);
    settings.setCreatedDate(new Date());
    settings.setUserId(user.getUserId());
    settings.setConfirmCode("confirm");
    settings.setAccessLevel(SiteAccessLevel.ADMINISTRATOR);

    FilledForm filledForm = TestUtil.createFilledForm(registration.getFormId());
    FilledFormItem filledFormItemDomainName =
        TestUtil.createFilledFormItem(FormItemName.YOUR_OWN_DOMAIN_NAME);
    List<String> values = Arrays.asList("domainName");
    filledFormItemDomainName.setValues(values);

    FilledFormItem filledFormItemSiteName =
        TestUtil.createFilledFormItem(FormItemName.YOUR_PAGE_SITE_NAME);
    List<String> siteNameValues = Arrays.asList("siteName");
    filledFormItemSiteName.setValues(siteNameValues);

    filledForm.setFilledFormItems(Arrays.asList(filledFormItemDomainName, filledFormItemSiteName));
    settings.setFilledFormId(filledForm.getFilledFormId());

    action.setSettingsId(settings.getChildSiteSettingsId());
    action.setConfirmCode("confirm");

    DraftChildSiteRegistration childSiteRegistration =
        TestUtil.createChildSiteRegistration("name", "comment");
    Site blueprint = TestUtil.createBlueprint();
    childSiteRegistration.setBlueprintsId(Arrays.asList(blueprint.getSiteId()));

    settings.setRequiredToUseSiteBlueprint(true);
    final SitePaymentSettings sitePaymentSettings = new SitePaymentSettings();
    sitePaymentSettings.setSiteStatus(SiteStatus.ACTIVE);
    settings.setSitePaymentSettings(sitePaymentSettings);
    settings.setChildSiteRegistration(childSiteRegistration);

    Assert.assertNull(user.getActiveted());
    Assert.assertNull(new UsersManager().getLoginedUser());
    Assert.assertNull(ServiceLocator.getPersistance().getSiteBySubDomain("domainname"));

    ForwardResolution resolutionMock = (ForwardResolution) action.show();
    Assert.assertNotNull(new UsersManager().getLoginedUser());
    Assert.assertEquals(user, new UsersManager().getLoginedUser());
    Assert.assertEquals(
        "/account/registration/childSiteRigistrationConfirmationFirstState.jsp",
        resolutionMock.getPath());

    Assert.assertNotNull(user.getActiveted());
    Assert.assertNotNull(new UsersManager().getLoginedUser());
    Assert.assertEquals(user, new UsersManager().getLoginedUser());
    Site site = ServiceLocator.getPersistance().getSiteBySubDomain("domainname");
    Assert.assertNotNull(site);
    Assert.assertNotNull(new UserRightManager(user).toSite(site).getSiteAccessType());
    Assert.assertEquals(
        settings.getAccessLevel(), new UserRightManager(user).toSite(site).getSiteAccessType());
    Assert.assertEquals("domainname", site.getSubDomain());
    Assert.assertEquals("http://domainname.web-deva.com", action.getUrl());
    Assert.assertNotNull(action.getTellFriendHtml());
    Assert.assertEquals(2, site.getPages().size());

    Assert.assertEquals("siteName", site.getTitle());
    Assert.assertEquals(blueprint, site.getBlueprintParent());
  }
  @RemoteMethod
  public GoToPaypalResponse goToPaypal(final PaypalRequest request) throws Exception {
    final PaymentReason paymentReason = PaymentReason.SHROGGLE_MONTHLY_PAYMENT;
    final Site site = ServiceLocator.getPersistance().getSite(request.getOwnerId());

    if (site == null) {
      throw new PaymentException(
          "Cannot pay for null site. Site by Id=" + request.getOwnerId() + " not found.");
    }

    final GoToPaypalResponse response = new GoToPaypalResponse();
    if (site.getSitePaymentSettings().getSiteStatus() == SiteStatus.ACTIVE
        && site.getSitePaymentSettings().getChargeType() == ChargeType.SITE_ONE_TIME_FEE) {
      response.setActivatedWithOneTimeFee(true);
      return response;
    }

    final String redirectOnErrorUrl = "/account/updatePaymentInfo.action?showPaypalError=true";
    final PaypalPaymentInfoRequest paymentInfoRequest =
        new PaypalPaymentInfoRequest(
            request.getOwnerId(),
            PaymentSettingsOwnerType.SITE,
            request.getChargeType(),
            request.getRedirectToUrl(),
            redirectOnErrorUrl,
            paymentReason,
            null);
    final int requestId =
        ServiceLocator.getPaypalPaymentInfoRequestStorage().put(paymentInfoRequest);

    final String description;
    if (request.getChargeType().getPaymentPeriod().equals(PaymentPeriod.MONTH)) {
      description = "Monthly cost of " + site.getTitle() + " site.";
    } else {
      description = "Annual cost of " + site.getTitle() + " site.";
    }
    // Here we should check, which paypal we should use: default Web-Deva`s or own. Tolik
    final PayPal payPal =
        (PayPal) new PaymentSettingsOwnerManager(site).getAppropriatePaymentSystem();

    final String applicationUrl =
        "http://" + ServiceLocator.getConfigStorage().get().getApplicationUrl();
    final String token =
        payPal.setCustomerBillingAgreement(
            applicationUrl + "/account/createProfile.action?requestId=" + requestId,
            applicationUrl + "/account/updatePaymentInfo.action",
            description,
            paymentReason,
            site.getSiteId(),
            null,
            null);

    response.setPaypalLink(payPal.getPaypalLink() + token);

    if (site.getSitePaymentSettings().getSiteStatus() == SiteStatus.ACTIVE) {
      if (site.getSitePaymentSettings().getPaymentMethod() == PaymentMethod.AUTHORIZE_NET) {
        response.setJavienActivated(true);
      } else if (payPal.getProfileStatus(site.getSitePaymentSettings().getRecurringPaymentId())
          == PayPalRecurringProfileStatus.ACTIVE) {
        response.setActiveProfile(true);
      }
    }
    return response;
  }