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:fr.paris.lutece.plugins.pluginwizard.web.PluginWizardApp.java

/**
 * The modification form of the plugin/*  w  w w.j a v  a2  s .  c om*/
 *
 * @param request The Http Request
 * @return The html code of the creation of plugin description
 */
@View(VIEW_MODIFY_PLUGIN)
public XPage getModifyPlugin(HttpServletRequest request) {
    return getXPage(TEMPLATE_MODIFY_PLUGIN, request.getLocale(), getPluginModel());
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StockBilletterieReservationApp.java

/**
 * Send a notification to all the admins when all the tickets of an
 * offer are booked/*  w w w  .j  av  a2  s . c om*/
 * @param request The HTTP request
 * @param purchase
 */
private void sendNotificationToAdmins(HttpServletRequest request, ReservationDTO purchase) {
    SeanceDTO seance = this._offerService.findSeanceById(purchase.getOffer().getId());

    if (seance != null && seance.getQuantity() < seance.getMinTickets()) {
        //Generate mail content
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(MARK_SEANCE, seance);
        model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request));

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

        Collection<AdminUser> listUsers = (List<AdminUser>) AdminUserHome.findUserList();

        for (AdminUser adminUser : listUsers) {
            // Create mail object
            NotificationDTO notificationDTO = new NotificationDTO();
            notificationDTO.setRecipientsTo(adminUser.getEmail());

            String[] args = new String[] { String.valueOf(seance.getId()) };
            notificationDTO.setSubject(I18nService.getLocalizedString(
                    MESSAGE_NOTIFICATION_ADMIN_OFFER_QUANTITY_SUBJECT, args, request.getLocale()));
            notificationDTO.setMessage(template.getHtml());

            // Send it
            _notificationService.send(notificationDTO);
        }
    }
}

From source file:fr.paris.lutece.plugins.extend.modules.actionbar.web.component.ActionbarResourceExtenderComponent.java

/**
 * {@inheritDoc}//from  w w w.j  a va2  s.  c om
 */
@Override
public String getPageAddOn(String strIdExtendableResource, String strExtendableResourceType,
        String strParameters, HttpServletRequest request) {
    // Method to get the html code of the extension in front office
    ActionbarExtenderConfig config = _configService.find(ActionbarResourceExtender.EXTENDER_TYPE,
            strIdExtendableResource, strExtendableResourceType);
    List<ActionButton> listActionsButtons;
    if (config.getAllButtons()) {
        listActionsButtons = _actionbarService.findActionButtonsByResourceType(strExtendableResourceType);
    } else {
        listActionsButtons = _actionbarService.findActionButtons(config.getListActionButtonId());
    }
    for (ActionButton action : listActionsButtons) {
        String strHtmlContent = action.getHtmlContent();
        strHtmlContent = strHtmlContent.replaceAll(PARAMETER_RESOURCE_ID, strIdExtendableResource);
        strHtmlContent = strHtmlContent.replaceAll(PARAMETER_RESOURCE_TYPE, strExtendableResourceType);
        action.setHtmlContent(strHtmlContent);
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_ACTIONS, listActionsButtons);
    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_ACTION_BAR, request.getLocale(), model);
    return template.getHtml();
}

