Example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml4

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeHtml4

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml4.

Prototype

public static final String escapeHtml4(final String input) 

Source Link

Document

Escapes the characters in a String using HTML entities.

For example:

"bread" & "butter"

becomes:

"bread" & "butter".

Usage

From source file:net.java.sip.communicator.plugin.notificationwiring.NotificationManager.java

/**
 * Implements the <tt>AdHocChatRoomMessageListener.messageReceived</tt>
 * method./*from  w ww  . ja va 2  s. c  o  m*/
 * <br>
 * @param evt the <tt>AdHocChatRoomMessageReceivedEvent</tt> that notified
 * us
 */
public void messageReceived(AdHocChatRoomMessageReceivedEvent evt) {
    try {
        AdHocChatRoom sourceChatRoom = evt.getSourceChatRoom();
        Contact sourceParticipant = evt.getSourceChatRoomParticipant();

        // Fire notification
        boolean fireChatNotification;

        String nickname = sourceChatRoom.getName();
        String messageContent = evt.getMessage().getContent();

        fireChatNotification = (nickname == null)
                || messageContent.toLowerCase().contains(nickname.toLowerCase());

        if (fireChatNotification) {
            String title = NotificationWiringActivator.getResources().getI18NString("service.gui.MSG_RECEIVED",
                    new String[] { sourceParticipant.getDisplayName() });
            final String htmlContent;
            if (HTML_CONTENT_TYPE.equals(evt.getMessage().getContentType())) {
                htmlContent = messageContent;
            } else {
                htmlContent = StringEscapeUtils.escapeHtml4(messageContent);
            }
            fireChatNotification(sourceChatRoom, INCOMING_MESSAGE, title, htmlContent,
                    evt.getMessage().getMessageUID());
        }
    } catch (Throwable t) {
        logger.error("Error notifying for adhoc message received", t);
    }
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void process(HttpServletRequest request, HttpServletResponse response, ServletContext context)
        throws Exception {

    HttpSession session = request.getSession();
    StatusRequest statusRequest = (StatusRequest) session.getAttribute(PDF_STATUS);
    // IPlainSigner plainSigner = (IPlainSigner) session
    // .getAttribute(PDF_SIGNER);

    String connector = (String) session.getAttribute(PDF_SL_INTERACTIVE);

    if (connector.equals("bku") || connector.equals("onlinebku") || connector.equals("mobilebku")) {
        BKUSLConnector bkuSLConnector = (BKUSLConnector) session.getAttribute(PDF_SL_CONNECTOR);

        if (statusRequest.needCertificate()) {
            logger.debug("Needing Certificate from BKU");
            // build SL Request to read certificate
            InfoboxReadRequestType readCertificateRequest = bkuSLConnector
                    .createInfoboxReadRequest(statusRequest.getSignParameter());

            JAXBElement<InfoboxReadRequestType> readRequest = of
                    .createInfoboxReadRequest(readCertificateRequest);

            String url = generateDataURL(request, response);
            String slRequest = SLMarschaller.marshalToString(readRequest);
            String template = getTemplateSL();
            String locale = getLocale(request, response);
            template = template.replace("##BKU##", generateBKUURL(connector));
            template = template.replace("##XMLRequest##", StringEscapeUtils.escapeHtml4(slRequest));
            template = template.replace("##DataURL##", url);
            template = template.replace("##LOCALE##", locale);

            if (statusRequest.getSignParameter().getTransactionId() != null) {
                template = template//from w  w  w  .ja  v  a 2s .co  m
                        .replace("##ADDITIONAL##",
                                "<input type=\"hidden\" name=\"TransactionId_\" value=\"" + StringEscapeUtils
                                        .escapeHtml4(statusRequest.getSignParameter().getTransactionId())
                                        + "\">");
            } else {
                template = template.replace("##ADDITIONAL##", "");
            }

            response.getWriter().write(template);
            // TODO: set content type of response!!
            response.setContentType("text/html");
            response.getWriter().close();
        } else if (statusRequest.needSignature()) {
            logger.debug("Needing Signature from BKU");
            // build SL Request for cms signature
            RequestPackage pack = bkuSLConnector.createCMSRequest(statusRequest.getSignatureData(),
                    statusRequest.getSignatureDataByteRange(), statusRequest.getSignParameter());

            String slRequest = SLMarschaller
                    .marshalToString(of.createCreateCMSSignatureRequest(pack.getRequestType()));

            logger.trace("SL Request: " + slRequest);

            response.setContentType("text/xml");
            response.getWriter().write(slRequest);
            response.getWriter().close();

        } else if (statusRequest.isReady()) {
            // TODO: store pdf document redirect to Finish URL
            logger.debug("Document ready!");

            SignResult result = pdfAs.finishSign(statusRequest);

            ByteArrayOutputStream baos = (ByteArrayOutputStream) session.getAttribute(PDF_OUTPUT);
            baos.close();

            PDFASVerificationResponse verResponse = new PDFASVerificationResponse();
            List<VerifyResult> verResults = PdfAsHelper.synchornousVerify(baos.toByteArray(), -2,
                    PdfAsHelper.getVerificationLevel(request), null);

            if (verResults.size() != 1) {
                throw new WebServiceException("Document verification failed!");
            }
            VerifyResult verifyResult = verResults.get(0);

            verResponse.setCertificateCode(verifyResult.getCertificateCheck().getCode());
            verResponse.setValueCode(verifyResult.getValueCheckCode().getCode());

            PdfAsHelper.setPDFASVerificationResponse(request, verResponse);
            PdfAsHelper.setSignedPdf(request, response, baos.toByteArray());
            PdfAsHelper.gotoProvidePdf(context, request, response);

            String signerCert = Base64.encodeBase64String(result.getSignerCertificate().getEncoded());

            PdfAsHelper.setSignerCertificate(request, signerCert);

        } else {
            throw new PdfAsWebException("Invalid state!");
        }
    } else {
        throw new PdfAsWebException("Invalid connector: " + connector);
    }
}

From source file:net.java.sip.communicator.plugin.notificationwiring.NotificationManager.java

/**
 * Implements the <tt>ChatRoomMessageListener.messageReceived</tt> method.
 * <br>/*from  w w w .j  a v a2  s .c  o  m*/
 * Obtains the corresponding <tt>ChatPanel</tt> and process the message
 * there.
 * @param evt the <tt>ChatRoomMessageReceivedEvent</tt> that notified us
 * that a message has been received
 */
public void messageReceived(ChatRoomMessageReceivedEvent evt) {
    try {
        ChatRoom sourceChatRoom = evt.getSourceChatRoom();
        ChatRoomMember sourceMember = evt.getSourceChatRoomMember();

        // Fire notification
        boolean fireChatNotification;

        final Message sourceMsg = evt.getMessage();
        String messageContent = sourceMsg.getContent();

        /*
         * It is uncommon for IRC clients to display popup notifications for
         * messages which are sent to public channels and which do not mention
         * the nickname of the local user.
         */
        if (sourceChatRoom.isSystem() || isPrivate(sourceChatRoom) || (messageContent == null))
            fireChatNotification = true;
        else {
            String nickname = sourceChatRoom.getUserNickname();

            int atIx = -1;

            if (nickname != null)
                atIx = nickname.indexOf("@");

            fireChatNotification = (nickname == null)
                    || messageContent.toLowerCase().contains(nickname.toLowerCase()) || ((atIx == -1) ? false
                            : messageContent.toLowerCase().contains(nickname.substring(0, atIx).toLowerCase()));
        }

        if (fireChatNotification) {
            String title = NotificationWiringActivator.getResources().getI18NString("service.gui.MSG_RECEIVED",
                    new String[] { sourceMember.getName() });
            final String htmlContent;
            if (HTML_CONTENT_TYPE.equals(sourceMsg.getContentType())) {
                htmlContent = messageContent;
            } else {
                htmlContent = StringEscapeUtils.escapeHtml4(messageContent);
            }
            fireChatNotification(sourceChatRoom, INCOMING_MESSAGE, title, htmlContent,
                    sourceMsg.getMessageUID());
        }
    } catch (Throwable t) {
        logger.error("Error notifying for chat room message received", t);
    }
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

/**
 * Returns the localized string for desired service and bound to the specified key.
 * @param serviceId The service ID./*from ww w . j a  v a2 s. c o m*/
 * @param locale Desired locale.
 * @param key Resource key.
 * @param escapeHtml True to apply HTML escaping, false otherwise.
 * @return Localized string
 */
public String lookupResource(String serviceId, Locale locale, String key, boolean escapeHtml) {
    try {
        String baseName = StringUtils.replace(serviceId, ".", "/") + "/locale";
        String value = ResourceBundle.getBundle(baseName, locale).getString(key);
        if (escapeHtml)
            value = StringEscapeUtils.escapeHtml4(value);
        return value;

    } catch (MissingResourceException ex) {
        return key;
        //logger.trace("Missing resource [{}, {}, {}]", baseName, locale.toString(), key, ex);
    }
}

From source file:net.java.sip.communicator.plugin.notificationwiring.NotificationManager.java

/**
 *  Fired on new messages.//  www. j a  v a  2 s . c om
 * @param evt the <tt>MessageReceivedEvent</tt> containing
 * details on the received message
 */
public void messageReceived(MessageReceivedEvent evt) {
    try {
        // Fire notification
        String title = NotificationWiringActivator.getResources().getI18NString("service.gui.MSG_RECEIVED",
                new String[] { evt.getSourceContact().getDisplayName() });

        final Message sourceMsg = evt.getSourceMessage();
        final String htmlContent;
        if (HTML_CONTENT_TYPE.equals(sourceMsg.getContentType())) {
            htmlContent = sourceMsg.getContent();
        } else {
            htmlContent = StringEscapeUtils.escapeHtml4(sourceMsg.getContent());
        }
        fireChatNotification(evt.getSourceContact(), INCOMING_MESSAGE, title, htmlContent,
                sourceMsg.getMessageUID());
    } catch (Throwable t) {
        logger.error("Error notifying for message received", t);
    }
}

From source file:fr.gouv.culture.thesaurus.service.impl.SesameThesaurus.java

/**
 * Abrge le libell en ne renvoyant que la premire occurrence du texte
 * trouv, avec le contexte et en surlignant les termes trouvs. Si aucune
 * occurrence n'a t trouve, renvoie la premire partie du libell.
 * //from ww w .j a v  a2  s  .c  om
 * @param matchingLabel
 *            Libell correspondant  la requte
 * @param queryPattern
 *            Requte d'origine sous forme d'expression rgulire
 * @return Premire occurrence du texte trouv avec le contexte et le
 *         surlignage en HTML
 */
private String abbreviateAndHighlightMatchingLabel(String matchingLabel, Pattern queryPattern) {
    final Matcher matcher = queryPattern.matcher(matchingLabel);
    final int maxDescriptionLength = configuration.getMatchingLabelFirstOccurrenceWidth();
    String abbreviatedVersion;

    if (matcher.find()) {
        final int contextMaxLength = configuration.getMatchingLabelContextLength();
        final int highlightMaxLength = maxDescriptionLength - 2 * contextMaxLength;
        if (highlightMaxLength < 1) {
            throw new IllegalArgumentException(
                    "Invalid configuration: the occurrence width is not long enough to hold the highlighted part and the context.");
        }

        abbreviatedVersion = TextUtils.htmlHighlightOccurrence(matchingLabel, matcher.start(), matcher.end(),
                highlightMaxLength, contextMaxLength, "<em>", "</em>");
    } else {
        /*
         * Pour une certaine raison, les termes trouvs par la recherche ne
         * sont pas localisables dans le texte trait avec Java. On renvoie
         * alors le dbut du libell correspondant.
         */
        abbreviatedVersion = StringEscapeUtils
                .escapeHtml4(TextUtils.leftAbbreviateOnWords(matchingLabel, maxDescriptionLength));
    }

    return abbreviatedVersion;
}

From source file:com.screenslicer.common.HtmlCoder.java

public static String encode(String string) {
    try {/*from  ww  w . ja v  a2 s.c  o  m*/
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < string.length();) {
            int codePoint = string.codePointAt(i);
            String symbol = codePointToSymbol(codePoint);
            char[] chars = symbol.toCharArray();
            if (chars.length == 1 && CharUtils.isAscii(chars[0])) {
                builder.append(StringEscapeUtils.escapeHtml4(Character.toString(chars[0])));
            } else {
                builder.append(symbol);
            }
            i += chars.length;
        }
        return builder.toString();
    } catch (Throwable t) {
        Log.exception(t);
        return string;
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 * Processes /me command in group chats.
 *
 * @param chatMessage the chat message// ww  w.  j ava  2 s .c om
 * @return the newly processed message string
 */
public String processMeCommand(ChatMessage chatMessage) {
    String contentType = chatMessage.getContentType();
    String message = chatMessage.getMessage();
    if (message.length() <= 4 || !message.startsWith("/me ")) {
        return "";
    }

    String msgID = ChatHtmlUtils.MESSAGE_TEXT_ID + chatMessage.getMessageUID();
    String chatString = "<DIV ID='" + msgID + "'><B><I>";
    String endHeaderTag = "</I></B></DIV>";

    chatString += GuiUtils.escapeHTMLChars("*** " + chatMessage.getContactName() + " " + message.substring(4))
            + endHeaderTag;

    Map<String, ReplacementService> listSources = GuiActivator.getReplacementSources();
    for (ReplacementService source : listSources.values()) {
        boolean isSmiley = source instanceof SmiliesReplacementService;
        if (!isSmiley) {
            continue;
        }
        String sourcePattern = source.getPattern();
        Pattern p = Pattern.compile(sourcePattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(chatString);
        chatString = m.replaceAll(ChatHtmlUtils.HTML_CONTENT_TYPE.equalsIgnoreCase(contentType) ? "$0"
                : StringEscapeUtils.escapeHtml4("$0"));
    }
    return chatString;
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.MainForm.java

private void updateActivehexCoord(final HexPosition position) {
    if (this.application == null) {
        final String comment = this.cellComments.getForHex(position);
        this.labelCellUnderMouse.setText("Hex " + position.getColumn() + ',' + position.getRow() + ' '
                + (comment == null ? "" : comment));
        if (this.hexMapPanel.isValidPosition(position)) {
            final StringBuilder buffer = new StringBuilder();

            if (comment != null) {
                buffer.append("<h4>").append(StringEscapeUtils.escapeHtml4(comment)).append("</h4>");
            }//w  ww .  ja va 2 s .c  o m

            for (int i = 0; i < this.layers.getSize(); i++) {
                final HexFieldLayer field = this.layers.getElementAt(i).getHexField();
                if (field.isLayerVisible()) {
                    final String layerName = field.getLayerName().isEmpty() ? "Untitled" : field.getLayerName();
                    final HexFieldValue layerValue = field.getHexValueAtPos(position.getColumn(),
                            position.getRow());
                    if (layerValue != null) {
                        if (buffer.length() > 0) {
                            buffer.append("<br>");
                        }
                        final String valueName = layerValue.getName().isEmpty() ? layerValue.getComment()
                                : layerValue.getName();
                        buffer.append("<b>").append(StringEscapeUtils.escapeHtml4(layerName)).append(":</b>")
                                .append(StringEscapeUtils.escapeHtml4(valueName));
                    }
                }
            }
            if (buffer.length() > 0) {
                this.hexMapPanel.setToolTipText("<html>" + buffer + "</html>");
            } else {
                this.hexMapPanel.setToolTipText(null);
            }
        } else {
            this.hexMapPanel.setToolTipText(null);
        }
    } else {
        this.hexMapPanel.setToolTipText(
                this.application.processHexAction(this.hexMapPanel, null, HexAction.OVER, position));
    }
}

From source file:com.squid.kraken.v4.api.core.analytics.AnalyticsServiceBaseImpl.java

/**
 * @param userContext //from  ww  w . ja v a 2s  . c o  m
 * @param dataTable 
 * @return
 */
private Response createHTMLPageTable(AppContext userContext, Space space, AnalyticsQuery query,
        DataTable data) {
    String title = space != null ? getPageTitle(space) : null;
    StringBuilder html = createHTMLHeader("Query: " + title);
    createHTMLtitle(html, title, query.getBBID(), getParentLink(space));
    createHTMLproblems(html, query.getProblems());
    if (data != null) {
        html.append("<table class='data'><tr>");
        html.append("<th></th>");
        for (Col col : data.getCols()) {
            html.append("<th>" + col.getName() + "</th>");
        }
        html.append("</tr>");
        int i = 1;
        if (query.getStartIndex() != null) {
            i = query.getStartIndex() + 1;
        }
        for (Row row : data.getRows()) {
            html.append("<tr>");
            html.append("<td valign='top'>#" + (i++) + "</td>");
            for (Col col : data.getCols()) {
                Object value = row.getV()[col.getPos()];
                if (value != null) {
                    if (col.getFormat() != null && col.getFormat().length() > 0) {
                        try {
                            value = String.format(col.getFormat(), value);
                        } catch (IllegalFormatException e) {
                            // ignore
                        }
                    }
                } else {
                    value = "";
                }
                html.append("<td valign='top'>" + value + "</td>");
            }
            html.append("</tr>");
        }
        html.append("</table>");
        createHTMLpagination(html, query, data);
    } else {
        html.append("<i>Result is not available, it's probably due to an error</i>");
        html.append("<p>");
        createHTMLdataLinks(html, query);
        html.append("</p<br>");
    }
    html.append("<form>");
    createHTMLfilters(html, query);
    {
        UriBuilder builder = getPublicBaseUriBuilder().path("/analytics/{" + BBID_PARAM_NAME + "}/query");
        builder.queryParam(STYLE_PARAM, Style.HTML);
        builder.queryParam("access_token", userContext.getToken().getOid());
        URI uri = builder.build(space.getBBID(Style.ROBOT));
        html.append("<a href=\"" + StringEscapeUtils.escapeHtml4(uri.toString()) + "\">"
                + StringEscapeUtils.escapeHtml4(space.getBBID(Style.HUMAN)) + "</a>");
    }
    html.append("<table>");
    html.append("<tr><td valign='top'>groupBy</td><td>");
    createHTMLinputArray(html, "text", "groupBy", query.getGroupBy());
    html.append(
            "</td><td valign='top'><p><i>Define the group-by facets to apply to results. Facet can be defined using it's ID or any valid expression. If empty, the subject default parameters will apply. You can use the * token to extend the subject default parameters.</i></p>");
    html.append("</td></tr>");
    html.append("<tr><td valign='top'>metrics</td><td>");
    createHTMLinputArray(html, "text", "metrics", query.getMetrics());
    html.append(
            "</td><td valign='top'><p><i>Define the metrics to compute. Metric can be defined using it's ID or any valid expression. If empty, the subject default parameters will apply. You can use the * token to extend the subject default parameters.</i></p>");
    html.append("</td></tr>");
    html.append("<tr><td valign='top'>orderBy</td><td>");
    createHTMLinputArray(html, "text", "orderBy", query.getOrderBy());
    html.append("</td></tr>");
    html.append("<tr><td>limit</td><td>");
    html.append("<input type=\"text\" name=\"limit\" value=\"" + getFieldValue(query.getLimit(), 0) + "\">");
    html.append("</td></tr>");
    html.append("<tr><td>maxResults</td><td>");
    html.append("<input type=\"text\" name=\"maxResults\" value=\"" + getFieldValue(query.getMaxResults(), 100)
            + "\">");
    html.append("</td></tr>");
    html.append("<tr><td>startIndex</td><td>");
    html.append("<input type=\"text\" name=\"startIndex\" value=\"" + getFieldValue(query.getStartIndex(), 0)
            + "\"></td><td><i>index is zero-based, so use the #count of the last row to view the next page</i>");
    html.append("</td></tr>");
    html.append("</table>" + "<input type=\"hidden\" name=\"style\" value=\"HTML\">"
            + "<input type=\"hidden\" name=\"access_token\" value=\"" + userContext.getToken().getOid() + "\">"
            + "<input type=\"submit\" value=\"Refresh\">" + "</form>");
    if (space != null)
        createHTMLscope(html, space, query);
    createHTMLAPIpanel(html, "runAnalysis");
    html.append("</body></html>");
    return Response.ok(html.toString(), "text/html").build();
}