Example usage for javax.servlet.http HttpServletRequest getLocale

List of usage examples for javax.servlet.http HttpServletRequest getLocale

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocale.

Prototype

public Locale getLocale();

Source Link

Document

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

Usage

From source file:com.jaspersoft.jasperserver.war.control.JSCommonController.java

protected void setupLoginPage(HttpServletRequest req) {
    Cookie[] cookies = req.getCookies();
    String locale = null;//from   w  w w . j  ava 2  s.  com
    String preferredTz = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals(JasperServerConstImpl.getUserLocaleSessionAttr()))
                locale = cookie.getValue();
            if (cookie.getName().equals(JasperServerConstImpl.getUserTimezoneSessionAttr()))
                preferredTz = cookie.getValue();
        }
    }

    Locale displayLocale = req.getLocale();
    String preferredLocale;
    if (locale == null || locale.length() == 0) {
        preferredLocale = displayLocale.toString();
    } else {
        preferredLocale = locale;
    }

    if (preferredTz == null) {
        preferredTz = timezones.getDefaultTimeZoneID();
    }

    req.setAttribute("preferredLocale", preferredLocale);
    req.setAttribute("userLocales", locales.getUserLocales(displayLocale));
    req.setAttribute("preferredTimezone", preferredTz);
    req.setAttribute("userTimezones", timezones.getTimeZones(displayLocale));
    try {
        if (Integer.parseInt(passwordExpirationInDays) > 0) {
            allowUserPasswordChange = "true";
        }
    } catch (NumberFormatException e) {
        // if the value is NaN, then assume it's non postive.
        // not overwrite allowUserPasswordChange
    }
    req.setAttribute("allowUserPasswordChange", allowUserPasswordChange);
    req.setAttribute("passwordExpirationInDays", passwordExpirationInDays);
    req.setAttribute("passwordPattern", userAuthService.getAllowedPasswordPattern().replace("\\", "\\\\"));
    req.setAttribute("autoCompleteLoginForm", autoCompleteLoginForm);
    req.setAttribute(IS_DEVELOPMENT_ENVIRONMENT_TYPE, false);
    req.setAttribute(USERS_EXCEEDED, false);
    req.setAttribute(BAN_USER, false);
    req.setAttribute("isEncryptionOn", SecurityConfiguration.isEncryptionOn());
}

From source file:fr.paris.lutece.plugins.calendar.service.AgendaSubscriberService.java

/**
 * Send an event to a list of subscribers
 * @param request the http request//from ww  w . ja  v  a  2 s .  c o  m
 * @param listSubscribers a Collection<CalendarSubscriber>
 * @param event the event
 * @param nCalendarId The id of the calendar
 */
public void sendSubscriberMail(HttpServletRequest request, Collection<CalendarSubscriber> listSubscribers,
        Event event, int nCalendarId) {
    String strUnsubscribelink = AppPropertiesService.getProperty(PROPERTY_UNSUBSCRIBE_LINK);
    String strSenderName = AppPropertiesService.getProperty(PROPERTY_SENDER_NAME);
    String strSenderEmail = AppPropertiesService.getProperty(PROPERTY_SENDER_EMAIL);
    String strContent = I18nService.getLocalizedString(PROPERTY_EMAIL_SUBSCRIBER_CONTENT, request.getLocale());
    String strObject = I18nService.getLocalizedString(PROPERTY_EMAIL_SUBSCRIBER_OBJECT, request.getLocale());

    String strBaseUrl = AppPathService.getBaseUrl(request);

    HashMap<String, Object> emailModel = new HashMap<String, Object>();

    for (CalendarSubscriber subscriber : listSubscribers) {
        emailModel.put(MARK_UNSUBSCRIBE_LINK, strUnsubscribelink);
        emailModel.put(MARK_EMAIL_CONTENT, strContent);
        emailModel.put(MARK_BASE_URL, strBaseUrl);
        emailModel.put(MARK_EVENT, event);
        emailModel.put(Constants.MARK_CALENDAR_ID, nCalendarId);
        emailModel.put(Constants.MARK_EVENT_ID, event.getId());
        emailModel.put(MARK_SUBSCRIBER_EMAIL, subscriber.getEmail());
        emailModel.put(Constants.PARAMETER_ACTION, Constants.ACTION_SHOW_RESULT);

        HtmlTemplate templateAgenda = AppTemplateService.getTemplate(TEMPLATE_SEND_NOTIFICATION_MAIL,
                request.getLocale(), emailModel);
        String strNewsLetterCode = templateAgenda.getHtml();

        MailService.sendMailHtml(subscriber.getEmail(), strSenderName, strSenderEmail, strObject,
                strNewsLetterCode);
        emailModel.clear();
    }
}