From source file:be.iminds.aiolos.ui.CommonServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Not necessary for plugin only as standalone app.
    // doGetPlugin allways needed.
    // check whether we are not at .../{webManagerRoot}
    final String pathInfo = request.getPathInfo();
    if (pathInfo == null || pathInfo.equals("/")) {
        String path = request.getRequestURI();
        if (!path.endsWith("/")) {
            path = path.concat("/");
        }//ww  w .j a  v  a 2s  .c  om
        path = path.concat(LABEL);
        response.sendRedirect(path);
        return;
    }

    int slash = pathInfo.indexOf("/", 1);
    if (slash < 2) {
        slash = pathInfo.length();
    }

    final String label = pathInfo.substring(1, slash);
    if (label != null && label.startsWith(LABEL)) {
        final RequestInfo reqInfo = new RequestInfo(request, LABEL);
        if (reqInfo.extension.equals("html")) {
            doGetPlugin(request, response);
        } else if (reqInfo.extension.equals("json")) {
            renderJSON(response, request.getLocale());
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.google.livingstories.servlet.StartPageServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String loggedInUser = userLoginService.getUserId();

    JSONObject lastVisitTimes = new JSONObject();
    if (loggedInUser != null) {
        // Note: the date format that will be transferred via JSON should match with the date format
        // being used in {@link StartPage} which parses it. In particular, the timezone must be
        // included in the date being transferred.
        DateFormat dateFormatter = new SimpleDateFormat("MMMMM d, yyyy HH:mm:ss aaa ZZZZ");
        Map<Long, Date> allStoryMap = userDataService.getAllLastVisitTimes(loggedInUser);
        for (Map.Entry<Long, Date> entry : allStoryMap.entrySet()) {
            if (entry.getValue() != null) {
                try {
                    lastVisitTimes.put(entry.getKey().toString(), dateFormatter.format(entry.getValue()));
                } catch (JSONException e) {
                    // Do nothing
                }//  w  w w  .  j av  a2 s . c  o  m
            }
        }
    }

    ExternalServiceKeyChain externalProperties = new ExternalServiceKeyChain(getServletContext());
    String currentUrl = req.getRequestURI();
    StartPageHtml.write(resp.getWriter(), new GxpContext(req.getLocale()), req.getRequestURI(),
            userLoginService.getUserDisplayName(), userLoginService.createLoginUrl(currentUrl),
            userLoginService.createLogoutUrl(currentUrl), lastVisitTimes,
            loggedInUser == null ? null : userDataService.getDefaultStoryView(loggedInUser),
            externalProperties.getLogoFileLocation(), externalProperties.getAnalyticsAccountId());
}

From source file:fr.paris.lutece.plugins.directory.web.DirectoryApp.java

/**
 * Returns the Directory XPage result content depending on the request
 * parameters and the current mode./*from w w  w  .j a v  a  2 s  .co  m*/
 *
 * @param request
 *            The HTTP request.
 * @param nMode
 *            The current mode.
 * @param plugin
 *            The Plugin.
 * @return The page content.
 * @throws SiteMessageException
 *             the SiteMessageException
 * @throws UserNotSignedException
 *             the UserNotSignedException
 */
@Override
public XPage getPage(HttpServletRequest request, int nMode, Plugin plugin)
        throws SiteMessageException, UserNotSignedException {
    XPage page = new XPage();

    page.setTitle(I18nService.getLocalizedString(PROPERTY_XPAGE_PAGETITLE, request.getLocale()));
    page.setPathLabel(I18nService.getLocalizedString(PROPERTY_XPAGE_PATHLABEL, request.getLocale()));

    Map<String, Object> model = new HashMap<String, Object>();

    String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY);
    String strIdDirectoryRecord = request.getParameter(PARAMETER_ID_DIRECTORY_RECORD);

    List<Record> listRecord = new ArrayList<Record>();
    List<Integer> listIdDirectory = new ArrayList<Integer>();

    Boolean bSingleResult = null;

    if ((strIdDirectory == null) && (strIdDirectoryRecord == null)) {
        page.setContent(getSearchPage(request, plugin));
    } else {
        Directory directory;
        HttpSession session = request.getSession();
        int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory);
        directory = DirectoryHome.findByPrimaryKey(nIdDirectory, plugin);

        DirectorySiteSearchFields searchFields = (session
                .getAttribute(SESSION_DIRECTORY_SITE_SEARCH_FIELDS) != null)
                        ? (DirectorySiteSearchFields) session.getAttribute(SESSION_DIRECTORY_SITE_SEARCH_FIELDS)
                        : getInitDirectorySearchField();

        model.put(MARK_DIRECTORY, directory);

        IRecordService recordService = SpringContextService.getBean(RecordService.BEAN_SERVICE);

        int nIdDirectoryRecord = DirectoryUtils.convertStringToInt(strIdDirectoryRecord);
        Record record = null;

        if (request.getParameter(PARAMETER_VIEW_DIRECTORY_RECORD) != null) {
            record = recordService.findByPrimaryKey(nIdDirectoryRecord, plugin);

            if ((record != null) && (record.getDirectory() != null)) {
                directory = DirectoryHome.findByPrimaryKey(record.getDirectory().getIdDirectory(), plugin);

                listRecord = (List<Record>) session.getAttribute(SESSION_ID_LAST_RECORD);

                if ((listRecord != null) && (listRecord.size() > 0)
                        && (listRecord.get(listRecord.size() - 1).getIdRecord() != record.getIdRecord())) {
                    listRecord.add(record);
                } else if (listRecord == null) {
                    listRecord = new ArrayList<Record>();
                    listRecord.add(record);
                }

                session.setAttribute(SESSION_ID_LAST_RECORD, listRecord);

                listIdDirectory = (List<Integer>) session.getAttribute(SESSION_ID_LAST_DIRECTORY);

                if ((listIdDirectory != null) && (listIdDirectory.size() > 0) && !listIdDirectory
                        .get(listIdDirectory.size() - 1).equals(record.getDirectory().getIdDirectory())) {
                    listIdDirectory.add(record.getDirectory().getIdDirectory());
                } else if (listIdDirectory == null) {
                    listIdDirectory = new ArrayList<Integer>();
                    listIdDirectory.add(record.getDirectory().getIdDirectory());
                }

                session.setAttribute(SESSION_ID_LAST_DIRECTORY, listIdDirectory);
            }
        }

        String strPortalUrl = AppPathService.getPortalUrl();
        UrlItem urlDirectoryXpage = new UrlItem(strPortalUrl);
        urlDirectoryXpage.addParameter(XPageAppService.PARAM_XPAGE_APP,
                AppPropertiesService.getProperty(PROPERTY_PAGE_APPLICATION_ID));
        urlDirectoryXpage.addParameter(PARAMETER_ID_DIRECTORY, strIdDirectory);

        if (directory == null) {
            SiteMessageService.setMessage(request, MESSAGE_ERROR, SiteMessage.TYPE_STOP);

            return null;
        }

        if ((directory.getRoleKey() != null) && !directory.getRoleKey().equals(Directory.ROLE_NONE)
                && SecurityService.isAuthenticationEnable()
                && !SecurityService.getInstance().isUserInRole(request, directory.getRoleKey())) {
            SiteMessageService.setMessage(request, MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_STOP);
        }

        if (directory.isEnabled()) {
            if (request.getParameter(PARAMETER_VIEW_DIRECTORY_RECORD) != null) {
                if ((record == null)
                        || ((record.getRoleKey() != null) && !record.getRoleKey().equals(Directory.ROLE_NONE)
                                && SecurityService.isAuthenticationEnable()
                                && !SecurityService.getInstance().isUserInRole(request, record.getRoleKey()))) {
                    SiteMessageService.setMessage(request, MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_STOP);

                    return null;
                }

                record.setDirectory(directory);

                bSingleResult = true;

                String strDirectoryRecord = getHtmlResultRecord(directory, record, request.getLocale(), plugin,
                        session);
                model.put(MARK_STR_RESULT_RECORD, strDirectoryRecord);
            } else {
                searchFields.setCurrentPageIndex(Paginator.getPageIndex(request, Paginator.PARAMETER_PAGE_INDEX,
                        searchFields.getCurrentPageIndex()));
                searchFields.setItemsPerPage(directory.getNumberRecordPerPage());
                // Init Map query if requested
                initMapQuery(request, searchFields, directory);

                if (request.getParameter(PARAMETER_SEARCH) != null) {
                    // get search filter
                    try {
                        HashMap<String, List<RecordField>> mapQuery = DirectoryUtils.getSearchRecordData(
                                request, directory.getIdDirectory(), plugin, request.getLocale());

                        searchFields.setMapQuery(mapQuery);
                        searchFields.setIdDirectory(directory.getIdDirectory());
                    } catch (DirectoryErrorException error) {
                        if (error.isMandatoryError()) {
                            Object[] tabRequiredFields = { error.getTitleField() };
                            SiteMessageService.setMessage(request, MESSAGE_DIRECTORY_ERROR_MANDATORY_FIELD,
                                    tabRequiredFields, SiteMessage.TYPE_STOP);
                        } else {
                            Object[] tabRequiredFields = { error.getTitleField(), error.getErrorMessage() };
                            SiteMessageService.setMessage(request, MESSAGE_DIRECTORY_ERROR, tabRequiredFields,
                                    SiteMessage.TYPE_STOP);
                        }
                    }
                }

                if (searchFields.getMapQuery() != null) {
                    // call search service
                    searchFields.setIsDisabled(RecordFieldFilter.FILTER_TRUE);

                    List<Integer> listResultRecordId = new ArrayList<Integer>();

                    if (SecurityService.isAuthenticationEnable()) {
                        SecurityService securityService = SecurityService.getInstance();
                        LuteceUser user = securityService.getRegisteredUser(request);
                        List<String> roleKeyList = new ArrayList<String>();

                        if (user != null) {
                            String[] lRoles = securityService.getRolesByUser(user);
                            if (lRoles != null) {
                                roleKeyList = new ArrayList<String>(Arrays.asList(lRoles));
                            }
                        }

                        searchFields.setRoleKeyList(roleKeyList);
                        searchFields.setIncludeRoleNone(true);
                        searchFields.setIncludeRoleNull(true);
                    }

                    //sort parameters
                    searchFields.setSortParameters(request, directory, plugin);

                    listResultRecordId = DirectoryUtils.getListResults(request, directory, false, true,
                            searchFields, null, request.getLocale());

                    boolean bIsDisplayedDirectly = Boolean.parseBoolean(
                            AppPropertiesService.getProperty(PROPERTY_DISPLAY_ONE_RESULT_DIRECTLY));

                    if (bIsDisplayedDirectly && (listResultRecordId.size() == 1)
                            && (session.getAttribute(SESSION_ONE_RECORD_ID) == null)) {
                        record = recordService.findByPrimaryKey(listResultRecordId.get(0), plugin);

                        if ((record != null) && (record.getDirectory() != null)) {
                            directory = DirectoryHome.findByPrimaryKey(record.getDirectory().getIdDirectory(),
                                    plugin);
                        }

                        if ((record == null) || ((record.getRoleKey() != null)
                                && !record.getRoleKey().equals(Directory.ROLE_NONE)
                                && SecurityService.isAuthenticationEnable()
                                && !SecurityService.getInstance().isUserInRole(request, record.getRoleKey()))) {
                            SiteMessageService.setMessage(request, MESSAGE_ACCESS_DENIED,
                                    SiteMessage.TYPE_STOP);

                            return null;
                        }

                        record.setDirectory(directory);

                        String strDirectoryRecord = getHtmlResultRecord(directory, record, request.getLocale(),
                                plugin, session);
                        model.put(MARK_STR_RESULT_RECORD, strDirectoryRecord);
                        bSingleResult = true;
                        model.put(MARK_ONE_RESULT, true);

                        session.setAttribute(SESSION_ONE_RECORD_ID, record.getIdRecord());

                        listRecord = (List<Record>) session.getAttribute(SESSION_ID_LAST_RECORD);

                        if ((listRecord != null) && (listRecord.size() > 0) && (listRecord
                                .get(listRecord.size() - 1).getIdRecord() != record.getIdRecord())) {
                            listRecord.add(record);
                        } else if (listRecord == null) {
                            listRecord = new ArrayList<Record>();
                            listRecord.add(record);
                        }

                        session.setAttribute(SESSION_ID_LAST_RECORD, listRecord);

                        listIdDirectory = (List<Integer>) session.getAttribute(SESSION_ID_LAST_DIRECTORY);

                        if ((listIdDirectory != null) && (listIdDirectory.size() > 0)
                                && !listIdDirectory.get(listIdDirectory.size() - 1)
                                        .equals(record.getDirectory().getIdDirectory())) {
                            listIdDirectory.add(record.getDirectory().getIdDirectory());
                        } else if (listIdDirectory == null) {
                            listIdDirectory = new ArrayList<Integer>();
                            listIdDirectory.add(record.getDirectory().getIdDirectory());
                        }

                        session.setAttribute(SESSION_ID_LAST_DIRECTORY, listIdDirectory);
                    } else {
                        session.setAttribute(SESSION_ONE_RECORD_ID, null);
                    }

                    if ((listResultRecordId.size() != 1) || !bIsDisplayedDirectly) {
                        bSingleResult = false;

                        Paginator<Integer> paginator = new Paginator<Integer>(listResultRecordId,
                                searchFields.getItemsPerPage(), urlDirectoryXpage.getUrl(),
                                Paginator.PARAMETER_PAGE_INDEX, searchFields.getCurrentPageIndex());

                        model.put(MARK_PAGINATOR, paginator);

                        List<Record> lRecord = recordService.loadListByListId(paginator.getPageItems(), plugin);

                        if (lRecord.size() > 0) {
                            String strResultList = getHtmlResultList(directory, lRecord, request.getLocale(),
                                    plugin);
                            model.put(MARK_STR_RESULT_LIST, strResultList);
                        }
                    }
                } else {
                    // if map_query is null, indicate that
                    model.put(MARK_NEW_SEARCH, Integer.valueOf(1));
                }

                String strFormSearch = getHtmlFormSearch(directory, searchFields.getMapQuery(), request,
                        plugin);
                model.put(MARK_STR_FORM_SEARCH, strFormSearch);
            }

            model.put(MARK_LOCALE, request.getLocale());
        } else {
            model.put(MARK_UNAVAILABILITY_MESSAGE, directory.getUnavailabilityMessage());
        }

        EntryFilter filterGeolocation = new EntryFilter();
        filterGeolocation.setIdDirectory(directory.getIdDirectory());
        filterGeolocation.setIdType(AppPropertiesService.getPropertyInt(PROPERTY_ENTRY_TYPE_GEOLOCATION, 16));

        if (bSingleResult != null) {
            if (bSingleResult) {
                filterGeolocation.setIsShownInResultRecord(1);
            } else {
                filterGeolocation.setIsShownInResultList(1);
            }
        }

        List<IEntry> entriesGeolocationList = EntryHome.getEntryList(filterGeolocation, plugin);
        model.put(MARK_ENTRY_LIST_GEOLOCATION, entriesGeolocationList);

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_XPAGE_FRAME_DIRECTORY,
                request.getLocale(), model);
        page.setContent(template.getHtml());
        session.setAttribute(SESSION_DIRECTORY_SITE_SEARCH_FIELDS, searchFields);
    }

    return page;
}

