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

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

Introduction

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

Prototype

public static final String escapeHtml4(final String input) 

Source Link

Document

Escapes the characters in a String using HTML entities.

For example:

"bread" & "butter"

becomes:

"bread" & "butter".

Usage

From source file:gg.pistol.sweeper.gui.component.DecoratedPanel.java

/**
 * Helper method to create a {@link JLabel} with word-wrapping.
 *//*www .ja  v  a 2s .  c  o m*/
protected JLabel createWordWrappingLabel(String text) {
    return new JLabel("<html>" + StringEscapeUtils.escapeHtml4(text) + "</html>");
}

From source file:com.nttec.everychan.chans.dobrochan.DobroModule.java

private PostModel mapPostModel(JSONObject json, String parentThread) {
    PostModel model = new PostModel();
    model.number = Long.toString(json.getLong("display_id"));
    model.parentThread = parentThread;/*from   w  w  w  .  ja v a 2 s .c  o  m*/
    model.comment = json.optString("message_html", "");
    if (TextUtils.isEmpty(model.comment)) {
        model.comment = RegexUtils
                .linkify(StringEscapeUtils.escapeHtml4(json.optString("message", "")).replace("\r\n", "<br />")
                        .replace("\n", "<br />").replaceAll("[_\\*][_\\*](.*?)[_\\*][_\\*]", "<b>$1</b>")
                        .replaceAll("[_\\*](.*?)[_\\*]", "<i>$1</i>")
                        .replaceAll("%%(.*?)%%", "<span class=\"spoiler\">$1</span>")
                        .replaceAll("`(.*?)`", "<tt>$1</tt>")
                        .replaceAll("&gt;&gt;(\\d+)\\b", "<a href=\"#i$1\">&gt;&gt;$1</a>")
                        .replaceAll("(^|<br />)(&gt;.*?)($|<br />)", "$1<span class=\"unkfunc\">$2</span>$3"). //<br />&gt;...<br />&gt;...
                        replaceAll("(^|<br />)(&gt;.*?)($|<br />)", "$1<span class=\"unkfunc\">$2</span>$3"));
    } else {
        model.comment = model.comment.replaceAll("<blockquote depth=\"\\d*\">",
                "<blockquote class=\"unkfunc\">");
    }
    model.subject = json.optString("subject", "");
    model.name = json.optString("name", "");
    try {
        model.timestamp = DATE_FORMAT.parse(json.getString("date")).getTime();
    } catch (Exception e) {
        Logger.e(TAG, e);
    }
    try {
        JSONArray files = json.getJSONArray("files");
        int filesLen = files.length();
        if (filesLen > 0) {
            AttachmentModel[] attachments = new AttachmentModel[filesLen];
            for (int i = 0; i < filesLen; ++i) {
                attachments[i] = mapAttachmentModel(files.getJSONObject(i));
            }
            model.attachments = attachments;
        }
    } catch (Exception e) {
        Logger.e(TAG, e);
    }
    return model;
}

From source file:com.netsteadfast.greenstep.bsc.service.logic.impl.OrganizationLogicServiceImpl.java

/**
 *  tree ?, json /*w  w w .j a  v  a  2s. c  o m*/
 * 
 * ??
 * {
 *       "identifier":"id",
 *       "label":"name",
 * 
 * ==================================================
 * ?? items 
 * ==================================================      
 * 
 *       "items":[
 *          ...............
 *       ]
 * ==================================================
 * 
 * }   
 * 
 * @param basePath
 * @param checkBox      ?checkBox
 * @param appendId      OID?,  1b2ac208-345c-4f93-92c5-4b26aead31d2;3ba52439-6756-45e8-8269-ae7b4fb6a3dc
 * @return
 * @throws ServiceException
 * @throws Exception
 */
@ServiceMethodAuthority(type = { ServiceMethodType.SELECT })
@Override
public List<Map<String, Object>> getTreeData(String basePath, boolean checkBox, String appendId)
        throws ServiceException, Exception {
    List<Map<String, Object>> items = new LinkedList<Map<String, Object>>();
    List<OrganizationVO> orgList = this.getOrganizationService().findForJoinParent();
    if (orgList == null || orgList.size() < 1) {
        return items;
    }
    for (OrganizationVO org : orgList) {
        // ORG-ID
        if (!(super.isBlank(org.getParId()) || BscConstants.ORGANIZATION_ZERO_ID.equals(org.getParId()))) {
            continue;
        }
        Map<String, Object> parentDataMap = new LinkedHashMap<String, Object>();
        parentDataMap.put("type", "parent");
        parentDataMap.put("name", (checkBox ? getCheckBoxHtmlContent(org, appendId) : "")
                + IconUtils.getMenuIcon(basePath, TREE_ICON_ID) + StringEscapeUtils.escapeHtml4(org.getName()));
        parentDataMap.put("id", org.getOid());
        parentDataMap.put("orgId", org.getOrgId());
        items.add(parentDataMap);
    }
    // ??
    for (int ix = 0; ix < items.size(); ix++) {
        Map<String, Object> parentDataMap = items.get(ix);
        String orgId = (String) parentDataMap.get("orgId");
        this.getTreeData(basePath, checkBox, appendId, parentDataMap, orgList, orgId);
    }
    return items;
}

