Java Examples for org.apache.commons.lang.StringEscapeUtils

The following java examples will help you to understand the usage of org.apache.commons.lang.StringEscapeUtils. These source code samples are taken from different open source projects.

Example 1
Project: Eemory-master  File: StringEscapeUtil.java View source code
/**
     * <p>
     * Escapes the characters in a String using ENML entities.
     * </p>
     *
     * @param string
     *            the String to escape, may be null
     * @return a new escaped String, null if null string input
     */
public static String escapeEnml(final String string, final int tabWidth) {
    if (StringUtil.isNull(string)) {
        return string;
    }
    String escapedXml = StringEscapeUtils.escapeXml10(string);
    escapedXml = escapedXml.replaceAll(StringUtils.SPACE, Constants.HTML_NBSP);
    escapedXml = escapedXml.replaceAll(ConstantsUtil.TAB, StringUtils.repeat(Constants.HTML_NBSP, tabWidth));
    return escapedXml;
}
Example 2
Project: MockMock-master  File: MailListHtmlBuilder.java View source code
private String buildMailRow(MockMail mail) {
    StringFromHtmlBuilder fromBuilder = new StringFromHtmlBuilder();
    fromBuilder.setMockMail(mail);
    String fromOutput = fromBuilder.build();
    StringRecipientHtmlBuilder recipientBuilder = new StringRecipientHtmlBuilder();
    recipientBuilder.setMaxLength(27);
    recipientBuilder.setMockMail(mail);
    recipientBuilder.setRecipientType(MimeMessage.RecipientType.TO);
    String toOutput = recipientBuilder.build();
    String subjectOutput;
    if (mail.getSubject() == null) {
        subjectOutput = "<em>No subject given</em>";
    } else {
        subjectOutput = StringEscapeUtils.escapeHtml(mail.getSubject());
    }
    return "<tr>\n" + "  <td>" + fromOutput + "</td>\n" + "  <td>" + toOutput + "</td>\n" + "  <td><a title=\"" + StringEscapeUtils.escapeHtml(mail.getSubject()) + "\" href=\"/view/" + mail.getId() + "\">" + subjectOutput + "</a></td>\n" + "  <td><a title=\"Delete this mail\" href=\"/delete/" + mail.getId() + "\"><em>Delete</em></a></td>\n" + "</tr>";
}
Example 3
Project: rassyeyanie-master  File: CustomMatchers.java View source code
public static Matcher<String> contains(final String value) {
    return new BaseMatcher<String>() {

        public boolean matches(Object actual) {
            return actual.toString().contains(value);
        }

        public void describeTo(Description description) {
            description.appendText("contains '" + StringEscapeUtils.escapeJava(value) + "'");
        }
    };
}
Example 4
Project: rtc2jira-master  File: AcceptanceCriteriaMapping.java View source code
@Override
public void map(Object value, Issue issue, StorageEngine storage) {
    String acceptanceCriteria = (String) value;
    if (acceptanceCriteria != null) {
        // anchors
        acceptanceCriteria = DescriptionMapping.replaceHtmlAnchors(acceptanceCriteria, false);
        // html tags (open-close)
        acceptanceCriteria = acceptanceCriteria.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();
        // line breaks
        acceptanceCriteria = acceptanceCriteria.replaceAll("<br/>", "\r\n");
        // entities
        acceptanceCriteria = StringEscapeUtils.unescapeHtml4(acceptanceCriteria);
        issue.getFields().setAcceptanceCriteria(acceptanceCriteria);
    }
}
Example 5
Project: Saturn-master  File: XssHttpServletRequestWrapper.java View source code
@Override
public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values != null) {
        int length = values.length;
        String[] escapseValues = new String[length];
        for (int i = 0; i < length; i++) {
            escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
        }
        return escapseValues;
    }
    return super.getParameterValues(name);
}
Example 6
Project: AntennaPod-master  File: AtomText.java View source code
/** Processes the content according to the type and returns it. */
public String getProcessedContent() {
    if (type == null) {
        return content;
    } else if (type.equals(TYPE_HTML)) {
        return StringEscapeUtils.unescapeHtml4(content);
    } else if (type.equals(TYPE_XHTML)) {
        return content;
    } else // Handle as text by default
    {
        return content;
    }
}
Example 7
Project: AntennaPodSP-master  File: AtomText.java View source code
/**
     * Processes the content according to the type and returns it.
     */
public String getProcessedContent() {
    if (type == null) {
        return content;
    } else if (type.equals(TYPE_HTML)) {
        return StringEscapeUtils.unescapeHtml4(content);
    } else if (type.equals(TYPE_XHTML)) {
        return content;
    } else {
        // Handle as text by default
        return content;
    }
}
Example 8
Project: atom-nuke-master  File: MixedContentHandler.java View source code
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    contentBuilder.appendValue("<");
    contentBuilder.appendValue(qName);
    for (int i = 0; i < attributes.getLength(); i++) {
        contentBuilder.appendValue(" ");
        contentBuilder.appendValue(attributes.getQName(i));
        contentBuilder.appendValue("\"");
        contentBuilder.appendValue(StringEscapeUtils.escapeXml(attributes.getValue(i)));
        contentBuilder.appendValue("\"");
    }
    contentBuilder.appendValue(">");
    depth++;
}
Example 9
Project: cgeo-master  File: CheckerUtils.java View source code
@Nullable
public static String getCheckerUrl(@NonNull final Geocache cache) {
    final String description = cache.getDescription();
    final Matcher matcher = Patterns.WEB_URL.matcher(description);
    while (matcher.find()) {
        final String url = matcher.group();
        for (final String checker : CHECKERS) {
            if (StringUtils.containsIgnoreCase(url, checker)) {
                return StringEscapeUtils.unescapeHtml4(url);
            }
        }
    }
    return null;
}
Example 10
Project: dk-master  File: QuestionService.java View source code
@SuppressWarnings("unchecked")
public void queryQuestionList(PageBean pageBean, String keyword, String username) throws Exception {
    StringBuffer sb = new StringBuffer();
    if (StringUtils.isNotBlank(keyword)) {
        sb.append(" and question like '%");
        sb.append(StringEscapeUtils.escapeSql(keyword));
        sb.append("%'");
    }
    if (StringUtils.isNotBlank(username)) {
        sb.append(" and username like '%");
        sb.append(StringEscapeUtils.escapeSql(username));
        sb.append("%'");
    }
    Connection conn = MySQL.getConnection();
    try {
        dataPage(conn, pageBean, "t_question", "*", "order by  puttime  desc ", sb.toString());
    } catch (Exception e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } finally {
        conn.close();
    }
}
Example 11
Project: EinschlafenPodcastAndroidApp-master  File: AtomText.java View source code
/**
     * Processes the content according to the type and returns it.
     */
