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.arago.rike.task.action.SaveMilestone.java

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

    DataHelperRike<Milestone> helper = new DataHelperRike<Milestone>(Milestone.class);
    Milestone milestone = null;//from   ww w  .  java2 s  .c om
    boolean newMilestoneCreated = false;

    if (data.getRequestAttribute("id") != null && !data.getRequestAttribute("id").isEmpty()) {
        milestone = helper.find(data.getRequestAttribute("id"));
    }

    if (milestone == null) {
        newMilestoneCreated = true;
        milestone = new Milestone();
    }

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

    milestone.setTitle(data.getRequestAttribute("title"));
    milestone.setUrl(data.getRequestAttribute("url"));
    milestone.setCreated(new Date());
    milestone.setCreator(SecurityHelper.getUser(data.getUser()).getEmailAddress());

    milestone.setPerformance(0);

    try {
        milestone.setPerformance(Integer.valueOf(data.getRequestAttribute("performance"), 10));
    } catch (Exception ignored) {
    }

    milestone.setRelease("");

    String release = data.getRequestAttribute("release");

    if (release != null && release.equals("_new_")) {
        milestone.setRelease(data.getRequestAttribute("new_release"));
    } else if (release != null) {
        milestone.setRelease(release);
    }

    helper.save(milestone);

    data.setSessionAttribute("milestone", milestone);
    data.setSessionAttribute("targetView", "viewMilestone");

    String message = " changed Milestone #";
    if (newMilestoneCreated) {
        message = " created Milestone #";
    }

    ActivityLogHelper.log(
            message + milestone.getId() + " <a href=\"/web/guest/rike/-/show/milestone/" + milestone.getId()
                    + "\">" + StringEscapeUtils.escapeHtml(milestone.getTitle()) + "</a>",
            "", milestone.getCreator(), data, milestone.toMap());

}

From source file:io.github.tavernaextras.biocatalogue.ui.search_results.RESTMethodListCellRenderer.java

/**
 * This entry can be in one of two states:
 * -- containing only the name of the resource and NOT loading further details;
 * -- containing only the name of the resource and LOADING further details.
 * //from  w w  w . j  a va 2 s  .  c  o  m
 * @param itemToRender
 * @return
 */
protected GridBagConstraints prepareInitiallyLoadingEntry(Object itemToRender) {
    LoadingResource resource = (LoadingResource) itemToRender;

    jlTypeIcon.setIcon(resourceType.getIcon());
    jlItemStatus.setIcon(ResourceManager.getImageIcon(ResourceManager.SERVICE_STATUS_UNCHECKED_ICON_LARGE));

    jlItemTitle.setText("<html>" + StringEscapeUtils.escapeHtml(Resource.getDisplayNameForResource(resource))
            + "<font color=\"gray\"><i>- fetching more information</i></font></html>");

    jlPartOf.setText("");
    jtDescription.setText(" ");
    jlMethodType.setText(" ");
    jlUrlTemplate.setText(" ");
    jlMethodParameters.setText(" ");
    jlInputRepresentations.setText(" ");
    jlOutputRepresentations.setText(" ");

    return (arrangeLayout());
}

From source file:com.bst.tags.JavascriptHref.java

/**
 * Construct a new Href parsing a URL. Parameters are stripped from the base url and saved in the parameters map.
 * @param baseUrl String/* w  ww .j  av a 2  s  . co  m*/
 */
public JavascriptHref(String baseUrl) {
    super(baseUrl);

    this.parameters = new HashMap();

    String noAnchorUrl;
    int anchorposition = baseUrl.indexOf('#');

    // extract anchor from url
    if (anchorposition != -1) {
        noAnchorUrl = baseUrl.substring(0, anchorposition);
        this.anchor = baseUrl.substring(anchorposition + 1);
    } else {
        noAnchorUrl = baseUrl;
    }

    if (noAnchorUrl.indexOf('?') == -1) {
        // simple url, no parameters
        this.url = noAnchorUrl;
        return;
    }

    // the Url already has parameters, put them in the parameter Map
    StringTokenizer tokenizer = new StringTokenizer(noAnchorUrl, "?"); //$NON-NLS-1$

    if (baseUrl.startsWith("?")) //$NON-NLS-1$
    {
        // support fake URI's which are just parameters to use with the current uri
        url = TagConstants.EMPTY_STRING;
    } else {
        // base url (before "?")
        url = tokenizer.nextToken();
    }

    if (!tokenizer.hasMoreTokens()) {
        return;
    }

    // process parameters
    StringTokenizer paramTokenizer = new StringTokenizer(tokenizer.nextToken(), "&"); //$NON-NLS-1$

    // split parameters (key=value)
    while (paramTokenizer.hasMoreTokens()) {
        // split key and value ...
        String[] keyValue = StringUtils.split(paramTokenizer.nextToken(), '=');

        // encode name/value to prevent css
        String escapedKey = StringEscapeUtils.escapeHtml(keyValue[0]);
        String escapedValue = keyValue.length > 1 ? StringEscapeUtils.escapeHtml(keyValue[1])
                : TagConstants.EMPTY_STRING;

        if (!this.parameters.containsKey(escapedKey)) {
            // ... and add it to the map
            this.parameters.put(escapedKey, escapedValue);
        } else {
            // additional value for an existing parameter
            Object previousValue = this.parameters.get(escapedKey);
            if (previousValue != null && previousValue.getClass().isArray()) {
                Object[] previousArray = (Object[]) previousValue;
                Object[] newArray = new Object[previousArray.length + 1];

                int j;

                for (j = 0; j < previousArray.length; j++) {
                    newArray[j] = previousArray[j];
                }

                newArray[j] = escapedValue;
                this.parameters.put(escapedKey, newArray);
            } else {
                this.parameters.put(escapedKey, new Object[] { previousValue, escapedValue });
            }
        }
    }
}