From source file:com.dell.asm.asmcore.asmmanager.util.ServiceTemplateValidator.java

/**
 * Validates the storage components within a ServiceTemplate.
 * /*from  w ww .  j av  a  2 s  . co  m*/
 * @param svcTemplate the service template to be validated, with non-required options removed
 * @param inventoryContainsEM
 * @param checkForUniqueVolume true if volume names are to be checked for uniqueness, or false if that
 *      validation is to be skipped.
 * @param originalTemplate the service template to be validated, as it is stored in DB
 * @param existingComponents Skip volume validation for these components
 */
public void validateStorageComponentFields(ServiceTemplate svcTemplate, boolean inventoryContainsEM,
        boolean checkForUniqueVolume, ServiceTemplate originalTemplate, List<String> existingComponents) {
    List<String> chapUserNames = new ArrayList<>();
    Boolean isChapValidationExecuted;
    isChapValidationExecuted = false;

    Map<String, Set<String>> uniqueStorageNames = getStorageVolumeMap(originalTemplate);

    List<String> volNames = new ArrayList<>();

    for (ServiceTemplateComponent component : safeList(svcTemplate.getComponents())) {
        boolean validateComponentVolume = existingComponents == null
                || !existingComponents.contains(component.getId());

        if (component.getType() == ServiceTemplateComponentType.STORAGE) {
            final ServiceTemplateValid componentValid = component.getComponentValid();
            final ServiceTemplateSetting titleSet = svcTemplate.getTemplateSetting(component,
                    ServiceTemplateSettingIDs.SERVICE_TEMPLATE_TITLE_ID);

            if (titleSet == null || StringUtils.isEmpty(titleSet.getValue())) {
                // bug in UI or controller
                componentValid.addMessage(AsmManagerMessages.internalError());
            }

            boolean isChapEverUsed = false;
            for (ServiceTemplateCategory category : safeList(component.getResources())) {
                boolean useChap = false;

                if (validateComponentVolume && checkForUniqueVolume && uniqueStorageNames != null
                        && !uniqueStorageNames.isEmpty()) {
                    String storageName = ServiceTemplateClientUtil.getVolumeNameForStorageComponent(category);
                    Set<String> existingStorageVolumes = new HashSet<>();
                    ServiceTemplateSetting targetSetting = svcTemplate.getTemplateSetting(component,
                            ServiceTemplateSettingIDs.SERVICE_TEMPLATE_ASM_GUID);
                    if (targetSetting != null) {
                        String targetName = targetSetting.getValue();
                        if (targetName != null) {
                            existingStorageVolumes = uniqueStorageNames.get(targetName);
                        }
                    }
                    // Verify the storagename is unique
                    if (ServiceTemplateClientUtil.isNewStorageVolume(category, false)) {
                        if (StringUtils.isNotEmpty(storageName)) {
                            if (!existingStorageVolumes.add(storageName)) {
                                duplicateVolNamesError(componentValid, storageName);
                            }
                        }
                    } else if (ServiceTemplateClientUtil.isExistingVolume(category)) {
                        // for existing volumes check those still exists
                        if (!existingStorageVolumes.contains(storageName)) {
                            LOGGER.error("Volume name do not exists: " + storageName);
                            componentValid.addMessage(AsmManagerMessages.nonexistentVolumeName(storageName));
                            break;
                        }
                    }
                }

                for (ServiceTemplateSetting setting : safeList(category.getParameters())) {

                    if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_TITLE_ID.equalsIgnoreCase(setting.getId())) {
                        String volumeNameInTemplate = ServiceTemplateClientUtil
                                .getVolumeNameForStorageComponent(category);
                        // if name should be generated, emulate it now
                        if (StringUtils.isEmpty(volumeNameInTemplate)
                                && ServiceTemplateSettingIDs.SERVICE_TEMPLATE_VOLUME_NAME_OPTION_AUTOGENERATE
                                        .equals(setting.getValue())) {
                            volumeNameInTemplate = HostnameUtil.generateNameFromNumTemplate(category
                                    .getParameter(
                                            ServiceTemplateSettingIDs.SERVICE_TEMPLATE_VOLUME_NAME_TEMPLATE)
                                    .getValue(), new HashSet<String>());
                        }
                        // skip dup test for autogen storage volume
                        if (StringUtils.isNotEmpty(volumeNameInTemplate)
                                && ServiceTemplateClientUtil.isNewStorageVolume(setting, false)) {
                            volNames.add(volumeNameInTemplate);
                            Set<String> volNameSet = new HashSet<>(volNames);
                            if (volNames.size() != 0 && (volNameSet.size() != volNames.size())) {
                                duplicateVolNamesError(componentValid, volumeNameInTemplate);
                            }
                        }

                        if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_EQL_COMP_ID
                                .equals(category.getId())) {
                            // volume name may be empty only if it is publish time and option is
                            // "create at deployment". We ignore it. We check all other cases.
                            if (StringUtils.isNotEmpty(volumeNameInTemplate)
                                    && ServiceTemplateClientUtil.isNewStorageVolume(setting, true)
                                    && !isEqlVolNameValid(volumeNameInTemplate)) {
                                LOGGER.error("Invalid volume name " + volumeNameInTemplate);
                                componentValid.addMessage(AsmManagerMessages.invalidEqlVolName(
                                        StringEscapeUtils.escapeHtml4(volumeNameInTemplate)));
                                break;
                            }
                        }

                        if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_COMPELLENT_COMP_ID
                                .equals(category.getId())) {
                            List<ServiceTemplateSetting> params = category.getParameters();
                            for (ServiceTemplateSetting param : params) {
                                if (param.getId().equalsIgnoreCase(
                                        ServiceTemplateSettingIDs.SERVICE_TEMPLATE_COMPELLENT_PORTTYPE_ID)
                                        && ServiceTemplateSettingIDs.SERVICE_TEMPLATE_COMPELLENT_PORTTYPE_ISCSI
                                                .equalsIgnoreCase(param.getValue())
                                        && !inventoryContainsEM) {
                                    LOGGER.error("No EM in inventory while CMPL exists in Template");
                                    componentValid.addMessage(AsmManagerMessages.noEmInInventory());
                                    break;
                                }

                                Map<String, ServiceTemplateComponent> map = svcTemplate.fetchComponentsMap();
                                if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_COMPELLENT_BOOT_VOLUME_ID
                                        .equalsIgnoreCase(param.getId())) {
                                    for (String key : component.getAssociatedComponents().keySet()) {
                                        if (map.get(key) != null && map.get(key)
                                                .getType() == ServiceTemplateComponentType.SERVER) {
                                            for (ServiceTemplateCategory serverCategory : safeList(
                                                    svcTemplate.findComponentById(key).getResources())) {
                                                for (ServiceTemplateSetting serverParam : safeList(
                                                        serverCategory.getParameters())) {
                                                    if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ID
                                                            .equals(serverParam.getId())) {
                                                        if (StringUtils.equals(param.getValue(), "true")
                                                                && !(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ISCSI
                                                                        .equals(serverParam.getValue())
                                                                        || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_FC
                                                                                .equals(serverParam
                                                                                        .getValue()))) {
                                                            LOGGER.error(
                                                                    "For a storage with Boot Volume option checked - the Target Boot Device of associated server component should be either Boot from SAN (FC) or Boot from SAN (iSCSI)");
                                                            componentValid.addMessage(
                                                                    AsmManagerMessages.bootVolumeChecked());
                                                        } else if (StringUtils.equals(param.getValue(), "false")
                                                                && (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ISCSI
                                                                        .equals(serverParam.getValue())
                                                                        || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_FC
                                                                                .equals(serverParam
                                                                                        .getValue()))) {
                                                            LOGGER.error(
                                                                    "For a storage with Boot Volume option not checked - the Target Boot Device of associated server component can not be Boot from SAN (FC) or Boot from SAN (iSCSI)");
                                                            componentValid.addMessage(
                                                                    AsmManagerMessages.bootVolumeNotChecked());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_COMPELLENT_PORTTYPE_ID
                                        .equalsIgnoreCase(param.getId())
                                        && ServiceTemplateSettingIDs.SERVICE_TEMPLATE_COMPELLENT_PORTTYPE_FIBRE_CHANNEL
                                                .equalsIgnoreCase(param.getValue())) {
                                    if (!isFcStorageWithFcServer(component, svcTemplate)
                                            && component.getAssociatedComponents().size() > 0) {
                                        LOGGER.error(
                                                "Server component attached with FC Storage component must have FC interface...");
                                        componentValid.addMessage(AsmManagerMessages.fcStorageWithServer());
                                        break;
                                    }
                                }
                            }
                        }
                        if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_VNX_VOLUME_ID
                                .equals(category.getId())) {
                            if (!isFcStorageWithFcServer(component, svcTemplate)
                                    && component.getAssociatedComponents().size() > 0) {
                                LOGGER.error(
                                        "Server component attached with FC Storage component must have FC interface...");
                                componentValid.addMessage(AsmManagerMessages.fcStorageWithServer());
                                break;
                            }
                        }
                    } else if (setting.getId().equalsIgnoreCase("size")
                            && ServiceTemplateClientUtil.isNewStorageVolume(titleSet, true)) {
                        if (category.getId().contains("compellent")) {
                            if (!Validator.isCompellentVolumeSizeValid(setting.getValue())) {
                                LOGGER.error("Invalid volume size " + setting.getValue());
                                componentValid.addMessage(
                                        AsmManagerMessages.invalidVolumeSizeCmpl(setting.getValue()));
                            }
                        } else if (category.getId().contains("equallogic")
                                || category.getId().contains("netapp")
                                || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_VNX_VOLUME_ID
                                        .equals(category.getId())) {
                            if (!Validator.isEquallogicVolumeSizeValid(setting.getValue())) {
                                LOGGER.error("Invalid volume size " + setting.getValue());
                                componentValid.addMessage(
                                        AsmManagerMessages.invalidVolumeSizeEql(setting.getValue()));
                            }
                        }
                    } else if (setting.getId().equalsIgnoreCase("snapreserve")
                            || setting.getId().equalsIgnoreCase("thinminreserve")
                            || setting.getId().equalsIgnoreCase("thingrowthwarn")
                            || setting.getId().equalsIgnoreCase("thingrowthmax")
                            || setting.getId().equalsIgnoreCase("thinwarnsoftthres")
                            || setting.getId().equalsIgnoreCase("thinwarnhardthres")) {
                        if (!Validator.isValidPercentage(setting.getValue())) {
                            LOGGER.error("Invalid percentage value" + setting.getValue());
                            componentValid
                                    .addMessage(AsmManagerMessages.invalidPercentageFormat(setting.getValue()));
                        }
                    } else if (setting.getId().equalsIgnoreCase(
                            ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_AUTH_TYPE_ID)) {
                        if (setting.getValue()
                                .equals(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_STORAGE_AUTH_TYPE_CHAP_ID)) {
                            useChap = true;
                            isChapEverUsed = true;
                        }
                    } else if (useChap && setting.getId().equalsIgnoreCase("chap_user_name")) {
                        chapUserNames.add(setting.getValue());
                        if (!Validator.isValidCHAPUsername(setting.getValue())) {
                            LOGGER.error("Invalid chap username" + setting.getValue());
                            componentValid
                                    .addMessage(AsmManagerMessages.invalidCHAPUserName(setting.getValue()));
                        }
                        Set<String> chapUserNameSet = new HashSet<>(chapUserNames);
                        if (chapUserNameSet.size() > 1 && !isChapValidationExecuted) {
                            isChapValidationExecuted = true;
                            chapUserNameError(componentValid);
                        }
                    } else if (useChap && setting.getId().equalsIgnoreCase("passwd")) {
                        if (!Validator.isValidCHAPPassword(setting.getValue())) {
                            LOGGER.error("Invalid chap password" + setting.getValue());
                            componentValid.addMessage(AsmManagerMessages.invalidCHAPPassword());
                        }
                    } else if (setting.getId().equalsIgnoreCase("volumefolder")
                            || setting.getId().equalsIgnoreCase("serverfolder")) {
                        if (!Validator.isValidFolderName(setting.getValue())) {
                            LOGGER.error("Invalid folder name" + setting.getValue());
                            componentValid.addMessage(AsmManagerMessages.invalidFolderName(setting.getValue()));
                        }
                    } else if (setting.getId().equalsIgnoreCase("wwn")) {
                        if (!Validator.isValidServerWWN(setting.getValue())) {
                            LOGGER.error("Invalid server wwn" + setting.getValue());
                            componentValid.addMessage(AsmManagerMessages.invalidServerWWN(setting.getValue()));
                        }
                    } else if (setting.getId().equalsIgnoreCase("iqnOrIP")
                            && StringUtils.isNotEmpty(setting.getValue())) {
                        String[] vals;
                        if (setting.getValue().indexOf(',') > 0) {
                            vals = setting.getValue().split(",");
                        } else {
                            vals = new String[1];
                            vals[0] = setting.getValue();
                        }
                        for (String s : vals) {
                            if (!Validator.isValidIPAddressWildcard(s) && !Validator.isValidIQN(s)) {
                                LOGGER.error("Invalid server iqnOrIP: " + s);
                                componentValid.addMessage(AsmManagerMessages.invalidServerIPorIQN(s));
                            }
                        }
                    } else if (setting.getId()
                            .equalsIgnoreCase(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NFS_NETWORK_ID)
                            && StringUtils.isNotEmpty(setting.getValue())) {
                        if (!Validator.isValidIPAddress(setting.getValue())) {
                            LOGGER.error("Invalid NFS/CIFS IP: " + setting.getValue());
                            componentValid.addMessage(AsmManagerMessages.invalidIPforNFS(setting.getValue()));
                        }
                    } else if ((setting.getId().equalsIgnoreCase("volume_notes")
                            || setting.getId().equalsIgnoreCase("server_notes"))
                            && StringUtils.isNotEmpty(setting.getValue())) {
                        if (!Validator.isLocalisedDisplayNameValid(setting.getValue())) {
                            LOGGER.error("Invalid notes " + setting.getValue());
                            componentValid.addMessage(AsmManagerMessages.invalidNotes(setting.getValue()));
                        }
                    }
                }
            }

            // Validate ICQN/IP vs Chap Settings for related Servers
            final Set<String> relCompsKeys = component.getAssociatedComponents().keySet();
            if (relCompsKeys.size() > 0) {
                // map to keep count of the number of times a server is added to the same cluster
                // used to make sure a server is not added to the same cluster more than once
                for (String key : relCompsKeys) {
                    final ServiceTemplateComponent relComp = svcTemplate.findComponentById(key);
                    // Loop through the related components and check for any servers that are added twice
                    if (relComp != null && relComp.getType() == ServiceTemplateComponentType.SERVER) {
                        for (ServiceTemplateCategory category : safeList(relComp.getResources())) {
                            for (ServiceTemplateSetting setting : safeList(category.getParameters())) {
                                if ((setting.getId().equalsIgnoreCase(
                                        ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ID)
                                        && setting.getValue().equals(
                                                ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ISCSI))
                                        && isChapEverUsed) {
                                    LOGGER.warn(
                                            "Invalid use of CHAP on Target Boot Device - Boot from SAN (ISCSI).");
                                    componentValid
                                            .addMessage(AsmManagerMessages.invalidAuthenticationForStorage());
                                }
                            }
                        }
                    }
                }
            }

            // if there are any validation error messages then template is invalid
            if (CollectionUtils.isNotEmpty(componentValid.getMessages())) {
                componentValid.setValid(Boolean.FALSE);
                svcTemplate.getTemplateValid().setValid(Boolean.FALSE);
            }
        }
    }
}