From source file:es.pode.gestorFlujo.presentacion.objetosCompartidos.importarCompartidos.ImportarCompartidosControllerImpl.java

/**
 * @see es.pode.gestorFlujo.presentacion.objetosCompartidos.importarCompartidos.ImportarCompartidosController#importarODE(org.apache.struts.action.ActionMapping, es.pode.gestorFlujo.presentacion.objetosCompartidos.importarCompartidos.ImportarODEForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from www .  j av a  2 s. com
public final void importarODE(ActionMapping mapping,
        es.pode.gestorFlujo.presentacion.objetosCompartidos.importarCompartidos.ImportarODEForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    //       long tamaino=new Long(request.getParameter("espacioLibre"));
    //       logger.debug("De la request:"+tamaino);

    ResultadoOperacionVO unResultado = new ResultadoOperacionVO();
    String archivosSubidos = new String("(");
    int nr_archivos_subidos = 0;
    ArrayList resultado = new ArrayList();
    Long diferencia = new Long(0);
    logger.debug("Importando ode");
    if (form.getTitulo() != null && form.getTitulo().length() != 0) {

        try {
            ResultadoImportacion resultadoParcial = new ResultadoImportacion();
            resultadoParcial.setTitulo(form.getTitulo());
            unResultado = importarUnODE(form.getIdODE(), form.getTitulo(), request.getLocale().getLanguage());
            if (unResultado.getIdResultado().equals("0.0")) {
                nr_archivos_subidos++;
                resultadoParcial.setValido(null);
                archivosSubidos = archivosSubidos + form.getTitulo() + ",";
                resultado.add(resultadoParcial);
            } else {
                resultadoParcial.setValido(RESULTADO_NO);
                logger.error("El archivo no se ha podido importar: " + unResultado.getDescripcion());
                resultadoParcial.setMensajes(unResultado.getDescripcion().split(SPLITTER));
                resultado.add(resultadoParcial);
            }
            logger.error(
                    "Mensajes despues del splitter[" + (unResultado.getDescripcion().split(SPLITTER) != null
                            ? unResultado.getDescripcion().split(SPLITTER).length
                            : 0) + "] ");
            logger.debug("Los atributos que pasamos a la jsp son: Una colleccion:[" + resultado
                    + "], con titulo [" + ((ResultadoImportacion) resultado.get(0)).getTitulo()
                    + " con mensajes [" + ((ResultadoImportacion) resultado.get(0)).getMensajes()
                    + " y validacion[" + ((ResultadoImportacion) resultado.get(0)).getValido());
        } catch (Exception ex) {
            logger.error("Excepcion al importar el ode compartido: ", ex);
            throw new ValidatorException("{gestorFlujo.error.inesperado}");
        }

    }
    logger.debug("Hemos llegado hasta aqui");
    if (nr_archivos_subidos > 0) {
        logger.info("Se ha importado correctamente el archivo: " + archivosSubidos);
        if (archivosSubidos.endsWith(",")) {
            archivosSubidos = (String) archivosSubidos.subSequence(0, archivosSubidos.length() - 1);
            archivosSubidos = nr_archivos_subidos + ": " + archivosSubidos;
            archivosSubidos = archivosSubidos + ")";
        }

    }
    form.setResultado(resultado);
}

From source file:com.salesmanager.catalog.common.AjaxCatalogUtil.java

/**
 * Add product to shopping cart//  ww  w  .  j a  v  a 2 s .c  om
 * 
 * @param productId
 * @param quantity
 * @param attributes
 * @return
 */