From source file:it.cilea.osd.jdyna.controller.DecoratorNestedPropertiesDefinitionController.java

protected ModelAndView handleDelete(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String paramOTipologiaProprietaId = request.getParameter("pDId");
    String parentOTipologiaProprietaId = request.getParameter("parentId");
    String boxId = request.getParameter("boxId");
    String tabId = request.getParameter("tabId");
    Integer tipologiaProprietaId = Integer.decode(paramOTipologiaProprietaId);
    Integer parentId = Integer.decode(parentOTipologiaProprietaId);

    try {//from  w  ww  .j  a  va  2 s .c  o  m

        NTP tip = applicationService.get(targetModel, tipologiaProprietaId);

        //cancello tutte le proprieta' salvate in passato
        applicationService.deleteAllProprietaByTipologiaProprieta(tip.getPropertyHolderClass(), tip);
        //cancello se fanno parte di qualche property holder      
        IContainable containable = applicationService.findContainableByDecorable(tip.getDecoratorClass(),
                tipologiaProprietaId);
        TTP ttp = applicationService.get(holderModel, parentId);
        ttp.getMask().remove(tip);
        applicationService.delete(tip.getDecoratorClass(), containable.getId());

        saveMessage(request, getText("action.propertiesdefinition.deleted", request.getLocale()));
    } catch (Exception ecc) {
        saveMessage(request, getText("action.propertiesdefinition.deleted.noSuccess", request.getLocale()));
    }

    return new ModelAndView(getListView() + "?id=" + boxId + "&tabId=" + tabId + "&path="
            + Utils.getAdminSpecificPath(request, null), model);
}

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