From source file:com.sonicle.webtop.mail.ICalendarRequest.java

/**
 * <p>/*w w w. ja  va 2s. c  om*/
 * Finds all "URL"s in the given _rawText, wraps them in 
 * HTML link tags and returns the result (with the rest of the text
 * html encoded).
 * </p>
 * <p>
 * We employ the procedure described at:
 * http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html
 * which is a <b>must-read</b>.
 * </p>
 * Basically, we allow any number of left parenthesis (which will get stripped away)
 * followed by http:// or https://.  Then any number of permitted URL characters
 * (based on http://www.ietf.org/rfc/rfc1738.txt) followed by a single character
 * of that set (basically, those minus typical punctuation).  We remove all sets of 
 * matching left & right parentheses which surround the URL.
 *</p>
 * <p>
 * This method *must* be called from a tag/component which will NOT
 * end up escaping the output.  For example:
 * <PRE>
 * <h:outputText ... escape="false" value="#{core:hyperlinkText(textThatMayHaveURLs, '_blank')}"/>
 * </pre>
 * </p>
 * <p>
 * Reason: we are adding <code>&lt;a href="..."&gt;</code> tags to the output *and*
 * encoding the rest of the string.  So, encoding the outupt will result in
 * double-encoding data which was already encoded - and encoding the <code>a href</code>
 * (which will render it useless).
 * </p>
 * <p>
 * 
 * @param   _rawText  - if <code>null</code>, returns <code>""</code> (empty string).
 * @param   _target   - if not <code>null</code> or <code>""</code>, adds a target attributed to the generated link, using _target as the attribute value.
 */
public static final String hyperlinkText(final String _rawText, final String _target) {

    String returnValue = null;

    if (!StringUtils.isBlank(_rawText)) {

        final Matcher matcher = URI_FINDER_PATTERN.matcher(_rawText);

        if (matcher.find()) {

            final int originalLength = _rawText.length();

            final String targetText = (StringUtils.isBlank(_target)) ? ""
                    : " target=\"" + _target.trim() + "\"";
            final int targetLength = targetText.length();

            // Counted 15 characters aside from the target + 2 of the URL (max if the whole string is URL)
            // Rough guess, but should keep us from expanding the Builder too many times.
            final StringBuilder returnBuffer = new StringBuilder(originalLength * 2 + targetLength + 15);

            int currentStart;
            int currentEnd;
            int lastEnd = 0;

            String currentURL;

            do {
                currentStart = matcher.start();
                currentEnd = matcher.end();
                currentURL = matcher.group();

                // Adjust for URLs wrapped in ()'s ... move start/end markers
                //      and substring the _rawText for new URL value.
                while (currentURL.startsWith("(") && currentURL.endsWith(")")) {
                    currentStart = currentStart + 1;
                    currentEnd = currentEnd - 1;

                    currentURL = _rawText.substring(currentStart, currentEnd);
                }

                while (currentURL.startsWith("(")) {
                    currentStart = currentStart + 1;

                    currentURL = _rawText.substring(currentStart, currentEnd);
                }

                // Text since last match
                returnBuffer.append(StringEscapeUtils.escapeHtml4(_rawText.substring(lastEnd, currentStart)));

                // Wrap matched URL
                returnBuffer.append("<a href=\"" + currentURL + "\"" + targetText + ">" + currentURL + "</a>");

                lastEnd = currentEnd;

            } while (matcher.find());

            if (lastEnd < originalLength) {
                returnBuffer.append(StringEscapeUtils.escapeHtml4(_rawText.substring(lastEnd)));
            }

            returnValue = returnBuffer.toString();
        }
    }

    if (returnValue == null) {
        returnValue = StringEscapeUtils.escapeHtml4(_rawText);
    }

    return returnValue;

}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * <p>/*  w  ww. j  ava 2 s .c  o  m*/
 * escape HTML see StringEscapeUtils.escapeHtml4(str)
 * </p>
 * <p>
 * Supports all known HTML 4.0 entities, including funky accents. Note that
 * the commonly used apostrophe escape character (&amp;apos;) is not a legal
 * entity and so is not supported).
 * </p>
 * <p>
 * For example:
 * </p>
 * <p>
 * <code>"bread" &amp; "butter"</code>
 * </p>
 * becomes:
 * <p>
 * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>
 * .
 * </p>
 *
 * @param str value
 * @return string
 */
