Example usage for org.apache.commons.lang StringEscapeUtils escapeHtml

List of usage examples for org.apache.commons.lang StringEscapeUtils escapeHtml

Introduction

In this page you can find the example usage for org.apache.commons.lang StringEscapeUtils escapeHtml.

Prototype

public static String escapeHtml(String input) 

Source Link

Usage

From source file:de.openflorian.web.security.XssHtmlTextParser.java

/**
 * Strip HTML tags: removes all html tags from text
 * /*from   w ww  .  jav a  2  s  . c  om*/
 * @param htmlText
 * @return
 */
public static String stripTags(String htmlText) {
    return StringEscapeUtils.escapeHtml(htmlText);
}

From source file:de.arago.rike.task.action.EvaluateTask.java

@Override
public void execute(IDataWrapper data) throws Exception {

    if (data.getRequestAttribute("id") != null) {

        Task task = TaskHelper.getTask(data.getRequestAttribute("id"));

        String user = SecurityHelper.getUserEmail(data.getUser());

        if (task.getStatusEnum() == Task.Status.UNKNOWN || task.getStatusEnum() == Task.Status.OPEN) {
            task.setMilestone(/*from ww  w  . j a  v  a 2 s . c  o m*/
                    new DataHelperRike<Milestone>(Milestone.class).find(data.getRequestAttribute("milestone")));
            task.setArtifact(
                    new DataHelperRike<Artifact>(Artifact.class).find(data.getRequestAttribute("artifact")));

            task.setDescription(data.getRequestAttribute("description"));

            try {
                task.setSizeEstimated(Integer.valueOf(data.getRequestAttribute("size_estimated"), 10));
            } catch (Exception ignored) {
            }

            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                task.setDueDate(format.parse(data.getRequestAttribute("due_date")));
            } catch (Exception ignored) {
            }

            task.setTitle(data.getRequestAttribute("title"));
            task.setUrl(data.getRequestAttribute("url"));
            int priority = Integer.parseInt(GlobalConfig.get(PRIORITY_NORMAL));

            try {
                priority = Integer.valueOf(data.getRequestAttribute("priority"), 10);
            } catch (Exception ignored) {
            }

            task.setPriority(priority);
            task.setRated(new Date());
            task.setRatedBy(user);
            task.setStatus(Task.Status.OPEN);
            if (GlobalConfig.get(WORKFLOW_TYPE).equalsIgnoreCase("arago Technologies") && priority == 1) {
                GregorianCalendar c = new GregorianCalendar();
                c.setTime(task.getRated());
                c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(GlobalConfig.get(WORKFLOW_DAYS_TOP_PRIO_TASK)));
                task.setDueDate(c.getTime());
            }

            TaskHelper.save(task);

            StatisticHelper.update();

            data.setSessionAttribute("task", task);

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

            notificationParam.put("id", data.getRequestAttribute("id"));
            data.setEvent("TaskUpdateNotification", notificationParam);

            data.removeSessionAttribute("targetView");

            ActivityLogHelper.log(
                    " rated Task #" + task.getId() + " <a href=\"/web/guest/rike/-/show/task/" + task.getId()
                            + "\">" + StringEscapeUtils.escapeHtml(task.getTitle()) + "</a> ",
                    task.getStatus(), SecurityHelper.getUserEmail(data.getUser()), data, task.toMap());
        }
    }
}

