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:com.redhat.rhn.frontend.taglibs.ListDisplayTagBase.java

protected void renderFilterBox(Writer out) throws IOException {
    LocalizationService ls = LocalizationService.getInstance();

    HtmlTag tag = new HtmlTag("div");
    tag.setAttribute("class", "spacewalk-filter-input input-group");

    StringBuilder buf = new StringBuilder();

    HtmlTag input = new HtmlTag("input");
    input.setAttribute("type", "text");
    input.setAttribute("class", "form-control");
    input.setAttribute("name", RequestContext.FILTER_STRING);
    input.setAttribute("value", pageList.getFilterData());
    String placeHolder = StringEscapeUtils
            .escapeHtml(ls.getMessage("message.filterby", ls.getMessage(filterBy)));
    input.setAttribute("placeholder", placeHolder);

    buf.append(input.render());//from w  w w .ja v  a  2s .  c  o  m

    input = new HtmlTag("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", RequestContext.PREVIOUS_FILTER_STRING);
    input.setAttribute("value", pageList.getFilterData());
    buf.append(input.render());

    HtmlTag btnSpan = new HtmlTag("span");
    btnSpan.setAttribute("class", "input-group-btn");

    HtmlTag btn = new HtmlTag("button");
    btn.setAttribute("class", "btn btn-default");
    btn.setAttribute("type", "submit");
    btn.setAttribute("name", FILTER_DISPATCH);
    btn.setAttribute("value", ls.getMessage(RequestContext.FILTER_KEY));

    IconTag icon = new IconTag("item-search");
    btn.addBody(icon.render());

    btnSpan.addBody(btn);

    buf.append(btnSpan.render());

    tag.addBody(buf.toString());
    out.append(tag.render());
}

From source file:com.fluidops.iwb.widget.ActionableResultWidget.java

/**
 * Demo method for testing which alerts the name that was clicked on.
 * //from   www.j a v  a 2  s  .c  o m
 * @param ceCtx
 * @param name
 */
@CallableFromWidget
public static void testColumnActions(CodeExecutionContext ceCtx, List<Value> selectedValues) {
    StringBuilder sb = new StringBuilder();
    for (Value v : selectedValues)
        sb.append(v.stringValue()).append("; ");
    ceCtx.parentComponent.doCallback(
            "alert('Selected the following rows: " + StringEscapeUtils.escapeHtml(sb.toString()) + "');");
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#service(HttpServletRequest, HttpServletResponse)
 *///from  w ww.  jav a  2s  . c om
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("getRequestURL:" + req.getRequestURL().toString());

    String artifact = req.getParameter(PARAM_SAMLARTIFACT);
    artifact = StringEscapeUtils.escapeHtml(artifact);

    try {
        if (artifact != null) {
            // check if SAML Artifact was already used in this session (in case of page reload)
            HttpSession session = req.getSession();
            if (null != session && artifact.equals(session.getAttribute(ATT_SAML_ARTIFACT))) {
                if (session.getAttribute(ATT_BROWSERREQU) == null) {
                    tunnelRequest(req, resp);
                } else {
                    login(req, resp); //login after browser login dialog
                }
            } else
                // it is the first time that the SAML Artifact was used
                login(req, resp);
        } else
            tunnelRequest(req, resp);
    } catch (MOAIDException ex) {
        handleError(ex.getMessage(), ex, req, resp);
    } catch (Throwable ex) {
        handleError(ex.getMessage(), ex, req, resp);
    }
}

From source file:com.anite.penguin.form.Field.java

/**
 * Gets the value as a HTML Safe String
 * @return
 */
public String getHTMLSafeValue() {
    return StringEscapeUtils.escapeHtml(this.value);
}

From source file:de.fhg.fokus.openride.services.rider.search.SearchService.java

