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: 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 2
Project: dk-master  File: SendSMSService.java View source code
/**
	 * 获取用户列表
	 * @param pageBean
	 * @param userName
	 * @param realName
	 * @throws SQLException
	 * @throws DataException
	 */
public void queryUserPage(PageBean<Map<String, Object>> pageBean, String userName, String realName, String ids) throws SQLException, DataException {
    Connection conn = connectionManager.getConnection();
    StringBuffer condition = new StringBuffer();
    if (StringUtils.isNotBlank(userName)) {
        condition.append("and username LIKE '%");
        condition.append(StringEscapeUtils.escapeSql(userName));
        condition.append("%'");
    }
    if (StringUtils.isNotBlank(realName)) {
        condition.append("and realname LIKE '%");
        condition.append(StringEscapeUtils.escapeSql(realName));
        condition.append("%'");
    }
    if (StringUtils.isNotBlank(ids)) {
        String idStr = StringEscapeUtils.escapeSql("'" + ids + "'");
        String idSQL = "-2";
        idStr = idStr.replaceAll("'", "");
        String[] array = idStr.split(",");
        for (int n = 0; n <= array.length - 1; n++) {
            idSQL += "," + array[n];
        }
        condition.append("and id in(");
        condition.append(idSQL);
        condition.append(")");
    }
    try {
        dataPage(conn, pageBean, "v_t_user_amountofrecords", "*", "", condition.toString());
    } catch (SQLException e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } catch (DataException e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } finally {
        conn.close();
    }
}
Example 3
Project: liferay-ide-master  File: LocaleBundleValidationService.java View source code
public Status compute() {
    final Element modelElement = context(Element.class);
    if (!modelElement.disposed() && modelElement instanceof SupportedLocales) {
        final IProject project = modelElement.adapt(IProject.class);
        final Portlet portlet = modelElement.nearest(Portlet.class);
        final IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
        final IClasspathEntry[] cpEntries = CoreUtil.getClasspathEntries(project);
        if (cpEntries != null) {
            final String locale = modelElement.property(context(ValueProperty.class)).text(false);
            final Value<Path> resourceBundle = portlet.getResourceBundle();
            if (locale == null) {
                return Status.createErrorStatus(Resources.localeMustNotEmpty);
            } else {
                final String bundleName = resourceBundle.text();
                if (resourceBundle != null && bundleName != null) {
                    final String localeString = PortletUtil.localeString(locale);
                    final String ioFileName = PortletUtil.convertJavaToIoFileName(bundleName, RB_FILE_EXTENSION, localeString);
                    for (IClasspathEntry iClasspathEntry : cpEntries) {
                        if (IClasspathEntry.CPE_SOURCE == iClasspathEntry.getEntryKind()) {
                            IPath entryPath = wroot.getFolder(iClasspathEntry.getPath()).getLocation();
                            entryPath = entryPath.append(ioFileName);
                            IFile resourceBundleFile = wroot.getFileForLocation(entryPath);
                            if (resourceBundleFile != null && resourceBundleFile.exists()) {
                                return Status.createOkStatus();
                            } else {
                                return Status.createWarningStatus(Resources.bind(StringEscapeUtils.unescapeJava(Resources.noResourceBundle), new Object[] { locale, bundleName, localeString }));
                            }
                        }
                    }
                }
            }
        }
    }
    return Status.createOkStatus();
}
Example 4
Project: jeboorker-master  File: CoverpageBookProcessor.java View source code
private String createCoverpageHtml(String title, String imageHref) {
    return "" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "\t<head>\n" + "\t\t<title>Cover</title>\n" + "\t\t<style type=\"text/css\"> img { max-width: 100%; } </style>\n" + "\t</head>\n" + "\t<body>\n" + "\t\t<div id=\"cover-image\">\n" + "\t\t\t<img src=\"" + StringEscapeUtils.escapeHtml(imageHref) + "\" alt=\"" + StringEscapeUtils.escapeHtml(title) + "\"/>\n" + "\t\t</div>\n" + "\t</body>\n" + "</html>\n";
}
Example 5
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 6
Project: OpenClinica-master  File: RssReaderServlet.java View source code
String feedHtml(SyndFeed feed) {
    HtmlBuilder htmlBuilder = new HtmlBuilder();
    htmlBuilder.h1().close().append(resword.getString("news")).h1End().ul().close();
    List<SyndEntryImpl> theFeeds = feed.getEntries();
    for (int i = 0; i < (theFeeds.size() >= 4 ? 4 : theFeeds.size()); i++) {
        SyndEntryImpl syndFeed = theFeeds.get(i);
        String description = null;
        if (syndFeed.getDescription().getValue().length() > 50) {
            Integer k = 50;
            while (syndFeed.getDescription().getValue().charAt(k) != ' ') {
                k--;
            }
            description = syndFeed.getDescription().getValue().substring(0, k) + " ...";
        } else {
            description = syndFeed.getDescription().getValue();
        }
        SimpleDateFormat sdf = new SimpleDateFormat(resformat.getString("mid_date_format"));
        String theDate = sdf.format(syndFeed.getPublishedDate());
        htmlBuilder.li().close().a().href(syndFeed.getLink()).append(" target=\"_blank\"").close().append(theDate + " - " + StringEscapeUtils.escapeHtml(syndFeed.getTitle()) + " - " + description).aEnd().liEnd();
    }
    if (rssMore != null && rssMore.length() > 0) {
        return htmlBuilder.ulEnd().a().href(rssMore).append(" target=\"_blank\"").close().div().align("right").close().append(resword.getString("more") + "...").divEnd().aEnd().toString();
    } else {
        return htmlBuilder.ulEnd().toString();
    }
}
Example 7
Project: skalli-master  File: HtmlBuilder.java View source code
@SuppressWarnings("nls")
public HtmlBuilder appendMailToLink(String icon, String link, String caption) {
    appendIcon(icon);
    if (StringUtils.isNotBlank(link)) {
        String urlEncoded = null;
        try {
            urlEncoded = URLEncoder.encode(link, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        sb.append("<a href=\"mailto:").append(urlEncoded).append("\">");
        if (StringUtils.isBlank(caption)) {
            caption = link;
        }
        caption = StringEscapeUtils.escapeHtml(caption);
        sb.append(caption).append("</a>");
    }
    return this;
}
Example 8
Project: eclipse-integration-commons-master  File: BlogsProvider.java View source code
private String trimText(String s) {
    // Remove html encoded entities
    s = StringEscapeUtils.unescapeHtml(s);
    // Remove line breaks and tabs
    s = s.replace("\n", " ");
    s = s.replace("\t", " ");
    // Remove whitespace between text
    String[] vals = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String v : vals) {
        if (v.trim().length() > 0) {
            sb.append(v).append(" ");
        }
    }
    if (sb.length() > FEEDS_DESCRIPTION_MAX) {
        return sb.substring(0, findEndOfWord(sb, FEEDS_DESCRIPTION_MAX)) + " ...";
    // return sb.substring(0, FEEDS_DESCRIPTION_MAX) + " ...";
    }
    return sb.toString();
}
Example 9
Project: framework-master  File: MultipleValidationErrors.java View source code
@Override
protected void setup(VaadinRequest request) {
    BeanItem<PersonBeanWithValidationAnnotations> item = new BeanItem<>(new PersonBeanWithValidationAnnotations());
    final FieldGroup fieldGroup = new FieldGroup(item);
    bindTextField(item, fieldGroup, "First Name", "firstName");
    bindTextField(item, fieldGroup, "Last Name", "lastName");
    final Label validationErrors = new Label();
    validationErrors.setId("validationErrors");
    addComponent(validationErrors);
    addButton("Submit", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            validationErrors.setValue("");
            try {
                fieldGroup.commit();
            } catch (FieldGroup.CommitException e) {
                if (e.getCause() != null && e.getCause() instanceof Validator.InvalidValueException) {
                    validationErrors.setValue(StringEscapeUtils.unescapeHtml(AbstractErrorMessage.getErrorMessageForException(e.getCause()).getFormattedHtmlMessage()));
                }
            }
        }
    });
}
Example 10
Project: lucene-solr-master  File: LoadAdminUiServlet.java View source code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // security: SOLR-7966 - avoid clickjacking for admin interface
    response.addHeader("X-Frame-Options", "DENY");
    // This attribute is set by the SolrDispatchFilter
    String admin = request.getRequestURI().substring(request.getContextPath().length());
    CoreContainer cores = (CoreContainer) request.getAttribute("org.apache.solr.CoreContainer");
    InputStream in = getServletContext().getResourceAsStream(admin);
    Writer out = null;
    if (in != null && cores != null) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            // Protect container owned streams from being closed by us, see SOLR-8933
            out = new OutputStreamWriter(new CloseShieldOutputStream(response.getOutputStream()), StandardCharsets.UTF_8);
            String html = IOUtils.toString(in, "UTF-8");
            Package pack = SolrCore.class.getPackage();
            String[] search = new String[] { "${contextPath}", "${adminPath}", "${version}" };
            String[] replace = new String[] { StringEscapeUtils.escapeJavaScript(request.getContextPath()), StringEscapeUtils.escapeJavaScript(CommonParams.CORES_HANDLER_PATH), StringEscapeUtils.escapeJavaScript(pack.getSpecificationVersion()) };
            out.write(StringUtils.replaceEach(html, search, replace));
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } else {
        response.sendError(404);
    }
}
Example 11
Project: tdq-studio-se-master  File: SoundexFrequencyExplorer.java View source code
@Override
protected String getInstantiatedClause() {
    // get function which convert data into a pattern
    String function = getFunction();
    // colName.
    if (function != null && (DbmsLanguageFactory.isInfomix(this.dbmsLanguage.getDbmsName()) || DbmsLanguageFactory.isOracle(this.dbmsLanguage.getDbmsName()))) {
        function = columnName;
    }
    // ~11005
    // MOD mzhao bug 9740 2009-11-10
    String clause = entity.isLabelNull() || function == null ? columnName + dbmsLanguage.isNull() : dbmsLanguage.getSoundexPrefix() + //$NON-NLS-1$ 
    "(" + function + ")" + dbmsLanguage.equal() + dbmsLanguage.getSoundexPrefix() + "('" + StringEscapeUtils.escapeSql(entity.getKey().toString()) + //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
    "')";
    return clause;
}
Example 12
Project: Desktop-master  File: AddOnsController.java View source code
/** make the translations of this add-on known system-wide. */
public static void registerAddOnResources(final AddOnProperties addOn, final ResourceController resourceController) {
    HashSet<String> languages = new HashSet<String>();
    languages.add(resourceController.getLanguageCode());
    languages.add(resourceController.getDefaultLanguageCode());
    for (String language : languages) {
        final Map<String, String> resources = addOn.getTranslations().get(language);
        if (resources != null) {
            for (Entry<String, String> entry : resources.entrySet()) {
                if (entry.getValue().indexOf('\\') != -1) {
                    entry.setValue(StringEscapeUtils.unescapeJava(entry.getValue()));
                }
            }
            resourceController.addLanguageResources(language, addOptionPanelPrefix(resources, addOn.getName()));
            resourceController.addLanguageResources(language, resources);
        }
    }
}
Example 13
Project: warlock2-master  File: StormFrontElement.java View source code
public String toXML(String prefix, boolean prettyPrint, boolean includeChildren) {
    StringBuffer xml = new StringBuffer();
    xml.append(prefix + "<" + name);
    if (attributes.getList().size() > 0) {
        xml.append(" ");
        for (Iterator<StormFrontAttribute> iter = attributes.getList().iterator(); iter.hasNext(); ) {
            StormFrontAttribute attribute = iter.next();
            xml.append(attribute.getName());
            xml.append("=");
            xml.append("\"");
            xml.append(StringEscapeUtils.escapeXml(attribute.getValue()));
            xml.append("\"");
            if (iter.hasNext())
                xml.append(" ");
        }
    }
    boolean hasContent = false;
    if (elements.size() > 0 || getText().length() > 0) {
        hasContent = true;
        xml.append(">");
        if (prettyPrint)
            xml.append("\n");
    }
    if (elements.size() > 0) {
        if (includeChildren) {
            for (StormFrontElement element : elements) {
                xml.append(element.toXML(prettyPrint ? prefix + "  " : "", prettyPrint, true));
            }
        }
    }
    if (getText().length() > 0) {
        xml.append(StringEscapeUtils.escapeXml(getText()));
    }
    if (hasContent) {
        xml.append(/* FIXME can't do this because it gets passed on as content: prefix +*/
        "</" + name + ">");
        if (prettyPrint)
            xml.append("\n");
    } else {
        xml.append("/>");
        if (prettyPrint)
            xml.append("\n");
    }
    return xml.toString();
}
Example 14
Project: iaf-master  File: MessageStoreSender.java View source code
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
    if (sessionKeys != null) {
        List<String> list = new ArrayList<String>();
        list.add(StringEscapeUtils.escapeCsv(message));
        StringTokenizer tokenizer = new StringTokenizer(sessionKeys, ",");
        while (tokenizer.hasMoreElements()) {
            String sessionKey = (String) tokenizer.nextElement();
            list.add(StringEscapeUtils.escapeCsv((String) prc.getSession().get(sessionKey)));
        }
        StrBuilder sb = new StrBuilder();
        sb.appendWithSeparators(list, ",");
        message = sb.toString();
    }
    String messageId = prc.getSession().getMessageId();
    if (prc != null && paramList != null && paramList.findParameter("messageId") != null) {
        try {
            messageId = (String) prc.getValueMap(paramList).get("messageId");
        } catch (ParameterException e) {
            throw new SenderException("Could not resolve parameter messageId", e);
        }
    }
    return storeMessage(messageId, correlationID, new Date(), null, null, message);
}
Example 15
Project: HDP-2.2-Patched-master  File: ReconfigurationServlet.java View source code
/**
   * Print configuration options that can be changed.
   */