From source file:com.redhat.rhn.frontend.action.rhnpackage.PackageDetailsAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {/*from   ww w .ja v a 2 s  .c o  m*/

    RequestContext requestContext = new RequestContext(request);
    User user = requestContext.getCurrentUser();

    //If this is an easy one and we have the pid
    if (request.getParameter("pid") != null) {
        long pid = requestContext.getRequiredParam("pid");
        Package pkg = PackageFactory.lookupByIdAndUser(pid, user);

        // show permission error if pid is invalid like we did before
        if (pkg == null) {
            throw new PermissionException("Invalid pid");
        }

        request.setAttribute("type", "rpm");
        request.setAttribute(PACKAGE_NAME, pkg.getFilename());
        if (!pkg.getPackageKeys().isEmpty()) {
            request.setAttribute(PACKAGE_KEY, pkg.getPackageKeys().iterator().next().getKey());
        }
        boolean isDebug = pkg.getPackageName().getName().contains("debuginfo");

        request.setAttribute("isDebuginfo", isDebug);
        if (!isDebug) {
            Package debugPkg = PackageManager.findDebugInfo(user, pkg);
            String ftpUrl = PackageManager.generateFtpDebugPath(pkg);
            if (debugPkg != null) {
                request.setAttribute("debugUrl", DownloadManager.getPackageDownloadPath(debugPkg, user));
            } else if (ftpUrl != null) {
                request.setAttribute("debugUrl", ftpUrl);
                request.setAttribute("debugFtp", true);
            }

        }

        if (DownloadManager.isFileAvailable(pkg.getPath())) {
            request.setAttribute("url", DownloadManager.getPackageDownloadPath(pkg, user));
        }

        List<PackageSource> src = PackageFactory.lookupPackageSources(pkg);

        if (!src.isEmpty() && DownloadManager.isFileAvailable(src.get(0).getPath())) {
            request.setAttribute("srpm_url",
                    DownloadManager.getPackageSourceDownloadPath(pkg, src.get(0), user));
            request.setAttribute("srpm_path", src.get(0).getFile());
        }

        // remove references to channels we can't see
        Set<Channel> channels = new HashSet<Channel>(pkg.getChannels());
        channels.retainAll(ChannelFactory.getAccessibleChannelsByOrg(user.getOrg().getId()));
        request.setAttribute("channels", channels);

        request.setAttribute("pack", pkg);
        // description can be null.
        if (pkg.getDescription() != null) {
            String description = StringEscapeUtils.escapeHtml(pkg.getDescription());
            request.setAttribute("description", description.replace("\n", "<BR>\n"));
        } else {
            request.setAttribute("description", pkg.getDescription());
        }
        request.setAttribute("packArches", PackageFactory.findPackagesWithDifferentArch(pkg));
        request.setAttribute("pid", pid);

        request.setAttribute("erratumEmpty", pkg.getPublishedErrata().isEmpty());
        request.setAttribute("erratum", pkg.getPublishedErrata());

        return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
    }
    PackageListItem item = PackageListItem.parse(request.getParameter("id_combo"));
    Package pkg;
    long nameId = item.getIdOne();
    long evrId = item.getIdTwo();
    long archId = 0;
    if (item.getIdThree() != null) {
        archId = item.getIdThree();
    }

    Long cid = requestContext.getParamAsLong("cid");
    Long sid = requestContext.getParamAsLong("sid");
    if (cid != null) {
        pkg = PackageManager.guestimatePackageByChannel(cid, nameId, evrId, user.getOrg());

    } else if (sid != null) {
        pkg = PackageManager.guestimatePackageBySystem(sid, nameId, evrId, archId, user.getOrg());

    } else {
        throw new BadParameterException("pid, cid, or sid");
    }

    // show permission error if pid is invalid like we did before
    if (pkg == null) {
        throw new PermissionException("Invalid id_combo and cid/sid");
    }

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("pid", pkg.getId());
    return getStrutsDelegate().forwardParams(mapping.findForward("package"), params);
}

From source file:edu.lafayette.metadb.web.search.SearchServlet.java

