Example usage for com.liferay.portal.kernel.servlet SessionMessages add

List of usage examples for com.liferay.portal.kernel.servlet SessionMessages add

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.servlet SessionMessages add.

Prototype

public static void add(PortletRequest portletRequest, String key) 

Source Link

Usage

From source file:com.liferay.staging.processes.web.internal.portlet.action.PublishLayoutsMVCActionCommand.java

License:Open Source License

@Override
protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    if (Validator.isNull(cmd)) {
        String portletId = _portal.getPortletId(actionRequest);

        SessionMessages.add(actionRequest, portletId);

        return;/* w ww .jav  a2s  . com*/
    }

    String redirect = ParamUtil.getString(actionRequest, "redirect");

    try {
        if (cmd.equals("copy_from_live")) {
            setLayoutIdMap(actionRequest);

            StagingUtil.copyFromLive(actionRequest);
        } else if (cmd.equals(Constants.PUBLISH_TO_LIVE)) {
            setLayoutIdMap(actionRequest);

            hideDefaultSuccessMessage(actionRequest);

            StagingUtil.publishToLive(actionRequest);
        } else if (cmd.equals(Constants.PUBLISH_TO_REMOTE)) {
            hideDefaultSuccessMessage(actionRequest);

            setLayoutIdMap(actionRequest);

            StagingUtil.publishToRemote(actionRequest);
        } else if (cmd.equals("schedule_copy_from_live")) {
            setLayoutIdMap(actionRequest);

            StagingUtil.scheduleCopyFromLive(actionRequest);
        } else if (cmd.equals("schedule_publish_to_live")) {
            setLayoutIdMap(actionRequest);

            StagingUtil.schedulePublishToLive(actionRequest);
        } else if (cmd.equals("schedule_publish_to_remote")) {
            setLayoutIdMap(actionRequest);

            StagingUtil.schedulePublishToRemote(actionRequest);
        } else if (cmd.equals("unschedule_copy_from_live")) {
            StagingUtil.unscheduleCopyFromLive(actionRequest);
        } else if (cmd.equals("unschedule_publish_to_live")) {
            StagingUtil.unschedulePublishToLive(actionRequest);
        } else if (cmd.equals("unschedule_publish_to_remote")) {
            StagingUtil.unschedulePublishToRemote(actionRequest);
        }

        sendRedirect(actionRequest, actionResponse, redirect);
    } catch (Exception e) {
        if (e instanceof PrincipalException) {
            SessionErrors.add(actionRequest, e.getClass());

            actionResponse.setRenderParameter("mvcPath", "/error/error.jsp");
        } else if (e instanceof AuthException || e instanceof DuplicateLockException
                || e instanceof LayoutPrototypeException || e instanceof RemoteAuthException
                || e instanceof RemoteExportException || e instanceof RemoteOptionsException
                || e instanceof SystemException) {

            if (e instanceof RemoteAuthException) {
                SessionErrors.add(actionRequest, AuthException.class, e);
            } else {
                SessionErrors.add(actionRequest, e.getClass(), e);
            }

            sendRedirect(actionRequest, actionResponse, redirect);
        } else if (e instanceof IllegalArgumentException) {
            SessionErrors.add(actionRequest, e.getClass(), e);
        } else {
            throw e;
        }
    }
}

From source file:com.liferay.stocks.portlet.StocksPortlet.java

License:Open Source License

protected void updatePreferences(ActionRequest actionRequest, ActionResponse actionResponse)
        throws IOException, PortletException {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    if (!cmd.equals(Constants.UPDATE)) {
        return;/* w w w . ja va  2 s  . co m*/
    }

    PortletPreferences portletPreferences = null;

    try {
        portletPreferences = PortletPreferencesFactoryUtil
                .getPortletPreferences(PortalUtil.getHttpServletRequest(actionRequest), PortletKeys.STOCKS);
    } catch (Exception e) {
        throw new PortletException(e);
    }

    String[] symbols = StringUtil.split(StringUtil.toUpperCase(ParamUtil.getString(actionRequest, "symbols")),
            StringPool.SPACE);

    Arrays.sort(symbols);

    portletPreferences.setValues("symbols", symbols);

    try {
        portletPreferences.store();
    } catch (ValidatorException ve) {
        SessionErrors.add(actionRequest, ValidatorException.class.getName(), ve);

        return;
    }

    SessionMessages.add(actionRequest,
            PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_UPDATED_PREFERENCES);
}

From source file:com.liferay.todo.TodoPortlet.java