private void printConf(PrintWriter out, Reconfigurable reconf) {
    Configuration oldConf = reconf.getConf();
    Configuration newConf = new Configuration();
    Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(newConf, oldConf);
    boolean changeOK = true;
    out.println("<form action=\"\" method=\"post\">");
    out.println("<table border=\"1\">");
    out.println("<tr><th>Property</th><th>Old value</th>");
    out.println("<th>New value </th><th></th></tr>");
    for (ReconfigurationUtil.PropertyChange c : changes) {
        out.print("<tr><td>");
        if (!reconf.isPropertyReconfigurable(c.prop)) {
            out.print("<font color=\"red\">" + StringEscapeUtils.escapeHtml(c.prop) + "</font>");
            changeOK = false;
        } else {
            out.print(StringEscapeUtils.escapeHtml(c.prop));
            out.print("<input type=\"hidden\" name=\"" + StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" + StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
        }
        out.print("</td><td>" + (c.oldVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.oldVal)) + "</td><td>" + (c.newVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.newVal)) + "</td>");
        out.print("</tr>\n");
    }
    out.println("</table>");
    if (!changeOK) {
        out.println("<p><font color=\"red\">WARNING: properties marked red" + " will not be changed until the next restart.</font></p>");
    }
    out.println("<input type=\"submit\" value=\"Apply\" />");
    out.println("</form>");
}
Example 16
Project: hadoop-on-lustre2-master  File: ReconfigurationServlet.java View source code
/**
   * Print configuration options that can be changed.
   */