public static String escapeHtml4(String str) {
    if (isBlank(str)) {
        return str;
    }
    return StringEscapeUtils.escapeHtml4(str);
}

From source file:ELK.ELKController.java

private void initializeRoutes() throws IOException {
    // this is the blog home page
    get(new FreemarkerBasedRoute("/", "ELKTemplate.ftl") {
        @Override//from   www  . j av  a 2 s  . com
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            // this is where we would normally load up the blog data
            // but this week, we just display a placeholder.
            HashMap<String, String> root = new HashMap<String, String>();

            template.process(root, writer);
        }
    });
    /*
            get(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
        ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
            
        SimpleHash root = new SimpleHash();
        System.out.println("We are good");
        BasicDBObject query = new BasicDBObject();
        VMsDBCollection.deleteMany(query);
            
        //HashMap<String, String> root = new HashMap<String, String>();
        if(!(mes == null || mes.length == 0)) {
            for (int i = 0; i < mes.length; i++) {
                Document text = new Document();
                VirtualMachine vm = (VirtualMachine) mes[i];
            
                if(!vm.getName().contains("Template")) {
                    String name = vm.getName();
                    text.append("name", name);
                    Document DB_VMs = new Document("_id", name);
            
                    if(vm.getConfig() != null) {
                        String instanceId = vm.getConfig().getInstanceUuid();
                        text.append("instanceId", instanceId);
                    }
            
                    System.out.println("VM Name : " + name);
            
                    String conectionState = vm.getRuntime().getConnectionState().toString();
                    text.append("conectionState", conectionState);
                    DB_VMs.append("conectionState", conectionState);
            
                    String ip = vm.getGuest().getIpAddress();
                    text.append("ip", ip);
                    DB_VMs.append("ip", ip);
            
                    String powerState = vm.getRuntime().getPowerState().toString();
                    text.append("powerState", powerState);
            
                    if (vm.getTriggeredAlarmState() == null) {
                        text.append("alarmState", "notTriggered");
                        DB_VMs.append("powerState", "notTriggered");
                    } else {
                        text.append("alarmState", "Triggered");
                        DB_VMs.append("powerState", "Triggered");
                    }
            
                    String launchTime = writeActualDate(vm.getRuntime().getBootTime());
                    text.append("launchTime", launchTime);
                    DB_VMs.append("launchTime", launchTime);
            
                    posts.add(text);
                    VMsDBCollection.insertOne(DB_VMs);
            
                }
            }
        }
        root.put("VMs", posts);
        template.process(root, writer);
    }
            });*/
    /*
            get(new FreemarkerBasedRoute("/create_vm", "create_vm.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        SimpleHash root = new SimpleHash();
        System.out.println("Inside Create VM backend");
            
        template.process(root, writer);
    }
            });*/
    /*
            post(new FreemarkerBasedRoute("/create_vm", "/create_vm.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            
        if (request.queryParams("Create") != null) {
            
            ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
            
            
            //Clone VM
            String vmname = request.queryParams("vmname");
            String vm_template = request.queryParams("OS");
            
            VirtualMachine vm = (VirtualMachine) new InventoryNavigator(
                    rootFolder).searchManagedEntity("VirtualMachine", vm_template);
            
            VirtualMachineRuntimeInfo vmri = vm.getRuntime();
            
            HostSystem hs = new HostSystem(vm.getServerConnection(), vmri.getHost());
            
            Datacenter dc = (Datacenter) new InventoryNavigator(rootFolder).searchManagedEntity("Datacenter", "T03-DC");
            ResourcePool rp = (ResourcePool) new InventoryNavigator(dc).searchManagedEntities("ResourcePool")[0];
            
            if (vm == null) {
                System.out.println("No VM found with name " + vm_template);
            
                SimpleHash root = new SimpleHash();
            
                root.put("login_error", "No template available");
                template.process(root, writer);
            } else {
                try {
                    VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
            
                    VirtualMachineRelocateSpec locateSpec = new VirtualMachineRelocateSpec();
                    locateSpec.setPool(rp.getMOR());
                    cloneSpec.setLocation(locateSpec);
                    cloneSpec.setPowerOn(false);
                    cloneSpec.setTemplate(false);
            
                    Task task = vm.cloneVM_Task((Folder) vm.getParent(),
                            vm_template, cloneSpec);
                    System.out.println("Launching the VM clone task. " + "Please wait ...");
                    String status = task.waitForTask();
                    if (status == Task.SUCCESS) {
                        System.out.println("VM got cloned successfully.");
                    } else {
                        System.out.println("Failure -: VM cannot be cloned");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            
                response.redirect("/display_vms");
            }
        } else if (request.queryParams("Cancle") != null) {
            
            response.redirect("/display_vms");
            
        }
    }
            });
    */

    /*
            post(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
        SimpleHash root = new SimpleHash();
            
        BasicDBObject query = new BasicDBObject();
        ArrayList<String> VM_list = new ArrayList<String>();
        MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator();
            
        while (cursor.hasNext()) {
            
            String a = cursor.next().toJson();
            System.out.println(a);
            
            try {
                JSONObject jsonObject = new JSONObject(a);
                String vm_name = jsonObject.getString("_id");
                VM_list.add(vm_name);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
        }
            
        //take VM list from DB
        if (request.queryParams("PowerOn") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Power ON VM " + VM_name);
                    powerOn(VM_name);
                }
            
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("PowerOff") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Power Off VM " + VM_name);
                    powerOff(VM_name);
                }
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("Delete") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox)
                    System.out.println("Delete VM "+ VM_name);
                deleteVM(VM_name);
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("Get_Chart") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Get VM " + VM_name +"Charts" );
                    CurrentSelectedVM = VM_name;
                }
            }
            response.redirect("/gChart");
            
        } else if (request.queryParams("Create") != null) {
            response.redirect("/create_vm");
            
        }else {
            System.out.println("Invalid ");
            response.redirect("/display_vms");
            // ???
        }
            
    }
            });
    */
    /*      // google chart handler
          get(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            
        if (CurrentSelectedVM != null) {
            
            ArrayList<ArrayList> gchartData = statsDAO.getGchart(CurrentSelectedVM);
            SimpleHash root = new SimpleHash();
            root.put("VMName", CurrentSelectedVM);
            CurrentSelectedVM = null;
            
            root.put("gcdata", gchartData);
            //System.out.println(gchartData);
            // System.out.println(gchartData.get(0));
            
            template.process(root, writer);
        }
            
    }
          });*/

    /*       post(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") {
    @Override
    protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            
        if (request.queryParams("Home") != null) {
            response.redirect("/display_vms");
        }
    }
           });
    */

    // handle the signup post
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/login");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for blog
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("welcome() can't identify the user, redirecting to signup");
                response.redirect("/signup");

            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the welcome page
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/ConfigureAlarm");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // allows the user to logout of the blog
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);

            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
    get(new FreemarkerBasedRoute("/ConfigureAlarm", "ConfigureAlarmForm.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });

}

From source file:com.basetechnology.s0.agentserver.util.XmlUtils.java

static public String escapeEntities(String string) {
    return StringEscapeUtils.escapeHtml4(string);
}

From source file:com.ah.ui.actions.admin.LicenseMgrAction.java

public boolean installOrderKey() {
    // check the order key
    String checkName = checkKeyExistsIgnoreDomain(primaryOrderKey);

    if (null != checkName) {
        addActionError(checkName);// w  w  w.  j  a v  a 2 s . c om
        return false;
    }
    String hmId = licenseInfo.getSystemId();
    HmDomain domain = getDomain();

    try {
        if (!Jsoup.isValid(primaryOrderKey, Whitelist.none())) {
            addActionError(MgrUtil.getUserMessage("error.license.orderkey.activate.Failed",
                    new String[] { StringEscapeUtils.escapeHtml4(primaryOrderKey) }));
            return false;
        }
        OrderKeyManagement.activateOrderKey(primaryOrderKey, domain.getDomainName(), hmId);

        doAfterInstallNewLicense();

        addActionMessage(MgrUtil.getUserMessage("info.license.orderKeyActivated", primaryOrderKey));
        generateAuditLog(HmAuditLog.STATUS_SUCCESS,
                MgrUtil.getUserMessage("hm.audit.log.entitlement.key.enter", primaryOrderKey));

        primaryOrderKey = "";

        // remove the expired info in session
        MgrUtil.removeSessionAttribute(LICENSE_INFO_IN_TITLE_AREA);
        return true;
    } catch (Exception e) {
        addActionError(MgrUtil.getUserMessage("error.license.orderkey.activate.Failed",
                new String[] { primaryOrderKey }) + "<br>" + e.getMessage());
        generateAuditLog(HmAuditLog.STATUS_FAILURE,
                MgrUtil.getUserMessage("hm.audit.log.entitlement.key.enter", primaryOrderKey));
    }
    return false;
}

From source file:mobac.gui.components.JMapSourceTree.java

/**
 * Static method used for dynamic generation of a tooltip with information about a mapSource
 * /*from   www  .j  a va  2s .  c  om*/
 * @param mapSource
 *            - of which information will be put into a tooltip
 * @return generated tooltip string
 */
public static String generateMapSourceTooltip(MapSource mapSource) {
    boolean multiLayer = (mapSource instanceof AbstractMultiLayerMapSource);
    boolean fileBased = (mapSource instanceof FileBasedMapSource);

    // Getting a localized string for an input to tooltip
    String locName = I18nUtils.localizedStringForKey("lp_map_source_tooltip_layer_name");
    String locInternalName = I18nUtils.localizedStringForKey("lp_map_source_tooltip_inernal_name");
    String locType = I18nUtils.localizedStringForKey("lp_map_source_tooltip_type");
    String locLoadedFrom = I18nUtils.localizedStringForKey("lp_map_source_tooltip_loaded_from");
    String locFileName = I18nUtils.localizedStringForKey("lp_map_source_tooltip_file_name");

    String locMultiLayer = I18nUtils.localizedStringForKey("lp_map_source_layer_multi");
    String locSingleLayer = I18nUtils.localizedStringForKey("lp_map_source_layer_single");
    String locFileBased = I18nUtils.localizedStringForKey("lp_map_source_layer_file_based");
    String locWebBased = I18nUtils.localizedStringForKey("lp_map_source_layer_web_based");

    // Getting a values for some attributes
    String name = StringEscapeUtils.escapeHtml4(mapSource.toString());
    String nameInternal = StringEscapeUtils.escapeHtml4(mapSource.getName());
    String type1 = multiLayer ? locMultiLayer : locSingleLayer;
    String type2 = fileBased ? locFileBased : locWebBased;

    String toolTipString = locName + ": <b>%s</b><br>" + locInternalName + ": %s<br>" + locType + ": %s (%s)";
    toolTipString = String.format(toolTipString, name, nameInternal, type1, type2);

    MapSourceLoaderInfo info = mapSource.getLoaderInfo();
    if (info != null) {
        toolTipString += "<br>" + locLoadedFrom + ": " + info.getLoaderType().displayName;

        File f = info.getSourceFile();
        if (f != null) {
            toolTipString += "<br>" + locFileName + ": <tt>" + StringEscapeUtils.escapeHtml4(f.getName())
                    + "</tt>";
        }
    }

    return "<html>" + toolTipString + "</html>";
}