@Override public void serialize(Configurable value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { provider.defaultSerializeValue(value.getValue(), jgen); } }
@GET public Response listLocales() { List<Locale> locales; Map<String, String> endpoints = Maps.newHashMap(); GeneralSettings settings = context.getSettings(GeneralSettings.class); locales = settings.getLocales().getOtherLocales().getValue(); locales.add(settings.getLocales().getMainLocale().getValue()); for (Locale locale : locales) { endpoints.put(locale.toLanguageTag(), "/api/localization/theme/" + locale.toLanguageTag()); } return Response.ok(endpoints).build(); }
public void notifyHook(final Webhook event, final Object payload) { WebhooksSettings hooksSettings = configurationService.getSettings(WebhooksSettings.class); List<Hook> hooks = FluentIterable.from(hooksSettings.getHooks().getValue()).filter(hookMatchesEvent(event)).toList(); for (final Hook hook : hooks) { Executors.newSingleThreadExecutor().submit(new Callable<Void>() { @Override public Void call() throws Exception { doNotifyHook(event, hook, payload); return null; } }); } }
@Override public boolean isEnabledInContext() { InvoicingSettings settings = configurationService.getSettings(InvoicingSettings.class); return settings.getEnabled().getValue(); }
private Optional<Rate> getRateDefinition(final String rate) { return FluentIterable.from(taxesSettings.getVat().getValue().getOtherRates()).filter(new Predicate<Rate>() { public boolean apply(Rate input) { return input.getId().equals(rate); } }).first(); }
private Strategy getActiveStrategy() { ShippingSettings settings = configurationService.getSettings(ShippingSettings.class); return settings.getStrategy().getValue(); }
@GET @Path("{slug}") @Authorized public Response getOrder(@PathParam("slug") String slug) { Order order = orderStore.get().findBySlug(slug); if (order == null) { return Response.status(Response.Status.NOT_FOUND).entity("Order not found").build(); } GeneralSettings settings = configurationService.getSettings(GeneralSettings.class); final DateTimeZone tenantTz = DateTimeZone.forTimeZone(settings.getTime().getTimeZone().getValue()); return Response.ok(new OrderRepresentation(tenantTz, order)).build(); }
@Override public DateTime deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { String str = parser.getText().trim(); if (Strings.isNullOrEmpty(str)) { return null; } ConfigurationService configurationService = Utils.getComponent(ConfigurationService.class); GeneralSettings settings = configurationService.getSettings(GeneralSettings.class); return new DateTime(str, DateTimeZone.forTimeZone(settings.getTime().getTimeZone().getValue())); } }
private Optional<Rate> getRateForId(final String id) { TaxesSettings taxesSettings = getTaxesSettings(); return FluentIterable.from(taxesSettings.getVat().getValue().getOtherRates()).filter(new Predicate<Rate>() { @Override public boolean apply(Rate rate) { return rate.getId().equals(id); } }).first(); }
private Locale getTenantDefaultLocale() { return context.getSettings(GeneralSettings.class).getLocales().getMainLocale().getValue(); } }
@Override public void supply(Map<String, Object> data) { // Manage list of locales and corresponding links String path = context.getRequest().getCanonicalPath(); Map<String, Map<String, String>> locales = Maps.newHashMap(); GeneralSettings settings = context.getSettings(GeneralSettings.class); final Locale mainLocale = settings.getLocales().getMainLocale().getValue(); locales.put(mainLocale.toLanguageTag(), buildLocale(mainLocale, path, true)); List<Locale> alternativeLocales = FluentIterable.from(settings.getLocales().getOtherLocales().getValue()).filter(Predicates.notNull()) .toList(); if (!alternativeLocales.isEmpty()) { for (final Locale locale : alternativeLocales) { locales.put(locale.toLanguageTag(), buildLocale(locale, path, false)); } } data.put("locales", locales); data.put("locale", buildLocale(context.getLocale(), path, mainLocale.equals(context.getLocale()))); data.put("localePath", context.isAlternativeLocale() ? ("/" + context.getLocale().toLanguageTag()) : ""); data.put("url", data.get("localePath") + path); data.put("canonicalUrl", path); }
@GET @Authorized public ResultSetRepresentation<OrderRepresentation> getAllOrders( @QueryParam("number") @DefaultValue("50") Integer number, @QueryParam("offset") @DefaultValue("0") Integer offset) { GeneralSettings settings = configurationService.getSettings(GeneralSettings.class); final DateTimeZone tenantTz = DateTimeZone.forTimeZone(settings.getTime().getTimeZone().getValue()); List<Order> orders = orderStore.get().findAllPaidOrAwaitingPayment(number, offset); Collection<OrderRepresentation> representations = Collections2.transform(orders, new Function<Order, OrderRepresentation>() { public OrderRepresentation apply(final Order order) { return new OrderRepresentation(tenantTz, order); } }); Integer total = this.orderStore.get().countAllPaidOrAwaitingPayment(); ResultSetRepresentation<OrderRepresentation> resultSet = new ResultSetRepresentation<>( "/api/orders", number, offset, new ArrayList<>(representations), total ); return resultSet; }
@GET @Path(PAYMENT_RETURN_PATH + "/{order}") public WebView returnFromPaymentService(@Context UriInfo uriInfo, @PathParam("order") String orderId) { Map<String, Object> bindings = new HashMap<>(); if (StringUtils.isNotBlank(orderId)) { Order order = orderStore.get().findById(UUID.fromString(orderId)); if (order != null) { Optional<Address> da = order.getDeliveryAddress() != null ? Optional.fromNullable(order.getDeliveryAddress()) : Optional.<Address>absent(); Optional<Address> ba = order.getBillingAddress() != null ? Optional.fromNullable(order.getBillingAddress()) : Optional.<Address>absent(); bindings.putAll( prepareContext(order, order.getCustomer(), ba, da, webContext.getTenant(), configurationService.getSettings(GeneralSettings.class).getLocales().getMainLocale() .getValue())); } } return new WebView().template("checkout/success.html").with(WebView.Option.FALLBACK_ON_DEFAULT_THEME) .data(bindings); }
@Override public BigDecimal getVatRate(Taxable taxable) { BigDecimal itemVatRate = null; TaxesSettings taxesSettings = getTaxesSettings(); BigDecimal defaultVatRate = taxesSettings.getVat().getValue().getDefaultRate(); final Optional<String> vatRateId = taxable.getVatRateId(); if (vatRateId.isPresent()) { Optional<Rate> rate = getRateForId(vatRateId.get()); if (rate.isPresent()) { itemVatRate = rate.get().getValue(); } } else if (taxable.getParent().isPresent() && taxable.getParent().get().isLoaded()) { final Taxable parent = (Taxable) taxable.getParent().get().get(); if (parent.getVatRateId().isPresent()) { Optional<Rate> rate = getRateForId(parent.getVatRateId().get()); if (rate.isPresent()) { itemVatRate = rate.get().getValue(); } } } if (itemVatRate == null) { itemVatRate = defaultVatRate; } return itemVatRate; }
/** * @see {@link org.xwiki.observation.EventListener#onEvent(org.xwiki.observation.event.Event, Object, Object)} */ public void onEvent(Event event, Object source, Object data) { GeneralSettings settings = configurationService.getSettings(GeneralSettings.class); final Order order = (Order) source; final Locale customerLocale = webContext.getLocale(); final Tenant tenant = webContext.getTenant(); final Locale tenantLocale = settings.getLocales().getMainLocale().getValue(); final boolean withInvoice = invoicingService.isEnabledInContext(); Executors.newSingleThreadExecutor().submit(new Callable<Void>() { @Override public Void call() throws Exception { sendNotificationMails(order, tenant, customerLocale, tenantLocale, withInvoice); return null; } }); }
private void sendValidationMail(final User createdUser, AccountsSettings settings, Map<String, Object> additionalContext) { MailTemplate mailTemplate = new MailTemplate().template("account-validation").to(createdUser.getEmail()) .from(generalSettings.getNotificationsEmail()); try { Map<String, Object> context = Maps.newHashMap(); context.putAll(additionalContext); String validationUriTemplate; if (!Strings.isNullOrEmpty(settings.getUserValidationUriTemplate().getValue())) { validationUriTemplate = settings.getUserValidationUriTemplate().getValue(); } else { validationUriTemplate = urlHelper.getContextWebURL("/account/validation/${validationKey}").toString(); } SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(); groovy.text.Template uriTemplate = templateEngine.createTemplate(validationUriTemplate); context.put("validationLink", uriTemplate.make(new HashMap() { { put("validationKey", createdUser.getValidationKey()); } }).toString()); context.put("siteName", siteSettings.getName()); mailTemplateService.sendTemplateMail(mailTemplate, context); } catch (MailException | ClassNotFoundException | IOException e) { logger.error("Failed to send validation email", e); } }
@Override public NewCookie[] getCookies(String username, String password, boolean remember) throws EncryptionException { AccountsSettings accountsSettings = configurationService.getSettings(AccountsSettings.class); int ageWhenRemember = 60 * (context.getRequest().isApiRequest() ? accountsSettings.getApiSessionDuration().getValue() : accountsSettings.getWebSessionDuration().getValue()); NewCookie newUserCookie = new NewCookie("username", crypter.encrypt(username), "/", null, null, remember ? ageWhenRemember : -1, false); NewCookie newPassCookie = new NewCookie("password", crypter.encrypt(password), "/", null, null, remember ? ageWhenRemember : -1, false); return new NewCookie[]{ newUserCookie, newPassCookie }; } }
@Override public CartContents getCart() { Session session = this.context.getSession(); if (session.getAttribute(SESSION_CART_KEY) != null) { try { CartInSession cartInSession = (CartInSession) session.getAttribute(SESSION_CART_KEY); CartContents cartContents = cartInSessionConverter.loadFromCartInSession(cartInSession); LOGGER.debug("Retrieved cart from session with {} items", cartContents.getItems().keySet()); return cartContents; } catch (ClassCastException e) { // Backward compatibility : the session attribute use to contain the cart directly. // We do nothing, the code below will create a new cart. } } CatalogSettings catalogSettings = configurationService.getSettings(CatalogSettings.class); CartContents cartContents = new CartContents(catalogSettings.getCurrencies().getMainCurrency().getValue()); session.setAttribute(SESSION_CART_KEY, cartInSessionConverter.convertToCartInSession(cartContents)); return cartContents; }
private void create(User user, Role initialRole, Map<String, Object> additionalContext) throws InvalidEntityException, EntityAlreadyExistsException, PasswordDoesNotMeetRequirementsException { AccountsSettings settings = getSettings(); Boolean validationIsRequired = settings.getUserValidation().getValue(); if (user.getPassword().length() < settings.getPasswordRequirements().getMinimalLength()) { throw new PasswordDoesNotMeetRequirementsException("Provided password does not meet requirements"); } if (validationIsRequired) { if (context.getTenant() != null) { throw new RuntimeException("Validation is not supported for local users"); } user.setActive(false); user.setValidationKey(generateSecret()); } else { user.setActive(true); } user.setPassword(this.passwordManager.hashPassword(user.getPassword())); final User createdUser = this.userStore.get().create(user, initialRole); if (validationIsRequired) { sendValidationMail(createdUser, settings, additionalContext); } }