private void printConf(PrintWriter out, Reconfigurable reconf) {
    Configuration oldConf = reconf.getConf();
    Configuration newConf = new Configuration();
    Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(newConf, oldConf);
    boolean changeOK = true;
    out.println("<form action=\"\" method=\"post\">");
    out.println("<table border=\"1\">");
    out.println("<tr><th>Property</th><th>Old value</th>");
    out.println("<th>New value </th><th></th></tr>");
    for (ReconfigurationUtil.PropertyChange c : changes) {
        out.print("<tr><td>");
        if (!reconf.isPropertyReconfigurable(c.prop)) {
            out.print("<font color=\"red\">" + StringEscapeUtils.escapeHtml(c.prop) + "</font>");
            changeOK = false;
        } else {
            out.print(StringEscapeUtils.escapeHtml(c.prop));
            out.print("<input type=\"hidden\" name=\"" + StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" + StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
        }
        out.print("</td><td>" + (c.oldVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.oldVal)) + "</td><td>" + (c.newVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.newVal)) + "</td>");
        out.print("</tr>\n");
    }
    out.println("</table>");
    if (!changeOK) {
        out.println("<p><font color=\"red\">WARNING: properties marked red" + " will not be changed until the next restart.</font></p>");
    }
    out.println("<input type=\"submit\" value=\"Apply\" />");
    out.println("</form>");
}
Example 17
Project: WordPress-Android-master  File: StatsInsightsLatestPostSummaryFragment.java View source code
protected void updateUI() {
    super.updateUI();
    if (!isAdded() || !hasDataAvailable()) {
        return;
    }
    // check if there are posts "published" on the blog
    if (!mInsightsLatestPostModel.isLatestPostAvailable()) {
        // entire fragment is hidden.
        return;
    }
    TextView moduleTitle = (TextView) getView().findViewById(R.id.stats_module_title);
    moduleTitle.setOnClickListener(ViewsTabOnClickListener);
    moduleTitle.setTextColor(getResources().getColor(R.color.stats_link_text_color));
    // update the tabs and the text now
    LinearLayout ll = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.stats_insights_latest_post_item, (ViewGroup) mResultContainer.getRootView(), false);
    String trendLabel = getString(R.string.stats_insights_latest_post_trend);
    String sinceLabel = StatsUtils.getSinceLabel(getActivity(), mInsightsLatestPostModel.getPostDate()).toLowerCase();
    String postTitle = StringEscapeUtils.unescapeHtml(mInsightsLatestPostModel.getPostTitle());
    if (TextUtils.isEmpty(postTitle)) {
        postTitle = getString(R.string.stats_insights_latest_post_no_title);
    }
    final String trendLabelFormatted = String.format(trendLabel, sinceLabel, postTitle);
    int startIndex, endIndex;
    startIndex = trendLabelFormatted.indexOf(postTitle);
    endIndex = startIndex + postTitle.length() + 1;
    Spannable descriptionTextToSpan = new SpannableString(trendLabelFormatted);
    descriptionTextToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.stats_link_text_color)), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    TextView trendLabelTextField = (TextView) ll.findViewById(R.id.stats_post_trend_label);
    trendLabelTextField.setText(descriptionTextToSpan);
    trendLabelTextField.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            StatsUtils.openPostInReaderOrInAppWebview(getActivity(), mInsightsLatestPostModel.getBlogID(), String.valueOf(mInsightsLatestPostModel.getPostID()), StatsConstants.ITEM_TYPE_POST, mInsightsLatestPostModel.getPostURL());
        }
    });
    LinearLayout tabs = (LinearLayout) ll.findViewById(R.id.stats_latest_post_tabs);
    for (int i = 0; i < tabs.getChildCount(); i++) {
        LinearLayout currentTab = (LinearLayout) tabs.getChildAt(i);
        switch(i) {
            case 0:
                setupTab(currentTab, FormatUtils.formatDecimal(mInsightsLatestPostModel.getPostViewsCount()), StatsVisitorsAndViewsFragment.OverviewLabel.VIEWS);
                break;
            case 1:
                setupTab(currentTab, FormatUtils.formatDecimal(mInsightsLatestPostModel.getPostLikeCount()), StatsVisitorsAndViewsFragment.OverviewLabel.LIKES);
                break;
            case 2:
                setupTab(currentTab, FormatUtils.formatDecimal(mInsightsLatestPostModel.getPostCommentCount()), StatsVisitorsAndViewsFragment.OverviewLabel.COMMENTS);
                break;
        }
    }
    mResultContainer.addView(ll);
}
Example 18
Project: linshare-core-master  File: AntiSamyServiceImpl.java View source code
@Override
public String clean(String value) throws BusinessException {
    if (value == null)
        return null;
    try {
        CleanResults cr = new AntiSamy().scan(value, policy);
        if (cr.getNumberOfErrors() > 0)
            logger.warn("Striped invalid chracters in : " + value);
        return StringEscapeUtils.unescapeHtml(cr.getCleanHTML().trim());
    } catch (ScanException e) {
        throw new BusinessException(BusinessErrorCode.XSSFILTER_SCAN_FAILED, "Antisamy is not able to scan the field");
    } catch (PolicyException e) {
        throw new BusinessException(BusinessErrorCode.XSSFILTER_SCAN_FAILED, "Antisamy is not able to scan the field");
    }
}
Example 19
Project: aipo-master  File: SendConfirmationEmail.java View source code
public void doPerform(RunData data) throws Exception {
    JetspeedUser user = JetspeedSecurity.getUser(data.getParameters().getString("username", ""));
    DynamicURI url = new DynamicURI(data).addPathInfo(JetspeedResources.PATH_TEMPLATE_KEY, "ConfirmRegistration").addPathInfo("username", user.getUserName()).addPathInfo("secretkey", user.getConfirmed()).addPathInfo("password", user.getPassword());
    try {
        //build body via template
        StringWriter email_body = new StringWriter();
        Context emailContext = TurbineVelocity.getContext(data);
        SimpleEmail se = new SimpleEmail();
        String charset = JetspeedResources.getString("newuser.notification.charset", "iso-8859-1");
        se.setCharset(charset);
        emailContext.put("firstname", StringEscapeUtils.unescapeHtml(user.getFirstName()));
        emailContext.put("lastname", StringEscapeUtils.unescapeHtml(user.getLastName()));
        emailContext.put("username", StringEscapeUtils.unescapeHtml(user.getUserName()));
        emailContext.put("data", data);
        emailContext.put("user", user);
        emailContext.put("config", new JetspeedResources());
        emailContext.put("urltojetspeed", url);
        emailContext.put("email", se);
        String templateFile = JetspeedResources.getString("newuser.confirm.email.template");
        String templatePath = TemplateLocator.locateEmailTemplate(data, templateFile);
        TurbineVelocity.handleRequest(emailContext, templatePath, email_body);
        se.setMsg(email_body.toString());
        Properties props = System.getProperties();
        String mailServerMachine = JetspeedResources.getString("mail.server");
        props.put("mail.host", mailServerMachine);
        props.put("mail.smtp.host", mailServerMachine);
        se.send();
        data.setMessage(Localization.getString(data, "SENDCONFIRMATIONEMAIL_SENT"));
    } catch (Exception e) {
        String errorTitle = Localization.getString("SENDCONFIRMATIONEMAIL_ERROR");
        String errorMessage = errorTitle + e.getMessage();
        logger.error(errorMessage, e);
        data.setMessage(errorTitle + errorMessage);
    }
}
Example 20
Project: FireflowEngine20-master  File: GetProcessDefsHandler.java View source code
protected void outputXmlWithinHtml(String processXml, HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
    HttpServletRequest request = req;
    String contextPath = request.getContextPath();
    if (contextPath == null)
        contextPath = "";
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("<!DOCTYPE html>\n").append("<html>\n").append("<head>\n").append("<script src=\"").append(contextPath).append(ClientWidgetBase.FIREFLOW_RESOURCE_SERVLET).append("/org/fireflow/webdesigner/resources/google-code-prettify/prettify.js\"></script>\n").append("<link rel=\"stylesheet\" href=\"").append(contextPath).append(ClientWidgetBase.FIREFLOW_RESOURCE_SERVLET).append("/org/fireflow/webdesigner/resources/google-code-prettify/prettify.css\"/>\n").append("<style>\n").append("body { margin: 0; padding: 0;font-size:12px }\n").append("pre { margin: 0 }\n").append("</style>\n").append("</head>\n").append("<body onload=\"prettyPrint();\">\n").append("<pre class=\"prettyprint lang-xml\">");
    String tmp = StringEscapeUtils.escapeXml(processXml);
    sbuf.append(tmp);
    sbuf.append("</pre>\n").append("</body>\n").append("</html>");
    // 设置contentType
    String encoding = Utils.findXmlCharset(processXml);
    resp.setContentType("text/html");
    resp.setCharacterEncoding(encoding);
    // 告诉浏览器不要缓存
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setIntHeader("Expires", -1);
    byte[] byteArr = sbuf.toString().getBytes(encoding);
    OutputStream outStream = resp.getOutputStream();
    outStream.write(byteArr);
}
Example 21
Project: raven-aws-emr-kissmetrics-mapreduce-parser-redshift-master  File: KissmetricsRowParser.java View source code
/***
	 * Used to parse, escape and enrich Kissmetircs Json records
	 * 
	 * @param rawJsonRow
	 * @param fileNameInputToMapper
	 * @return
	 */