From source file:com.denimgroup.threadfix.service.channel.AppScanEnterpriseChannelImporter.java

/**
 * This is added so we can use retrieveByName on the AppScan vulnerability mappings.
 *//*from   w w w.  ja  v  a2 s  . c o  m*/
@Override
protected ChannelVulnerability getChannelVulnerability(String code) {
    if (channelType == null || code == null || channelVulnerabilityDao == null)
        return null;

    if (channelVulnerabilityMap == null)
        initializeMaps();

    if (channelVulnerabilityMap == null)
        return null;

    if (channelVulnerabilityMap.containsKey(code)) {
        return channelVulnerabilityMap.get(code);
    } else {
        ChannelVulnerability vuln = channelVulnerabilityDao.retrieveByName(channelType, code);
        if (vuln == null) {
            if (channelType != null)
                log.warn("A " + channelType.getName() + " channel vulnerability with code "
                        + StringEscapeUtils.escapeHtml(code) + " was requested but not found.");
            return null;
        } else {
            if (channelVulnerabilityDao.hasMappings(vuln.getId())) {
                log.info("The " + channelType.getName() + " channel vulnerability with code "
                        + StringEscapeUtils.escapeHtml(code) + " has no generic mapping.");
            }
        }

        channelVulnerabilityMap.put(code, vuln);
        return vuln;
    }
}

From source file:com.silverpeas.glossary.HighlightGlossaryTerms.java

String highlight(String term, String content, String definition, String className, boolean onlyFirst) {
    // escape HTML character
    String escapedTerm = StringEscapeUtils.escapeHtml(term);
    // regular expression which allows to search all the term except the HTML tag
    // Searches the exact term
    String regex = "((?i)\\b" + escapedTerm + "\\b)(?=[^>]*<(?!/a))";

    // highlights the term
    String replacement = "<a href=\"#\" class=\"" + className + "\" title=\""
            + definition.replaceAll("\"", "&quot;") + "\">" + escapedTerm + "</a>";

    if (onlyFirst) {
        // highlights only the first occurrence
        return content.replaceFirst(regex, replacement);
    }/*from   ww  w.j ava2  s .  co m*/
    return content.replaceAll(regex, replacement);
}

From source file:mitm.djigzo.web.components.RegExprFilter.java

/**
 * Returns the regular expression pattern. If the user did not select the regular expression checkbox the regular
 * expression that's being returned is prepended with (?i) (ie. case insensitive) search. If escapeHTML is true
 * the search expression is HTML escaped before a pattern is build. This is needed when you want to match
 * the pattern against a HTML file but you want the user to be able to search for HTML special characters (like <)
 * without the user having to change it into the HTML entity.
 *//*from w  w  w  .j a v a  2s.  c o m*/
public Pattern getPattern(boolean escapeHTML) {
    /*
     * We will always return a Pattern but if the user did not select the regular expression 
     * checkbox we will create a pattern from the filter 
     */
    String expression = filter;

    Pattern pattern = null;

    if (expression != null && expression.length() > 0) {
        if (escapeHTML) {
            expression = StringEscapeUtils.escapeHtml(expression);
        }

        if (!regExpr) {
            /*
             * We need to escape all characters that have a special meaning for regular expressions 
             */
            expression = "(?i)" + RegExprUtils.escape(expression);
        }

        try {
            pattern = Pattern.compile(expression);
        } catch (IllegalArgumentException e) {
            /*
             * Even though the for does not validate getPattern is still called so we should
             * catch any compile errors.
             */
            logger.error("Error in regular expression.");
        }
    }

    return pattern;
}

