Example usage for java.util.regex Pattern matches

List of usage examples for java.util.regex Pattern matches

Introduction

In this page you can find the example usage for java.util.regex Pattern matches.

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.clustercontrol.http.factory.RunMonitorHttpScenario.java

/**
 * HTTP ?// w  w w. j  a va  2s. co  m
 * 
 * @param facilityId ID
 * @return ???????true
 */
public List<MonitorRunResultInfo> collectList(String facilityId) {
    // ???????
    if (!m_isMonitorJob && (!m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg()
            && !m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg())) {
        if (m_log.isDebugEnabled()) {
            m_log.debug("http scenario monitor " + m_httpScenarioCheckInfo.getMonitorId()
                    + " is not enabled, skip filtering.");
        }
        return Collections.emptyList();
    }

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;

    GetHttpResponse.GetHttpResponseBuilder builder = null;
    try {
        builder = GetHttpResponse.custom()
                .setAuthType(m_httpScenarioCheckInfo.getAuthType() == null ? GetHttpResponse.AuthType.NONE
                        : AuthType.valueOf(m_httpScenarioCheckInfo.getAuthType()))
                .setAuthUser(m_httpScenarioCheckInfo.getAuthUser())
                .setAuthPassword(m_httpScenarioCheckInfo.getAuthPassword())
                .setUserAgent(m_httpScenarioCheckInfo.getUserAgent())
                .setConnectTimeout(m_httpScenarioCheckInfo.getConnectTimeout() == null ? 0
                        : m_httpScenarioCheckInfo.getConnectTimeout())
                .setRequestTimeout(m_httpScenarioCheckInfo.getRequestTimeout() == null ? 0
                        : m_httpScenarioCheckInfo.getRequestTimeout())
                .setCancelProxyCache(HinemosPropertyUtil
                        .getHinemosPropertyBool("monitor.http.scenario.disable.proxy.cache", true))
                .setKeepAlive(true).setNeedAuthSSLCert(
                        !HinemosPropertyUtil.getHinemosPropertyBool("monitor.http.ssl.trustall", true));
        if (m_httpScenarioCheckInfo.getProxyFlg()) {
            builder.setProxyURL(m_httpScenarioCheckInfo.getProxyUrl())
                    .setProxyPort(m_httpScenarioCheckInfo.getProxyPort() == null ? 0
                            : m_httpScenarioCheckInfo.getProxyPort())
                    .setProxyUser(m_httpScenarioCheckInfo.getProxyUser())
                    .setProxyPassword(m_httpScenarioCheckInfo.getProxyPassword());
        }
    } catch (URISyntaxException e) {
        m_log.warn("fail to initialize GetHttpResponse : " + e.getMessage(), e);

        MonitorRunResultInfo info = new MonitorRunResultInfo();
        info.setFacilityId(facilityId);
        info.setMonitorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg());
        info.setCollectorFlg(false);
        info.setCollectorResult(false);
        info.setCheckResult(-1);
        info.setPriority(PriorityConstant.TYPE_UNKNOWN);
        info.setMessage(MessageConstant.MESSAGE_FAIL_TO_ANALYZE_PROXY_URL.getMessage());
        StringBuffer messageOrg = new StringBuffer();
        messageOrg.append(e.getMessage());
        messageOrg.append("\n");
        messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PROXYURL.getMessage());
        messageOrg.append(" : ");
        messageOrg.append(m_httpScenarioCheckInfo.getProxyUrl());
        info.setMessageOrg(messageOrg.toString());
        info.setNodeDate(m_nodeDate);
        info.setProcessType(true);
        info.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId());

        return Arrays.asList(info);
    }

    int responseTime = 0;
    ResultType endResultType = ResultType.SUCCESS;
    MonitorRunResultInfo errorResultInfo = null;
    List<PageResponse> responses = new ArrayList<PageResponse>();
    try (GetHttpResponse m_request = builder.build()) {
        Map<String, String> variables = RepositoryUtil.createNodeParameter(nodeInfo.get(facilityId));

        List<Page> pages = new ArrayList<>(m_httpScenarioCheckInfo.getPages());
        Collections.sort(pages, new Comparator<Page>() {
            @Override
            public int compare(Page o1, Page o2) {
                return o1.getId().getPageOrderNo().compareTo(o2.getId().getPageOrderNo());
            }
        });

        loopEnd: for (Page page : pages) {
            ResultType resultType = ResultType.SUCCESS;
            MonitorRunResultInfo resultInfo = null;
            StringBinder strbinder = new StringBinder(variables);
            String url = page.getUrl();
            url = strbinder.bindParam(url);

            String post = page.getPost();
            if (post != null && !post.isEmpty())
                post = strbinder.bindParam(post);

            if (m_log.isTraceEnabled())
                m_log.trace("http request. (nodeInfo = " + nodeInfo + ", facilityId = " + facilityId
                        + ", url = " + url + ")");

            PageResponse response = null;
            List<String> rurls = new ArrayList<>();
            String nextUrl = url;
            String nextPost = post;
            while (true) {
                m_request.execute(nextUrl, nextPost);
                response = new PageResponse(page, m_request.getResult());

                if (response.response.exception == null) {
                    // ??????
                    if (response.response.statusCode == 301 || response.response.statusCode == 302
                            || response.response.statusCode == 303 || response.response.statusCode == 307) {
                        for (Header h : response.response.headers) {
                            if (h.getName().equals("Location")) {
                                nextUrl = h.getValue();
                                nextPost = null;
                                break;
                            }
                        }

                        if (nextUrl != null) {
                            rurls.add(nextUrl);
                        } else {
                            // ?????
                            resultType = ResultType.NOT_FOUND_URL_FOR_REDIRECT;
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

            if (ResultType.NOT_FOUND_URL_FOR_REDIRECT.equals(resultType)) {
                resultInfo = createNotFoundUrlForRedirectMonitorRunResultInfo(page, response.response, url,
                        rurls);
                resultInfo.setFacilityId(facilityId);
            }

            if (ResultType.SUCCESS.equals(resultType) && response.response.exception != null) {
                if (SocketTimeoutException.class.equals(response.response.exception.getClass())) {
                    resultType = ResultType.TIMEOUT;
                    resultInfo = createTimeoutMonitorRunResultInfo(page, response.response, url, rurls);
                    resultInfo.setFacilityId(facilityId);
                } else {
                    resultType = ResultType.UNEXPECTED;
                    resultInfo = createUnexpectedMonitorRunResultInfo(page, response.response, url, rurls);
                    resultInfo.setFacilityId(facilityId);
                }
            }

            if (ResultType.SUCCESS.equals(resultType) && !(page.getStatusCode() == null
                    || Pattern.matches("(\\s*|.*,\\s*)" + response.response.statusCode + "(\\s*,.*|\\s*)",
                            page.getStatusCode()))) {
                resultType = ResultType.NOT_MATCH_EXPECTED_STATUS_CODES;
                resultInfo = createUnmatchedStatusCodeMonitorRunResultInfo(page, m_request.getResult(), url);
                resultInfo.setFacilityId(facilityId);
            }

            if (ResultType.SUCCESS.equals(resultType) && !page.getPatterns().isEmpty()) {
                List<com.clustercontrol.http.model.Pattern> patterns = new ArrayList<>(page.getPatterns());
                Collections.sort(patterns, new Comparator<com.clustercontrol.http.model.Pattern>() {
                    @Override
                    public int compare(com.clustercontrol.http.model.Pattern o1,
                            com.clustercontrol.http.model.Pattern o2) {
                        return o1.getId().getPatternOrderNo().compareTo(o2.getId().getPatternOrderNo());
                    }
                });

                com.clustercontrol.http.model.Pattern matchedPattern = null;
                Boolean exceptionProcessType = null;
                for (int i = 0; i < patterns.size(); ++i) {
                    com.clustercontrol.http.model.Pattern pe = patterns.get(i);

                    if (!pe.getValidFlg() || pe.getPattern() == null)
                        continue;

                    try {
                        // ?????
                        Pattern pattern = null;
                        if (pe.getCaseSensitivityFlg()) {
                            pattern = Pattern.compile(pe.getPattern(),
                                    Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
                        }
                        // ???
                        else {
                            pattern = Pattern.compile(pe.getPattern(), Pattern.DOTALL);
                        }

                        // ????
                        String body = response.response.responseBody;
                        if (body == null) {
                            body = "";
                        }
                        ; // 404?????body?null???????
                        Matcher matcher = pattern.matcher(body);
                        if (matcher.matches()) {
                            matchedPattern = pe;
                            break;
                        }
                    } catch (PatternSyntaxException e) {
                        m_log.info("collectList(): PatternSyntax is not valid." + " description="
                                + pe.getDescription() + ", patternSyntax=" + pe.getPattern() + ", value="
                                + response.response.responseBody + " : " + e.getClass().getSimpleName() + ", "
                                + e.getMessage());
                        exceptionProcessType = pe.getProcessType();
                    } catch (Exception e) {
                        m_log.warn("collectList(): PatternSyntax is not valid." + " description="
                                + pe.getDescription() + ", patternSyntax=" + pe.getPattern() + ", value="
                                + response.response.responseBody + " : " + e.getClass().getSimpleName() + ", "
                                + e.getMessage(), e);
                        exceptionProcessType = pe.getProcessType();
                    }
                }

                if (matchedPattern != null) {
                    resultType = ResultType.MATCH_PATTERN;
                    resultInfo = createMatchedPatternMonitorRunResultInfo(page, matchedPattern,
                            response.response, url);
                    resultInfo.setFacilityId(facilityId);
                } else {
                    resultType = ResultType.NOT_MATCH_PATTERNS;
                    resultInfo = createNotmatchedPatternsMonitorRunResultInfo(page, response.response, url,
                            exceptionProcessType);
                    resultInfo.setFacilityId(facilityId);
                }
            }

            // ???
            switch (resultType) {
            case NOT_MATCH_EXPECTED_STATUS_CODES:
            case NOT_MATCH_PATTERNS:
            case TIMEOUT:
            case UNEXPECTED:
            case NOT_FOUND_URL_FOR_REDIRECT:
                errorResultInfo = resultInfo;
                endResultType = resultType;
                break loopEnd;
            case MATCH_PATTERN:
                if (resultInfo.getProcessType().booleanValue()) {
                    endResultType = resultType;
                    errorResultInfo = resultInfo;
                    break loopEnd;
                }
                break;
            default:
                // SUCCESS
                break;
            }

            // ??
            for (Variable variable : page.getVariables()) {
                String value = null;
                if (variable.getMatchingWithResponseFlg()) {
                    if (response.response.responseBody != null) {
                        Matcher m = Pattern.compile(variable.getValue(), Pattern.DOTALL)
                                .matcher(response.response.responseBody);
                        if (m.matches()) {
                            try {
                                value = m.group(1);
                            } catch (IndexOutOfBoundsException e) {
                                m_log.warn(String.format(
                                        "not contain group paragraph in pattern for variable. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s",
                                        facilityId, m_httpScenarioCheckInfo.getMonitorId(),
                                        page.getId().getPageOrderNo(), variable.getId().getName(),
                                        variable.getValue()));
                            }
                        } else {
                            // ????
                            m_log.debug(String.format(
                                    "variable not match. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s",
                                    facilityId, m_httpScenarioCheckInfo.getMonitorId(),
                                    page.getId().getPageOrderNo(), variable.getId().getName(),
                                    variable.getValue()));
                        }
                    } else {
                        // ????
                        m_log.warn(String.format(
                                "Not foudnd previous post. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s",
                                facilityId, m_httpScenarioCheckInfo.getMonitorId(),
                                page.getId().getPageOrderNo(), variable.getId().getName(),
                                variable.getValue()));
                    }
                } else {
                    value = variable.getValue();
                }

                if (value != null) {
                    variables.put(variable.getId().getName(), value);
                }
            }

            responses.add(response);
            responseTime += m_request.getResult().responseTime;
        }
    } catch (IOException e) {
        m_log.warn("fail to close HttpClient : " + e.getMessage(), e);
    }

    List<MonitorRunResultInfo> resultInfos = new ArrayList<>();
    if (ResultType.SUCCESS.equals(endResultType)) {
        MonitorRunResultInfo info = new MonitorRunResultInfo();
        info.setFacilityId(facilityId);
        info.setMonitorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg());
        info.setCollectorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg());
        info.setCollectorResult(true);
        info.setCheckResult(0);
        info.setItemCode("0");
        info.setItemName(m_httpScenarioCheckInfo.getMonitorInfo().getItemName());
        info.setDisplayName("");
        info.setPriority(PriorityConstant.TYPE_INFO);
        info.setMessage(String.format("%s : %s",
                MessageConstant.MONITOR_HTTP_SCENARIO_TOTAL_RESPONSETIME_MS.getMessage(),
                NumberFormat.getNumberInstance().format(responseTime)));
        int pageOrderNo = 1;
        StringBuffer messageOrg = new StringBuffer();
        messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_TOTAL_RESPONSETIME.getMessage());
        messageOrg.append(" : ");
        messageOrg.append(responseTime);
        messageOrg.append("\n");
        for (PageResponse pr : responses) {
            messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_ORDERNO.getMessage());
            messageOrg.append(" : ");
            messageOrg.append(pageOrderNo++);
            messageOrg.append("\n");
            messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_URL.getMessage());
            messageOrg.append(" : ");
            messageOrg.append(pr.response.url);
            messageOrg.append("\n");
            messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_STATUSCODE.getMessage());
            messageOrg.append(" : ");
            messageOrg.append(pr.response.statusCode);
            messageOrg.append("\n");
            messageOrg.append(MessageConstant.RESPONSE_TIME_MILLI_SEC.getMessage());
            messageOrg.append(" : ");
            messageOrg.append(pr.response.responseTime);
            messageOrg.append("\n");
        }
        info.setMessageOrg(messageOrg.toString());
        info.setNodeDate(m_nodeDate);
        info.setValue((double) responseTime);
        info.setProcessType(true);
        info.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId());
        resultInfos.add(info);

        // ???
        if (!m_isMonitorJob && m_httpScenarioCheckInfo.getMonitoringPerPageFlg()
                && m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg()) {
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (PageResponse pr : responses) {
                Integer count = map.get(pr.page.getUrl());
                if (count == null) {
                    count = 1;
                    map.put(pr.page.getUrl(), count);
                } else {
                    map.put(pr.page.getUrl(), ++count);
                }

                MonitorRunResultInfo pagetResultInfo = new MonitorRunResultInfo();
                pagetResultInfo.setFacilityId(facilityId);
                pagetResultInfo.setMonitorFlg(false);
                pagetResultInfo.setCollectorFlg(true);
                pagetResultInfo.setCollectorResult(true);
                pagetResultInfo.setItemCode(Integer.toString(pr.page.getId().getPageOrderNo() + 1));
                pagetResultInfo.setDisplayName(pr.page.getUrl() + " (" + count + ")");
                pagetResultInfo.setPriority(pr.page.getPriority());
                pagetResultInfo.setNodeDate(m_nodeDate);
                pagetResultInfo.setValue((double) pr.response.responseTime);
                pagetResultInfo.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId());
                resultInfos.add(pagetResultInfo);
            }
        }
    } else {
        resultInfos.add(errorResultInfo);
    }
    return resultInfos;
}