/**
 * Returns the contact form's result page
 * @param request The Http request/*from w  w w .j  av  a  2  s .c o  m*/
 * @param plugin The plugin
 * @return The Html template
 * @throws SiteMessageException The Site message exception
 */
public String getFaqList(HttpServletRequest request, Plugin plugin) throws SiteMessageException {
    String strKeywords = request.getParameter(PARAMETER_KEYWORDS);
    String strDateBegin = request.getParameter(PARAMETER_DATE_BEGIN);
    String strDateEnd = request.getParameter(PARAMETER_DATE_END);
    boolean bSearchPage = true;
    Collection<QuestionAnswer> listQuestionAnswer = null;

    if (StringUtils.isBlank(strKeywords) && StringUtils.isBlank(strDateBegin)
            && StringUtils.isBlank(strDateEnd)) {
        bSearchPage = false;
    } else {
        if (StringUtils.isBlank(strDateBegin) ^ StringUtils.isBlank(strDateEnd)) {
            SiteMessageService.setMessage(request, MESSAGE_SEARCH_DATE_MANDATORY, SiteMessage.TYPE_STOP);
        }

        Date dateBegin = DateUtil.formatDate(strDateBegin, request.getLocale());
        Date dateEnd = DateUtil.formatDate(strDateEnd, request.getLocale());

        if ((dateBegin == null) ^ (dateEnd == null)) {
            SiteMessageService.setMessage(request, MESSAGE_SEARCH_DATE_VALIDITY, SiteMessage.TYPE_STOP);
        }

        listQuestionAnswer = HelpdeskSearchService.getInstance().getSearchResults(strKeywords, dateBegin,
                dateEnd, request, plugin);
    }

    HashMap<String, Object> model = new HashMap<String, Object>();
    Collection<Faq> faqList = null;

    if (SecurityService.isAuthenticationEnable()) {
        //filter by role
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);
        String[] arrayRoleKey = null;

        if (user != null) {
            arrayRoleKey = user.getRoles();
        }

        faqList = FaqHome.findAuthorizedFaq(arrayRoleKey, plugin);
    } else {
        faqList = FaqHome.findAll(plugin);
    }

    model.put(MARK_SEARCH_PAGE, bSearchPage);
    model.put(MARK_QUESTIONANSWER_LIST, listQuestionAnswer);
    model.put(MARK_PLUGIN, plugin);
    model.put(MARK_FILTER_SEARCHED_KEYWORDS, strKeywords);
    model.put(MARK_FILTER_DATE_BEGIN, strDateBegin);
    model.put(MARK_FILTER_DATE_END, strDateEnd);
    model.put(MARK_PATH_LABEL, HelpdeskPlugin.PLUGIN_NAME);
    model.put(MARK_LOCALE, request.getLocale());
    model.put(MARK_ANCHOR_SUBJECT, ANCHOR_SUBJECT);
    model.put(MARK_ANCHOR_QUESTION_ANSWER, ANCHOR_QUESTION_ANSWER);
    model.put(MARK_FAQ_LIST, faqList);
    //useful if you want to work with Portal.jsp and RunStandaloneApp.jsp
    model.put(FULL_URL, request.getRequestURL());

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

    return template.getHtml();
}