public ShoppingCart addProductToCart(HttpServletRequest req, HttpServletResponse resp, long productId,
        int quantity, ProductAttribute[] attributes) {

    HttpSession session = req.getSession();

    ShoppingCart cart = SessionUtil.getMiniShoppingCart(req);

    MerchantStore store = (MerchantStore) session.getAttribute("STORE");

    if (store == null) {
        cart = new ShoppingCart();
        LabelUtil label = LabelUtil.getInstance();
        label.setLocale(req.getLocale());
        String msg = label.getText("error.sessionexpired");
        cart.setErrorMessage(msg);
        return cart;
    }

    Locale locale = (Locale) session.getAttribute("WW_TRANS_I18N_LOCALE");

    if (cart == null) {
        cart = new ShoppingCart();
    }
    cart.setErrorMessage(null);

    try {

        // get products
        Collection productsCollection = cart.getProducts();

        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
        Product p = cservice.getProduct(productId);

        if (p == null || store == null) {
            String message = LabelUtil.getInstance().getText(locale, "errors.addtocart");
            cart.setErrorMessage(message);
            return cart;
        }

        if (quantity > p.getProductQuantityOrderMax()) {
            String message = LabelUtil.getInstance().getText(locale, "messages.invalid.quantity");
            cart.setErrorMessage(message);
            return cart;
        }

        ((I18NEntity) p).setLocale(locale, store.getCurrency());

        if (p.getMerchantId() != store.getMerchantId())
            return cart;

        boolean productFound = false;
        if (productsCollection != null && (attributes == null || attributes.length == 0)) {
            Iterator i = productsCollection.iterator();
            while (i.hasNext()) {
                ShoppingCartProduct scp = (ShoppingCartProduct) i.next();
                if (scp.getAttributes() != null && scp.getAttributes().size() > 0) {
                    continue;
                }
                if (scp.getProductId() == productId) {
                    int qty = scp.getQuantity();

                    if (qty + quantity > p.getProductQuantityOrderMax()) {
                        String message = LabelUtil.getInstance().getText(locale, "messages.invalid.quantity");
                        cart.setErrorMessage(message);
                        return cart;
                    }

                    scp.setQuantity(qty + quantity);
                    productFound = true;
                    break;
                }
            }
        }

        if (!productFound) {

            ShoppingCartProduct scp = new ShoppingCartProduct();
            scp.setProductId(p.getProductId());
            scp.setQuantity(quantity);
            if (!StringUtils.isBlank(p.getSmallImagePath())) {
                scp.setImage(p.getSmallImagePath());
            } else if (!StringUtils.isBlank(p.getLargeImagePath())) {
                scp.setImage(p.getLargeImagePath());
            } else {
                // nothing for now
            }

            if (attributes != null && attributes.length > 0) {
                Map ids = new HashMap();
                for (int i = 0; i < attributes.length; i++) {
                    ids.put(new Long(attributes[i].getName()), attributes[i]);
                }
                Collection attrs = cservice.getProductAttributes(new ArrayList(ids.keySet()),
                        locale.getLanguage());

                if (attrs != null && attrs.size() > 0) {
                    BigDecimal priceWithAttributes = ProductUtil.determinePriceWithAttributes(p, attrs, locale,
                            store.getCurrency());
                    scp.setPrice(priceWithAttributes);
                    scp.setPriceText(CurrencyUtil.displayFormatedAmountWithCurrency(priceWithAttributes,
                            store.getCurrency()));

                    Iterator attrIt = attrs.iterator();
                    List attrList = new ArrayList();
                    while (attrIt.hasNext()) {
                        //com.salesmanager.core.entity.catalog.ProductAttribute prodAttr = (com.salesmanager.core.entity.catalog.ProductAttribute) attrIt
                        //      .next();
                        com.salesmanager.core.entity.catalog.ProductAttribute productAttribute = (com.salesmanager.core.entity.catalog.ProductAttribute) attrIt
                                .next();
                        ShoppingCartProductAttribute scpa = new ShoppingCartProductAttribute();
                        scpa.setAttributeId(productAttribute.getProductAttributeId());
                        ProductAttribute pa = (ProductAttribute) ids
                                .get(new Long(productAttribute.getProductAttributeId()));
                        if (pa != null) {
                            scpa.setAttributeValue(pa.getValue());
                            if (pa.isStringValue()) {
                                scpa.setTextValue(pa.getTextValue());
                            }
                            attrList.add(scpa);
                        }
                    }
                    scp.setAttributes(attrList);

                } else {
                    scp.setPrice(ProductUtil.determinePrice(p, locale, store.getCurrency()));
                    BigDecimal price = ProductUtil.determinePrice(p, locale, store.getCurrency());
                    scp.setPriceText(
                            CurrencyUtil.displayFormatedAmountWithCurrency(price, store.getCurrency()));
                }
            } else {
                scp.setPrice(ProductUtil.determinePrice(p, locale, store.getCurrency()));
                BigDecimal price = ProductUtil.determinePrice(p, locale, store.getCurrency());
                scp.setPriceText(CurrencyUtil.displayFormatedAmountWithCurrency(price, store.getCurrency()));
            }
            scp.setProductName(p.getName());

            Collection products = cart.getProducts();
            if (products == null) {
                products = new ArrayList();
                cart.setProducts(products);
            }
            products.add(scp);
        }

        MiniShoppingCartUtil.calculateTotal(cart, store);

        SessionUtil.setMiniShoppingCart(cart, req);

        //save the cart in the cookie
        setMiniCartCookie(req, resp, cart);

        return cart;

    } catch (Exception e) {
        logger.error(e);
        cart.setErrorMessage(LabelUtil.getInstance().getText(locale, "errors.technical"));
        return cart;
    }

}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeDate.java