private JSONObject getFormattedResult(ArrayList<Item> results, ArrayList<String> tokens) {
    JSONObject output = new JSONObject();

    try {/*w ww.j a v a  2 s  .  c  o  m*/
        JSONArray thumb_urls = new JSONArray();
        JSONArray zoom_urls = new JSONArray();
        JSONArray projnames = new JSONArray();
        JSONArray indices = new JSONArray();
        JSONArray data = new JSONArray();
        for (Item item : results) {
            String projname = item.getProjname();
            int index = item.getItemNumber();
            String thumbPath = ItemsDAO.getThumbFilePath(projname, index);
            String thumbName = new File(thumbPath).getName();
            String thumbFilePath = Global.PATH_PROJECT + projname + "/" + thumbName;
            String mediumPath = new File(ItemsDAO.getZoomDerivPath(projname, index)).getName();
            String mediumFilePath = Global.PATH_PROJECT + projname + "/" + mediumPath;
            thumb_urls.put(thumbFilePath);
            zoom_urls.put(mediumFilePath);
            projnames.put(projname);
            indices.put(index);
            JSONArray attrs = new JSONArray();
            for (AdminDescItem adminDescData : item.search(tokens)) {
                String label = adminDescData.getLabel();
                String attrData = "<p><span style='font-weight:bold'>" + adminDescData.getElement();
                if (!label.equals(""))
                    attrData += "." + label;
                attrData += ":</span>" + StringEscapeUtils.escapeHtml(adminDescData.getData()) + "</p>";
                attrs.put(attrData);
            }
            data.put(attrs);
        }
        output.put("zoom_urls", zoom_urls);
        output.put("thumb_urls", thumb_urls);
        output.put("projectNames", projnames);
        output.put("indices", indices);
        output.put("data", data);
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    return output;
}

From source file:com.agiletec.aps.system.common.renderer.BaseEntityRenderer.java

protected List<TextAttributeCharReplaceInfo> convertSpecialCharacters(IApsEntity entity, String langCode) {
    List<TextAttributeCharReplaceInfo> conversions = new ArrayList<TextAttributeCharReplaceInfo>();
    Lang defaultLang = this.getLangManager().getDefaultLang();
    EntityAttributeIterator attributeIter = new EntityAttributeIterator(entity);
    while (attributeIter.hasNext()) {
        AttributeInterface currAttribute = (AttributeInterface) attributeIter.next();
        if (currAttribute instanceof ITextAttribute) {
            String attributeLangCode = langCode;
            ITextAttribute renderizable = (ITextAttribute) currAttribute;
            if (renderizable.needToConvertSpecialCharacter()) {
                String textToConvert = renderizable.getTextForLang(attributeLangCode);
                if (null == textToConvert || textToConvert.trim().length() == 0) {
                    attributeLangCode = defaultLang.getCode();
                    textToConvert = renderizable.getTextForLang(attributeLangCode);
                }/*from w w  w .  j av  a 2 s. c o m*/
                if (null != textToConvert && textToConvert.trim().length() > 0) {
                    conversions.add(
                            new TextAttributeCharReplaceInfo(renderizable, textToConvert, attributeLangCode));
                    String convertedText = StringEscapeUtils.escapeHtml(textToConvert);
                    renderizable.setText(convertedText, attributeLangCode);
                }
            }
        }
    }
    return conversions;
}

From source file:de.knurt.fam.template.util.TemplateHtml.java

public String getEntities(String raw) {
    return StringEscapeUtils.escapeHtml(raw);
}

From source file:au.com.gaiaresources.bdrs.model.file.ManagedFile.java

@Transient
public String getFileURL() {
    try {/*from   w w w  .ja  va 2 s.c  om*/
        return String.format(FileService.FILE_URL_TMPL,
                URLEncoder.encode(getClass().getCanonicalName(), "UTF-8"), getId(),
                URLEncoder.encode(getFilename(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return String.format(FileService.FILE_URL_TMPL,
                StringEscapeUtils.escapeHtml(getClass().getCanonicalName()), getId(),
                StringEscapeUtils.escapeHtml(getFilename()));
    }
}

From source file:it.eng.spagobi.engines.network.bean.CrossNavigationLink.java

/**
 * Get the map (name/value) for the fixed parameters.
 * The fixed parameters are the ones with type RELATIVE and ABSOLUTE
 * @return//  w  w w. java  2  s.com
 */
public Map<String, String> getFixedParameters() {
    CrossNavigationParameter parameter;
    Map<String, String> fixedParameter = new HashMap<String, String>();
    for (int i = 0; i < parameters.size(); i++) {
        parameter = parameters.get(i);
        if (parameter.getType().equals(CrossNavigationParameterType.RELATIVE)
                || parameter.getType().equals(CrossNavigationParameterType.ABSOLUTE)) {
            fixedParameter.put(StringEscapeUtils.escapeHtml(parameter.getName()),
                    StringEscapeUtils.escapeHtml(parameter.getValue()));
        }
    }
    return fixedParameter;
}

From source file:com.edgenius.wiki.render.handler.RepoHandler.java

public List<RenderPiece> handle(RenderContext renderContext, Map<String, String> values) {
    List<RenderPiece> pieces = new ArrayList<RenderPiece>();

    List<FileNode> files = new ArrayList<FileNode>();
    if (atts != null) {
        files = getFileList(values != null ? values.get("filter") : null,
                renderContext.getPageVisibleAttachments());
    }//from  www  .j ava2s  . co  m

    List<String> urls = new ArrayList<String>();
    //try to find the image from repository
    for (FileNode node : files) {
        //found attachment
        urls.add(renderContext.buildDownloadURL(node.getFilename(), node.getNodeUuid(), true));
    }

    int id = renderContext.createIncremetalKey();
    StringBuffer attachBuf = new StringBuffer("<div aid=\"repository\" id=\"repository-").append(id)
            .append("\" class=\"").append(WikiConstants.mceNonEditable).append("\" ");
    if (values != null && values.size() > 0) {
        attachBuf.append("wajax=\"")
                .append(RichTagUtil.buildWajaxAttributeString(this.getClass().getName(), values)).append("\" ");
    }
    attachBuf.append(">");

    attachBuf.append("<table class=\"macroAttachment\">");
    //TODO: i18n, header
    attachBuf.append(
            "<tr><th>File</th><th>Author</th><th>Size</th><th>Date</th><th>Owner page</th><th>Comment</th></tr>");
    int sum = urls.size();
    if (sum > 0) {
        for (int idx = 0; idx < sum; idx++) {
            FileNode node = files.get(idx);
            attachBuf.append("<tr>");
            //filename
            attachBuf.append("<td class='column1'><a href=\"");
            attachBuf.append(urls.get(idx));
            attachBuf.append("\" title=\"Download file\">");
            attachBuf.append(node.getFilename());
            attachBuf.append("</a></td>");
            //author
            attachBuf.append("<td class='column2'>").append(StringEscapeUtils.escapeHtml(node.getCreateor()))
                    .append("</td>");
            //size
            attachBuf.append("<td class='column3'>").append(GwtUtils.convertHumanSize(node.getSize()))
                    .append("</td>");
            //date
            attachBuf.append("<td class='column4'>").append(
                    DateUtil.toDisplayDate(WikiUtil.getUser(), new Date(node.getDate()), messageService))
                    .append("</td>");
            //owner page
            attachBuf.append("<td class='column6'>");
            String pageTitle = getPageTitle(node.getIdentifier());
            if (pageTitle != null) {
                attachBuf.append("<a href=\"")
                        .append(WikiUtil.getPageRelativeTokenURL(spaceUname, pageTitle, null)).append("\">")
                        .append(pageTitle).append("</a>");
            } else {
                attachBuf.append("Unknown");
            }
            attachBuf.append("</td>");
            //comment
            attachBuf.append("<td>").append(StringEscapeUtils.escapeHtml(node.getComment())).append("</td>");
            attachBuf.append("</tr>");
        }
    } else {
        //TODO: i18n
        attachBuf.append("<tr><td colspan='6'>").append("No matched files").append("</td></tr>");
    }

    attachBuf.append("</table></div>");
    pieces.add(new TextModel(attachBuf.toString()));
    return pieces;

}

From source file:de.suse.swamp.modules.actions.LoginActions.java

/**
 * Checks the if the login data is correct, 
 * and provides Turbine with a Turbineuser afterwards.
 * //from   w  w  w  . j  av a2 s .  c o  m
 * @author Thomas Schmidt
 * @param data - Turbine information.
 * @exception Exception, a generic exception.
 */
public void doLoginuser(RunData data, Context context) throws Exception {

    ParameterParser pp = data.getParameters();
    String username = pp.getString("username", "").toLowerCase();
    String password = pp.getString("password", "");
    // cause of login-error 
    String cause = null;

    if (StringUtils.isEmpty(username)) {
        return;
    }

    try {

        User user = TurbineSecurity.getAuthenticatedUser(username, password);
        // Store the user object.
        data.setUser(user);
        // Mark the user as being logged in.
        user.setHasLoggedIn(new Boolean(true));
        // Save the User object into the session.
        data.save();
        Logger.LOG(username + " has successfully logged in.");

        // if we have a "query", it's a redirect from the login page:
        // if we want restrict to do direct logins to special actions, we have to restrict it here
        if (pp.containsKey("query") && !pp.get("query").equals("")
                && !(pp.get("query").indexOf("doLogoutuser") > 0)) {
            Logger.DEBUG("Found a query, redirecting to " + pp.get("query"));
            data.declareDirectResponse();
            data.setRedirectURI(pp.get("query"));
        }
    } catch (Exception e) {
        Logger.ERROR("Login Error: " + e.getMessage());
        // Retrieve an anonymous user.
        data.setUser(TurbineSecurity.getAnonymousUser());
        data.setScreen(Turbine.getConfiguration().getString("screen.login"));
        data.setScreenTemplate(Turbine.getConfiguration().getString("template.login"));
        data.setLayoutTemplate("DefaultLayout.vm");

        // set the right error-message:
        if (e instanceof StorageException) {
            cause = "Error in communicating with authentication server: " + e.getMessage();
        } else if (e instanceof PasswordMismatchException) {
            cause = "Wrong password entered for username: " + username;
        } else if (e instanceof UnknownEntityException) {
            cause = "Unknown username: " + username;
        } else if (e instanceof NoSuchElementException) {
            cause = "Unknown username: " + username;
        } else if (e instanceof DataBackendException) {
            cause = "Could not connect to user database: " + e.getMessage();
        } else {
            cause = "Fatal Error : " + e.getMessage();
        }
        data.setMessage("Login failed. Cause: " + StringEscapeUtils.escapeHtml(cause));

    }

    // Check for XML-Output for external scripts
    if (data.getParameters().containsKey("xmlresponse")
            && data.getParameters().get("xmlresponse").equals("true")) {
        if (cause != null && !cause.equals("")) {
            // FIXME: Mapping ERROR to Errornumber must happen here
            ExternalActions.doSendXMLOutput(data, "1", StringEscapeUtils.escapeHtml(cause));
        } else {
            ExternalActions.doSendXMLOutput(data, "0", "Your are logged in");
        }
    }
}