public String getProcessedContent() {
    if (type == null) {
        return content;
    } else if (type.equals(TYPE_HTML)) {
        return StringEscapeUtils.unescapeHtml4(content);
    } else if (type.equals(TYPE_XHTML)) {
        return content;
    } else {
        // Handle as text by default
        return content;
    }
}
Example 12
Project: fluxtream-app-master  File: TwitterDirectMessageFacetVO.java View source code
@Override
public void fromFacet(TwitterDirectMessageFacet facet, TimeInterval timeInterval, GuestSettings settings) throws OutsideTimeBoundariesException {
    Date date = new Date(facet.start);
    if (SecurityUtils.isDemoUser())
        this.description = "***demo - text content hidden***";
    else
        this.description = StringEscapeUtils.escapeHtml(facet.text);
    if (facet.sent == 1) {
        this.profileImageUrl = facet.recipientProfileImageUrl;
        this.userName = facet.recipientName;
    } else {
        this.profileImageUrl = facet.senderProfileImageUrl;
        this.userName = facet.senderName;
    }
    this.sent = facet.sent == 1;
}
Example 13
Project: Harvest-Festival-master  File: PageUtensilList.java View source code
@Override
public void draw(int mouseX, int mouseY) {
    boolean hoverX = mouseX >= 166 && mouseX <= 288;
    //Left
    gui.drawString(45, 13, TextFormatting.BOLD + "" + TextFormatting.UNDERLINE + TextHelper.translate("cookbook"));
    gui.drawString(25, 25, StringEscapeUtils.unescapeJava(TextHelper.translate("meal.intro")));
    //Right
    gui.drawString(205, 13, TextFormatting.BOLD + "" + TextFormatting.UNDERLINE + TextHelper.translate("utensils"));
    for (int i = 0; i < pages.size(); i++) {
        ItemStack stack = pages.get(i).getItem();
        boolean hoverY = mouseY >= 21 + 31 * i && mouseY <= 21 + 31 * i + 30;
        if (hoverX && hoverY) {
            GlStateManager.color(1F, 1F, 1F);
            gui.mc.getTextureManager().bindTexture(LEFT_GUI);
            gui.drawTexture(163, 23 + i * 31, 131, 222, 125, 34);
            gui.drawString(202, 37 + i * 31, TextFormatting.ITALIC + stack.getDisplayName());
        } else
            gui.drawString(202, 37 + i * 31, stack.getDisplayName());
        gui.drawStack(167, 26 + i * 31, stack, 1.9F);
    }
}
Example 14
Project: hsearch-obsolete-master  File: FacetField.java View source code
public String toXml() {
    StringBuilder sb = new StringBuilder();
    sb.append("<f>");
    sb.append("<v>").append(StringEscapeUtils.escapeXml(this.facet)).append("</v>");
    sb.append("<c>").append(this.size).append("</c>");
    sb.append("<i>").append(this.docIds).append("</i>");
    sb.append("</f>");
    return sb.toString();
}
Example 15
Project: jade4j-master  File: ExpressionNode.java View source code
@Override
public void execute(IndentWriter writer, JadeModel model, JadeTemplate template) throws JadeCompilerException {
    try {
        Object result = template.getExpressionHandler().evaluateExpression(getValue(), model);
        if (result == null || !buffer) {
            return;
        }
        String string = result.toString();
        if (escape) {
            string = StringEscapeUtils.escapeHtml4(string);
        }
        writer.append(string);
        if (hasBlock()) {
            writer.increment();
            block.execute(writer, model, template);
            writer.decrement();
            writer.newline();
        }
    } catch (ExpressionException e) {
        throw new JadeCompilerException(this, template.getTemplateLoader(), e);
    }
}
Example 16
Project: jblog-master  File: HomeController.java View source code
@RequestMapping("/q")
public ModelAndView query(HttpServletRequest request, String q) {
    ModelAndView av = new ModelAndView("/home/index");
    av.addObject("page", request.getParameter("page"));
    try {
        if (null != q && !q.isEmpty()) {
            String s = BlogUtil.filterXss(q);
            av.addObject("fulltext", s);
            av.addObject("keyword", StringEscapeUtils.unescapeHtml(s));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return av;
}
Example 17
Project: jmxterm-master  File: ValueFormat.java View source code
/**
     * Parse given syntax of string
     *
     * @param value String value
     * @return Escaped string value
     */
public static String parseValue(String value) {
    if (StringUtils.isEmpty(value)) {
        return null;
    }
    if (value.equals(NULL)) {
        return null;
    }
    String s;
    if (value.charAt(0) == '\"' && value.charAt(value.length() - 1) == '\"') {
        s = value.substring(1, value.length() - 1);
    } else {
        s = value;
    }
    return StringEscapeUtils.unescapeJava(s);
}
Example 18
Project: ktdocumentindexer-master  File: QueryHit.java View source code
public static String toJSON(QueryHit[] docs) throws Exception {
    String jsonBuilder = "[";
    for (int i = 0; i < docs.length; i++) {
        if (i > 0) {
            jsonBuilder += ",";
        }
        QueryHit doc = docs[i];
        String title = (doc.Title == null) ? "" : doc.Title;
        String content = (doc.Content == null) ? "" : doc.Content;
        String version = (doc.Version == null) ? "" : doc.Version;
        jsonBuilder += "{" + "\"DocumentID\":" + doc.DocumentID + "," + "\"Rank\":" + doc.Rank + "," + "\"Title\":\"" + StringEscapeUtils.escapeJava(title) + "\"," + "\"Version\":\"" + StringEscapeUtils.escapeJava(version) + "\"," + "\"Content\":\"" + StringEscapeUtils.escapeJava(content) + "\"" + "}";
    }
    jsonBuilder += "]";
    IndexerManager manager = IndexerManager.get();
    manager.getLogger().debug("found: " + jsonBuilder);
    return jsonBuilder;
}
Example 19
Project: molgenis-master  File: LimitMethod.java View source code
private String limit(String s, int nrOfCharacters, String container) {
    if (s.length() > nrOfCharacters) {
        String jsEscaped = StringEscapeUtils.escapeEcmaScript(s);
        return s.substring(0, nrOfCharacters - 8) + " [<a id='" + container + "-all' href='#'> ... </a>]<script>$('#" + container + "-all').on('click', function(){$('#" + container + "').html('" + jsEscaped + "')});</script>";
    }
    return s;
}
Example 20
Project: nuxeo-master  File: AbstractPreviewer.java View source code
protected String getPreviewTitle(DocumentModel dm) {
    StringBuffer sb = new StringBuffer();
    sb.append(dm.getTitle());
    sb.append(" ");
    String vl = dm.getVersionLabel();
    if (vl != null) {
        sb.append(vl);
    }
    sb.append(" (preview)");
    String title = sb.toString();
    return StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(title));
}
Example 21
Project: opencit-master  File: BuildIdentityXMLCmd.java View source code
@Override
public void execute() {
    String responseXML = "<client_request> " + "<timestamp>" + new Date(System.currentTimeMillis()).toString() + "</timestamp>" + "<clientIp>" + StringEscapeUtils.escapeXml(CommandUtil.getHostIpAddress()) + "</clientIp>" + "<error_code>" + context.getErrorCode().getErrorCode() + "</error_code>" + "<error_message>" + StringEscapeUtils.escapeXml(context.getErrorCode().getMessage()) + "</error_message>" + "<aikcert>" + StringEscapeUtils.escapeXml(context.getAIKCertificate()) + "</aikcert>" + "</client_request>";
    context.setResponseXML(responseXML);
}
Example 22
Project: polly-master  File: EscapeProvider.java View source code
@Override
public void setup() throws SetupException {
    // HACK: this is a hack to expose html escaping from apache
    //       commons to all plugins with avoiding a new dependency 
    HTMLTools.UTIL = new HTMLTools.HTMLToolsUtil() {

        @Override
        public String escape(String s) {
            return StringEscapeUtils.escapeHtml(s);
        }

        @Override
        public String unsecape(String s) {
            return StringEscapeUtils.unescapeHtml(s);
        }

        @Override
        public void gainFieldAccess(Map<String, Object> targetContext, Class<?> container, String key) {
            targetContext.put(key, new FieldMethodizer(container.getName()));
        }
    };
}
Example 23
Project: push-bot-master  File: ListSubscriptionsCommandHandler.java View source code
@Override
public void handle(JID user, String... args) {
    List<Subscription> subscriptions = Subscription.getSubscriptionsForUser(user);
    if (subscriptions.isEmpty()) {
        Xmpp.sendMessage(user, "You have no subscriptions.");
        return;
    }
    Multimap<String, Subscription> subscriptionsByHub = ArrayListMultimap.create();
    for (Subscription subscription : subscriptions) {
        subscriptionsByHub.put(subscription.getHubUrl().toString(), subscription);
    }
    StringBuilder message = new StringBuilder("Subscriptions:");
    for (String hubUrl : subscriptionsByHub.keySet()) {
        message.append("\n  at hub ").append(hubUrl).append(":");
        for (Subscription subscription : subscriptionsByHub.get(hubUrl)) {
            message.append("\n    ").append(subscription.getFeedUrl());
            String title = subscription.getTitle();
            if (title != null && !title.isEmpty()) {
                message.append(" (").append(StringEscapeUtils.unescapeHtml4(title)).append(")");
            }
        }
    }
    Xmpp.sendMessage(user, message.toString());
}
Example 24
Project: restapi-java-sdk-master  File: PictureMultimediaObject.java View source code
@Override
public String getAttachmentXml() {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + NL);
    buffer.append("<common:attachment xsi:type=\"common:Picture\" xmlns:common=\"http://rest.immobilienscout24.de/schema/common/1.0\" xmlns:ns3=\"http://rest.immobilienscout24.de/schema/platform/gis/1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + NL);
    buffer.append("<title>" + StringEscapeUtils.escapeXml(getTitle()) + "</title>" + NL);
    buffer.append("<floorplan>" + isFloorplan() + "</floorplan>" + NL);
    buffer.append("<titlePicture>" + isTitlePicture + "</titlePicture>" + NL);
    buffer.append("</common:attachment>");
    return buffer.toString();
}
Example 25
Project: selenify-master  File: SelenifyParser.java View source code
/** @return a String[] of command, arg1, arg2 */
public static String[] parse(String line) {
    // Parse this line into an HTML table row, Ignore comments
    if (line.trim().length() == 0 || line.startsWith("#")) {
        return null;
    }
    String command;
    String arg1 = "";
    String arg2 = "";
    int firstSpace = line.indexOf(" ");
    if (firstSpace == -1) {
        command = line;
    } else {
        command = line.substring(0, firstSpace);
        // Hack to do command/arg1 (not arg2) in one line
        String args = arg1 = line.substring(firstSpace + 1);
        String[] splitOnColon = args.split("(?<!\\\\): ");
        if (splitOnColon.length > 1) {
            arg1 = splitOnColon[0];
            arg2 = splitOnColon[1];
            for (int j = 2; j < splitOnColon.length; j++) {
                arg2 += ": " + splitOnColon[j];
            }
        } else if (SelenifyParser.defaultValueCommands.contains(command) || SelenifyParser.customValueCommands.contains(command)) {
            arg2 = arg1;
            arg1 = "";
        }
    }
    arg1 = StringEscapeUtils.escapeHtml(arg1.replaceAll("\\\\:", ":"));
    arg2 = StringEscapeUtils.escapeHtml(arg2.replaceAll("\\\\:", ":"));
    return new String[] { command, arg1, arg2 };
}
Example 26
Project: Skylark-master  File: DefaultURLAnnouncer.java View source code
@Override
public String getTitleForURL(String url) {
    try {
        HttpRequest req = HttpRequest.get(url).accept("text/html").followRedirects(true);
        if (req.code() >= 400)
            return null;
        String[] splitContentType = req.contentType().split(";");
        for (int i = 0; i < splitContentType.length; i++) {
            splitContentType[i] = splitContentType[i].trim();
        }
        if (splitContentType[0].equals("text/html")) {
            Matcher m = TITLE_PATTERN.matcher(req.body());
            if (m.find()) {
                String title = m.group(1).replaceAll("\\s+", " ").trim();
                title = StringEscapeUtils.unescapeHtml4(title);
                return String.format("[%s]", title);
            }
        }
    } catch (Exception e) {
    }
    return null;
}
Example 27
Project: TechnologyReadinessTool-master  File: TextTag.java View source code
@Override
public void doTag() throws JspException, IOException {
    ActionContext actionContext = ActionContext.getContext();
    TextProvider textProvider = actionContext.getContainer().getInstance(TextProvider.class);
    textProvider.getText(name);
    String message = textProvider.getText(name);
    if (escapeHtml) {
        message = StringEscapeUtils.escapeHtml4(message);
    }
    if (!message.equals(name)) {
        if (StringUtils.isBlank(var)) {
            getJspContext().getOut().append(message);
        } else {
            getJspContext().setAttribute(var, message);
        }
    }
}
Example 28
Project: vlove-master  File: FormValidatorVisitor.java View source code
@Override
public void component(FormComponent<?> formComponent, IVisit<Void> visit) {
    if (!formComponent.isValid() && formComponent.isEnabled() && formComponent.isRequired()) {
        String errorMessage = null;
        FeedbackMessage message = formComponent.getFeedbackMessage();
        if (message != null) {
            message.markRendered();
            ValidationErrorFeedback feedback = (ValidationErrorFeedback) message.getMessage();
            errorMessage = StringEscapeUtils.escapeEcmaScript(feedback.getMessage());
        }
        if (formComponent instanceof RadioGroup<?>) {
            target.appendJavaScript(String.format("groupRequired('%s','%s');", formComponent.getMarkupId(), errorMessage));
        } else {
            target.appendJavaScript(String.format("inputRequired('%s','%s');", formComponent.getMarkupId(), errorMessage));
        }
    } else {
        String compId = formComponent.getMarkupId();
        target.appendJavaScript(String.format("clearError('%s');", compId));
    }
}
Example 29
Project: molgenis_apps-legacy-master  File: OverlibText.java View source code
public static Map<String, String> getOverlibText(Database db, List<String> rowNames, List<String> colNames) throws Exception {
    List<ObservationTarget> rows = db.find(ObservationTarget.class, new QueryRule("name", Operator.IN, rowNames));
    List<ObservationTarget> cols = db.find(ObservationTarget.class, new QueryRule("name", Operator.IN, colNames));
    List<String> foundRows = new ArrayList<String>();
    List<String> foundCols = new ArrayList<String>();
    for (Nameable iden : rows) {
        foundRows.add(iden.getName());
    }
    for (Nameable iden : cols) {
        foundCols.add(iden.getName());
    }
    for (String rowName : rowNames) {
        if (!foundRows.contains(rowName)) {
            ObservationTarget nullIden = new ObservationTarget();
            nullIden.setName(rowName);
            nullIden.set("id", "-1");
            rows.add(nullIden);
        }
    }
    for (String colName : colNames) {
        if (!foundCols.contains(colName)) {
            ObservationTarget nullIden = new ObservationTarget();
            nullIden.setName(colName);
            nullIden.set("id", "-1");
            cols.add(nullIden);
        }
    }
    Map<String, String> overlibText = new HashMap<String, String>();
    for (Nameable iden : rows) {
        String text = appendFields(iden);
        overlibText.put(iden.getName(), org.apache.commons.lang.StringEscapeUtils.escapeHtml(text));
    }
    for (Nameable iden : cols) {
        String text = appendFields(iden);
        overlibText.put(iden.getName(), org.apache.commons.lang.StringEscapeUtils.escapeHtml(text));
    // overlibText.put(iden.getName(), text);
    }
    return overlibText;
}
Example 30
Project: support-tools-master  File: VpsDao.java View source code
public static String sendPost(String url, HashMap<String, String> jSonQuery) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    String urlParameters = "";
    Object[] keys = jSonQuery.keySet().toArray();
    for (int i = 0; i < keys.length; i++) {
        String key = (String) keys[i];
        urlParameters += key + "=" + jSonQuery.get(key);
        if (!(i == keys.length - 1))
            urlParameters += "&";
    }
    con.setDoOutput(true);
    System.out.println("Передаю параметры: " + urlParameters);
    OutputStream os = con.getOutputStream();
    os.write(StringUtils.getBytesUtf8(urlParameters));
    os.flush();
    os.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String result = in.readLine();
    //        result = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(result);
    byte[] bytes = result.getBytes();
    result = new String(bytes, "UTF-8");
    System.out.println("Ответ: " + result);
    in.close();
    return result;
}
Example 31
Project: FindBug-for-Domino-Designer-master  File: Strings.java View source code
/**
     * Escape XML entities and illegal characters in the given string. This
     * enhances the functionality of
     * org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping
     * low-valued unprintable characters, which are not permitted by the W3C XML
     * 1.0 specification.
     * 
     * @param s
     *            a string
     * @return the same string with characters not permitted by the XML
     *         specification escaped
     * @see <a href="http://www.w3.org/TR/REC-xml/#charsets">Extensible Markup
     *      Language (XML) 1.0 (Fifth Edition)</a>
     * @see <a
     *      href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils
     *      javadoc</a>
     */