public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper, String filePath) {
    String jsonString = "";
    boolean wasOctalParsingNeeded = false;
    try {
        System.setProperty("file.encoding", "UTF-8");
        s = rawJsonRow.toString();
        Charset charSet = Charset.forName("UTF-8");
        byte[] encoded = s.getBytes(charSet);
        decodedStrRaw = new String(encoded, charSet);
        // Test new Apache Lang3
        // decodedStr = StringEscapeUtils.unescapeJava(decodedStr);
        //Replace any remaining Octal encoded Characters
        decodedStrParsed = replaceOctalUft8Char(decodedStrRaw);
        if (decodedStrParsed.compareTo(decodedStrRaw) == 0) {
            wasOctalParsingNeeded = false;
        } else {
            wasOctalParsingNeeded = true;
        }
        if (decodedStrParsed != null && decodedStrParsed != "") {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed);
            // get email and user_id
            if (jsonObject.get("_p2") != null) {
                p2 = jsonObject.get("_p2").toString().toLowerCase();
                if (p2.contains("@")) {
                    jsonObject.put("user_email", p2);
                    jsonObject.put("user_email_back", p2);
                } else if (p2 != null && p2.length() > 0) {
                    jsonObject.put("user_km_id", p2);
                }
            }
            // get email and user_id
            if (jsonObject.get("_p") != null) {
                p = jsonObject.get("_p").toString().toLowerCase();
                if (p.contains("@")) {
                    jsonObject.put("user_email", p);
                    jsonObject.put("user_email_back", p);
                } else if (p != null && p.length() > 0) {
                    jsonObject.put("user_km_id", p);
                }
            }
            // Add Event
            if (jsonObject.get("_n") != null) {
                event = jsonObject.get("_n").toString();
                if (event != null) {
                    jsonObject.put("event", event);
                }
            }
            // add unix timestamp and datetime
            long currentDateTime = System.currentTimeMillis();
            Date currentDate = new Date(currentDateTime);
            if (jsonObject.get("_t") == null) {
                return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE));
            }
            long kmTimeDateMilliSeconds;
            long kmTimeDateMilliSecondsMobile;
            try {
                tTimestampValue = (String) jsonObject.get("_t").toString();
                //See if new record with server timestamp
                if (jsonObject.get("_server_timestamp") != null) {
                    serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString();
                } else {
                    serverTimestampValue = "0";
                }
                //Deal with mobile timedate cases
                if (jsonObject.get("_c") != null) {
                    if (serverTimestampValue.equals("0")) {
                        timestampValueOutput = tTimestampValue;
                        kmTimeDateMilliSecondsMobile = 0;
                    } else {
                        timestampValueOutput = serverTimestampValue;
                        mobileTimestampValueOutput = tTimestampValue;
                        jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput);
                        kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000;
                    }
                } else //Ignore server time
                {
                    //TODO Need a way to resolve mobile identify events
                    serverTimestampValue = "0";
                    timestampValueOutput = tTimestampValue;
                    kmTimeDateMilliSecondsMobile = 0;
                }
                jsonObject.put("km_timestamp", timestampValueOutput);
                kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000;
            } catch (Exception e) {
                return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE));
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(kmTimeDateMilliSeconds);
            String event_timedate = dateFormatter.format(calendar.getTime());
            jsonObject.put("event_timedate", event_timedate);
            if (kmTimeDateMilliSecondsMobile > 0) {
                calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile);
                String event_timedate_mobile = dateFormatter.format(calendar.getTime());
                jsonObject.put("event_timedate_mobile", event_timedate_mobile);
            }
            // add Map Reduce json_filename
            jsonObject.put("filename", fileNameInputToMapper);
            jsonString = jsonObject.toString();
            //Add bucket path
            jsonObject.put("bucket", filePath);
            jsonString = jsonObject.toString();
            return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW, wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED));
        }
    } catch (Exception e) {
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logger.error(errors.toString());
        logger.error("log - file " + fileNameInputToMapper);
        System.out.println("file " + fileNameInputToMapper);
        logger.error("log - row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("Error skipping row");
        logger.error("Log - Error skipping row");
    }
    return null;
}
Example 22
Project: yarn-comment-master  File: ReconfigurationServlet.java View source code
/**
   * Print configuration options that can be changed.
   */