License:Open Source License

public void contact(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    if (_log.isInfoEnabled()) {
        _log.info("Process action for contact form works");
    }// w  w  w  . j av  a  2  s  . c  o m

    String birthday = ParamUtil.getString(actionRequest, "birthday");
    String comment = ParamUtil.getString(actionRequest, "comment");
    String email = ParamUtil.getString(actionRequest, "email");
    String lastName = ParamUtil.getString(actionRequest, "last-name");
    String name = ParamUtil.getString(actionRequest, "name");

    if (comment.isEmpty()) {
        SessionErrors.add(actionRequest, "formSubmissionFailed");

        SessionMessages.add(actionRequest,
                PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
    } else {
        StringBundler sb = new StringBundler(9);

        sb.append(name);
        sb.append(StringPool.COMMA);
        sb.append(lastName);
        sb.append(StringPool.COMMA);
        sb.append(email);
        sb.append(StringPool.COMMA);
        sb.append(birthday);
        sb.append(StringPool.COMMA);
        sb.append(comment);

        if (_log.isInfoEnabled()) {
            _log.info(sb.toString());
        }

        SessionMessages.add(actionRequest, "formSuccessfullySubmitted");
    }

    actionResponse.setRenderParameter("mvcPath", "/contact.jsp");
}

From source file:com.liferay.users.admin.web.internal.portlet.action.EditUserMVCActionCommand.java

License:Open Source License

protected Object[] updateUser(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    User user = portal.getSelectedUser(actionRequest);

    Contact contact = user.getContact();

    String oldPassword = AdminUtil.getUpdateUserPassword(actionRequest, user.getUserId());

    String oldScreenName = user.getScreenName();
    String screenName = BeanParamUtil.getString(user, actionRequest, "screenName");
    String oldEmailAddress = user.getEmailAddress();
    String emailAddress = BeanParamUtil.getString(user, actionRequest, "emailAddress");
    long facebookId = user.getFacebookId();

    boolean deleteLogo = ParamUtil.getBoolean(actionRequest, "deleteLogo");

    byte[] portraitBytes = null;

    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");

    if (fileEntryId > 0) {
        FileEntry fileEntry = _dlAppLocalService.getFileEntry(fileEntryId);

        portraitBytes = FileUtil.getBytes(fileEntry.getContentStream());
    }//w  w w . j av a  2 s  .  com

    String languageId = BeanParamUtil.getString(user, actionRequest, "languageId");
    String firstName = BeanParamUtil.getString(user, actionRequest, "firstName");
    String middleName = BeanParamUtil.getString(user, actionRequest, "middleName");
    String lastName = BeanParamUtil.getString(user, actionRequest, "lastName");
    long prefixId = BeanParamUtil.getInteger(contact, actionRequest, "prefixId");
    long suffixId = BeanParamUtil.getInteger(contact, actionRequest, "suffixId");
    boolean male = BeanParamUtil.getBoolean(user, actionRequest, "male", true);

    Calendar birthdayCal = CalendarFactoryUtil.getCalendar();

    birthdayCal.setTime(contact.getBirthday());

    int birthdayMonth = ParamUtil.getInteger(actionRequest, "birthdayMonth", birthdayCal.get(Calendar.MONTH));
    int birthdayDay = ParamUtil.getInteger(actionRequest, "birthdayDay", birthdayCal.get(Calendar.DATE));
    int birthdayYear = ParamUtil.getInteger(actionRequest, "birthdayYear", birthdayCal.get(Calendar.YEAR));

    String comments = BeanParamUtil.getString(user, actionRequest, "comments");
    String jobTitle = BeanParamUtil.getString(user, actionRequest, "jobTitle");

    ServiceContext serviceContext = ServiceContextFactory.getInstance(User.class.getName(), actionRequest);

    user = _userService.updateUser(user.getUserId(), oldPassword, null, null, user.getPasswordReset(), null,
            null, screenName, emailAddress, facebookId, user.getOpenId(), !deleteLogo, portraitBytes,
            languageId, user.getTimeZoneId(), user.getGreeting(), comments, firstName, middleName, lastName,
            prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, null, null, null, null, null,
            jobTitle, null, null, null, null, null, null, null, null, null, null, serviceContext);

    if (oldScreenName.equals(user.getScreenName())) {
        oldScreenName = StringPool.BLANK;
    }

    boolean updateLanguageId = false;

    if (user.getUserId() == themeDisplay.getUserId()) {

        // Reset the locale

        HttpServletRequest request = portal
                .getOriginalServletRequest(portal.getHttpServletRequest(actionRequest));
        HttpServletResponse response = portal.getHttpServletResponse(actionResponse);
        HttpSession session = request.getSession();

        session.removeAttribute(Globals.LOCALE_KEY);

        Locale locale = LocaleUtil.fromLanguageId(languageId);

        LanguageUtil.updateCookie(request, response, locale);

        // Clear cached portlet responses

        PortletSession portletSession = actionRequest.getPortletSession();

        InvokerPortletImpl.clearResponses(portletSession);

        updateLanguageId = true;
    }

    Company company = portal.getCompany(actionRequest);

    if (company.isStrangersVerify() && !StringUtil.equalsIgnoreCase(oldEmailAddress, emailAddress)) {

        SessionMessages.add(actionRequest, "verificationEmailSent");
    }

    return new Object[] { user, oldScreenName, updateLanguageId };
}

From source file:com.liferay.users.admin.web.internal.portlet.action.ExportUsersMVCResourceCommand.java

License:Open Source License

@Override
protected void doServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    try {/*w w  w.  j  a  v  a 2 s  .c  o m*/
        SessionMessages.add(resourceRequest,
                _portal.getPortletId(resourceRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);

        String csv = getUsersCSV(resourceRequest, resourceResponse);

        PortletResponseUtil.sendFile(resourceRequest, resourceResponse, "users.csv", csv.getBytes(),
                ContentTypes.TEXT_CSV_UTF8);
    } catch (Exception e) {
        SessionErrors.add(resourceRequest, e.getClass());

        _log.error(e, e);
    }
}

From source file:com.liferay.weather.portlet.WeatherPortlet.java

License:Open Source License

protected void updatePreferences(ActionRequest actionRequest, ActionResponse actionResponse)
        throws IOException, PortletException {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    if (!cmd.equals(Constants.UPDATE)) {
        return;//from   ww w .  jav a  2 s  .  c  om
    }

    PortletPreferences preferences = actionRequest.getPreferences();

    String[] zips = StringUtil.split(ParamUtil.getString(actionRequest, "zips"), "\n");

    boolean fahrenheit = ParamUtil.get(actionRequest, "fahrenheit", true);

    preferences.setValues("zips", zips);
    preferences.setValue("fahrenheit", String.valueOf(fahrenheit));

    try {
        preferences.store();
    } catch (ValidatorException ve) {
        SessionErrors.add(actionRequest, ValidatorException.class.getName(), ve);

        return;
    }

    PortletConfig portletConfig = getPortletConfig();

    SessionMessages.add(actionRequest,
            portletConfig.getPortletName() + SessionMessages.KEY_SUFFIX_UPDATED_PREFERENCES);
}

From source file:com.liferay.webform.portlet.WebFormPortlet.java

License:Open Source License

public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String portletId = PortalUtil.getPortletId(actionRequest);

    PortletPreferences preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletId);

    boolean requireCaptcha = GetterUtil.getBoolean(preferences.getValue("requireCaptcha", StringPool.BLANK));
    String successURL = GetterUtil.getString(preferences.getValue("successURL", StringPool.BLANK));
    boolean sendAsEmail = GetterUtil.getBoolean(preferences.getValue("sendAsEmail", StringPool.BLANK));
    boolean saveToDatabase = GetterUtil.getBoolean(preferences.getValue("saveToDatabase", StringPool.BLANK));
    String databaseTableName = GetterUtil
            .getString(preferences.getValue("databaseTableName", StringPool.BLANK));
    boolean saveToFile = GetterUtil.getBoolean(preferences.getValue("saveToFile", StringPool.BLANK));
    String fileName = GetterUtil.getString(preferences.getValue("fileName", StringPool.BLANK));

    if (requireCaptcha) {
        try {//from ww  w .java 2s  .c  om
            CaptchaUtil.check(actionRequest);
        } catch (CaptchaTextException cte) {
            SessionErrors.add(actionRequest, CaptchaTextException.class.getName());

            return;
        }
    }

    Map<String, String> fieldsMap = new LinkedHashMap<String, String>();

    for (int i = 1; true; i++) {
        String fieldLabel = preferences.getValue("fieldLabel" + i, StringPool.BLANK);

        String fieldType = preferences.getValue("fieldType" + i, StringPool.BLANK);

        if (Validator.isNull(fieldLabel)) {
            break;
        }

        if (StringUtil.equalsIgnoreCase(fieldType, "paragraph")) {
            continue;
        }

        fieldsMap.put(fieldLabel, actionRequest.getParameter("field" + i));
    }

    Set<String> validationErrors = null;

    try {
        validationErrors = validate(fieldsMap, preferences);
    } catch (Exception e) {
        SessionErrors.add(actionRequest, "validationScriptError", e.getMessage().trim());

        return;
    }

    if (validationErrors.isEmpty()) {
        boolean emailSuccess = true;
        boolean databaseSuccess = true;
        boolean fileSuccess = true;

        if (sendAsEmail) {
            emailSuccess = sendEmail(themeDisplay.getCompanyId(), fieldsMap, preferences);
        }

        if (saveToDatabase) {
            if (Validator.isNull(databaseTableName)) {
                databaseTableName = WebFormUtil.getNewDatabaseTableName(portletId);

                preferences.setValue("databaseTableName", databaseTableName);

                preferences.store();
            }

            databaseSuccess = saveDatabase(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    databaseTableName);
        }

        if (saveToFile) {
            fileSuccess = saveFile(fieldsMap, fileName);
        }

        if (emailSuccess && databaseSuccess && fileSuccess) {
            if (Validator.isNull(successURL)) {
                SessionMessages.add(actionRequest, "success");
            } else {
                SessionMessages.add(actionRequest,
                        portletId + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
            }
        } else {
            SessionErrors.add(actionRequest, "error");
        }
    } else {
        for (String badField : validationErrors) {
            SessionErrors.add(actionRequest, "error" + badField);
        }
    }

    if (SessionErrors.isEmpty(actionRequest) && Validator.isNotNull(successURL)) {

        actionResponse.sendRedirect(successURL);
    }
}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