public static String escapeXml(String s) {
    initializeEscapeMap();
    if (s == null || s.length() == 0)
        return s;
    char[] sChars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    int lastReplacement = 0;
    for (int i = 0; i < sChars.length; i++) {
        if (isInvalidXMLCharacter(sChars[i])) {
            // append intermediate string to string builder
            sb.append(sChars, lastReplacement, i - lastReplacement);
            // substitute control character with escape sequence
            sb.append(xmlLowValueEscapeStrings[sChars[i]]);
            // advance last pointer past this character
            lastReplacement = i + 1;
        }
    }
    if (lastReplacement < sChars.length)
        sb.append(sChars, lastReplacement, sChars.length - lastReplacement);
    return StringEscapeUtils.escapeXml(sb.toString());
}
Example 32
Project: findbugs-rcp-master  File: Strings.java View source code
/**
     * Escape XML entities and illegal characters in the given string. This
     * enhances the functionality of
     * org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping
     * low-valued unprintable characters, which are not permitted by the W3C XML
     * 1.0 specification.
     * 
     * @param s
     *            a string
     * @return the same string with characters not permitted by the XML
     *         specification escaped
     * @see <a href="http://www.w3.org/TR/REC-xml/#charsets>Extensible Markup
     *      Language (XML) 1.0 (Fifth Edition)</a>
     * @see <a
     *      href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils
     *      javadoc</a>
     */
public static String escapeXml(String s) {
    initializeEscapeMap();
    if (s == null || s.length() == 0)
        return s;
    char[] sChars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    int lastReplacement = 0;
    for (int i = 0; i < sChars.length; i++) {
        if (isInvalidXMLCharacter(sChars[i])) {
            // append intermediate string to string builder
            sb.append(sChars, lastReplacement, i - lastReplacement);
            // substitute control character with escape sequence
            sb.append(xmlLowValueEscapeStrings[sChars[i]]);
            // advance last pointer past this character
            lastReplacement = i + 1;
        }
    }
    if (lastReplacement < sChars.length)
        sb.append(sChars, lastReplacement, sChars.length - lastReplacement);
    return StringEscapeUtils.escapeXml(sb.toString());
}
Example 33
Project: org.revisionfilter-master  File: Strings.java View source code
/**
	 * Escape XML entities and illegal characters in the given string.
	 * This enhances the functionality of
	 * org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping
	 * low-valued unprintable characters, which are not permitted by the
	 * W3C XML 1.0 specification.
	 * 
	 * @param s a string
	 * @return the same string with characters not permitted by the XML specification escaped
	 * @see <a href="http://www.w3.org/TR/REC-xml/#charsets>Extensible Markup Language (XML) 1.0 (Fifth Edition)</a>
	 * @see <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils javadoc</a>
	 */