From source file:org.apache.falcon.resource.EntityManagerJerseyIT.java

public void testVersion() throws FalconException, IOException, FalconCLIException {
    String json = falconUnitClient.getVersion(null);
    String buildVersion = BuildProperties.get().getProperty("build.version");
    String deployMode = DeploymentProperties.get().getProperty("deploy.mode");
    Assert.assertTrue(Pattern.matches(
            ".*\\{\\s*\"key\"\\s*:\\s*\"Version\"\\s*,\\s*\"value\"\\s*:\\s*\"" + buildVersion + "\"\\s*}.*",
            json), "No build.version found in /api/admin/version");
    Assert.assertTrue(Pattern.matches(
            ".*\\{\\s*\"key\"\\s*:\\s*\"Mode\"\\s*,\\s*\"value\"\\s*:\\s*\"" + deployMode + "\"\\s*}.*", json),
            "No deploy.mode found in /api/admin/version");
}

From source file:com.smanempat.controller.ControllerClassification.java

public void validasiNumberofNearest(java.awt.event.KeyEvent evt, JTextField textNumberOfK,
        JLabel labelPesanError) {
    ModelClassification modelClassification = new ModelClassification();
    String numberValidate = textNumberOfK.getText();
    int modelRow = modelClassification.getRowCount();
    if (Pattern.matches("[0-9]+", numberValidate) == false && numberValidate.length() > 0) {
        evt.consume();/*from ww w  .j  a va  2  s.co m*/
        labelPesanError.setText("Number of Nearest Neighbor tidak valid");
    } else if (numberValidate.length() == 9) {
        evt.consume();
        labelPesanError.setText("Number of Nearest Neighbor terlalu panjang");
    } else {
        labelPesanError.setText("");
    }

}