License:Open Source License

public void execute(ActionRequest actionRequest, ActionResponse actionResponse) {
    try {/*w w  w . j  a  v  a 2 s .c o m*/
        sCheckPermissions(actionRequest);

        String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(100 * 1024 * 1024);
        PortletFileUpload upload = new PortletFileUpload(factory);

        FileItem fileUploaded = null;
        List<FileItem> items = upload.parseRequest(actionRequest);
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                actionRequest.setAttribute(fi.getFieldName(), fi.getString());
                if (fi.getFieldName().startsWith(portletId)) {
                    actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString());
                }
            } else {
                fileUploaded = fi;
            }
        }

        String cmd = (String) actionRequest.getAttribute("cmd");
        String language = (String) actionRequest.getAttribute("language");
        String script = (String) actionRequest.getAttribute("script");
        String editorheight = (String) actionRequest.getAttribute("editorheight");
        String themesel = (String) actionRequest.getAttribute("themesel");
        if (language == null) {
            language = getDefaultLanguage();
        }
        if (script == null) {
            script = StringPool.BLANK;
        }
        actionResponse.setRenderParameter("language", language);
        actionResponse.setRenderParameter("script", script);
        actionResponse.setRenderParameter("editorheight", editorheight);
        actionResponse.setRenderParameter("themesel", themesel);

        if ("execute".equals(cmd)) {

            Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(),
                    getPortletContext(), actionRequest, actionResponse);

            UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

            UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream);

            portletObjects.put("out", unsyncPrintWriter);

            _log.info("Executing script");
            ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY);
            unsyncPrintWriter.flush();
            actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString());
        } else if ("save".equals(cmd)) {
            String newscriptname = (String) actionRequest.getAttribute("newscriptname");
            if (newscriptname == null || newscriptname.trim().length() == 0) {
                actionResponse.setRenderParameter("script_trace", "No script name specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving new script: " + newscriptname.trim());
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + newscriptname.trim(), script);
            prefs.setValue("lang." + newscriptname.trim(), language);
            prefs.store();
        } else if ("saveinto".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + scriptname, script);
            prefs.setValue("lang." + scriptname, language);
            prefs.store();
        } else if ("loadfrom".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to load from!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Loading saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            language = prefs.getValue("lang." + scriptname, getDefaultLanguage());
            script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK);
            actionResponse.setRenderParameter("language", language);
            actionResponse.setRenderParameter("script", script);
        } else if ("delete".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to delete!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Deleting saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.reset("savedscript." + scriptname);
            prefs.reset("lang." + scriptname);
            prefs.store();
        } else if ("import".equals(cmd)) {
            if (fileUploaded == null) {
                actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            StringBuilder output = new StringBuilder();

            InputStream instream = fileUploaded.getInputStream();
            ZipInputStream zipstream = null;
            try {
                zipstream = new ZipInputStream(instream);
                ZipEntry entry = zipstream.getNextEntry();
                while (entry != null) {
                    String filename = entry.getName();
                    if (filename.contains("/")) {
                        int qs = filename.lastIndexOf("/");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }
                    if (filename.contains("\\")) {
                        int qs = filename.lastIndexOf("\\");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }

                    String ext = StringPool.BLANK;
                    if (filename.length() > 0) {
                        int qs = filename.lastIndexOf(".");
                        if (qs > 0) {
                            ext = filename.substring(qs + 1);
                            filename = filename.substring(0, qs);
                        }
                    }

                    String lang = resolveLanguage(ext);
                    String imscript = getStreamAsString(zipstream, "utf-8", false);

                    if (imscript != null && imscript.length() > 0) {
                        _log.info("Importing script \"" + filename + "\" of type " + lang);
                        output.append("Importing script \"" + filename + "\" of type " + lang + "\n");

                        PortletPreferences prefs = actionRequest.getPreferences();
                        prefs.setValue("savedscript." + filename, imscript);
                        prefs.setValue("lang." + filename, lang);
                        prefs.store();
                    }

                    entry = zipstream.getNextEntry();
                }

                actionResponse.setRenderParameter("script_output", output.toString());
            } finally {
                try {
                    if (zipstream != null) {
                        zipstream.close();
                    }
                } catch (Exception e) {
                }
                try {
                    if (instream != null) {
                        instream.close();
                    }
                } catch (Exception e) {
                }
            }

            _log.info(fileUploaded.getName());
        }
        SessionMessages.add(actionRequest, "success");
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.close();
        actionResponse.setRenderParameter("script_trace", sw.toString());
        _log.error(e);
        SessionErrors.add(actionRequest, e.toString());
    }
}