From source file:de.unidue.inf.is.ezdl.gframedl.converter.HTMLConversionTest.java

@Before
public void setUp() throws Exception {

    String authorLabel = new String(i18n.getLocString("field.authors"));
    // String conferenceLabel = new
    // String(i18n.getLocString("field.conference"));
    String abstractLabel = new String(i18n.getLocString("field.abstract"));
    // String journalLabel = new String(i18n.getLocString("field.journal"));
    String yearLabel = new String(i18n.getLocString("field.year"));

    cs = new TestableHTMLConversionStrategy();

    title = "Java and other OOP languages";
    journalTitle = "Google 4tw journal";
    conferenceTitle = "Java World OOP Language Conference";
    year = 1997;//from w  w w  .  j a  va2s  .  c  om
    abstractText = "Diese 8. Auflage des Java-Kultbuches wurde grndlich " + //
            "berarbeitet und aktualisiert. Besonders Einsteiger mit" + //
            " Programmierkenntnissen und Industrieprogrammierer profitieren" + //
            " von diesem umfassenden Werk. Tipps und Tricks aus den Java-FAQs " + //
            "werden regelmig mit in die Insel aufgenommen, um wirklich das" + //
            " abzudecken, was Sie im Alltag brauchen. Die Einfhrung in die " + //
            "Sprache Java ist anschaulich und immer praxisorientiert. Schnell " + //
            "geht es weiter mit fortgeschrittenen Themen wie Threads, Swing," + //
            " Netzwerkprogrammierung, JavaBeans, RMI, XML-Verarbeitung mit Java," + //
            " Servlets und Java ServerPages, JDBC und vielem mehr. Neu in dieser Fassung:" + //
            " JAXB-API, umfangreichere Abschnitte zu regulren Ausdrcken und viele neue Beispiele.";

    document = createDocument(title, year, journalTitle, conferenceTitle, abstractText, "Peter Lustig",
            "Hans Dieter", "Roflmao Lolz");

    documentExpectedOutput = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + styleSheetPath
            + "\"></head>" + //
            "<body><h2>" + StringEscapeUtils.escapeHtml(title) + "</h2>" + //
            "<p><b>" + yearLabel + "</b>: " + year + "</p>" + //
            "<p><b>" + authorLabel + "</b></p>" + //
            "<ul id =\"author\" style=\" list-style-image: url(" + iconPath + "author_16.png);\">" + //
            "<li><a href=\"ezdl://" + EzDLProtocolHandler.INTERNAL_QUERY
            + "?Author=%22Peter+Lustig%22\">Peter Lustig</a></li><li><a href=\"ezdl://"
            + EzDLProtocolHandler.INTERNAL_QUERY
            + "?Author=%22Hans+Dieter%22\">Hans Dieter</a></li><li><a href=\"ezdl://"
            + EzDLProtocolHandler.INTERNAL_QUERY + "?Author=%22Roflmao+Lolz%22\">Roflmao Lolz</a></li></ul>" //
            // + "<p><b>" //
            // + conferenceLabel + "</b></p>" +
            // "<ul id =\"conference\" style=\" list-style-image: url("
            // + iconPath + "conference_16.png);\">" + //
            // "<li>" +
            // StringEscapeUtils.escapeHtml(conferenceTitle) +
            // "</li></ul>" + //
            // "<p><b>" + journalLabel + "</b></p>" + //
            // "<ul id =\"journal\" style=\" list-style-image: url("
            // + iconPath + "journal_16.png);\">" + //
            // "<li>" + StringEscapeUtils.escapeHtml(journalTitle) +
            // "</li></ul>" + //
            + "<p><b>" + abstractLabel + "</b></p>" + //
            "<div><p>" + StringEscapeUtils.escapeHtml(abstractText)
            + "</p></div><br/><br/><br/><br/><br/></body></html>";

    conferenceExpectedOutput = "<html><head><body>" + conferenceTitle + "</body></head></html>";
    journalExpectedOutput = "<html><head><body>" + journalTitle + "</body></head></html>";

    documentOutput = cs.print(document).toString();
    // conferenceOutput = cs.print(document.getConference()).toString();
    // journalOutput = cs.print(document.getJournal()).toString();
}