public static String escapeXml(String s) {
    initializeEscapeMap();
    if (s == null || s.length() == 0)
        return s;
    char[] sChars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    int lastReplacement = 0;
    for (int i = 0; i < sChars.length; i++) {
        if (isInvalidXMLCharacter(sChars[i])) {
            // append intermediate string to string builder 
            sb.append(sChars, lastReplacement, i - lastReplacement);
            // substitute control character with escape sequence
            sb.append(xmlLowValueEscapeStrings[(int) sChars[i]]);
            // advance last pointer past this character
            lastReplacement = i + 1;
        }
    }
    if (lastReplacement < sChars.length)
        sb.append(sChars, lastReplacement, sChars.length - lastReplacement);
    return StringEscapeUtils.escapeXml(sb.toString());
}
Example 34
Project: gocd-master  File: HgModificationSplitter.java View source code
private Modification parseChangeset(Element changeset) throws ParseException {
    Date modifiedTime = DateUtils.parseRFC822(changeset.getChildText("date"));
    String author = org.apache.commons.lang.StringEscapeUtils.unescapeXml(changeset.getChildText("author"));
    String comment = org.apache.commons.lang.StringEscapeUtils.unescapeXml(changeset.getChildText("desc"));
    String revision = changeset.getChildText("node");
    Modification modification = new Modification(author, comment, null, modifiedTime, revision);
    Element files = changeset.getChild("files");
    List<File> modifiedFiles = parseFiles(files, "modified");
    List<File> addedFiles = parseFiles(files, "added");
    List<File> deletedFiles = parseFiles(files, "deleted");
    modifiedFiles.removeAll(addedFiles);
    modifiedFiles.removeAll(deletedFiles);
    addModificationFiles(modification, ModifiedAction.added, addedFiles);
    addModificationFiles(modification, ModifiedAction.deleted, deletedFiles);
    addModificationFiles(modification, ModifiedAction.modified, modifiedFiles);
    return modification;
}
Example 35
Project: rendersnake-master  File: Hash.java View source code
public String toJavascript() {
    StringBuilder sb = new StringBuilder();
    sb.append('{');
    boolean separate = false;
    for (Object each : map.keySet()) {
        if (separate)
            sb.append(',');
        else
            separate = true;
        sb.append(each).append(':');
        Object value = map.get(each);
        if (value instanceof String)
            sb.append('\'').append(StringEscapeUtils.escapeXml((String) value)).append('\'');
        else
            sb.append(value);
    }
    sb.append('}');
    return sb.toString();
}
Example 36
Project: ali-idea-plugin-master  File: PlainTextType.java View source code
@Override
public String translate(String value, ValueCallback callback) {
    try {
        final StringBuffer buf = new StringBuffer();
        new ParserDelegator().parse(new StringReader(value), new HTMLEditorKit.ParserCallback() {

            @Override
            public void handleText(char[] data, int pos) {
                if (buf.length() > 0 && !StringUtils.isWhitespace(buf.substring(buf.length() - 1))) {
                    buf.append(" ");
                }
                buf.append(data);
            }
        }, false);
        return buf.toString();
    } catch (IOException e) {
        return StringEscapeUtils.escapeHtml(value);
    }
}
Example 37
Project: ambari-master  File: LogsearchSimpleAuthenticationProvider.java View source code
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!authPropsConfig.isAuthSimpleEnabled()) {
        logger.debug("Simple auth is disabled");
        return authentication;
    }
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    username = StringEscapeUtils.unescapeHtml(username);
    if (StringUtils.isBlank(username)) {
        throw new BadCredentialsException("Username can't be null or empty.");
    }
    User user = new User();
    user.setUsername(username);
    authentication = new UsernamePasswordAuthenticationToken(username, password, getAuthorities());
    return authentication;
}
Example 38
Project: apps-android-wikipedia-master  File: CsvColumn.java View source code
private String join(@NonNull Collection<String> strs) {
    StringBuilder builder = new StringBuilder();
    for (String str : strs) {
        builder.append(StringEscapeUtils.escapeCsv(str));
        builder.append(',');
    }
    if (builder.length() > 0) {
        builder.deleteCharAt(builder.length() - 1);
    }
    return builder.toString();
}
Example 39
Project: aries-master  File: TwitterQuery.java View source code
/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
public void start(BundleContext context) throws Exception {
    Twitter twitter = new Twitter();
    Query query = new Query("from:theasf");
    try {
        QueryResult result = twitter.search(query);
        List<Tweet> tweets = result.getTweets();
        System.out.println("hits:" + tweets.size());
        for (Tweet tweet : tweets) {
            System.out.println(tweet.getFromUser() + ":" + StringEscapeUtils.unescapeXml(tweet.getText()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 40
Project: beakerx-master  File: ControlCharacterUtils.java View source code
public static String escapeControlCharacters(final String value) {
    if (StringUtils.isNotEmpty(value)) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            if (Character.isISOControl(value.charAt(i))) {
                sb.append(StringEscapeUtils.escapeJson(value.substring(i, i + 1)));
            } else {
                sb.append(value.charAt(i));
            }
        }
        return sb.toString();
    }
    return StringUtils.EMPTY;
}
Example 41
Project: BitHub-master  File: CoinbaseTransactionParser.java View source code
public String parseDestinationFromMessage() {
    String message = StringEscapeUtils.unescapeHtml4(coinbaseTransaction.getNotes());
    int startToken = message.indexOf("__");
    if (startToken == -1) {
        return "Unknown";
    }
    int endToken = message.indexOf("__", startToken + 1);
    if (endToken == -1) {
        return "Unknown";
    }
    return message.substring(startToken + 2, endToken);
}
Example 42
Project: burp-Dirbuster-master  File: CSRFTokenScanIssue.java View source code
@Override
public String getIssueDetail() {
    StringBuilder details = new StringBuilder().append("CSRF attack possible in this form. Please read more completely about this in OWASP TOP-10");
    String stringResponse = callbacks.getHelpers().bytesToString(requestResponse.getResponse());
    List<int[]> markers = ((IHttpRequestResponseWithMarkers) requestResponse).getResponseMarkers();
    markers.forEach( marker -> {
        details.append("<br/>");
        details.append(StringEscapeUtils.escapeHtml4(stringResponse.substring(marker[0], marker[1])));
    });
    details.append("<br/><img src=\"http://www.terrariaonline.com/attachments/small-trollface-jpg.9747/\">");
    return details.toString();
}
Example 43
Project: cms-ce-master  File: PortletErrorMessageMarkupCreator.java View source code
private String getDetails(final Exception e) {
    Throwable error = e;
    final StringWriter writer = new StringWriter();
    if (error instanceof PortletXsltViewTransformationException) {
        error = error.getCause();
    }
    error.printStackTrace(new PrintWriter(writer));
    return StringEscapeUtils.escapeHtml(writer.toString());
}
Example 44
Project: common_gui_tools-master  File: EscapeUtils.java View source code
/**
	 * 转义字符.
	 * 
	 * @param string 字符
	 * @param type 字符类型
	 */
public static String escape(String string, String type) {
    String unescape = "�支�对" + type + "字符的转义";
    if (type.equals(LanguageUtils.CONST_HTML)) {
        unescape = StringEscapeUtils.escapeHtml(string);
    } else if (type.equals(LanguageUtils.CONST_XML)) {
        unescape = StringEscapeUtils.escapeXml(string);
    } else if (type.equals(LanguageUtils.CONST_SQL)) {
        unescape = StringEscapeUtils.escapeSql(string);
    } else if (type.equals(LanguageUtils.CONST_JAVA)) {
        unescape = StringEscapeUtils.escapeJava(string);
    } else if (type.equals(LanguageUtils.CONST_JavaScript)) {
        unescape = StringEscapeUtils.escapeJavaScript(string);
    } else if (type.equals(LanguageUtils.CONST_CSV)) {
        unescape = StringEscapeUtils.escapeCsv(string);
    }
    return unescape;
}
Example 45
Project: confluence2wordpress-master  File: TagAttributesSetter.java View source code
public boolean visit(TagNode parentNode, HtmlNode htmlNode) {
    if (htmlNode instanceof TagNode) {
        TagNode tag = (TagNode) htmlNode;
        String tagName = tag.getName();
        String attributesString = tagAttributes.get(tagName);
        if (attributesString != null) {
            Map<String, String> attributes = extractAttributes(attributesString);
            for (Entry<String, String> entry : attributes.entrySet()) {
                tag.setAttribute(entry.getKey(), StringEscapeUtils.escapeXml(entry.getValue()));
            }
        }
    }
    return true;
}
Example 46
Project: constellio-master  File: NiceTitle.java View source code
private void runJavascript() {
    String titleEscaped = StringEscapeUtils.escapeJavaScript(title);
    String componentId = component.getId();
    if (componentId == null) {
        componentId = new UUIDV1Generator().next();
        component.setId(componentId);
    }
    component.addStyleName("nicetitle-link");
    StringBuilder js = new StringBuilder();
    String getById = "document.getElementById(\"" + componentId + "\")";
    js.append("if (" + getById + ") {");
    if (visibleWhenDisabled) {
        js.append(getById + ".className = " + getById + ".className.replace(\"v-disabled\", \"" + DISABLED_STYLE + "\")");
        js.append(";");
    }
    js.append(getById + ".setAttribute(\"title\", \"" + titleEscaped + "\")");
    js.append(";");
    js.append("makeNiceTitleA(" + getById + ")");
    js.append("}");
    JavaScript javascript = JavaScript.getCurrent();
    javascript.execute(js.toString());
}
Example 47
Project: discord.jar-master  File: MessagePoll.java View source code
@Override
public void process(JSONObject content, JSONObject rawRequest, Server server) {
    try {
        String id = content.getString("channel_id");
        String authorId = content.getJSONObject("author").getString("id");
        Group group = api.getGroupById(id);
        User user = api.getUserById(authorId);
        group = (group == null) ? api.getGroupById(authorId) : group;
        user = (user == null) ? api.getBlankUser() : user;
        String msgContent = StringEscapeUtils.unescapeJson(content.getString("content"));
        String msgId = content.getString("id");
        String webhookId = content.has("webhook_id") ? !content.isNull("webhook_id") ? content.getString("webhook_id") : null : null;
        if (webhookId != null && content.has("author")) {
            JSONObject author = content.getJSONObject("author");
            user = new UserImpl(author.getString("username"), webhookId, webhookId, api);
            ((UserImpl) user).setAvatar(author.getString("avatar"));
        }
        MessageImpl msg = new MessageImpl(msgContent, msgId, id, webhookId, api);
        msg.setSender(user);
        if (content.has("embed"))
            msg.addEmbed(new Embed(content.getJSONObject("embed")));
        if (content.has("embeds")) {
            for (Object obj : content.getJSONArray("embeds")) msg.addEmbed(new Embed((JSONObject) obj));
        }
        if (!content.isNull("edited_timestamp"))
            msg.setEdited(true);
        GroupUser gUser = (group.getServer() == null || webhookId != null) ? new GroupUser(user, "User", user.getId()) : group.getServer().getGroupUserById(authorId);
        api.getEventManager().executeEvent(new UserChatEvent(group, gUser, msg));
    } catch (Exception e) {
        api.log("Failed to process message:\n >" + content);
    }
}
Example 48
Project: documentr-master  File: TwitterMacroTest.java View source code
@Test
public void getHtml() {
    //$NON-NLS-1$
    when(context.getParameters()).thenReturn("\"searchParams\"");
    String html = runnable.getHtml(context);
    @SuppressWarnings("nls") String expectedHtml = "<script charset=\"UTF-8\" src=\"http://widgets.twimg.com/j/2/widget.js\"></script>\n" + "<script>\n" + "new TWTR.Widget({" + "version: 2," + "type: 'search'," + "search: '" + StringEscapeUtils.escapeEcmaScript("\"searchParams\"") + "'," + "interval: 15000," + "title: ''," + "subject: ''," + "width: 300," + "height: 300," + "features: {" + "scrollbar: true," + "loop: false," + "live: true," + "behavior: 'default'" + "}" + "}).render().start(); require(['documentr/fixTwitterCss']);\n" + "</script>\n";
    assertEquals(expectedHtml, html);
}
Example 49
Project: fastcatsearch-master  File: SearchPageSettingsTest.java View source code
@Test
public void testRead() throws JAXBException {
    String data = "<span color=\"text-danger $id\">\n\n$body</span>";
    System.out.println(">>>>" + data.replaceAll("\\$body", ">>>>>"));
    String fieldIdPattern = "\\$[a-zA-Z_-]+";
    Pattern patt = Pattern.compile(fieldIdPattern);
    Matcher matcher = patt.matcher(data);
    int i = 0;
    while (matcher.find()) {
        String g = matcher.group();
        System.out.println(i++ + " > " + g.substring(1));
    }
    data = StringEscapeUtils.escapeHtml4(data);
    String xml = "<search-page>" + "<search-category-list>" + "    <search-category>" + "        <body-field>" + data + "</body-field>" + //"        <body-field><span>$body</span></body-field>" +
    "    </search-category>" + "</search-category-list>" + "<search-list-size>0</search-list-size>" + "<total-search-list-size>0</total-search-list-size>" + "</search-page>";
    Reader reader = new StringReader(xml);
    SearchPageSettings searchPageSettings = JAXBConfigs.readConfig(reader, SearchPageSettings.class);
    for (SearchCategorySetting cs : searchPageSettings.getSearchCategorySettingList()) {
        System.out.println(cs.getBodyField());
    }
}
Example 50
Project: find-sec-bugs-master  File: XssServlet3.java View source code
public void writeWithEncoders(PrintWriter pw, String input1) {
    pw.write(input1);
    String encoded = ESAPI.encoder().encodeForHTML(input1);
    pw.write(encoded.toLowerCase() + SAFE_VALUE);
    pw.write(StringEscapeUtils.escapeHtml(input1));
    pw.write(ESAPI.encoder().decodeForHTML(encoded) + SAFE_VALUE);
    pw.write(myEncode(input1));
    pw.write(myDecode(encoded));
    pw.write(input1.replaceAll("[\"'<>&]", ""));
}
Example 51
Project: FluentLenium-master  File: CssSupportImpl.java View source code
@Override
public void inject(String cssText) {
    InputStream injectorScript = getClass().getResourceAsStream("/org/fluentlenium/core/css/injector.js");
    String injectorJs;
    try {
        injectorJs = IOUtils.toString(injectorScript, Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new IOError(e);
    } finally {
        IOUtils.closeQuietly(injectorScript);
    }
    cssText = cssText.replace("\r\n", "").replace("\n", "");
    cssText = StringEscapeUtils.escapeEcmaScript(cssText);
    executeScriptRetry("cssText = \"" + cssText + "\"" + ";\n" + injectorJs);
}
Example 52
Project: gatein-shindig-master  File: UserPrefSubstituter.java View source code
public void addSubstitutions(Substitutions substituter, GadgetContext context, GadgetSpec spec) {
    UserPrefs values = context.getUserPrefs();
    for (UserPref pref : spec.getUserPrefs().values()) {
        String name = pref.getName();
        String value = values.getPref(name);
        if (value == null) {
            value = pref.getDefaultValue();
            if (value == null) {
                value = "";
            }
        }
        substituter.addSubstitution(Substitutions.Type.USER_PREF, name, StringEscapeUtils.escapeHtml(value));
    }
}
Example 53
Project: gazetteer-master  File: APIUtils.java View source code
public static JSONObject encodeSearchResult(SearchResponse searchResponse, boolean fullGeometry, boolean explain, AnswerDetalization detalization) {
    JSONObject result = new JSONObject();
    result.put("result", "success");
    JSONArray features = new JSONArray();
    result.put("features", features);
    result.put("hits", searchResponse.getHits().getTotalHits());
    for (SearchHit hit : searchResponse.getHits().getHits()) {
        JSONObject feature = new JSONObject(hit.getSource());
        if (detalization == AnswerDetalization.SHORT) {
            JSONObject source = feature;
            feature = new JSONObject();
            feature.put("id", source.getString("id"));
            feature.put("center_point", source.getJSONObject("center_point"));
            feature.put("address", getAddressText(source));
        }
        if (!fullGeometry) {
            feature.remove("full_geometry");
        }
        if (detalization != AnswerDetalization.SHORT) {
            feature.put("_hit_score", hit.getScore());
        }
        features.put(feature);
    }
    if (explain) {
        JSONArray explanations = new JSONArray();
        result.put("explanations", explanations);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            explanations.put(StringEscapeUtils.escapeHtml4(hit.explanation().toString()));
        }
    }
    return result;
}
Example 54
Project: geotoolkit-master  File: NoCharacterEscapeHandler.java View source code
@Override
public void escape(char[] buf, int start, int len, boolean b, Writer out) throws IOException {
    if (len > CDATA_START_TAG.length()) {
        String s = new String(Arrays.copyOfRange(buf, start, CDATA_START_TAG.length()));
        if (s.equals(CDATA_START_TAG)) {
            out.write(buf, start, len);
            return;
        }
    }
    String escapedString = StringEscapeUtils.escapeXml(new String(Arrays.copyOfRange(buf, start, len)));
    out.write(escapedString);
}
Example 55
Project: ginco-master  File: SKOSCustomConceptAttributeExporter.java View source code
public Model exportCustomConceptAttributes(ThesaurusConcept concept, Model model, Resource conceptResource, OntModel ontModel) {
    List<CustomConceptAttribute> attributes = customConceptAttributeService.getAttributesByEntity(concept);
    DatatypeProperty customAttrOnt = ontModel.createDatatypeProperty(GINCO.getURI() + "CustomConceptAttribute");
    Literal l = ontModel.createLiteral("CustomConceptAttribute");
    customAttrOnt.addLabel(l);
    for (CustomConceptAttribute attribute : attributes) {
        if (attribute.getType().getExportable()) {
            Resource customAttrRes = model.createResource(GINCO.getURI() + attribute.getType().getCode(), GINCO.CUSTOM_CONCEPT_ATTRIBUTE);
            model.add(customAttrRes, RDFS.label, StringEscapeUtils.unescapeXml(attribute.getType().getCode()));
            if (StringUtils.isNotEmpty(attribute.getLexicalValue())) {
                Property customAttributeProperty = model.createProperty(GINCO.getURI() + attribute.getType().getCode());
                model.add(conceptResource, customAttributeProperty, attribute.getLexicalValue());
            }
        }
    }
    return model;
}
Example 56
Project: HippoWeblog-master  File: Menu.java View source code
@Override
public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
    super.doBeforeRender(request, response);
    request.setAttribute("menu", request.getRequestContext().getHstSiteMenus().getSiteMenu("main"));
    String query = getPublicRequestParameter(request, "searchfor");
    if (StringUtils.isBlank(query)) {
        query = request.getParameter("searchfor");
    }
    if (StringUtils.isNotBlank(query)) {
        request.setAttribute("searchfor", StringEscapeUtils.escapeHtml(query));
    }
}
Example 57
Project: HoloAPI-master  File: UnicodeFormatter.java View source code
public static String replaceAll(String s) {
    YAMLConfig config = HoloAPI.getConfig(ConfigType.MAIN);
    ConfigurationSection cs = config.getConfigurationSection("specialCharacters");
    if (cs != null) {
        for (String key : cs.getKeys(false)) {
            if (s.contains(key)) {
                s = s.replace(key, StringEscapeUtils.unescapeJava("\\u" + config.getString("specialCharacters." + key)));
            }
        }
    }
    return s;
}
Example 58
Project: hsac-fitnesse-fixtures-master  File: SlimFixtureException.java View source code
private static String createMessage(boolean stackTraceInWiki, String message) {
    String result = message;
    if (!stackTraceInWiki) {
        // Until https://github.com/unclebob/fitnesse/issues/731 is fixed
        if (message.contains("\n")) {
            if (!message.startsWith("<") || !message.endsWith(">")) {
                // it is not yet HTML, make it HTML so we can use <br/>
                message = StringEscapeUtils.escapeHtml4(message);
                message = String.format("<div>%s</div>", message);
            }
            message = message.replaceAll("(\\r)?\\n", "<br/>");
        }
        result = String.format("message:<<%s>>", message);
    }
    return result;
}
Example 59
Project: infoglue-calendarOld-master  File: CalendarServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    StringBuffer sb = new StringBuffer();
    try {
        Session session = HibernateUtil.currentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            StringBuffer allCalendarsProperty = new StringBuffer("");
            Set<Calendar> calendarSet = CalendarController.getController().getCalendarList(session);
            Iterator calendarSetIterator = calendarSet.iterator();
            while (calendarSetIterator.hasNext()) {
                Calendar calendar = (Calendar) calendarSetIterator.next();
                sb.append("    <property name=\"" + StringEscapeUtils.unescapeHtml(calendar.getName()) + "\" value=\"" + calendar.getId() + "\"/>");
                if (allCalendarsProperty.length() > 0)
                    allCalendarsProperty.append(",");
                allCalendarsProperty.append(calendar.getId());
            }
            sb.insert(0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?><properties><property name=\"All\" value=\"" + allCalendarsProperty + "\"/>");
            sb.append("</properties>");
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw e;
        } finally {
            HibernateUtil.closeSession();
        }
    } catch (Exception e) {
        logger.error("En error occurred when we tried to create a new contentVersion:" + e.getMessage(), e);
    }
    response.setContentType("text/xml");
    PrintWriter pw = response.getWriter();
    pw.println(sb.toString());
    pw.flush();
    pw.close();
}
Example 60
Project: jbehave-core-master  File: PendingStepMethodGenerator.java View source code
public String generateMethod(PendingStep step) {
    String stepAsString = step.stepAsString();
    String previousNonAndStepAsString = step.previousNonAndStepAsString();
    StepType stepType = null;
    if (keywords.isAndStep(stepAsString) && previousNonAndStepAsString != null) {
        stepType = keywords.stepTypeFor(previousNonAndStepAsString);
    } else {
        stepType = keywords.stepTypeFor(stepAsString);
    }
    String stepPattern = keywords.stepWithoutStartingWord(stepAsString, stepType);
    String stepAnnotation = StringUtils.capitalize(stepType.name().toLowerCase());
    String methodName = methodName(stepType, stepPattern);
    String pendingAnnotation = Pending.class.getSimpleName();
    return format(METHOD_SOURCE, stepAnnotation, StringEscapeUtils.escapeJava(stepPattern), pendingAnnotation, methodName, keywords.pending());
}
Example 61
Project: jbehave-eclipse-master  File: Marks.java View source code
public static MarkData putStepsAsHtml(MarkData mark, Iterable<StepCandidate> candidates) {
    StringBuilder builder = new StringBuilder();
    builder.append("<ul>");
    for (StepCandidate pStep : candidates) {
        String qualifiedName = JDTUtils.formatQualifiedName(pStep.method);
        builder.append("<li>").append("<b>").append(StringEscapeUtils.escapeHtml(pStep.stepPattern)).append("</b>").append(" (<code>").append("<a href=\"").append(qualifiedName).append("\">").append(qualifiedName).append("</a>").append("</code>)").append("</li>");
    }
    builder.append("</ul>");
    return mark.attribute(STEPS_HTML, builder.toString());
}
Example 62
Project: jbpm-form-modeler-master  File: SetListValuesInstruction.java View source code
public void updateListValues(List newValues) {
    StringBuffer sb = new StringBuffer();
    sb.append("<setListValues name=\"").append(StringEscapeUtils.escapeXml(fieldName)).append("\">");
    for (int i = 0; i < newValues.size(); i++) {
        Object[] objects = (Object[]) newValues.get(i);
        String id = String.valueOf(objects[0]);
        String value = String.valueOf(objects[1]);
        String selected = String.valueOf(objects[2]);
        sb.append("<option value=\"").append(StringEscapeUtils.escapeXml(id)).append("\" text=\"").append(StringEscapeUtils.escapeXml(value)).append("\"");
        if (objects[2] != null) {
            sb.append(" selected=\"").append(selected).append("\"");
        }
        sb.append("></option>");
    }
    sb.append("</setListValues>");
    XMLrepresentation = sb.toString();
}
Example 63
Project: jcr-master  File: UnescapeHTMLFilter.java View source code
@Override
public final boolean incrementToken() throws IOException {
    if (!input.incrementToken()) {
        return false;
    }
    final char[] buffer = termAtt.buffer();
    final int bufferLength = termAtt.length();
    String tokenText = new String(buffer);
    tokenText = tokenText.replaceAll("<br", "");
    tokenText = StringEscapeUtils.unescapeHtml(tokenText);
    tokenText = tokenText.replaceAll("\\<.*?>", "");
    int newLen = tokenText.toCharArray().length;
    if (newLen < bufferLength) {
        termAtt.copyBuffer(tokenText.toCharArray(), 0, newLen);
        termAtt.setLength(newLen);
    }
    return true;
}
Example 64
Project: jeboorker-master  File: ToolsResourceUtil.java View source code
/**
	 * Retrieves whatever it finds between <title>...</title> or <h1-7>...</h1-7>.
	 * The first match is returned, even if it is a blank string.
	 * If it finds nothing null is returned.
	 * @param resource
	 * @return
	 */
