@RemoteProxy @Filter( type = SynchronizeForDwrFilter.class, params = {}) public class DeleteBlogPostService extends AbstractService { @SynchronizeByMethodParameter(entityClass = BlogPost.class, method = SynchronizeMethod.WRITE) @RemoteMethod public void execute(final int blogPostId) { final User user = new UsersManager().getLoginedUser(); final Integer loginedUserId = user != null ? user.getUserId() : null; final BlogPost blogPost = BlogRight.getBlogPostOnEdit(loginedUserId, blogPostId); persistanceTransaction.execute( new Runnable() { public void run() { persistance.removeBlogPost(blogPost); } }); } private final SessionStorage sessionStorage = ServiceLocator.getSessionStorage(); private final Persistance persistance = ServiceLocator.getPersistance(); private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); }
/** @author Artem Stasuk */ @RemoteProxy @Filter(type = SynchronizeForDwrFilter.class) public class ShowRequestContentService extends ServiceWithExecutePage { @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"); } public List<Site> getSites() { return sites; } public Site getTargetSite() { return targetSite; } public List<Site> getTargetSites() { return targetSites; } public String getUserSitesUrl() { return userSitesUrl; } private List<Site> sites; private List<Site> targetSites; private Site targetSite; private String userSitesUrl; private final Persistance persistance = ServiceLocator.getPersistance(); private final ConfigStorage configStorage = ServiceLocator.getConfigStorage(); }
@Test public void executeFromManageItems() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final ContactUs contactUs = TestUtil.createContactUs(site); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail("[email protected]"); request.setHeader("header"); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); final FunctionalWidgetInfo response = service.execute(request); Assert.assertNotNull(response); Assert.assertNull(response.getWidget()); Assert.assertEquals("name", contactUs.getName()); Assert.assertEquals("header", contactUs.getDescription()); Assert.assertTrue(contactUs.isShowDescription()); Assert.assertEquals(FormType.CONTACT_US, contactUs.getType()); }
/** @author dmitry.solomadin */ @RemoteProxy @Filter(type = SynchronizeForDwrFilter.class) public class TrafficPagesService extends ServiceWithExecutePage { @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"); } private final SessionStorage sessionStorage = ServiceLocator.getSessionStorage(); private final StatisticsPageSort statisticsPageSort = new StatisticsPageSort(); }
@Test(expected = InvalidContactUsEmailException.class) public void executeWithoutEmail() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final ContactUs contactUs = TestUtil.createContactUs(site); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail(null); request.setHeader("header"); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); service.execute(request); }
/** @author dmitry.solomadin */ @RemoteProxy public class CreateItemSizeService { // todo. Add tests. @SynchronizeByMethodParameter(entityClass = Widget.class) @RemoteMethod public void execute(final CreateItemSizeRequest request) throws IOException, ServletException { final UserManager userManager = new UsersManager().getLogined(); persistanceTransaction.execute( new Runnable() { @Override public void run() { if (request.getWidgetId() != null) { // Saving with widget (from Site Edit Page or from Dashboard). final Widget widget = userManager.getRight().getSiteRight().getWidgetForEdit(request.getWidgetId()); final WidgetManager widgetManager = new WidgetManager(widget); if (request.isSaveItemSizeInCurrentPlace()) { widgetManager.setItemSizeInCurrentPlace(request.getItemSize()); } else { widgetManager.setItemSizeInAllPlaces(request.getItemSize()); } } else if (request.getDraftItemId() != null) { // Saving with draftItem (from Manage Items). new ItemManager(request.getDraftItemId()).updateItemSize(request.getItemSize()); } } }); } private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); }
public Resource get(final ResourceRequest request) { final DraftGallery gallery = ServiceLocator.getPersistance().getDraftItem(request.getSizeId()); if (gallery == null) { return null; } final Resource resource = ServiceLocator.getPersistance().getFormFileById(request.getId()); if (resource == null) { return null; } final ResourceSize resourceSize = ResourceSizeCustom.createByWidthHeight( gallery.getThumbnailWidth(), gallery.getThumbnailHeight()); return ResourceCustom.copyWithSize(resource, resourceSize); }
@DefaultHandler public Resolution execute() { try { new UsersManager().getLogined(); } catch (final UserException exception) { return ServiceLocator.getResolutionCreator().loginInUser(this); } try { final FormExportTaskManager manager = new FormExportTaskManager(formExportTaskId); return ServiceLocator.getResolutionCreator() .resourceDownload( new StringInputStream(manager.createCSVFile()), manager.createCsvFileName()); } catch (Exception e) { logger.log(Level.SEVERE, "Unable to create csv file.", e); return null; } }
/** @author Artem Stasuk, dmitry.solomadin */ @RemoteProxy public class SaveScriptService extends AbstractService { @RemoteMethod public FunctionalWidgetInfo execute(final SaveScriptRequest request) throws Exception { final UserManager userManager = new UsersManager().getLogined(); final WidgetItem widget; if (request.getWidgetId() != null) { widget = (WidgetItem) userManager .getRight() .getSiteRight() .getWidgetForEditInPresentationalService(request.getWidgetId()); } else { widget = null; } persistanceTransaction.execute( new Runnable() { @Override public void run() { final DraftScript draftScript = persistance.getDraftItem(request.getScriptItemId()); if (draftScript == null || draftScript.getSiteId() <= 0) { throw new ScriptNotFoundException( "Cannot find script item by Id=" + request.getScriptItemId()); } draftScript.setText(request.getText()); draftScript.setName(request.getName()); draftScript.setDescription(request.getDescription()); draftScript.setShowDescription(request.isShowDescription()); } }); return new GetFunctionalWidgetsService().createFunctionalWidgetInfo(widget, "widget", true); } private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); private Persistance persistance = ServiceLocator.getPersistance(); }
private TimeCounter createTimeCounter(final String sql) { if (sql == null) { return new TimeCounterCreatorEmpty().create(sql); } final TimeCounterCreator timeCounterCreator = ServiceLocator.getTimeCounterCreator(); if (timeCounterCreator == null) { return new TimeCounterCreatorEmpty().create("sql://" + sql); } return timeCounterCreator.create(sql); }
@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); }
/** @author Balakirev Anatoliy */ @RemoteProxy public class RestoreDefaultStructureService extends AbstractService { @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; } private final Persistance persistance = ServiceLocator.getPersistance(); private final Logger logger = Logger.getLogger(this.getClass().getName()); }
@Before public void before() { action.setContext(new ActionBeanContext()); action.getContext().setRequest(new MockHttpServletRequest("", "")); ServiceLocator.getConfigStorage().get().setApplicationUrl("www.web-deva.com"); FileSystemMock fileSystemMock = ((FileSystemMock) ServiceLocator.getFileSystem()); Template template = TestUtil.createTemplate(); template.setLayouts( new ArrayList<Layout>() { { Layout layout = new Layout(); layout.setName("layout"); layout.setFile("layout"); add(layout); } }); fileSystemMock.putTemplate(template); fileSystemMock.addTemplateResource( "directory", "layout", "<!-- MEDIA_BLOCK --><!-- MEDIA_BLOCK --><!-- MEDIA_BLOCK -->"); }
@Test public void execute() throws Exception { TestUtil.createUserAndLogin(); final Site site = TestUtil.createSite(); final PageManager pageVersion = TestUtil.createPageVersionSiteUser(); Widget widgetCustomForm = TestUtil.createCustomFormWidget(pageVersion); final DraftCustomForm customForm = TestUtil.createCustomForm(site); final List<FilledFormItem> filledFormItems = TestUtil.createFilledFormItems(FormItemName.FIRST_NAME, FormItemName.LAST_NAME); filledFormItems.get(0).setValue("FN1"); filledFormItems.get(1).setValue("LN1"); final SubmitCustomFormRequest request = new SubmitCustomFormRequest(); request.setFormId(customForm.getFormId()); request.setWidgetId(widgetCustomForm.getWidgetId()); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setVerificationCode("aaaaaa"); request.setFilledFormItems(filledFormItems); ServiceLocator.getSessionStorage() .setNoBotCode(null, "customForm" + widgetCustomForm.getWidgetId(), "aaaaaa"); final SubmitCustomFormResponse response = service.execute(request); Assert.assertNull(response.getNextPageHtml()); final FilledForm filledCustomForm = ServiceLocator.getPersistance().getFilledFormById(response.getFilledFormId()); Assert.assertNotNull(filledCustomForm); Assert.assertEquals( filledFormItems.get(0).getValues(), filledCustomForm.getFilledFormItems().get(0).getValues()); Assert.assertEquals( filledFormItems.get(1).getValues(), filledCustomForm.getFilledFormItems().get(1).getValues()); }
public FormData(final FilledForm filledForm) { description = filledForm.getFormDescription(); final DraftForm form = ServiceLocator.getPersistance().getFormById(filledForm.getFormId()); formId = form.getFormId(); formName = form.getName(); showDescription = form.isShowDescription(); termsAndConditions = form instanceof DraftRegistrationForm ? ((DraftRegistrationForm) form).getTermsAndConditions() : null; requireTermsAndConditions = form instanceof DraftRegistrationForm && ((DraftRegistrationForm) form).isRequireTermsAndConditions(); updateChildSiteRegistrationFields(form); this.formItems = FormItemsManager.createFormItemsByFilledForm(filledForm, form); }
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(expected = WrongVerificationCodeException.class) public void executeWithoutCustomForm() throws Exception { TestUtil.createUserAndLogin(); final Site site = TestUtil.createSite(); final PageManager pageVersion = TestUtil.createPageVersionSiteUser(); Widget widgetCustomForm = TestUtil.createCustomFormWidget(pageVersion); final List<FilledFormItem> filledFormItems = TestUtil.createFilledFormItems(FormItemName.FIRST_NAME, FormItemName.LAST_NAME); filledFormItems.get(0).setValue("FN1"); filledFormItems.get(1).setValue("LN1"); final SubmitCustomFormRequest request = new SubmitCustomFormRequest(); request.setWidgetId(widgetCustomForm.getWidgetId()); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setFilledFormItems(filledFormItems); ServiceLocator.getSessionStorage() .setNoBotCode(null, "customForm" + widgetCustomForm.getWidgetId(), "aaaaaa"); service.execute(request); }
@DefaultHandler public Resolution upload() { try { if (fileData == null || filledFormId < 1) { throw new UnsupportedOperationException(); } final FilledForm filledForm = persistance.getFilledFormById(filledFormId); final DraftForm form = persistance.getFormById(filledForm.getFormId()); final FilledFormItem filledFormItem = FilledFormManager.getFilledFormItemByItemPosition(filledForm, position); final FormVideo formVideo = getFormVideoOrCreateNew(filledFormItem); final int siteId = form.getSiteId(); final SourceVideoFileCreator sourceVideoFileCreator = new SourceVideoFileCreator( siteId, FileNameUtil.createExtension(fileData.getFileName()), fileData.getFileName(), fileData.getInputStream()); final Video video = sourceVideoFileCreator.execute(); persistanceTransaction.execute( new PersistanceTransactionContext<Void>() { public Void execute() { if (formItemName == FormItemName.VIDEO_FILE_UPLOAD) { try { video.setFilledFormId(filledForm.getFilledFormId()); video.setFilledFormItemId(filledFormItem.getItemId()); formVideo.setVideoId(video.getVideoId()); FlvVideoManager.getFlvVideoOrCreateNew( video.getVideoId(), video.getSourceWidth(), video.getSourceHeight(), formVideo.getQuality(), video.getSiteId()); } catch (Exception exception) { logger.log(Level.SEVERE, "Can`t create video file!", exception); } } else if (formItemName == FormItemName.IMAGE_FILE_UPLOAD) { formVideo.setImageId((new CreateFormFileUtil().createFormFile(fileData, siteId))); } return null; } }); ServiceLocator.getPersistanceTransaction() .execute( new Runnable() { public void run() { GalleriesManager.updateVideoFilesForGalleriesThatUseCurentForm( filledForm.getFormId()); } }); } catch (Exception exception1) { try { this.getContext().getResponse().getOutputStream().println("-200"); } catch (Exception exception2) { logger.log(Level.SEVERE, "Error while writing file", exception2); } logger.log(Level.SEVERE, "Error while writing file", exception1); return resolutionCreator.forwardToUrl("/SWFUpload/error.jsp"); } return resolutionCreator.forwardToUrl("/SWFUpload/success.jsp"); }
/** @author Balakirev Anatoliy */ @UrlBinding("/uploadFormVideoFiles.action") public class UploadFormVideoFilesAction extends Action implements UploadedFiles { @DefaultHandler public Resolution upload() { try { if (fileData == null || filledFormId < 1) { throw new UnsupportedOperationException(); } final FilledForm filledForm = persistance.getFilledFormById(filledFormId); final DraftForm form = persistance.getFormById(filledForm.getFormId()); final FilledFormItem filledFormItem = FilledFormManager.getFilledFormItemByItemPosition(filledForm, position); final FormVideo formVideo = getFormVideoOrCreateNew(filledFormItem); final int siteId = form.getSiteId(); final SourceVideoFileCreator sourceVideoFileCreator = new SourceVideoFileCreator( siteId, FileNameUtil.createExtension(fileData.getFileName()), fileData.getFileName(), fileData.getInputStream()); final Video video = sourceVideoFileCreator.execute(); persistanceTransaction.execute( new PersistanceTransactionContext<Void>() { public Void execute() { if (formItemName == FormItemName.VIDEO_FILE_UPLOAD) { try { video.setFilledFormId(filledForm.getFilledFormId()); video.setFilledFormItemId(filledFormItem.getItemId()); formVideo.setVideoId(video.getVideoId()); FlvVideoManager.getFlvVideoOrCreateNew( video.getVideoId(), video.getSourceWidth(), video.getSourceHeight(), formVideo.getQuality(), video.getSiteId()); } catch (Exception exception) { logger.log(Level.SEVERE, "Can`t create video file!", exception); } } else if (formItemName == FormItemName.IMAGE_FILE_UPLOAD) { formVideo.setImageId((new CreateFormFileUtil().createFormFile(fileData, siteId))); } return null; } }); ServiceLocator.getPersistanceTransaction() .execute( new Runnable() { public void run() { GalleriesManager.updateVideoFilesForGalleriesThatUseCurentForm( filledForm.getFormId()); } }); } catch (Exception exception1) { try { this.getContext().getResponse().getOutputStream().println("-200"); } catch (Exception exception2) { logger.log(Level.SEVERE, "Error while writing file", exception2); } logger.log(Level.SEVERE, "Error while writing file", exception1); return resolutionCreator.forwardToUrl("/SWFUpload/error.jsp"); } return resolutionCreator.forwardToUrl("/SWFUpload/success.jsp"); } private FormVideo getFormVideoOrCreateNew(final FilledFormItem filledFormItem) { final FormVideo formVideo = persistance.getFormVideoById(FilledFormItemManager.getIntValue(filledFormItem)); if (formVideo == null) { return persistanceTransaction.execute( new PersistanceTransactionContext<FormVideo>() { public FormVideo execute() { final FormVideo newFormVideo = new FormVideo(); persistance.putFormVideo(newFormVideo); filledFormItem.setValue("" + newFormVideo.getFormVideoId()); return newFormVideo; } }); } else { return formVideo; } } public FormItemName getFormItemName() { return formItemName; } public void setFormItemName(FormItemName formItemName) { this.formItemName = formItemName; } public int getFilledFormId() { return filledFormId; } public void setFilledFormId(int filledFormId) { this.filledFormId = filledFormId; } public FileBean getFileData() { return fileData; } public void setFileData(FileBean fileData) { this.fileData = fileData; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } private FormItemName formItemName; private int filledFormId; private int position; private final Persistance persistance = ServiceLocator.getPersistance(); private final ResolutionCreator resolutionCreator = ServiceLocator.getResolutionCreator(); private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); private static final Logger logger = Logger.getLogger(UploadFormFilesAction.class.getName()); private FileBean fileData; public String getResourceUrl() { return null; // To change body of implemented methods use File | Settings | File Templates. } public int getResourceId() { return 0; // To change body of implemented methods use File | Settings | File Templates. } public ResourceType getResourceType() { return null; // To change body of implemented methods use File | Settings | File Templates. } }
@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; }
@RemoteMethod public String goToPaypalCSR(final PaypalRequest request) throws Exception { final PaymentReason paymentReason = PaymentReason.CHILD_SITE_CREATION; // Modifying redirect url // Check on hash presence. We sould remove all old hash. if (request.getRedirectToUrl().contains("#")) { request.setRedirectToUrl( request.getRedirectToUrl().substring(0, request.getRedirectToUrl().indexOf("#"))); } if (request.getPageBreakIndex() > request.getTotalPageBreaks()) { // If payment page is last page then update return url with setting that will show message // about registration completion. request.setRedirectToUrl( request.getRedirectToUrl() + "#showSuccessMessageLastPage" + request.getWidgetId()); } else { // Upadting return from paypal url with correct form page. request.setRedirectToUrl( request.getRedirectToUrl() + (request.getRedirectToUrl().contains("?") ? "&" : "?") + "pageBreaksToPass="******"&filledFormToUpdateId=" + request.getFilledFormToUpdateId() + "&childSiteUserId=" + request.getChildSiteUserId() + "&settingsId=" + request.getSettingsId() + "#showSuccessMessage" + request.getWidgetId()); } final PaypalPaymentInfoRequest paymentInfoRequest = new PaypalPaymentInfoRequest( request.getOwnerId(), PaymentSettingsOwnerType.CHILD_SITE_SETTINGS, request.getChargeType(), request.getRedirectToUrl(), createRedirectOnErrorUrl(request), paymentReason, request.getChildSiteUserId()); final int requestId = ServiceLocator.getPaypalPaymentInfoRequestStorage().put(paymentInfoRequest); final ChildSiteSettings childSiteSettings = ServiceLocator.getPersistance().getChildSiteSettingsById(request.getSettingsId()); // Here we should check, which paypal we should use: default Web-Deva`s or own. Tolik final PayPal payPal = (PayPal) new PaymentSettingsOwnerManager(childSiteSettings).getAppropriatePaymentSystem(); final String networkName = childSiteSettings.getChildSiteRegistration().getName(); final String applicationUrl = "http://" + ServiceLocator.getConfigStorage().get().getApplicationUrl(); final String token = payPal.setCustomerBillingAgreement( applicationUrl + "/account/createProfile.action?requestId=" + requestId, request.getRedirectToUrl() + (request.getRedirectToUrl().contains("?") ? "&" : "?") + "pageBreaksToPass="******"&filledFormToUpdateId=" + request.getFilledFormToUpdateId(), (networkName + " fee for child site"), paymentReason, null, request.getOwnerId(), request.getChildSiteUserId()); return (payPal.getPaypalLink() + token); }
@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()); }
@Test public void executeWithPageBreaksFromAddRecord() throws Exception { TestUtil.createUserAndLogin(); final Site site = TestUtil.createSite(); final DraftCustomForm customForm = TestUtil.createCustomForm(site); final List<DraftFormItem> formItems = new ArrayList<DraftFormItem>(); formItems.add(TestUtil.createFormItem(FormItemName.FIRST_NAME, 0)); formItems.add(TestUtil.createFormItem(FormItemName.PAGE_BREAK, 1)); formItems.add(TestUtil.createFormItem(FormItemName.LAST_NAME, 2)); customForm.setFormItems(formItems); // FIRST PAGE List<FilledFormItem> filledFormItems = TestUtil.createFilledFormItems(FormItemName.FIRST_NAME); filledFormItems.get(0).setValue("FN1"); SubmitCustomFormRequest request = new SubmitCustomFormRequest(); request.setFormId(customForm.getFormId()); request.setWidgetId(0); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setRequestNextPage(true); request.setPageBreaksToPass(1); request.setVerificationCode("aaaaaa"); request.setFilledFormItems(filledFormItems); request.setShowFromAddRecord(true); SubmitCustomFormResponse response = service.execute(request); Assert.assertEquals( "/site/showCustomForm.action?formId=" + request.getFormId() + "&showFromAddRecord=true" + "&pageBreaksToPass="******"&filledFormToUpdateId=" + response.getFilledFormId(), response.getNextPageHtml()); FilledForm filledContactUsForm = ServiceLocator.getPersistance().getFilledFormById(response.getFilledFormId()); Assert.assertNotNull(filledContactUsForm); Assert.assertEquals( filledFormItems.get(0).getValues(), filledContactUsForm.getFilledFormItems().get(0).getValues()); // SECOND PAGE filledFormItems = TestUtil.createFilledFormItems(FormItemName.LAST_NAME); filledFormItems.get(0).setValue("LN1"); request = new SubmitCustomFormRequest(); request.setFormId(customForm.getFormId()); request.setWidgetId(0); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setShowFromAddRecord(true); request.setRequestNextPage(true); request.setFilledFormId(response.getFilledFormId()); request.setPageBreaksToPass(2); request.setFilledFormItems(filledFormItems); response = service.execute(request); Assert.assertNull(response.getNextPageHtml()); filledContactUsForm = ServiceLocator.getPersistance().getFilledFormById(response.getFilledFormId()); Assert.assertEquals( filledFormItems.get(0).getValues(), filledContactUsForm.getFilledFormItems().get(1).getValues()); }
static TimeCounter createTimeCounter(final String name) { return ServiceLocator.getTimeCounterCreator().create("internationalStorage://" + name); }
@Test public void executeWithPageBreaks() throws Exception { TestUtil.createUserAndLogin(); final Site site = TestUtil.createSite(); final PageManager pageVersion = TestUtil.createPageVersionSiteUser(); Widget widgetCustomForm = TestUtil.createCustomFormWidget(pageVersion); final DraftCustomForm customForm = TestUtil.createCustomForm(site); final List<DraftFormItem> formItems = new ArrayList<DraftFormItem>(); formItems.add(TestUtil.createFormItem(FormItemName.FIRST_NAME, 0)); formItems.add(TestUtil.createFormItem(FormItemName.PAGE_BREAK, 1)); formItems.add(TestUtil.createFormItem(FormItemName.LAST_NAME, 2)); customForm.setFormItems(formItems); // FIRST PAGE List<FilledFormItem> filledFormItems = TestUtil.createFilledFormItems(FormItemName.FIRST_NAME); filledFormItems.get(0).setValue("FN1"); SubmitCustomFormRequest request = new SubmitCustomFormRequest(); request.setFormId(customForm.getFormId()); request.setWidgetId(widgetCustomForm.getWidgetId()); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setRequestNextPage(true); request.setPageBreaksToPass(1); request.setVerificationCode("aaaaaa"); request.setFilledFormItems(filledFormItems); ServiceLocator.getSessionStorage() .setNoBotCode(null, "customForm" + widgetCustomForm.getWidgetId(), "aaaaaa"); SubmitCustomFormResponse response = service.execute(request); Assert.assertNotNull(response.getNextPageHtml()); FilledForm filledContactUsForm = ServiceLocator.getPersistance().getFilledFormById(response.getFilledFormId()); Assert.assertNotNull(filledContactUsForm); Assert.assertEquals( filledFormItems.get(0).getValues(), filledContactUsForm.getFilledFormItems().get(0).getValues()); // SECOND PAGE filledFormItems = TestUtil.createFilledFormItems(FormItemName.LAST_NAME); filledFormItems.get(0).setValue("LN1"); request = new SubmitCustomFormRequest(); request.setFormId(customForm.getFormId()); request.setWidgetId(widgetCustomForm.getWidgetId()); request.setFilledFormItems(new ArrayList<FilledFormItem>()); request.setRequestNextPage(true); request.setFilledFormId(response.getFilledFormId()); request.setPageBreaksToPass(2); request.setFilledFormItems(filledFormItems); response = service.execute(request); // Ok, now after we have filled out last form page we need to show first form page again with // the // message about successfull form submit. Assert.assertNotNull(response.getNextPageHtml()); Assert.assertTrue(response.isShowSuccessfullSubmitMessage()); filledContactUsForm = ServiceLocator.getPersistance().getFilledFormById(response.getFilledFormId()); Assert.assertEquals( filledFormItems.get(0).getValues(), filledContactUsForm.getFilledFormItems().get(1).getValues()); }
/** @author Artem Stasuk */ public class FormFiltersManager { public FormFiltersManager(final UserManager userManager) { this.userManager = userManager; } public FormFilterManager save(final FormFilterEdit edit) { return persistanceTransaction.execute( new PersistanceTransactionContext<FormFilterManager>() { @Override public FormFilterManager execute() { final DraftFormFilter originalFormFilter = persistance.getFormFilterByNameAndFormId(edit.getName(), edit.getFormId()); if (originalFormFilter != null && edit.getId() == null) { throw new FormFilterNotUniqueNameException("Not unique name " + edit.getName()); } else if (originalFormFilter != null && originalFormFilter.getFormFilterId() != edit.getId()) { throw new FormFilterNotUniqueNameException("Not unique name " + edit.getName()); } final DraftFormFilter formFilter; final UserRightManager userRightManager = userManager.getRight(); if (edit.getId() == null) { final DraftForm form = persistance.getFormById(edit.getFormId()); if (userRightManager.toSiteItem(form) != SiteOnItemRightType.EDIT) { throw new FormNotFoundException("Can't find form " + edit.getFormId()); } formFilter = new DraftFormFilter(); formFilter.setName(edit.getName()); form.addFilter(formFilter); persistance.putFormFilter(formFilter); } else { formFilter = persistance.getFormFilterById(edit.getId()); if (formFilter == null || userRightManager.toSiteItem(formFilter.getForm()) != SiteOnItemRightType.EDIT) { throw new FormFilterNotFoundException("Can't find " + edit.getId()); } formFilter.setName(edit.getName()); } final List<DraftFormFilterRule> rules = new ArrayList<DraftFormFilterRule>(formFilter.getRules()); for (final DraftFormFilterRule rule : rules) { persistance.removeFormFilterRule(rule); } for (final FormFilterRuleEdit ruleEdit : edit.getRules()) { final DraftFormFilterRule rule = new DraftFormFilterRule(); rule.setInclude(ruleEdit.isInclude()); rule.setCriteria(ruleEdit.getCriteria()); rule.setFormItemId(ruleEdit.getFormItemId()); formFilter.addRule(rule); persistance.putFormFilterRule(rule); } return new FormFilterManager(formFilter); } }); } public List<FormFilterManager> getFilters() { final List<DraftFormFilter> filters = persistance.getFormFiltersByUserId(userManager.getUserId()); final List<FormFilterManager> filterManagers = new ArrayList<FormFilterManager>(filters.size()); for (final DraftFormFilter filter : filters) { filterManagers.add(new FormFilterManager(filter)); } return filterManagers; } public FormFilterManager get(final Integer id) { if (id != null) { final DraftFormFilter formFilter = persistance.getFormFilterById(id); if (formFilter != null) { return new FormFilterManager(formFilter); } } throw new FormFilterNotFoundException("Can't find " + id); } public String getDefaultName(final int formId) { final Set<String> usedNames = new HashSet<String>(); for (final DraftFormFilter filter : persistance.getFormById(formId).getDraftFilters()) { usedNames.add(filter.getName()); } int number = 1; final String name = "Form Filter"; while (true) { if (!usedNames.contains(name + number)) { return name + number; } if (number >= Integer.MAX_VALUE) { number = (int) Math.round(Math.random()); } else { number++; } } } public void delete(final int id) { final DraftFormFilter formFilter = persistance.getFormFilterById(id); final UserRightManager userRightManager = userManager.getRight(); if (formFilter != null && userRightManager.toSiteItem(formFilter.getForm()) == SiteOnItemRightType.EDIT) { persistanceTransaction.execute( new Runnable() { @Override public void run() { persistance.removeFormFilter(formFilter); formFilter.getDraftForm().removeFilter(formFilter); } }); } } private final UserManager userManager; private final Persistance persistance = ServiceLocator.getPersistance(); private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); }
@Test public void testExecute() { final Config config = ServiceLocator.getConfigStorage().get(); /*--------------------------------------------------1245 Gb---------------------------------------------------*/ config.setMaxPostSize("1245GB"); Assert.assertEquals(1245 * 1024 * 1024 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1245Gb"); Assert.assertEquals(1245 * 1024 * 1024 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1245gb"); Assert.assertEquals(1245 * 1024 * 1024 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1245g"); Assert.assertEquals(1245 * 1024 * 1024 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals( (1245 * 1024 * 1024 * 1024L) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*--------------------------------------------------1245 Gb---------------------------------------------------*/ /*--------------------------------------------------1000 Mb---------------------------------------------------*/ config.setMaxPostSize("1000MB"); Assert.assertEquals(1000 * 1024 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1000Mb"); Assert.assertEquals(1000 * 1024 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1000mb"); Assert.assertEquals(1000 * 1024 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1000m"); Assert.assertEquals(1000 * 1024 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals((1000 * 1024 * 1024) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*--------------------------------------------------1000 Mb---------------------------------------------------*/ /*---------------------------------------------------10 Kb----------------------------------------------------*/ config.setMaxPostSize("10KB"); Assert.assertEquals(10 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("10Kb"); Assert.assertEquals(10 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("10kb"); Assert.assertEquals(10 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("10k"); Assert.assertEquals(10 * 1024L, MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals((10 * 1024L) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*---------------------------------------------------10 Kb----------------------------------------------------*/ /*-------------------------------------------------10 bytes---------------------------------------------------*/ config.setMaxPostSize("10B"); Assert.assertEquals(10, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("10b"); Assert.assertEquals(10, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("10"); Assert.assertEquals(10, MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals((10) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*-------------------------------------------------10 bytes---------------------------------------------------*/ /*-----------------------------------------Without value in config--------------------------------------------*/ config.setMaxPostSize(null); Assert.assertEquals( MaxPostSizeCreator.getDefaultMaxPostSize(), MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals( (MaxPostSizeCreator.getDefaultMaxPostSize()) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*-----------------------------------------Without value in config--------------------------------------------*/ /*---------------------------------------With wrong value in config-------------------------------------------*/ config.setMaxPostSize("adfasdfwea"); Assert.assertEquals( MaxPostSizeCreator.getDefaultMaxPostSize(), MaxPostSizeCreator.createMaxPostSizeInBytes()); Assert.assertEquals( (MaxPostSizeCreator.getDefaultMaxPostSize()) + " B", MaxPostSizeCreator.createMaxPostSizeString()); /*---------------------------------------With wrong value in config-------------------------------------------*/ config.setMaxPostSize("100,2KB"); Assert.assertEquals(100 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1054.2KB"); Assert.assertEquals(1054 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); config.setMaxPostSize("1054.222222KB"); Assert.assertEquals(1054 * 1024, MaxPostSizeCreator.createMaxPostSizeInBytes()); }
@RunWith(value = TestRunnerWithMockServices.class) public class CreateContactUsServiceTest { @Before public void before() { MockWebContext mockWebContext = (MockWebContext) service.getContext(); mockWebContext.setHttpServletRequest(new MockHttpServletRequest("", "")); } @Test public void executeFromSiteEditPage() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final PageManager pageVersion = TestUtil.createPageVersionAndPage(site); final ContactUs contactUs = TestUtil.createContactUs(site); WidgetItem widget = TestUtil.createTextWidget(); widget.setPosition(0); persistance.putWidget(widget); pageVersion.addWidget(widget); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail("[email protected]"); request.setHeader("header"); request.setWidgetId(widget.getWidgetId()); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); final FunctionalWidgetInfo response = service.execute(request); Assert.assertNotNull(response); Assert.assertEquals(widget.getWidgetId(), response.getWidget().getWidgetId()); Assert.assertEquals("name", contactUs.getName()); Assert.assertEquals("header", contactUs.getDescription()); Assert.assertTrue(contactUs.isShowDescription()); Assert.assertEquals(FormType.CONTACT_US, contactUs.getType()); } @Test public void executeFromManageItems() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final ContactUs contactUs = TestUtil.createContactUs(site); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail("[email protected]"); request.setHeader("header"); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); final FunctionalWidgetInfo response = service.execute(request); Assert.assertNotNull(response); Assert.assertNull(response.getWidget()); Assert.assertEquals("name", contactUs.getName()); Assert.assertEquals("header", contactUs.getDescription()); Assert.assertTrue(contactUs.isShowDescription()); Assert.assertEquals(FormType.CONTACT_US, contactUs.getType()); } @Test(expected = InvalidContactUsEmailException.class) public void executeWithBadEmail() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final ContactUs contactUs = TestUtil.createContactUs(site); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail("a"); request.setHeader("header"); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); service.execute(request); } @Test(expected = InvalidContactUsEmailException.class) public void executeWithoutEmail() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final ContactUs contactUs = TestUtil.createContactUs(site); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail(null); request.setHeader("header"); request.setContactUsId(contactUs.getId()); DraftFormItem item = new DraftFormItem(); item.setPosition(0); item.setRequired(true); item.setFormItemName(FormItemName.FIRST_NAME); ServiceLocator.getPersistance().putFormItem(item); List<DraftFormItem> items = new ArrayList<DraftFormItem>(); items.add(item); request.setFormItems(items); service.execute(request); } @Test(expected = PageBreakBeforeRequiredFieldsException.class) public void executeWithPageBreakBeforeMandatory() throws ServletException, IOException { final Site site = TestUtil.createSite(); TestUtil.createUserAndUserOnSiteRightAndLogin(site, SiteAccessLevel.ADMINISTRATOR); final PageManager pageVersion = TestUtil.createPageVersionAndPage(site); WidgetItem widget = TestUtil.createWidgetItem(); widget.setPosition(0); persistance.putWidget(widget); pageVersion.addWidget(widget); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setDisplayHeader(true); request.setEmail("*****@*****.**"); request.setHeader("header"); request.setWidgetId(widget.getWidgetId()); final List<DraftFormItem> formItems = TestUtil.createFormItems( FormItemName.FIRST_NAME, FormItemName.PAGE_BREAK, FormItemName.REGISTRATION_EMAIL); request.setFormItems(formItems); service.execute(request); } @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(expected = ContactUsNotFoundException.class) public void executeWithNotFoundContactUs() 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); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setContactUsName("name"); request.setContactUsId(-1); request.setDisplayHeader(true); request.setEmail("[email protected]"); request.setHeader("header"); final List<DraftFormItem> formItems = TestUtil.createFormItems(FormItemName.FIRST_NAME, FormItemName.REGISTRATION_EMAIL); request.setFormItems(formItems); service.execute(request); } @Test(expected = UserNotLoginedException.class) public void executeWithoutLogin() throws ServletException, IOException { final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); service.execute(request); } @Test(expected = WidgetNotFoundException.class) public void executeWithoutWidget() throws ServletException, IOException { TestUtil.createUserAndLogin(); final CreateContactUsWidgetRequest request = new CreateContactUsWidgetRequest(); request.setWidgetId(2); service.execute(request); } private final CreateContactUsService service = new CreateContactUsService(); private final Persistance persistance = ServiceLocator.getPersistance(); }
@RemoteProxy public class ShowVisitorLoginService extends ServiceWithExecutePage { /** * @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"); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForRegistration(final int widgetId) throws IOException, ServletException { returnToRegistration = true; return execute(widgetId, false); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForChildSiteRegistration(final int widgetId) throws IOException, ServletException { returnToChildSiteRegistration = true; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForManageVotes(final int widgetId, final int formId) throws IOException, ServletException { returnToManageVotes = true; this.formId = formId; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForGalleryWithForm( final int widgetId, final int formId, final Integer shouldBeRegisteredFromRightFormId) throws IOException, ServletException { returnToGallery = true; this.formId = formId; this.shouldBeRegisteredFromRightFormId = shouldBeRegisteredFromRightFormId; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForShoppingCart(final int widgetId, final int formId) throws IOException, ServletException { returnToShoppingCart = true; this.formId = formId; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForGallery(final int widgetId) throws IOException, ServletException { returnToGallery = true; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForForum(final int widgetId) throws IOException, ServletException { returnToForum = true; return execute(widgetId, true); } @RemoteMethod @SynchronizeByMethodParameter(entityClass = Widget.class) public String executeForBlog(final int widgetId) throws IOException, ServletException { returnToBlog = true; return execute(widgetId, true); } public User getVisitor() { return user; } public int getWidgetId() { return widgetId; } public void setWidgetId(int widgetId) { this.widgetId = widgetId; } public void setVisitor(User user) { this.user = user; } public Widget getWidget() { return widget; } public boolean isReturnToRegistration() { return returnToRegistration; } public boolean isReturnToChildSiteRegistration() { return returnToChildSiteRegistration; } public boolean isReturnToManageVotes() { return returnToManageVotes; } public boolean isReturnToGallery() { return returnToGallery; } public Integer getFormId() { return formId; } public boolean isReturnToForum() { return returnToForum; } public boolean isReturnToBlog() { return returnToBlog; } public Integer getShouldBeRegisteredFromRightFormId() { return shouldBeRegisteredFromRightFormId; } public boolean isReturnToShoppingCart() { return returnToShoppingCart; } private final Persistance persistance = ServiceLocator.getPersistance(); private final SessionStorage sessionStorage = ServiceLocator.getSessionStorage(); private int widgetId; private Integer formId; private Integer shouldBeRegisteredFromRightFormId; private User user; private Widget widget; private boolean returnToRegistration; private boolean returnToChildSiteRegistration; private boolean returnToManageVotes; private boolean returnToGallery; private boolean returnToForum; private boolean returnToBlog; private boolean returnToShoppingCart; }
/** * @author Tolik, Dima, Artem * @see com.shroggle.presentation.account.accessPermissions.AddEditPermissionsService */ @UrlBinding("/account/createUser.action") public class CreateUserAction extends Action implements LoginedUserInfo { /** @return - show page for create account */ @SynchronizeByLoginUser @DefaultHandler public Resolution show() { state = new CreateUserState(request); request.setMode(CreateUserMode.NEW); return showInternal(); } /** * It's general method. * * @return - show create account page. */ private Resolution showInternal() { loginUser = new UsersManager().getLoginedUser(); return resolutionCreator.forwardToUrl("/account/createUser.jsp"); } /** * Need link /account/createUser.action ?showForInvited=true &request.confirmCode=X * &request.userId=X &request.invitedUserId=X * * @return - show page for accept user settings */ @SynchronizeByLoginUser @SynchronizeByClassProperties({ @SynchronizeByClassProperty( entityClass = User.class, entityIdFieldPath = "request.invitedUserId"), @SynchronizeByClassProperty(entityClass = User.class, entityIdFieldPath = "request.userId") }) public Resolution showForInvited() { state = new CreateUserState(request); request.setNotWantNewUser(true); request.setAgree(true); request.setMode(CreateUserModeCreator.get(request, state)); request.getMode().getShow().execute(this); return showInternal(); } /** * Step by step: * * <p>0. validate user 1. get or create user 2. get or create or move right and activate it 3. * login user 4. redirect to need page * * @return - resolution to next page */ @SynchronizeByAllEntity(entityClass = User.class) public Resolution execute() { state = new CreateUserState(request); final CreateUserMode mode = CreateUserModeCreator.next(request, state); request.setMode(mode); mode.getValidate().execute(this); if (getContext().getValidationErrors().size() > 0) { if (mode == CreateUserMode.INVITED_NEW) { return showForInvited(); } else { return showInternal(); } } persistanceTransaction.execute( new PersistanceTransactionContext<Void>() { @Override public Void execute() { mode.getCreateUser().execute(CreateUserAction.this); mode.getRight().execute(state); return null; } }); mode.getLogin().execute(this); return mode.getRedirect().execute(state); } public void setRequest(final CreateUserRequest request) { this.request = request; } public CreateUserRequest getRequest() { return request; } public User getLoginUser() { return loginUser; } /** * This method used only in logic code for action. It don't have public modificator. * * @return - state */ CreateUserState getState() { return state; } void setState(final CreateUserState state) { // for tests. Tolik this.state = state; } private final ResolutionCreator resolutionCreator = ServiceLocator.getResolutionCreator(); private final PersistanceTransaction persistanceTransaction = ServiceLocator.getPersistanceTransaction(); private CreateUserRequest request = new CreateUserRequest(); private CreateUserState state; private User loginUser; }