/**
 * {@inheritDoc}//from  ww w  .j  a v  a  2  s.c  o  m
 */
@Override
public GenericAttributeError getResponseData(Entry entry, HttpServletRequest request,
        List<Response> listResponse, Locale locale) {
    String strValueEntry = request.getParameter(PREFIX_ATTRIBUTE + entry.getIdEntry()).trim();
    Response response = new Response();
    response.setEntry(entry);

    if (strValueEntry != null) {
        Date tDateValue = DateUtil.formatDate(strValueEntry, locale);

        if (tDateValue != null) {
            response.setResponseValue(DateUtil.getDateString(tDateValue, locale));
        } else {
            response.setResponseValue(strValueEntry);
        }

        if (StringUtils.isNotBlank(response.getResponseValue())) {
            Date date = DateUtil.formatDate(response.getResponseValue(), request.getLocale());

            if (date != null) {
                response.setToStringValueResponse(getResponseValueForRecap(entry, request, response, locale));
            } else {
                response.setToStringValueResponse(StringUtils.EMPTY);
            }
        } else {
            response.setToStringValueResponse(StringUtils.EMPTY);
        }

        listResponse.add(response);

        // Checks if the entry value contains XSS characters
        if (StringUtil.containsXssCharacters(strValueEntry)) {
            GenericAttributeError error = new GenericAttributeError();
            error.setMandatoryError(false);
            error.setTitleQuestion(entry.getTitle());
            error.setErrorMessage(I18nService.getLocalizedString(MESSAGE_XSS_FIELD, request.getLocale()));

            return error;
        }

        if (entry.isMandatory()) {
            if (StringUtils.isBlank(strValueEntry)) {
                return new MandatoryError(entry, locale);
            }
        }

        if (StringUtils.isNotBlank(strValueEntry) && (tDateValue == null)) {
            String strError = I18nService.getLocalizedString(MESSAGE_ILLOGICAL_DATE, locale);
            GenericAttributeError error = new GenericAttributeError();
            error.setTitleQuestion(entry.getTitle());
            error.setMandatoryError(false);
            error.setErrorMessage(strError);

            return error;
        }
    }

    return null;
}