From source file:fr.paris.lutece.plugins.workflow.modules.archive.web.DownloadArchive.java

/**
 * Initialize a download of a zip file if the user is authorized. The autorization is based on the signature given in parameter of the request.
 * @param request The request//from   w  w w.java2  s  .  co  m
 * @param response the response
 */
public void doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
    String strIdRecord = request.getParameter(PARAM_ID_RECORD);
    String strIdDirectory = request.getParameter(PARAM_ID_DIRECTORY);
    String strIdConfigProducer = request.getParameter(PARAM_ID_CONFIG_PRODUCER);
    Plugin plugin = PluginService.getPlugin(WorkflowArchivePlugin.PLUGIN_NAME);

    if (_authenticator.isRequestAuthenticated(request) && StringUtils.isNotBlank(strIdRecord)) {
        Directory directory = DirectoryHome.findByPrimaryKey(Integer.parseInt(strIdDirectory), plugin);

        String strZipFolderPath = AppPathService
                .getAbsolutePathFromRelativePath(AppPropertiesService.getProperty(PROPERTY_ZIP_FOLDER_PATH));
        String strZIPFileName = strIdDirectory + CONSTANT_UNDERSCORE + strIdRecord + EXTENSION_FILE_ZIP;

        String strDownloadFileName = null;
        IConfigProducer configProducer = ConfigProducerHome.loadConfig(plugin,
                Integer.parseInt(strIdConfigProducer));
        if (configProducer != null) {
            strDownloadFileName = PDFUtils.getFileNameFromConfig(directory, configProducer,
                    Integer.parseInt(strIdRecord), request.getLocale());
        } else {
            strDownloadFileName = StringUtil.replaceAccent(directory.getTitle()) + CONSTANT_UNDERSCORE
                    + strIdRecord + EXTENSION_FILE_ZIP;
        }

        response.setHeader("Content-Disposition", "attachment ;filename=\"" + strDownloadFileName + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate,post-check=0,pre-check=0");

        response.setContentType(ZipGenerateUtil.ARCHIVE_MIME_TYPE_ZIP);
        try {
            OutputStream os = response.getOutputStream();

            File zipFile = new File(strZipFolderPath + CONSTANT_SLASH + strZIPFileName);
            byte[] buffer = new byte[(int) zipFile.length()];
            FileInputStream is = new FileInputStream(zipFile);
            is.read(buffer);
            is.close();
            os.write(buffer);
            os.flush();
            os.close();
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }
    }
}