@GET
@Produces("text/json")
public Response getSearches(@Context HttpServletRequest request) {
    List<RiderUndertakesRideEntity> activeRides = riderUndertakesRideControllerBean
            .getActiveRideRequests(request.getRemoteUser());
    Search s;//from www. jav a 2 s. com
    ArrayList<Search> searches = new ArrayList<Search>();
    //FIXME: either adapt the DB or the Search-Class
    for (RiderUndertakesRideEntity r : activeRides) {
        if (r != null) {
            s = new Search(r.getRiderrouteId() != null ? r.getRiderrouteId() : -1,
                    r.getRideId() != null ? r.getRideId().getRideId() : -1,
                    r.getStartpt() != null ? r.getStartpt().getX() : null,
                    r.getStartpt() != null ? r.getStartpt().getY() : null,
                    r.getEndpt() != null ? r.getEndpt().getX() : null,
                    r.getEndpt() != null ? r.getEndpt().getY() : null,
                    r.getStarttimeLatest() != null ? r.getStarttimeLatest().getTime() : null,
                    StringEscapeUtils.escapeHtml(r.getComment()),
                    Math.round((r.getStarttimeLatest().getTime() - r.getStarttimeEarliest().getTime()) / 1000
                            / 60),
                    r.getNoPassengers(), false,
                    r.getStarttimeEarliest() != null ? r.getStarttimeEarliest().getTime() : null, r.getPrice(),
                    StringEscapeUtils.escapeHtml(r.getStartptAddress()),
                    StringEscapeUtils.escapeHtml(r.getEndptAddress()));
            s.setUpdated(riderUndertakesRideControllerBean.isRideUpdated(r.getRiderrouteId()));
            searches.add(s);
        }
    }

    ArrayList list = new ArrayList();
    list.add(new Search());

    XStream x = Utils.getJasonXStreamer(list);
    Response response = Response.ok(x.toXML(searches)).build();
    return response;
}

From source file:com.thoughtworks.go.server.presentation.models.StageJsonPresentationModelTest.java

@Test
public void shouldEscapeBuildCauseMessage() throws Exception {
    String userWithHtmlCharacters = "<user>";
    pipeline.setBuildCause(BuildCause.createManualForced(materialRevisions(userWithHtmlCharacters),
            new Username(new CaseInsensitiveString(userWithHtmlCharacters))));
    StageJsonPresentationModel presenter = new StageJsonPresentationModel(pipeline, stage, null, new Agents());

    JsonTester jsonTester = new JsonTester(presenter.toJson());
    String expected = StringEscapeUtils.escapeHtml(userWithHtmlCharacters);
    jsonTester.shouldContain("{'buildCause':'Forced by " + expected + "'}");
}

From source file:it.unimi.di.big.mg4j.query.QueryServlet.java