private void printConf(PrintWriter out, Reconfigurable reconf) {
    Configuration oldConf = reconf.getConf();
    Configuration newConf = new Configuration();
    Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(newConf, oldConf);
    boolean changeOK = true;
    out.println("<form action=\"\" method=\"post\">");
    out.println("<table border=\"1\">");
    out.println("<tr><th>Property</th><th>Old value</th>");
    out.println("<th>New value </th><th></th></tr>");
    for (ReconfigurationUtil.PropertyChange c : changes) {
        out.print("<tr><td>");
        if (!reconf.isPropertyReconfigurable(c.prop)) {
            out.print("<font color=\"red\">" + StringEscapeUtils.escapeHtml(c.prop) + "</font>");
            changeOK = false;
        } else {
            out.print(StringEscapeUtils.escapeHtml(c.prop));
            out.print("<input type=\"hidden\" name=\"" + StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" + StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
        }
        out.print("</td><td>" + (c.oldVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.oldVal)) + "</td><td>" + (c.newVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.newVal)) + "</td>");
        out.print("</tr>\n");
    }
    out.println("</table>");
    if (!changeOK) {
        out.println("<p><font color=\"red\">WARNING: properties marked red" + " will not be changed until the next restart.</font></p>");
    }
    out.println("<input type=\"submit\" value=\"Apply\" />");
    out.println("</form>");
}
Example 23
Project: eGov-master  File: EGovExcelReadOnlyView.java View source code
/**
	 * Escape certain values that are not permitted in excel cells.
	 * @param rawValue the object value
	 * @return the escaped value
	 */