From source file:com.platts.portlet.documentlibrary.DLSetSeoUrl.java

License:Open Source License

@Override
public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig,
        ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortalException, SystemException, IOException {
    LOGGER.info("the process action for struts action DLSetSeoUrl is getting called");
    String uri = ParamUtil.getString(actionRequest, "uri", null);
    String seoURL = ParamUtil.getString(actionRequest, "seoURL", null);
    Long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
    LOGGER.info("uri is " + uri + " seourl is " + seoURL + " fileEntryId " + fileEntryId);
    FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId);
    // sample url http://10.206.111.1:8030/v1/resources/content?uri=/test/holiday.xml&seoUrl=/EditorBios/regina1233johnson.xml
    StringBuilder url = new StringBuilder("http://10.206.111.1:8030/v1/resources/content?uri=");
    url.append(uri).append(StringPool.SLASH).append(fileEntry.getTitle()).append("&seoUrl=").append(seoURL);
    LOGGER.info("the url is " + url.toString());
    PlattsExportUtil exportUtil = new PlattsExportUtil();
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    File file = exportUtil.getFileFromDLFile(themeDisplay.getUserId(), fileEntry.getFileEntryId(),
            fileEntry.getLatestFileVersion().getVersion());
    //LOGGER.info("the file is " + FileUtils.readFileToString(file));
    FileEntity fileEntity = new FileEntity(file);
    fileEntity.setContentType("application/xml");
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("CPUser", "CPUser22");
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();
    HttpPost postRequest = new HttpPost(url.toString());
    postRequest.setEntity(fileEntity);/*from   w  w  w  .  j a v a 2 s .  c  om*/
    try {
        CloseableHttpResponse response = httpClient.execute(postRequest);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity);
        Document document = SAXReaderUtil.read(responseString);
        String responseText = document.getRootElement().selectSingleNode("/response").getText();
        if (responseText.equalsIgnoreCase("ok")) {
            SessionMessages.add(actionRequest, "seoURLActionSuccess");
            hideDefaultSuccessMessage(actionRequest);
            String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));
            try {
                actionResponse.sendRedirect(redirect);
            } catch (IOException e) {
                LOGGER.error("error redirecting ", e);
            }
        } else {
            SessionErrors.add(actionRequest, "seoURLActionFailure");
            LOGGER.info("the error text is " + responseText);
            actionResponse.setRenderParameter("errorMessage", responseText);
        }
        response.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.platts.portlet.documentlibrary.DLSetSeoUrl.java

License:Open Source License

protected void hideDefaultSuccessMessage(PortletRequest portletRequest) {
    SessionMessages.add(portletRequest,
            PortalUtil.getPortletId(portletRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
}