public Template handleRequest(final HttpServletRequest request, final HttpServletResponse response,
        final Context context) {

    try {/*from   w  ww . j ava2  s  .  c  om*/
        response.setCharacterEncoding("UTF-8");

        // This string is URL-encoded, and with the wrong coding.
        //String query = request.getParameter( "q" ) != null ? new String( request.getParameter( "q" ).getBytes( "ISO-8859-1" ), "UTF-8" ) : null;
        String query = request.getParameter("q");
        context.put("action", request.getContextPath() + request.getServletPath());

        // Sanitise parameters.
        int start = 0, maxNumItems = STD_MAX_NUM_ITEMS;
        try {
            maxNumItems = Integer.parseInt(request.getParameter("m"));
        } catch (NumberFormatException dontCare) {
        }
        try {
            start = Integer.parseInt(request.getParameter("s"));
        } catch (NumberFormatException dontCare) {
        }

        if (maxNumItems < 0 || maxNumItems > 1000)
            maxNumItems = STD_MAX_NUM_ITEMS;
        if (start < 0)
            start = 0;

        if (query != null && query.length() != 0) {

            // This is used to display again the query in the input control.
            context.put("q", StringEscapeUtils.escapeHtml(query));
            // This is used to put the query in URLs.
            context.put("qUrl", URLEncoder.encode(query, "UTF-8"));
            context.put("firstItem", new Integer(start));

            // First of all, we check that the query is correct

            long time = -System.currentTimeMillis();
            ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>> results = new ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>>();

            int globNumItems;

            try {
                globNumItems = queryEngine.copy().process(query, start, maxNumItems, results);
            } catch (QueryBuilderVisitorException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (QueryParserException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (Exception e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.toString()));
                return getTemplate(template);
            }

            time += System.currentTimeMillis();

            ObjectArrayList<ResultItem> resultItems = new ObjectArrayList<ResultItem>();

            if (!results.isEmpty()) {
                SelectedInterval[] selectedInterval = null;

                final DocumentCollection collection = documentCollection != null ? documentCollection.copy()
                        : null;

                for (int i = 0; i < results.size(); i++) {
                    DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>> dsi = results.get(i);
                    LOGGER.debug("Intervals for item " + i);
                    final ResultItem resultItem = new ResultItem(dsi.document, dsi.score);
                    resultItems.add(resultItem);

                    if (collection != null) {
                        final Document document = collection.document(dsi.document);
                        // If both collection and title list are present, we override the collection title (cfr. Query)
                        resultItem.title = StringEscapeUtils
                                .escapeHtml(titleList != null ? titleList.get(resultItem.doc).toString()
                                        : document.title().toString());
                        if (useUri) {
                            if (document.uri() != null)
                                resultItem.uri = StringEscapeUtils.escapeHtml(document.uri().toString());
                        } else {
                            if (document.uri() != null) {
                                String stringUri = document.uri().toString();
                                // TODO: this is a quick patch to get the file server running with relative files
                                final String documentUri = URLEncoder.encode(derelativise
                                        ? new File(stringUri.startsWith("file:") ? stringUri.substring(5)
                                                : stringUri).getAbsoluteFile().toURI().toASCIIString()
                                        : document.uri().toString(), "UTF-8");
                                resultItem.uri = StringEscapeUtils.escapeHtml("./Item?doc=" + resultItem.doc
                                        + "&m=" + urlEncodedMimeType + "&uri=" + documentUri);
                            } else
                                resultItem.uri = StringEscapeUtils.escapeHtml(
                                        "./Item?doc=" + resultItem.doc + "&m=" + urlEncodedMimeType);
                        }

                        MarkingMutableString snippet = new MarkingMutableString(TextMarker.HTML_STRONG,
                                MarkingMutableString.HTML_ESCAPE);

                        for (int j = 0; j < sortedIndex.length; j++) {
                            if (!sortedIndex[j].hasPositions || dsi.info == null)
                                continue;
                            selectedInterval = dsi.info.get(sortedIndex[j]);
                            if (selectedInterval != null) {
                                final int field = documentCollection.factory().fieldIndex(sortedIndex[j].field);
                                // If the field is not present (e.g., because of parallel indexing) or it is not text we skip
                                if (field == -1 || documentCollection.factory()
                                        .fieldType(field) != DocumentFactory.FieldType.TEXT)
                                    continue;
                                LOGGER.debug(
                                        "Found intervals for " + sortedIndex[j].field + " (" + field + ")");
                                final Reader content = (Reader) document.content(field);
                                snippet.startField(selectedInterval)
                                        .appendAndMark(document.wordReader(field).setReader(content))
                                        .endField();
                            }
                            if (LOGGER.isDebugEnabled())
                                LOGGER.debug(sortedIndex[j].field + ": "
                                        + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                            document.close();
                        }

                        resultItem.text = snippet;
                    } else {
                        if (titleList != null) {
                            // TODO: this is a bit radical
                            resultItem.title = resultItem.uri = titleList.get(resultItem.doc);
                        } else {
                            resultItem.title = "Document #" + resultItem.doc;
                            resultItem.uri = new MutableString("./Item?doc=").append(resultItem.doc)
                                    .append("&m=").append(urlEncodedMimeType);
                        }

                        MutableString text = new MutableString();
                        for (Iterator<Index> j = indexMap.values().iterator(); j.hasNext();) {
                            final Index index = j.next();
                            selectedInterval = dsi.info.get(index);
                            if (selectedInterval != null)
                                text.append("<p>").append(index.field).append(": ")
                                        .append(Arrays.asList(selectedInterval));
                            LOGGER.debug(index.field + ": "
                                    + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                        }
                        resultItem.text = text;
                    }
                }

                if (collection != null)
                    collection.close();
            }

            // Note that if we pass an array to the template we lose the possibility of measuring its length.
            context.put("result", resultItems);
            /* Note that this number is just the number of relevant documents met while
               trying to obtain the current results. Due to the short-circuit semantics of the
               "and then" operator, it  might not reflect accurately the overall number of
               results of the query. */
            context.put("globNumItems", new Integer(globNumItems));
            context.put("start", new Integer(start));
            context.put("maxNumItems", new Integer(maxNumItems));
            context.put("time", new Integer((int) time));
            context.put("speed", new Long((int) (globNumItems * 1000L / (time + 1))));
        }

        return getTemplate(template);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }
}