From source file:at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Logger.info("Receive " + GenerateIFrameTemplateServlet.class + " Request");

    String pendingRequestID = null;

    try {/*from   ww  w. ja va 2 s.  c o  m*/
        String bkuid = req.getParameter(PARAM_BKU);
        String useMandate = req.getParameter(PARAM_USEMANDATE);
        String ccc = req.getParameter(PARAM_CCC);
        String moasessionid = req.getParameter(PARAM_SESSIONID);

        moasessionid = StringEscapeUtils.escapeHtml(moasessionid);

        AuthenticationSession moasession = null;

        if (MiscUtil.isEmpty(bkuid) || MiscUtil.isEmpty(moasessionid)) {
            Logger.warn("MOASessionID or BKU-type is empty. Maybe an old BKU-selection template is in use.");
            throw new MOAIDException("auth.23", new Object[] {});
        }

        try {
            pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid);

            moasession = AuthenticationSessionStoreage.getSession(moasessionid);

            //              AuthenticationSessionStoreage.changeSessionID(moasession);

        } catch (MOADatabaseException e) {
            Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database");
            throw new MOAIDException("init.04", new Object[] { moasessionid });

        } catch (Throwable e) {
            Logger.info("No HTTP Session found!");
            throw new MOAIDException("auth.18", new Object[] {});
        }

        //load OA Config
        OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(moasession.getOAURLRequested());

        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { moasession.getOAURLRequested() });

        else {

            //get Target from config or from request in case of SAML 1            
            String target = null;
            IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
            if (MiscUtil.isNotEmpty(pendingReq.getTarget())
                    && pendingReq.requestedModule().equals(SAML1Protocol.PATH))
                target = pendingReq.getTarget();
            else
                target = oaParam.getTarget();

            String bkuURL = oaParam.getBKUURL(bkuid);
            if (MiscUtil.isEmpty(bkuURL)) {
                Logger.info("No OA specific BKU defined. Use BKU from default configuration");
                bkuURL = AuthConfigurationProvider.getInstance().getDefaultBKUURL(bkuid);
            }

            //search for OA specific template
            String templateURL = null;
            List<TemplateType> oaTemplateURLList = oaParam.getTemplateURL();
            if (oaTemplateURLList != null && oaTemplateURLList.size() > 0
                    && MiscUtil.isNotEmpty(oaTemplateURLList.get(0).getURL())) {
                templateURL = oaTemplateURLList.get(0).getURL();

            } else {
                templateURL = AuthConfigurationProvider.getInstance().getSLRequestTemplates(bkuid);
            }

            //make url absolut if it is a local url
            if (MiscUtil.isNotEmpty(templateURL))
                templateURL = FileUtils.makeAbsoluteURL(templateURL,
                        AuthConfigurationProvider.getInstance().getRootConfigFileDir());

            if (oaParam.isOnlyMandateAllowed())
                useMandate = "true";

            if (!oaParam.isShowMandateCheckBox())
                useMandate = "false";

            //parse all OA parameters i
            StartAuthentificationParameterParser.parse(moasession, target, moasession.getOAURLRequested(),
                    bkuURL, templateURL, useMandate, ccc, moasession.getModul(), moasession.getAction(), req);
        }

        ExecutionContext ec = new ExecutionContextImpl();
        // set execution context
        ec.put("ccc", moasession.getCcc());
        ec.put("useMandate", moasession.getUseMandate());
        ec.put("bkuURL", moasession.getBkuURL());

        // select and create process instance
        String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec);
        String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec);

        if (processDefinitionId == null) {
            Logger.warn("No suitable process found for SessionID " + moasession.getSessionID());
            throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() });
        }

        // keep process instance id in moa session
        moasession.setProcessInstanceId(processInstanceId);

        // make sure moa session has been persisted before running the process
        try {
            AuthenticationSessionStoreage.storeSession(moasession);
        } catch (MOADatabaseException e) {
            Logger.error("Database Error! MOASession is not stored!");
            throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() });
        }

        // start process
        getProcessEngine().start(processInstanceId);

    } catch (WrongParametersException ex) {
        handleWrongParameters(ex, req, resp);
    }

    catch (MOAIDException ex) {
        handleError(null, ex, req, resp, pendingRequestID);

    } catch (Exception e) {
        Logger.error("BKUSelectionServlet has an interal Error.", e);

    }

    finally {
        ConfigurationDBUtils.closeSession();
    }
}

From source file:de.hybris.platform.commercefacades.search.solrfacetsearch.converters.populator.SolrSearchStatePopulator.java

protected String buildUrlQueryString(final SolrSearchQueryData source, final SearchStateData target) {
    final String searchQueryParam = target.getQuery().getValue();
    if (StringUtils.isNotBlank(searchQueryParam)) {
        try {/*  w  w  w.j  a  v  a2s. c o m*/
            return "?q=" + URLEncoder.encode(searchQueryParam, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            return "?q=" + StringEscapeUtils.escapeHtml(searchQueryParam);
        }
    }
    return "";
}

From source file:de.skuzzle.polly.http.internal.HttpEventImpl.java

@Override
public String getEscaped(String key) {
    return StringEscapeUtils.escapeHtml(this.get.get(key));
}