protected HSSFRichTextString escapeColumnValue(final Object rawValue) {
    if (rawValue == null) {
        return null;
    }
    String returnString = ObjectUtils.toString(rawValue);
    // escape the String to get the tabs, returns, newline explicit as \t \r \n
    returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));
    // remove tabs, insert four whitespaces instead
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", "    ");
    // remove the return, only newline valid in excel
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");
    // unescape so that \n gets back to newline
    returnString = StringEscapeUtils.unescapeJava(returnString);
    returnString = removeHtmlTagsAndSpaces(returnString);
    return new HSSFRichTextString(returnString);
}
Example 24
Project: hadoop-20-master  File: ReconfigurationServlet.java View source code
/**
   * Print configuration options that can be changed.
   */
private void printConf(PrintWriter out, Reconfigurable reconf) {
    Configuration oldConf = reconf.getConf();
    Configuration newConf = new Configuration();
    if (reconf instanceof ReconfigurableBase)
        ((ReconfigurableBase) reconf).preProcessConfiguration(newConf);
    Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(newConf, oldConf);
    boolean changeOK = true;
    out.println("<form action=\"\" method=\"post\">");
    out.println("<table border=\"1\">");
    out.println("<tr><th>Property</th><th>Old value</th>");
    out.println("<th>New value </th></tr>");
    for (ReconfigurationUtil.PropertyChange c : changes) {
        out.print("<tr><td>");
        if (!reconf.isPropertyReconfigurable(c.prop)) {
            out.print("<font color=\"red\">" + StringEscapeUtils.escapeHtml(c.prop) + "</font>");
            changeOK = false;
        } else {
            out.print(StringEscapeUtils.escapeHtml(c.prop));
            out.print("<input type=\"hidden\" name=\"" + StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" + StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
        }
        out.print("</td><td>" + (c.oldVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.oldVal)) + "</td><td>" + (c.newVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml(c.newVal)) + "</td>");
        out.print("</tr>\n");
    }
    out.println("</table>");
    if (!changeOK) {
        out.println("<p><font color=\"red\">WARNING: properties marked red" + " will not be changed until the next restart.</font></p>");
    }
    out.println("<input type=\"submit\" value=\"Apply\" />");
    out.println("</form>");
}
Example 25
Project: dataverse-master  File: RolePermissionFragment.java View source code
private void assignRole(RoleAssignee ra, DataverseRole r) {
    try {
        String privateUrlToken = null;
        commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken));
        JH.addMessage(FacesMessage.SEVERITY_INFO, "Role " + r.getName() + " assigned to " + ra.getDisplayInfo().getTitle() + " on " + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()));
    } catch (CommandException ex) {
        JH.addMessage(FacesMessage.SEVERITY_ERROR, "Can't assign role: " + ex.getMessage());
    }
}