From source file:ai.ilikeplaces.servlets.ServletFileUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request__/*from w  w  w  . ja v a 2  s. c om*/
 * @param response__
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__)
        throws ServletException, IOException {
    response__.setContentType("text/html;charset=UTF-8");
    Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"),
            request__.getLocale());
    PrintWriter out = response__.getWriter();

    final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI");

    try {
        fileUpload: {
            if (!isFileUploadPermitted()) {
                errorTemporarilyDisabled(out);
                break fileUpload;
            }
            processSignOn: {
                final HttpSession session = request__.getSession(false);

                if (session == null) {
                    errorNoLogin(out);
                    break fileUpload;
                } else if (session.getAttribute(ServletLogin.HumanUser) == null) {
                    errorNoLogin(out);
                    break processSignOn;
                }

                processRequestType: {
                    @SuppressWarnings("unchecked")
                    final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session
                            .getAttribute(ServletLogin.HumanUser)).getBoundInstance();
                    try {
                        /*Check that we have a file upload request*/
                        final boolean isMultipart = ServletFileUpload.isMultipartContent(request__);
                        if (!isMultipart) {
                            LoggerFactory.getLogger(ServletFileUploads.class.getName()).error(
                                    logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001"));
                            errorNonMultipart(out);

                            break processRequestType;
                        }

                        processRequest: {

                            // Create a new file upload handler
                            final ServletFileUpload upload = new ServletFileUpload();
                            // Parse the request
                            FileItemIterator iter = upload.getItemIterator(request__);
                            boolean persisted = false;

                            loop: {
                                Long locationId = null;
                                String photoDescription = null;
                                String photoName = null;
                                Boolean isPublic = null;
                                Boolean isPrivate = null;
                                boolean fileSaved = false;

                                while (iter.hasNext()) {
                                    FileItemStream item = iter.next();
                                    String name = item.getFieldName();
                                    String absoluteFileSystemFileName = FilePath;

                                    InputStream stream = item.openStream();
                                    @_fix(issue = "Handle no extension files")
                                    String usersFileName = null;
                                    String randomFileName = null;

                                    if (item.isFormField()) {
                                        final String value = Streams.asString(stream);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0002"),
                                                name);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0003"),
                                                value);
                                        if (name.equals("locationId")) {
                                            locationId = Long.parseLong(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0004")));
                                        }

                                        if (name.equals("photoDescription")) {
                                            photoDescription = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0005")));
                                        }

                                        if (name.equals("photoName")) {
                                            photoName = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0006")));
                                        }

                                        if (name.equals("isPublic")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPublic = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0008")));

                                        }
                                        if (name.equals("isPrivate")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPrivate = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName.");

                                        }

                                    }
                                    if ((!item.isFormField())) {
                                        Loggers.DEBUG.debug((logMsgs.getString(
                                                "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name));
                                        Loggers.DEBUG.debug((logMsgs
                                                .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010")
                                                + item.getName()));
                                        // Process the input stream
                                        if (!(item.getName().lastIndexOf(".") > 0)) {
                                            errorFileType(out, item.getName());
                                            break processRequest;
                                        }

                                        usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName()
                                                : item.getName()
                                                        .substring(item.getName().lastIndexOf("\\") + 1));

                                        final String userUploadedFileName = item.getName();

                                        String fileExtension = "error";

                                        if (userUploadedFileName.toLowerCase().endsWith(".jpg")) {
                                            fileExtension = ".jpg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) {
                                            fileExtension = ".jpeg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".png")) {
                                            fileExtension = ".png";
                                        } else {
                                            errorFileType(out, gUI.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0019"));
                                            break processRequest;
                                        }

                                        randomFileName = getRandomFileName(locationId);

                                        randomFileName += fileExtension;

                                        final File uploadedFile = new File(
                                                absoluteFileSystemFileName += randomFileName);
                                        final FileOutputStream fos = new FileOutputStream(uploadedFile);
                                        while (true) {
                                            final int dataByte = stream.read();
                                            if (dataByte != -1) {
                                                fos.write(dataByte);
                                            } else {
                                                break;
                                            }

                                        }
                                        fos.close();
                                        stream.close();
                                        fileSaved = true;
                                    }

                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011")
                                                    + locationId);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012")
                                                    + fileSaved);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013")
                                                    + photoDescription);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014")
                                                    + photoName);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015")
                                                    + isPublic);

                                    if (fileSaved && (photoDescription != null)) {
                                        persistData: {
                                            handlePublicPrivateness: {
                                                if ((isPublic != null) && isPublic && (locationId != null)) {
                                                    Return<PublicPhoto> r = DB
                                                            .getHumanCRUDPublicPhotoLocal(true)
                                                            .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    locationId, absoluteFileSystemFileName,
                                                                    photoName, photoDescription,
                                                                    new String(CDN + randomFileName), 4);
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, logMsgs.getString(
                                                                "ai.ilikeplaces.servlets.ServletFileUploads.0016"));
                                                    } else {
                                                        errorBusy(out);
                                                    }

                                                } else if ((isPrivate != null) && isPrivate) {
                                                    Return<PrivatePhoto> r = DB
                                                            .getHumanCRUDPrivatePhotoLocal(true)
                                                            .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    absoluteFileSystemFileName, photoName,
                                                                    photoDescription,
                                                                    new String(CDN + randomFileName));
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, "private");
                                                    } else {
                                                        errorBusy(out);
                                                    }
                                                } else {
                                                    throw UNSUPPORTED_OPERATION_EXCEPTION;
                                                }
                                            }
                                        }
                                        /*We got what we need from the loop. Lets break it*/

                                        break loop;
                                    }

                                }

                            }
                            if (!persisted) {
                                errorMissingParameters(out);
                                break processRequest;
                            }

                        }

                    } catch (FileUploadException ex) {
                        Loggers.EXCEPTION.error(null, ex);
                        errorBusy(out);
                    }
                }

            }

        }
    } catch (final Throwable t_) {
        Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_);
    }

}