public static String findTitleFromXhtml(Resource resource) {
    if (resource == null) {
        return "";
    }
    if (resource.getTitle() != null) {
        return resource.getTitle();
    }
    Pattern h_tag = Pattern.compile("^h\\d\\s*", Pattern.CASE_INSENSITIVE);
    String title = null;
    Scanner scanner = null;
    try {
        Reader content = resource.getReader();
        scanner = new Scanner(content);
        scanner.useDelimiter("<");
        while (scanner.hasNext()) {
            String text = scanner.next();
            int closePos = text.indexOf('>');
            String tag = text.substring(0, closePos);
            if (tag.equalsIgnoreCase("title") || h_tag.matcher(tag).find()) {
                title = text.substring(closePos + 1).trim();
                title = StringEscapeUtils.unescapeHtml(title);
                break;
            }
        }
    } catch (IOException e) {
        log.warning(e.getMessage());
    } finally {
        IOUtils.closeQuietly(scanner);
    }
    resource.setTitle(title);
    return title;
}
Example 65
Project: jinjava-master  File: XmlAttrFilter.java View source code
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
    if (var == null || !Map.class.isAssignableFrom(var.getClass())) {
        return var;
    }
    @SuppressWarnings("unchecked") Map<String, Object> dict = (Map<String, Object>) var;
    List<String> attrs = new ArrayList<>();
    for (Map.Entry<String, Object> entry : dict.entrySet()) {
        attrs.add(new StringBuilder(entry.getKey()).append("=\"").append(StringEscapeUtils.escapeXml10(Objects.toString(entry.getValue(), ""))).append("\"").toString());
    }
    String space = " ";
    if (args.length > 0 && !BooleanUtils.toBoolean(args[0])) {
        space = "";
    }
    return space + StringUtils.join(attrs, "\n");
}
Example 66
Project: Jnario-master  File: ErrorMessageProvider.java View source code
protected String handleFailed(final Failed result) {
    StringConcatenation _builder = new StringConcatenation();
    {
        List<SpecFailure> _failures = result.getFailures();
        for (final SpecFailure failure : _failures) {
            _builder.append("<pre class=\"errormessage\">");
            _builder.newLine();
            String _message = failure.getMessage();
            String _escapeHtml = StringEscapeUtils.escapeHtml(_message);
            _builder.append(_escapeHtml, "");
            _builder.append("</pre>");
            _builder.newLineIfNotEmpty();
        }
    }
    return _builder.toString();
}
Example 67
Project: jspTeet-master  File: TweetParser.java View source code
public static String parseText(String text) {
    Perl5Util perl = new Perl5Util();
    String text_e = StringEscapeUtils.escapeHtml(text);
    String temp;
    String url_reg = "s/\\b([a-zA-Z]+:\\/\\/[\\w_.\\-]+\\.[a-zA-Z]{2,6}[\\/\\w\\-~.?=&%#+$*!:;]*)\\b/<a href=\"$1\" class=\"twitter-link\" class=\"web_link\" target=\"_blank\">$1<\\/a>/ig";
    String mail_reg = "s/\\b([a-zA-Z][a-zA-Z0-9\\_\\.\\-]*[a-zA-Z]*\\@[a-zA-Z][a-zA-Z0-9\\_\\.\\-]*[a-zA-Z]{2,6})\\b/<a href=\"mailto:$1\" class=\"web_link\" >$1<\\/a>/ig";
    String user_reg = "s/([\\s|\\.|\\,|\\:|\\xA1|\\xBF\\>|\\{|\\(]?)@{1}(\\w*)([\\.|\\,|\\:|\\!|\\?|\\>|\\}|\\)]?)([\\s]|$)/$1\\<a href=\"\\/user\\?id=$2\" class=\"user_link\"\\>@$2\\<\\/a\\>$3 /ig";
    String trend_reg = "s/([\\s|\\.|\\,|\\:|\\xA1|\\xBF\\>|\\{|\\(]?)#{1}(\\w*)([\\.|\\,|\\:|\\!|\\?|\\>|\\}|\\)]?)([\\s]|$)/$1\\<a href=\"\\/search\\?s=%23$2\" class=\"search_link\"\\>#$2\\<\\/a\\>$3 /ig";
    String shorturl_reg = "m/(href=\\\"http:\\/\\/(bit.ly|j.mp|ff.im)\\/[\\w\\-]{3,10})\\\"/i";
    String rst = perl.substitute(url_reg, text_e);
    rst = perl.substitute(mail_reg, rst);
    rst = perl.substitute(user_reg, rst);
    rst = perl.substitute(trend_reg, rst);
    temp = rst;
    while (perl.match(shorturl_reg, temp)) {
        rst = rst.replace(perl.group(0), "href=\"/expend?u=" + Base64.encode(Base64.encode(perl.group(0).substring(6, perl.group(0).length() - 1).getBytes()).getBytes()) + "\"");
        temp = perl.postMatch();
    }
    temp = text_e;
    rst = "<div class=\"twittertext\">" + rst + "</div>";
    return rst;
}
Example 68
Project: judgesubmit-master  File: MockHttpClient.java View source code
public static JudgeHttpClient create(SocketConnectionData conn) {
    final String caller = RecordingHttpClient.toCallerKey(Thread.currentThread().getStackTrace()[2]);
    final Queue<Pair<String, String>> q = GoodQueueFactory.getInstance().create();
    File f = RecordingHttpClient.getRecordFile(caller);
    AssertStatus.assertTrue(f.exists(), "not exist for caller: " + caller);
    try {
        Scanner in = new Scanner(f);
        while (in.hasNextLine()) {
            String key = StringEscapeUtils.unescapeJava(in.nextLine());
            String body = StringEscapeUtils.unescapeJava(in.nextLine());
            q.enque(Pair.create(key, body));
        }
        in.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new JudgeHttpClient() {

        @Override
        public void clearCookie() {
        // ignores.
        }

        @Override
        public String receivePostBodyString(String path, Map<String, String> param, String encoding) throws IOException, JudgeServiceException {
            return dequeBody(q, RecordingHttpClient.toPostRequestKey(path, param, encoding));
        }

        @Override
        public String receiveGetBodyString(String path, String encoding) throws IOException, JudgeServiceException {
            return dequeBody(q, RecordingHttpClient.toGetResultKey(path, encoding));
        }

        private String dequeBody(final Queue<Pair<String, String>> q, String key) {
            AssertStatus.assertTrue(!q.isEmpty(), "no more mock data: " + key);
            Pair<String, String> p = q.deque();
            if (!p.v1.equals(key))
                throw new RuntimeException("invalid request.  next data is " + p.v1 + " but requested " + key);
            return p.v2;
        }
    };
}
Example 69
Project: khs-sherpa-master  File: StringParamParser.java View source code
private String applyEncoding(String value, String format) {
    String result = value;
    if (format != null) {
        if (format.equals(Encode.XML)) {
            result = StringEscapeUtils.escapeXml(value);
        } else if (format.equals(Encode.HTML)) {
            result = StringEscapeUtils.escapeHtml4(value);
        } else if (format.equals(Encode.CSV)) {
            result = StringEscapeUtils.escapeCsv(value);
        }
    }
    return result;
}
Example 70
Project: liferay-ide-master  File: LiferayPortletNameValidationService.java View source code
@Override
protected Status compute() {
    final Element modelElement = context(Element.class);
    if (!modelElement.disposed()) {
        liferayPortletName = (String) modelElement.property(context(ValueProperty.class)).content();
        final IProject project = modelElement.adapt(IProject.class);
        String[] portletNames = new PortletDescriptorHelper(project).getAllPortletNames();
        if (portletNames != null) {
            for (String portletName : portletNames) {
                if (portletName.equals(liferayPortletName)) {
                    return Status.createOkStatus();
                }
            }
        }
    }
    return Status.createErrorStatus(Resources.bind(StringEscapeUtils.unescapeJava(Resources.portletNameInvalid), new Object[] { liferayPortletName }));
}
Example 71
Project: mayfly-master  File: TimestampDataType.java View source code
TimestampCell stringToDate(String text, Location location) {
    try {
        LocalDateTime stamp = parseTimestamp(text);
        if (stamp != null) {
            return new TimestampCell(stamp);
        } else {
            LocalDate date = DateDataType.parseDate(text);
            if (date != null) {
                LocalDateTime stampFromDate = new LocalDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), 0, 0, 0, 000);
                return new TimestampCell(stampFromDate);
            }
        }
        throw new MayflyException("'" + StringEscapeUtils.escapeSql(text) + "' is not in format yyyy-mm-dd hh:mm:ss", location);
    } catch (IllegalFieldValueException e) {
        throw new MayflyException(e.getMessage(), location);
    }
}
Example 72
Project: mpd-2014-i41n-master  File: DealerStudentMapper.java View source code
public Student mapToStudent(String line) {
    if (previous != line)
        throw new IllegalArgumentException("This mapper should be used in a stream with the hasStudentInfo as the previous filter funcion");
    int grade = tokens.length >= 4 ? Integer.parseInt(tokens[3]) : 10;
    tokens[2] = StringEscapeUtils.unescapeHtml4(tokens[2]);
    return new Student(Integer.parseInt(tokens[0]), tokens[2], grade);
}
Example 73
Project: MyCC98-master  File: PmListViewAdapter.java View source code
/**
	 * 
	 * @param position
	 * @param itemView
	 */