From source file:com.microfocus.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchListItems(String logicalListName, String term, String instanceId, long workspaceId,
        boolean multiValue, boolean extensible) {
    int defaultSize = 10;
    JSONObject ret = new JSONObject();
    OctaneClient octaneClient = OctaneSDK.getClientByInstanceId(instanceId);
    try {// www  .ja  va 2  s .  c  o m
        ResponseEntityList listItemPagedList = queryListItems(octaneClient, logicalListName, term, workspaceId,
                defaultSize);
        List<Entity> listItems = listItemPagedList.getData();
        boolean moreResults = listItemPagedList.getTotalCount() > listItems.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        if (!multiValue) {
            String quotedTerm = Pattern.quote(term.toLowerCase());
            if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
                JSONObject notSpecifiedItemJson = new JSONObject();
                notSpecifiedItemJson.put("id", -1);
                notSpecifiedItemJson.put("text", NOT_SPECIFIED);
                retArray.add(notSpecifiedItemJson);
            }
        }

        for (Entity item : listItems) {
            if (!toBeFiltered(item)) {
                JSONObject itemJson = new JSONObject();
                itemJson.put("id", item.getId());
                itemJson.put("text", item.getName());
                retArray.add(itemJson);
            }

        }
        // we shall use "if (extensible){}" on following line, but we do not have UI ready for the case: multiValue = true & extensible = true
        if (extensible && !multiValue) {
            //if exactly one item matches, we do not want to bother user with "new value" item
            if ((listItems.size() != 1)
                    || (!listItems.get(0).getName().toLowerCase().equals(term.toLowerCase()))) {
                retArray.add(createNewValueJson("0"));
            }
        }

        ret.put("results", retArray);
    } catch (Exception e) {
        logger.warn("Failed to retrieve list items", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:cn.teamlab.wg.framework.struts2.json.PackageBasedActionConfigBuilder.java

private UrlSet buildUrlSet(List<URL> resourceUrls) throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(resourceUrls);
    urlSet = urlSet.include(new UrlSet(classLoaderInterface, this.fileProtocols));

    // excluding the urls found by the parent class loader is desired, but
    // fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        // exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        // if reload is enabled, we need to step up one level, otherwise the
        // UrlSet will be empty
        // this happens because the parent of the realoding class loader is
        // the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {// w w w .  ja v a2 s.  c o m
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    // try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface, new UrlSet.FileProtocolNormalizer() {
        public URL normalizeToFileProtocol(URL url) {
            return fileManager.normalizeToFileProtocol(url);
        }
    });

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home
        // directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    String[] localIncludeJars = cn.teamlab.wg.framework.struts2.json.util.StringUtils.concat(includeJars,
            conventionIncludeJars);

    if (localIncludeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        // jar urls regexes were specified
        List<URL> rawIncludedUrls = urlSet.getUrls();
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[localIncludeJars.length];

        for (URL url : rawIncludedUrls) {
            if (fileProtocols.contains(url.getProtocol())) {
                // it is a jar file, make sure it macthes at least a url
                // regex
                for (int i = 0; i < localIncludeJars.length; i++) {
                    String includeJar = localIncludeJars[i];
                    if (Pattern.matches(includeJar, url.toExternalForm())) {
                        includeUrls.add(url);
                        patternUsed[i] = true;
                        break;
                    }
                }
            } else {
                // it is not a jar
                includeUrls.add(url);
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            localIncludeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:es.cenobit.struts2.json.PackageBasedActionConfigBuilder.java

private UrlSet buildUrlSet(List<URL> resourceUrls) throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(resourceUrls);
    urlSet = urlSet.include(new UrlSet(classLoaderInterface, this.fileProtocols));

    // excluding the urls found by the parent class loader is desired, but
    // fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        // exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        // if reload is enabled, we need to step up one level, otherwise the
        // UrlSet will be empty
        // this happens because the parent of the realoding class loader is
        // the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {/*from w ww.  j a v a2s .c  om*/
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    // try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface, new UrlSet.FileProtocolNormalizer() {
        public URL normalizeToFileProtocol(URL url) {
            return fileManager.normalizeToFileProtocol(url);
        }
    });

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home
        // directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    String[] localIncludeJars = es.cenobit.struts2.json.util.StringUtils.concat(includeJars,
            conventionIncludeJars);

    if (localIncludeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        // jar urls regexes were specified
        List<URL> rawIncludedUrls = urlSet.getUrls();
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[localIncludeJars.length];

        for (URL url : rawIncludedUrls) {
            if (fileProtocols.contains(url.getProtocol())) {
                // it is a jar file, make sure it macthes at least a url
                // regex
                for (int i = 0; i < localIncludeJars.length; i++) {
                    String includeJar = localIncludeJars[i];
                    if (Pattern.matches(includeJar, url.toExternalForm())) {
                        includeUrls.add(url);
                        patternUsed[i] = true;
                        break;
                    }
                }
            } else {
                // it is not a jar
                includeUrls.add(url);
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            localIncludeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:net.rim.ejde.internal.util.VMUtils.java

/**
 * Returns the version of the given VM. It looks from the last segment of "ee.description". If it is not a valid version
 * string (x.x.x.x), returns default version 0.0.0.0.
 *
 * @param vm/*from   ww w  .  ja v  a  2 s . c o m*/
 *            The VM
 * @return The version of the VM.
 */
public static String getVMVersion(IVMInstall vm) {
    BlackBerrySDKInstall bbVM = (BlackBerrySDKInstall) vm;

    String ver = bbVM.getAttribute(BlackBerryVMInstallType.ATTR_VERSION);
    // new VMs has version in ee.version property
    if (ver != null) {
        return ver;
    }

    String desc = bbVM.getAttribute(BlackBerryVMInstallType.ATTR_DESCRIPTION);
    // Handle old VMs that do not have the description attribute
    if (desc == null) {
        return IConstants.DEFAULT_VM_VERSION;
    }
    String[] tokens = desc.split(" ");
    String version = IConstants.DEFAULT_VM_VERSION;
    if (tokens.length > 0) {
        if (Pattern.matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+", tokens[tokens.length - 1])) {
            version = tokens[tokens.length - 1];
        } else {
            _log.error("Invalid VM version found on " + vm.getId());
        }
    }
    return version;
}

From source file:com.hp.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchReleases(String term, long workspaceId) {
    int defaultSize = 5;
    JSONObject ret = new JSONObject();

    MqmRestClient client;// w  w  w .jav  a2s .co  m
    try {
        client = createClient();
    } catch (ClientException e) {
        logger.warn(PRODUCT_NAME + " connection failed", e);
        return error(e.getMessage(), e.getLink());
    }
    try {
        PagedList<Release> releasePagedList = client.queryReleases(term, workspaceId, 0, defaultSize);
        List<Release> releases = releasePagedList.getItems();
        boolean moreResults = releasePagedList.getTotalCount() > releases.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        String quotedTerm = Pattern.quote(term.toLowerCase());
        if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
            JSONObject notSpecifiedItemJson = new JSONObject();
            notSpecifiedItemJson.put("id", -1);
            notSpecifiedItemJson.put("text", NOT_SPECIFIED);
            retArray.add(notSpecifiedItemJson);
        }

        for (Release release : releases) {
            JSONObject relJson = new JSONObject();
            relJson.put("id", release.getId());
            relJson.put("text", release.getName());
            retArray.add(relJson);
        }
        ret.put("results", retArray);

    } catch (RequestException e) {
        logger.warn("Failed to retrieve releases", e);
        return error("Unable to retrieve releases");
    }

    return ret;
}

From source file:de.rub.nds.burp.espresso.gui.attacker.saml.UIDTDAttack.java

private void adjustDTDButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adjustDTDButtonActionPerformed
    switch ((String) dtdComboBox.getSelectedItem()) {
    case "Billion Laughs Attack":
        if (Pattern.matches("[0-9]+", recursiveEntitieTextField.getText())
                && Pattern.matches("[0-9]+", entityReferencesTextField.getText())) {
            String tmp = "\n";
            int rec = Integer.parseInt(recursiveEntitieTextField.getText());
            int entity = Integer.parseInt(entityReferencesTextField.getText());
            for (int i = 1; i <= rec; i++) {
                tmp += "<!ENTITY a" + i + " \"";
                for (int j = 1; j <= entity; j++) {
                    tmp += "&a" + (i - 1) + ";";
                }//  w w  w  .ja  va2s  . c o m
                tmp += "\">\n";
            }
            tmp += "]>\n" + "<data>&a" + rec + ";</data>";
            currentDtdServer = selectedDtdServer.substring(0, selectedDtdServer.lastIndexOf("\"dos\" >") + 7)
                    .concat(tmp);
        }
        break;
    case "Billion Laughs Attack with Parameter Entities":
        if (Pattern.matches("[0-9]+", recursiveEntitieTextField.getText())
                && Pattern.matches("[0-9]+", entityReferencesTextField.getText())) {
            String tmp = "\n";
            int rec = Integer.parseInt(recursiveEntitieTextField.getText());
            int entity = Integer.parseInt(entityReferencesTextField.getText());
            for (int i = 1; i <= rec; i++) {
                tmp += "<!ENTITY % a" + i + " \"";
                for (int j = 1; j <= entity; j++) {
                    tmp += "%a" + (i - 1) + ";";
                }
                tmp += "\">\n";
            }
            tmp += "<!ENTITY g  \"%a" + rec + ";\">";
            currentDtdHelper = selectedDtdHelper.substring(0, selectedDtdHelper.lastIndexOf("\"dos\" >") + 7)
                    .concat(tmp);
        }
        break;
    case "Quadratic Blowup Attack":
        if (Pattern.matches("[0-9]+", entityReferencesTextField.getText())) {
            int entity = Integer.parseInt(entityReferencesTextField.getText());
            String tmp = "";
            for (int i = 1; i <= entity; i++) {
                tmp += "&a0;";
            }
            tmp += "</data>";
            currentDtdServer = selectedDtdServer.substring(0, selectedDtdServer.lastIndexOf("<data>") + 6)
                    .concat(tmp);
        }
        break;
    }
    setDTD();
}

From source file:eu.eidas.node.auth.connector.AUCONNECTORSAML.java

private void validateAttributeValueFormat(String value, String currentAttrName, String attrNameToTest,
        String pattern) throws ValidationException {
    if (currentAttrName.equals(attrNameToTest) && !Pattern.matches(pattern, value)) {
        throw new ValidationException(attrNameToTest + " has incorrect format.");
    }/*from ww  w. j  a  v  a 2 s  .c o  m*/

}