From source file:fr.paris.lutece.plugins.helpdesk.web.HelpdeskApp.java

/**
 * Returns the contact form//from   w w w .j a  v  a 2 s .  c om
 * @param request The Html request
 * @param plugin The plugin
 * @param faq The {@link Faq} concerned by contact form
 * @return The Html template
 */
public String getContactForm(HttpServletRequest request, Plugin plugin, Faq faq) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_THEME_LIST, (Collection<Theme>) ThemeHome.getInstance().findByIdFaq(faq.getId(), plugin));
    model.put(MARK_PLUGIN, plugin);
    model.put(MARK_DEFAULT_VALUE, "");
    model.put(MARK_FAQ, faq);
    model.put(FULL_URL, request.getRequestURL());

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_CONTACT_FORM, request.getLocale(), model);

    return template.getHtml();
}

From source file:fr.paris.lutece.plugins.extend.modules.rating.web.component.RatingResourceExtenderComponent.java

/**
 * {@inheritDoc}/*w  w w. j a  v a 2 s  .  c o m*/
 */
@Override
public String getConfigHtml(ResourceExtenderDTO resourceExtender, Locale locale, HttpServletRequest request) {
    ReferenceList listIdsMailingList = new ReferenceList();
    listIdsMailingList.addItem(-1, I18nService
            .getLocalizedString(RatingConstants.PROPERTY_RATING_CONFIG_LABEL_NO_MAILING_LIST, locale));
    listIdsMailingList.addAll(AdminMailingListService.getMailingLists(AdminUserService.getAdminUser(request)));

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(RatingConstants.MARK_RATING_CONFIG, _configService.find(resourceExtender.getIdExtender()));
    model.put(RatingConstants.MARK_LIST_IDS_MAILING_LIST, listIdsMailingList);
    model.put(RatingConstants.MARK_LIST_IDS_VOTE_TYPE, _voteTypeService.findAll());
    model.put(MARK_LOCALE, request.getLocale());

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_RATING_CONFIG, request.getLocale(), model);

    return template.getHtml();
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            return getCancelView();
        } else {//from  ww  w .  j  a  v  a2 s  .  c o m
            return getSuccessView();
        }
    }

    if (validator != null) { // validator is null during testing
        validator.validate(user, errors);

        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return "userform";
        }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        getUserManager().removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), locale));

        return getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE) || request.isUserInRole(Constants.USER_ROLE)) {
            String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (String roleName : userRoles) {
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            saveMessage(request, getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                saveMessage(request, getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                message.setSubject(getText("signup.email.subject", locale));

                try {
                    sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (MailException me) {
                    saveError(request, me.getCause().getLocalizedMessage());
                }

                return getSuccessView();
            } else {
                saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "userform";
}