private void fillDataIntoView(int position, ListItemView itemView) {
    // fill data into itemView
    itemView.senderName.setText(StringEscapeUtils.unescapeHtml4(items.get(position).getSender()));
    itemView.topic.setText(StringEscapeUtils.unescapeHtml4(items.get(position).getTopic()));
    itemView.time.setText(items.get(position).getSendTime());
    if (items.get(position).isNew()) {
        itemView.topic.setTextColor(context.getResources().getColorStateList(R.color.pm_title_unread));
    } else {
        itemView.topic.setTextColor(context.getResources().getColorStateList(R.color.post_text));
    }
}
Example 74
Project: oerworldmap-master  File: I18n.java View source code
public Result get() {
    Map<String, Object> i18n = new HashMap<>();
    Map<String, String> messages = new HashMap<>();
    ResourceBundle messageBundle = ResourceBundle.getBundle("messages", getLocale());
    for (String key : Collections.list(ResourceBundle.getBundle("messages", getLocale()).getKeys())) {
        try {
            String message = StringEscapeUtils.unescapeJava(new String(messageBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8"));
            messages.put(key, message);
        } catch (UnsupportedEncodingException e) {
            messages.put(key, messageBundle.getString(key));
        }
    }
    i18n.put("messages", messages);
    i18n.put("countries", Countries.map(getLocale()));
    i18n.put("languages", Languages.map(getLocale()));
    String countryMap = new ObjectMapper().convertValue(i18n, JsonNode.class).toString();
    return ok("window.i18nStrings = ".concat(countryMap)).as("application/javascript");
}
Example 75
Project: openemm-master  File: EventHandler.java View source code
@Override
public Object methodException(Class aClass, String method, Exception e) throws Exception {
    String error = "an " + e.getClass().getName() + " was thrown by the " + method + " method of the " + aClass.getName() + " class [" + StringEscapeUtils.escapeHtml(e.getMessage().split("\n")[0]) + "]";
    errors.add(error, new ActionMessage("Method exception: " + error));
    return error;
}
Example 76
Project: openwayback-master  File: JsonWriter.java View source code
@Override
public int writeLine(CDXLine line) {
    if (firstLine) {
        if (writeHeader) {
            writeHeader(line.getNames());
            writer.println(',');
        }
        firstLine = false;
    } else {
        writer.println(',');
    }
    writer.print('[');
    boolean firstField = true;
    for (int i = 0; i < line.getNumFields(); i++) {
        String field = line.getField(i);
        if (firstField) {
            writer.print('\"');
            firstField = false;
        } else {
            writer.print("\", \"");
        }
        writer.print(StringEscapeUtils.escapeJava(field));
    }
    if (!firstField) {
        writer.print('\"');
    }
    writer.print(']');
    return 1;
}
Example 77
Project: paoding-rose-master  File: HttpErrorInstruction.java View source code
@Override
public void doRender(Invocation inv) throws Exception {
    String message = resolvePlaceHolder(this.message, inv);
    //输出到页�之�对HTML转义,防止XSS注入
    message = StringEscapeUtils.escapeHtml(message);
    if (StringUtils.isEmpty(message)) {
        inv.getResponse().sendError(code);
    } else {
        inv.getResponse().sendError(code, message);
    }
}
Example 78
Project: pbox-master  File: LocalizedNameDirective.java View source code
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    if (!params.containsKey("of")) {
        throw new TemplateModelException("LocalizedNameDirective directive expects 'of'.");
    }
    if (params.size() != 1) {
        throw new TemplateModelException("TeamDirective directive expects the only parameter named 'of'.");
    }
    Object obj = DeepUnwrap.unwrap((TemplateModel) params.get("of"));
    if (obj instanceof Localized) {
        Localized localized = (Localized) obj;
        String name;
        if (LocaleUtil.isRussian(ApplicationContext.getInstance().getLocale())) {
            name = StringUtil.isEmpty(localized.getRussianName()) ? localized.getEnglishName() : localized.getRussianName();
        } else {
            name = StringUtil.isEmpty(localized.getEnglishName()) ? localized.getRussianName() : localized.getEnglishName();
        }
        name = StringEscapeUtils.escapeHtml(name);
        name = Patterns.LINE_BREAK_PATTERN.matcher(name).replaceAll("<br/>");
        env.getOut().write(name);
    }
}
Example 79
Project: Piggydb-master  File: EscapeHtmlFilter.java View source code
public Object referenceInsert(String reference, Object value) {
    if (value == null) {
        return "";
    }
    if (value instanceof Inescapable) {
        return value;
    }
    for (Pattern pattern : this.inescapablePatterns) {
        if (ThreadLocalCache.get(Perl5Matcher.class).contains(reference, pattern)) {
            return value;
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("escaping reference: " + reference);
    return StringEscapeUtils.escapeHtml(value.toString());
}
Example 80
Project: PM-master  File: CSVRenderer.java View source code
@Override
public String render(Iterator<Match> matches) {
    StringBuilder csv = new StringBuilder(1000);
    if (!lineCountPerFile) {
        csv.append("lines").append(separator);
    }
    csv.append("tokens").append(separator).append("occurrences").append(PMD.EOL);
    while (matches.hasNext()) {
        Match match = matches.next();
        if (!lineCountPerFile) {
            csv.append(match.getLineCount()).append(separator);
        }
        csv.append(match.getTokenCount()).append(separator).append(match.getMarkCount()).append(separator);
        for (Iterator<Mark> marks = match.iterator(); marks.hasNext(); ) {
            Mark mark = marks.next();
            csv.append(mark.getBeginLine()).append(separator);
            if (lineCountPerFile) {
                csv.append(mark.getLineCount()).append(separator);
            }
            csv.append(StringEscapeUtils.escapeCsv(mark.getFilename()));
            if (marks.hasNext()) {
                csv.append(separator);
            }
        }
        csv.append(PMD.EOL);
    }
    return csv.toString();
}
Example 81
Project: pmd-master  File: CSVRenderer.java View source code
@Override
public String render(Iterator<Match> matches) {
    StringBuilder csv = new StringBuilder(1000);
    if (!lineCountPerFile) {
        csv.append("lines").append(separator);
    }
    csv.append("tokens").append(separator).append("occurrences").append(PMD.EOL);
    while (matches.hasNext()) {
        Match match = matches.next();
        if (!lineCountPerFile) {
            csv.append(match.getLineCount()).append(separator);
        }
        csv.append(match.getTokenCount()).append(separator).append(match.getMarkCount()).append(separator);
        for (Iterator<Mark> marks = match.iterator(); marks.hasNext(); ) {
            Mark mark = marks.next();
            csv.append(mark.getBeginLine()).append(separator);
            if (lineCountPerFile) {
                csv.append(mark.getLineCount()).append(separator);
            }
            csv.append(StringEscapeUtils.escapeCsv(mark.getFilename()));
            if (marks.hasNext()) {
                csv.append(separator);
            }
        }
        csv.append(PMD.EOL);
    }
    return csv.toString();
}
Example 82
Project: proctor-webapp-library-master  File: FormatDefinitionRevisionDisplayTagHandler.java View source code
public String formatRevisionDisplay(final Revision revision) {
    final String defaultFormattedRevision = revision.getAuthor() + " @ " + revision.getDate() + " (" + revision.getRevision() + ")";
    final ServletContext servletContext = pageContext.getServletContext();
    final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    try {
        final Map<String, DefinitionRevisionDisplayFormatter> formatterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, DefinitionRevisionDisplayFormatter.class);
        if (formatterBeans.isEmpty()) {
            //No bean found, which is acceptable.
            return StringEscapeUtils.escapeHtml(defaultFormattedRevision);
        } else if (formatterBeans.size() == 1) {
            DefinitionRevisionDisplayFormatter formatter = formatterBeans.values().iterator().next();
            return formatter.formatRevision(revision);
        } else {
            throw new IllegalArgumentException("Multiple beans of type " + DefinitionRevisionDisplayFormatter.class.getSimpleName() + " found, expected 0 or 1.");
        }
    } catch (Exception e) {
        LOGGER.error("An error occurred when retrieving revision url.", e);
        return defaultFormattedRevision;
    }
}
Example 83
Project: ProjectAres-master  File: TextInspector.java View source code
@Override
public String scalar(Object value, Inspection options) {
    if (options.quote()) {
        if (value instanceof Character) {
            final char c = (char) value;
            switch(c) {
                case '\'':
                    return "'\\''";
                case '"':
                    return "'\"'";
                default:
                    return "'" + StringEscapeUtils.escapeJava(String.valueOf(c)) + "'";
            }
        } else if (value instanceof String) {
            return "\"" + StringEscapeUtils.escapeJava((String) value) + "\"";
        }
    }
    if (value instanceof Class) {
        // Short class names are usually enough
        return ((Class) value).getSimpleName();
    }
    // everything else
    return String.valueOf(value);
}
Example 84
Project: RoyalBot-master  File: ChuckCommand.java View source code
@Override
public void onCommand(GenericMessageEvent event, CallInfo callInfo, String[] args) {
    final String url;
    try {
        url = "http://api.icndb.com/jokes/random" + ((args.length > 0) ? "?limitTo=[" + URLEncoder.encode(args[0], "UTF-8") + "]" : "");
    } catch (UnsupportedEncodingException ex) {
        notice(event, "Couldn't encode in UTF-8.");
        return;
    }
    JsonNode jn;
    try {
        jn = om.readTree(BotUtils.getContent(url));
    } catch (Exception ex) {
        notice(event, "Invalid category, probably.");
        return;
    }
    String joke = jn.path("value").path("joke").asText();
    if (joke.isEmpty()) {
        notice(event, "Couldn't find a joke!");
        return;
    }
    event.respond(StringEscapeUtils.unescapeHtml4(joke));
}
Example 85
Project: selenese-runner-java-master  File: DumpEnvTest.java View source code
private void printEntry(String key, String value, int indent) {
    indent(indent);
    out.printf("%s=[", key);
    if (key.endsWith(".class.path")) {
        for (String path : value.split(File.pathSeparator)) {
            out.print('\n');
            indent(indent + 2);
            out.print(path);
        }
        out.print('\n');
        indent(indent);
        out.print("]\n");
    } else {
        out.printf("[%s]\n", StringEscapeUtils.escapeJava(value));
    }
}
Example 86
Project: shifter-plugin-master  File: StringHtmlEncodable.java View source code
/**
     * Shift to HTML encoded/decoded variant of given string
     *
     * @param  word     word to be shifted
     * @return String
     */
public static String getShifted(String word) {
    Integer strLenOriginal = word.length();
    String decoded = StringEscapeUtils.unescapeHtml(word);
    Integer strLenDecoded = decoded.length();
    if (!strLenOriginal.equals(strLenDecoded)) {
        return decoded;
    }
    String encoded = StringEscapeUtils.escapeHtml(word);
    Integer strLenEncoded = encoded.length();
    return !strLenOriginal.equals(strLenEncoded) ? encoded : word;
}
Example 87
Project: Shindig-master  File: UserPrefSubstituter.java View source code
public static void addSubstitutions(Substitutions substituter, GadgetSpec spec, UserPrefs values) {
    for (UserPref pref : spec.getUserPrefs()) {
        String name = pref.getName();
        String value = values.getPref(name);
        if (value == null) {
            value = pref.getDefaultValue();
            if (value == null) {
                value = "";
            }
        }
        substituter.addSubstitution(Substitutions.Type.USER_PREF, name, StringEscapeUtils.escapeHtml(value));
    }
}
Example 88
Project: SmartHome-master  File: FrameRenderer.java View source code
/**
     * {@inheritDoc}
     */
@Override
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException {
    String snippet = getSnippet("frame");
    snippet = StringUtils.replace(snippet, "%label%", StringEscapeUtils.escapeHtml(itemUIRegistry.getLabel(w)));
    // Process the color tags
    snippet = processColor(w, snippet);
    sb.append(snippet);
    return itemUIRegistry.getChildren((Frame) w);
}
Example 89
Project: spacewalk-master  File: CatalinaAction.java View source code
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) {
    String catalinaBase = System.getProperty("catalina.base");
    String contents = FileUtils.getTailOfFile(catalinaBase + "/logs/catalina.out", 1000);
    contents = StringEscapeUtils.escapeHtml(contents);
    request.setAttribute("contents", contents);
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
Example 90
Project: structr-master  File: EscapeJsonFunction.java View source code
@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (!arrayHasMinLengthAndAllElementsNotNull(sources, 1)) {
            return null;
        }
        return StringEscapeUtils.escapeJson(sources[0].toString());
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Example 91
Project: swf-all-master  File: FileUploadView.java View source code
protected Control createLoadForm() {
    Table table = new Table();
    Row row = table.createRow();
    FileTextBox ftb = new FileTextBox();
    ftb.setName("datafile");
    row.createColumn().addControl(ftb);
    row.createColumn().addControl(new Submit("Load"));
    Form loadForm = new Form();
    loadForm.setMethod(SubmitMethod.POST);
    loadForm.setProperty("enctype", "multipart/form-data");
    String action = StringEscapeUtils.escapeHtml4(getPath().getOriginalRequestUrl());
    loadForm.setAction(action);
    loadForm.addControl(table);
    return loadForm;
}
Example 92
Project: TadpoleForDBTools-master  File: ZipUtils.java View source code
public String map(String name) {
    try {
        if (!StringUtils.equals(name, StringEscapeUtils.escapeJava(name))) {
            name = "download_files" + StringUtils.substring(name, StringUtils.lastIndexOf(name, '.'));
        }
        name = new String(name.getBytes(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.error("zip pack", e);
    }
    return name;
}
Example 93
Project: trident-ml-master  File: TwitterTokenizer.java View source code
protected String preprocess(String tweet) {
    // Remove urls
    tweet = tweet.replaceAll(URL_REGEX, "");
    // Remove @username
    tweet = tweet.replaceAll("@([^\\s]+)", "");
    // Remove character repetition
    tweet = tweet.replaceAll(CONSECUTIVE_CHARS, "$1");
    // Remove words starting with a number
    tweet = tweet.replaceAll(STARTS_WITH_NUMBER, "");
    // Escape HTML
    tweet = tweet.replaceAll("&", "&");
    tweet = StringEscapeUtils.unescapeHtml(tweet);
    return tweet;
}
Example 94
Project: uncc2014watsonsim-master  File: RedirectSynonyms.java View source code
@Override
public List<Answer> question(Question q, List<Answer> answers) {
    // For logging 
    int synonym_count = 0;
    List<Answer> new_answers = new ArrayList<Answer>();
    for (Answer a : answers) {
        try {
            s.setString(1, a.text);
            ResultSet results = s.executeQuery();
            while (results.next()) {
                synonym_count++;
                Answer new_answer = new Answer(new ArrayList<>(a.passages), a.scores.clone(), StringEscapeUtils.unescapeXml(results.getString("source")));
                a.scores.put("IS_WIKI_REDIRECT", 1.0);
                new_answers.add(new_answer);
            }
        } catch (SQLException e) {
            return answers;
        }
    }
    log.info("Found " + synonym_count + " synonyms for " + answers.size() + " candidate answers using Wikipedia redirects.");
    return new_answers;
}
Example 95
Project: webpie-master  File: JsonCatchAllFilter.java View source code
@Override
protected byte[] translateClientError(ClientDataError t) {
    String escapeJson = StringEscapeUtils.escapeJson(t.getMessage());
    JsonError error = new JsonError();
    error.setError("400 bad request: " + escapeJson);
    error.setCode(0);
    try {
        return mapper.writeValueAsBytes(error);
    } catch (JsonGenerationException e) {
        throw new RuntimeException(e);
    } catch (JsonMappingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 96
Project: tap-plugin-master  File: DiagnosticUtil.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void createDiagnosticTableRecursively(String tapFile, String parentKey, Map<String, Object> diagnostic, StringBuilder sb, int depth) {
    sb.append(INNER_TABLE_HEADER);
    RENDER_TYPE renderType = getMapEntriesRenderType(diagnostic);
    if (renderType == RENDER_TYPE.IMAGE) {
        for (Entry<String, Object> entry : diagnostic.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            sb.append("<tr>");
            for (int i = 0; i < depth; ++i) {
                sb.append("<td width='5%' class='hidden'> </td>");
            }
            sb.append("<td style=\"width: auto;\">" + key + "</td>");
            if (key.equals("File-Content")) {
                String fileName = "attachment";
                Object o = diagnostic.get("File-Name");
                if (o != null && o instanceof String) {
                    fileName = (String) o;
                }
                String downloadKey = fileName;
                if (parentKey != null) {
                    if (depth > 3 && !parentKey.trim().equalsIgnoreCase("files") && !parentKey.trim().equalsIgnoreCase("extensions")) {
                        downloadKey = parentKey;
                    }
                }
                sb.append("<td><a href='downloadAttachment?f=" + tapFile + "&key=" + downloadKey + "'>" + fileName + "</a></td>");
            } else {
                sb.append("<td><pre>" + org.apache.commons.lang.StringEscapeUtils.escapeHtml(value.toString()) + "</pre></td>");
            }
            sb.append("</tr>");
        }
    } else {
        for (Entry<String, Object> entry : diagnostic.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            sb.append("<tr>");
            for (int i = 0; i < depth; ++i) {
                sb.append("<td width='5%' class='hidden'> </td>");
            }
            sb.append("<td style=\"width: auto;\">" + key + "</td>");
            if (value instanceof java.util.Map) {
                sb.append("<td> </td>");
                createDiagnosticTableRecursively(tapFile, key, (java.util.Map) value, sb, (depth + 1));
            } else {
                sb.append("<td><pre>" + org.apache.commons.lang.StringEscapeUtils.escapeHtml(value.toString()) + "</pre></td>");
            }
            sb.append("</tr>");
        }
    }
    sb.append(INNER_TABLE_FOOTER);
}
Example 97
Project: agile-itsm-master  File: HTMLSelect.java View source code
public void addOptions(Collection colOptions, String namePropertyValue, String namePropertyText, String valueSelected) throws Exception {
    if (colOptions == null)
        return;
    if (namePropertyValue == null)
        return;
    if (namePropertyText == null)
        return;
    Object obj;
    Object value, text;
    int i = iIndice;
    for (Iterator it = colOptions.iterator(); it.hasNext(); ) {
        obj = it.next();
        value = CitAjaxReflexao.getPropertyValue(obj, namePropertyValue);
        text = CitAjaxReflexao.getPropertyValue(obj, namePropertyText);
        if (value == null) {
            value = "";
        }
        if (text == null) {
            text = "";
        }
        this.addOption(value.toString(), StringEscapeUtils.escapeJavaScript(text.toString()));
        if (valueSelected != null) {
            if (valueSelected.equalsIgnoreCase(value.toString())) {
                this.setSelectedIndex(i);
            }
        }
        i++;
    }
}
Example 98
Project: apropos-master  File: DownloadPropertiesServlet.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    if (StringUtils.isBlank(name)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing package name!");
        return;
    }
    PropertyPackage propertyPackage = PropertiesManager.getPropertyPackage(name.trim());
    StringEscapeUtils.escapeHtml(name);
    if (propertyPackage == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Property package called " + StringEscapeUtils.escapeHtml(name) + " was not found!");
        return;
    }
    String type = req.getParameter("type");
    if (StringUtils.isBlank(type)) {
        type = "properties";
    }
    if (type.toLowerCase().equals("properties")) {
        resp.setContentType("text/plain; charset=ASCI");
        propertyPackage.asProperties().store(resp.getOutputStream(), "Property file obtained from " + req.getLocalName());
    } else if (type.toLowerCase().equals("xml")) {
        resp.setContentType("text/xml; charset=UTF-8");
        propertyPackage.asProperties().storeToXML(resp.getOutputStream(), "Property file obtained from " + req.getRequestURI());
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported type: " + StringEscapeUtils.escapeHtml(type) + " !");
        return;
    }
}
Example 99
Project: arkref-master  File: WriteEntityXml.java View source code
public static void go(EntityGraph eg, PrintWriter pw) throws FileNotFoundException {
    pw.printf("<entities>\n");
    List<Entity> ents = eg.sortedEntities();
    for (Entity e : ents) {
        pw.printf("<entity id=\"%s\">\n", e.id);
        for (Mention m : e.sortedMentions()) {
            pw.printf("  <mention ");
            pw.printf(" id=\"%s\"", m.ID());
            Sentence s = m.getSentence();
            pw.printf(" sentence=\"%s\"", s.ID());
            pw.printf(">\n");
            if (m.node() != null) {
                pw.printf("    <tokens>%s</tokens>\n", StringEscapeUtils.escapeXml(m.node().yield().toString()));
            }
            pw.printf("  </mention>\n");
        }
        pw.printf("</entity>\n");
    }
    pw.printf("</entities>\n");
    pw.close();
}
Example 100
Project: axis2-java-master  File: XMPPClientSidePacketListener.java View source code
/**
	 * This method will be triggered, when a message is arrived at client side
	 */
public void processPacket(Packet packet) {
    Message message = (Message) packet;
    String xml = StringEscapeUtils.unescapeXml(message.getBody());
    log.info("Client received message : " + xml);
    this.responseReceived = true;
    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    messageContext.setProperty(MessageContext.TRANSPORT_IN, inputStream);
}
Example 101
Project: btpka3.github.com-master  File: Test123.java View source code
public static void testHtmlSanitizer() {
    StringBuilder buf = new StringBuilder();
    HtmlStreamRenderer renderer = HtmlStreamRenderer.create(buf, // Receives notifications on a failure to write to the output.
    new Handler<IOException>() {

        public void handle(IOException ex) {
            // System.out suppresses IOExceptions
            Throwables.propagate(ex);
        }
    }, // truly bizarre inputs.
    new Handler<String>() {

        public void handle(String x) {
            throw new AssertionError(x);
        }
    });
    HtmlSanitizer.sanitize(drityInput, EbayPolicyExample.POLICY_DEFINITION.apply(renderer));
    System.out.println(buf);
    System.out.println(StringEscapeUtils.unescapeHtml4(buf.toString()));
}