From source file:org.guanxi.sp.engine.service.shibboleth.AuthConsumerServiceThread.java

/**
 * This creates an AuthConsumerServiceThread that can be used
 * to retrieve the attributes from the AA URL and then pass them
 * to the Guard.//w  ww  .  ja  v a  2s.  c  o m
 * 
 * @param parent              This is the AuthConsumerService object that has spawned this object.
 * @param guardSession        This is the Guard Session string that has been passed to the Engine.
 * @param acsURL              This is the URL of the Attribute Consumer Service on the Guard.
 * @param aaURL               This is the URL of the Attribute Authority on the IdP.
 * @param podderURL           This is the URL of the Podder Service on the Guard.
 * @param entityID            This is the entityID of the Guard that will be used when talking to the IdP.
 * @param keystoreFile        This is the location of the KeyStore which will be used to authenticate the client in secure communications.
 * @param keystorePassword    This is the password for the KeyStore file.
 * @param truststoreFile      This is the TrustStore file which will be used to authenticate the server in secure communications.
 * @param truststorePassword  This is the password for the TrustStore file.
 * @param idpProviderId       This is the providerId for the IdP that provides the Attributes.
 * @param idpNameIdentifier   This is the name identifier that the IdP requires.
 * @param samlResponse        This is the initial SAML response from the IdP that confirmed that the user had logged in.
 * @param messages            This is the source of localised messages the thread must display
 * @param request             This is the request this thread is associated with
 * @param manager             This is the entity manager for the AA
 */
public AuthConsumerServiceThread(AuthConsumerService parent, String guardSession, String acsURL, String aaURL,
        String podderURL, String entityID, String keystoreFile, String keystorePassword, String truststoreFile,
        String truststorePassword, String idpProviderId, String idpNameIdentifier, ResponseType samlResponse,
        MessageSource messages, HttpServletRequest request, EntityManager manager) {
    this.parent = parent;
    this.guardSession = guardSession;
    this.acsURL = acsURL;
    this.aaURL = aaURL;
    this.podderURL = podderURL;
    this.entityID = entityID;
    this.keystoreFile = keystoreFile;
    this.keystorePassword = keystorePassword;
    this.truststoreFile = truststoreFile;
    this.truststorePassword = truststorePassword;
    this.idpProviderId = idpProviderId;
    this.idpNameIdentifier = idpNameIdentifier;
    this.samlResponse = samlResponse;
    this.messages = messages;
    this.manager = manager;

    preparingAARequest.addObject(progressTextKey,
            messages.getMessage("engine.acs.preparing.aa.request", null, request.getLocale()));
    readingAAResponse.addObject(progressTextKey,
            messages.getMessage("engine.acs.comm.with.aa", null, request.getLocale()));
    preparingGuardRequest.addObject(progressTextKey,
            messages.getMessage("engine.acs.preparing.guard.request", null, request.getLocale()));
    readingGuardResponse.addObject(progressTextKey,
            messages.getMessage("engine.acs.comm.with.guard", null, request.getLocale()));
}