Example usage for java.util.regex Pattern DOTALL

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

Introduction

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

Prototype

int DOTALL

To view the source code for java.util.regex Pattern DOTALL.

Click Source Link

Document

Enables dotall mode.

Usage

From source file:opennlp.tools.similarity.apps.utils.Utils.java

public static String stripStyleTags(String text) {
    Pattern p = java.util.regex.Pattern.compile("\\<STYLE.*?</STYLE>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Matcher matcher = p.matcher(text);
    String tmp = matcher.replaceAll("");
    return tmp;//from  w w w .j a  v  a  2  s  .c  o m
}

From source file:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Returns {@code true} if the query content matches an SQL SELECT statement
 * syntax (see {@link #RX_SELECT}./*from w w  w. j  a v a2 s. c  o m*/
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL SELECT statement
 *         syntax
 */
public boolean isSelect(String code) {
    Matcher matcher = Pattern.compile(RX_SELECT, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(code);
    return matcher.matches();
}

From source file:com.ichi2.libanki.Finder.java

private String _findField(String field, String val) {
    /*/*w  w w .  j a  va 2s.co  m*/
     * We need two expressions to query the cards: One that will use JAVA REGEX syntax and another
     * that should use SQLITE LIKE clause syntax.
     */
    String sqlVal = val.replace("%", "\\%") // For SQLITE, we escape all % signs
            .replace("*", "%"); // And then convert the * into non-escaped % signs

    /*
     * The following three lines make sure that only _ and * are valid wildcards.
     * Any other characters are enclosed inside the \Q \E markers, which force
     * all meta-characters in between them to lose their special meaning
     */
    String javaVal = val.replace("_", "\\E.\\Q").replace("*", "\\E.*\\Q");
    /*
     * For the pattern, we use the javaVal expression that uses JAVA REGEX syntax
     */
    Pattern pattern = Pattern.compile("\\Q" + javaVal + "\\E", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    // find models that have that field
    Map<Long, Object[]> mods = new HashMap<Long, Object[]>();
    try {
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") });
                }
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (mods.isEmpty()) {
        // nothing has that field
        return null;
    }
    LinkedList<Long> nids = new LinkedList<Long>();
    Cursor cur = null;
    try {
        /*
         * Here we use the sqlVal expression, that is required for LIKE syntax in sqllite.
         * There is no problem with special characters, because only % and _ are special
         * characters in this syntax.
         */
        cur = mCol.getDb().getDatabase()
                .rawQuery("select id, mid, flds from notes where mid in "
                        + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'",
                        new String[] { "%" + sqlVal + "%" });

        while (cur.moveToNext()) {
            String[] flds = Utils.splitFields(cur.getString(2));
            int ord = (Integer) mods.get(cur.getLong(1))[1];
            String strg = flds[ord];
            if (pattern.matcher(strg).matches()) {
                nids.add(cur.getLong(0));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (nids.isEmpty()) {
        return "0";
    }
    return "n.id in " + Utils.ids2str(nids);
}

From source file:com.ikanow.infinit.e.data_model.store.config.source.SourcePojo.java

public static void initSearchIndexFilter(SourceSearchIndexFilter searchIndexFilter) {
    if (null != searchIndexFilter) { // Initialize regex
        if ((null != searchIndexFilter.assocFilter) && (null == searchIndexFilter.assocFilterRegex)) {
            if (searchIndexFilter.assocFilter.startsWith("+")
                    || searchIndexFilter.assocFilter.startsWith("-")) {
                searchIndexFilter.assocFilterRegex = Pattern.compile(searchIndexFilter.assocFilter.substring(1),
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
            } else {
                searchIndexFilter.assocFilterRegex = Pattern.compile(searchIndexFilter.assocFilter,
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
            }/*  w w w .j  a va  2s. c o m*/
        }
        if ((null != searchIndexFilter.assocGeoFilter) && (null == searchIndexFilter.assocGeoFilterRegex)) {
            if (searchIndexFilter.assocGeoFilter.startsWith("+")
                    || searchIndexFilter.assocGeoFilter.startsWith("-")) {
                searchIndexFilter.assocGeoFilterRegex = Pattern.compile(
                        searchIndexFilter.assocGeoFilter.substring(1),
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
            } else {
                searchIndexFilter.assocGeoFilterRegex = Pattern.compile(searchIndexFilter.assocGeoFilter,
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
            }
        }
        if ((null != searchIndexFilter.entityFilter) && (null == searchIndexFilter.entityFilterRegex)) {
            if (searchIndexFilter.entityFilter.startsWith("+")
                    || searchIndexFilter.entityFilter.startsWith("-")) {
                searchIndexFilter.entityFilterRegex = Pattern
                        .compile(searchIndexFilter.entityFilter.substring(1), Pattern.CASE_INSENSITIVE);
            } else {
                searchIndexFilter.entityFilterRegex = Pattern.compile(searchIndexFilter.entityFilter,
                        Pattern.CASE_INSENSITIVE);
            }
        }
        if ((null != searchIndexFilter.entityGeoFilter) && (null == searchIndexFilter.entityGeoFilterRegex)) {
            if (searchIndexFilter.entityGeoFilter.startsWith("+")
                    || searchIndexFilter.entityGeoFilter.startsWith("-")) {
                searchIndexFilter.entityGeoFilterRegex = Pattern
                        .compile(searchIndexFilter.entityGeoFilter.substring(1), Pattern.CASE_INSENSITIVE);
            } else {
                searchIndexFilter.entityGeoFilterRegex = Pattern.compile(searchIndexFilter.entityGeoFilter,
                        Pattern.CASE_INSENSITIVE);
            }
        }
    } // (end if search filter specified)
}

From source file:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Returns {@code true} if the query content matches an SQL UPDATE statement
 * syntax (see {@link #RX_UPDATE}.//  w w  w.j  a v  a2s. c  o m
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL UPDATe statement
 *         syntax
 */
public boolean isUpdate(String code) {
    Matcher matcher = Pattern.compile(RX_UPDATE, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(code);
    return matcher.matches();
}

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

/**
 * HTTP ?//from   w  w  w.  j a  v a 2s. c om
 * 
 * @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:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Returns {@code true} if the query content matches an SQL INSERT statement
 * syntax (see {@link #RX_INSERT}./*  w  ww  .  ja v  a2  s .  c om*/
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL INSERT statement
 *         syntax
 */
public boolean isInsert(String code) {
    Matcher matcher = Pattern.compile(RX_INSERT, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(code);
    return matcher.matches();
}

From source file:tk.halfgray.pcommandbot.PCommandBot.java

/**
 * Process any commands in a message into an array of responses.
 * @param channel Channel from which the message originated,
 * or {@code null} if it was a private message
 * @param sender Sender of the message/*from  www . j  a v  a  2  s  .c  o  m*/
 * @param message Message text
 * @return Array of responses (with mentions added), possibly empty
 * @throws IllegalStateException If the bot is not ready
 * @see #isReady()
 */
protected String[] processCommands(String channel, String sender, String message) {
    if (!isReady()) {
        throw new IllegalStateException("Bot is not ready");
    }
    String termpattern;
    if (getArgumentTerminator().isEmpty()) {
        termpattern = "$";
    } else {
        termpattern = "(?:" + Pattern.quote(getArgumentTerminator()) + "|$)";
    }
    Matcher matcher = Pattern
            .compile(Pattern.quote(getCommandPrefix()) + "([^\\p{javaSpaceChar}\\p{javaISOControl}]+?)" + "("
                    + Utilities.WHITESPACE.pattern() + "(.*?)" + ")?" + termpattern, Pattern.DOTALL)
            .matcher(message);
    String[] mentions;
    if (channel != null) {
        mentions = getMentions(channel, message);
    } else {
        mentions = new String[0];
    }
    List<String> responses = new java.util.ArrayList<String>();
    String lccmdstr;
    String argument;
    String[] synonyms;
    String response;
    while (matcher.find()) {
        lccmdstr = matcher.group(1).toLowerCase(Locale.ENGLISH);
        argument = matcher.group(3);
        //If there is nothing after the command string,
        //groups 2 and 3 will be null
        if (argument == null) {
            argument = "";
        } else {
            argument = Utilities.supertrim(argument);
        }
        //Check synonymous command
        if (getSynonymousCommands().containsKey(lccmdstr)) {
            synonyms = getSynonymousCommands().get(lccmdstr);
            for (String synonym : synonyms) {
                if (getResponders().containsKey(synonym)) {
                    response = getResponders().get(synonym).respond(channel, sender, mentions, argument);
                    if (!response.isEmpty()) {
                        responses.add(Utilities.toMentionPrefix(mentions) + response);
                    }
                }
            }
            //Do not check regular responder
            continue;
        }
        //Check regular responder
        if (getResponders().containsKey(lccmdstr)) {
            response = getResponders().get(lccmdstr).respond(channel, sender, mentions, argument);
            if (!response.isEmpty()) {
                responses.add(Utilities.toMentionPrefix(mentions) + response);
            }
        }
    }
    return responses.toArray(new String[0]);
}

From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java

/**
 * Process the mappings after xsl transformation
 * //from  w  w  w  .j ava 2 s. c  o  m
 * @param xrefElement
 * @return the processed Element
 */
private Element processMappings(Element xrefElement) throws XtentisException {

    try {

        String xrefcluster = xrefElement.getAttribute("xrefCluster"); //$NON-NLS-1$

        String xrefIn = xrefElement.getAttribute("xrefIn"); //$NON-NLS-1$
        String xrefOut = xrefElement.getAttribute("xrefOut"); //$NON-NLS-1$
        String xrefIgnore = xrefElement.getAttribute("xrefIgnore"); //$NON-NLS-1$
        String xrefDefault = xrefElement.getAttribute("xrefDefault"); //$NON-NLS-1$

        Logger.getLogger(XSLTTransformerPluginBean.class)
                .debug("\n xrefIgnore=" + xrefIgnore + "\n xrefDefault=" + xrefDefault); //$NON-NLS-1$ //$NON-NLS-2$

        // parse xrefbein dockey1:xrefkey1,dockey2:xrefkey2
        String[] mappings = xrefIn.split(","); //$NON-NLS-1$
        HashMap<String, String> itemvals = new HashMap<String, String>();
        for (int j = 0; j < mappings.length; j++) {
            String[] relations = mappings[j].split("="); //$NON-NLS-1$
            String docpath = relations[0];
            String xrefpath = relations[1];
            String itemval = ""; //$NON-NLS-1$
            try {
                if (docpath.startsWith("[")) // hardcoded value //$NON-NLS-1$
                    itemval = docpath.substring(1, docpath.length() - 1);
                else
                    itemval = Util.getFirstTextNode(xrefElement, docpath);
            } catch (Exception x) {
                throw new XtentisException(
                        "Value for business element '" + xrefElement.getNodeName() + '/' + docpath //$NON-NLS-1$
                                + "' cannot be found!"); //$NON-NLS-1$
            }
            if (itemval == null)
                itemval = ""; //$NON-NLS-1$
            String content = stripeOuterBracket(itemval);
            if (content.split(",").length >= mappings.length) //$NON-NLS-1$
                itemvals.put(xrefpath, content.split(",")[j]); //$NON-NLS-1$
            else
                itemvals.put(xrefpath, ""); //$NON-NLS-1$
        }

        WhereAnd wAnd = new WhereAnd();

        Collection<Map.Entry<String, String>> c = itemvals.entrySet();
        int i = 0;
        for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) {
            i++;
            Map.Entry<String, String> entry = iter.next();
            wAnd.add(new WhereCondition(entry.getKey(), WhereCondition.EQUALS, entry.getValue(),
                    WhereCondition.PRE_NONE, false));
        }

        ArrayList<String> resList = Util.getItemCtrl2Local().xPathsSearch(new DataClusterPOJOPK(xrefcluster),
                null, new ArrayList<String>(Arrays.asList(new String[] { xrefOut })), wAnd, -1, // spell
                0, // start
                1, // limit
                false);

        String val = ""; //$NON-NLS-1$

        if ((resList == null) || (resList.size() == 0)) {
            if (xrefIgnore.equals("true") || xrefIgnore.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$
                if (xrefDefault != null)
                    val = xrefDefault;
                else
                    val = ""; //$NON-NLS-1$
            } else {
                String ks = ""; //$NON-NLS-1$
                c = itemvals.entrySet();
                for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) {
                    Map.Entry<String, String> entry = iter.next();
                    ks += " " + entry.getKey() + "=\"" + entry.getValue() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                }
                throw new XtentisException("Foreign keys values not found for: " + ks); //$NON-NLS-1$
            }
        } else {
            // read result
            Pattern p = Pattern.compile("<.*?>(.*?)</.*>", Pattern.DOTALL); //$NON-NLS-1$
            Matcher m = p.matcher(resList.iterator().next());

            if (m.matches())
                val = StringEscapeUtils.unescapeXml(m.group(1));
            else {
                Pattern p2 = Pattern.compile("<.*?/>", Pattern.DOTALL); //$NON-NLS-1$
                Matcher m2 = p2.matcher(resList.iterator().next());
                if (!m2.matches() && !(xrefIgnore.equals("true") || xrefIgnore.equals("1"))) { //$NON-NLS-1$ //$NON-NLS-2$
                    throw new XtentisException("Result values were not understood for crossref element"); //$NON-NLS-1$
                }
            }
        }

        NodeList l = xrefElement.getChildNodes();
        for (int j = 0; j < l.getLength(); j++) {
            switch (l.item(j).getNodeType()) {
            case Node.TEXT_NODE:
                l.item(j).setNodeValue(val);
                break;
            case Node.ELEMENT_NODE:
                xrefElement.removeChild(l.item(j));
                break;
            default:

            }
        }

        xrefElement.removeAttribute("xrefCluster"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefIgnore"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefDefault"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefIn"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefOut"); //$NON-NLS-1$

        return xrefElement;
    } catch (Exception e) {
        String err = "Unable to process the mappings for the element '" + xrefElement.getLocalName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$
        LOG.error(err, e);
        throw new XtentisException(err);
    }
}

From source file:de.mpg.mpdl.inge.exportmanager.Export.java

/**
 * Walk around the itemList XML, fetch all files from components via URIs and put them into the
 * archive {@link OutputStream} aos/*www .j a  v  a  2  s. co  m*/
 * 
 * @param aos - array {@link OutputStream}
 * @param itemList - XML with the files to be fetched, see NS:
 *        http://www.escidoc.de/schemas/components/0.7
 * @throws ExportManagerException
 */
private void fetchComponentsDo(OutputStream aos, String itemList) throws ExportManagerException {
    Document doc = parseDocument(itemList);
    NodeIterator ni = getFilteredNodes(new ComponentNodeFilter(), doc);

    // login only once
    String userHandle;
    try {
        userHandle = AdminHelper.loginUser(USER_ID, PASSWORD);
    } catch (Exception e) {
        throw new ExportManagerException("Cannot login", e);
    }

    String fileName;
    Node n;
    while ((n = ni.nextNode()) != null) {

        Element componentElement = (Element) n;
        NodeList nl = componentElement.getElementsByTagNameNS(COMPONENTS_NS, "content");
        Element contentElement = (Element) nl.item(0);
        if (contentElement == null) {
            throw new ExportManagerException(
                    "Wrong item XML: {" + COMPONENTS_NS + "}component element doesn't contain content element. "
                            + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
        }
        String href = contentElement.getAttributeNS(XLINK_NS, "href");
        String storageStatus = contentElement.getAttribute("storage");

        // get file name
        if ("internal-managed".equals(storageStatus)) {
            NodeIterator nif = ((DocumentTraversal) doc).createNodeIterator(componentElement,
                    NodeFilter.SHOW_ELEMENT, new FileNameNodeFilter(), true);
            Node nf;

            if ((nf = nif.nextNode()) != null) {
                fileName = ((Element) nf).getTextContent();

                // names of files for
                Matcher m = Pattern.compile("^([\\w.]+?)(\\s+|$)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
                        .matcher(fileName);
                m.find();
                fileName = m.group(1);
            } else {
                throw new ExportManagerException("Missed file property: {" + COMPONENTS_NS
                        + "}component element doesn't contain file-name element (md-records/md-record/file:file/dc:title). "
                        + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
            }
        }
        // TODO: the external-managed will be processed later
        else {
            throw new ExportManagerException("Missed internal-managed file in {" + COMPONENTS_NS
                    + "}component: components/component/content[@storage=\"internal-managed\"]"
                    + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
        }

        logger.info("link to the content: " + href);
        logger.info("storage status: " + storageStatus);
        logger.info("fileName: " + fileName);

        // get file via URI
        String url;
        try {
            url = PropertyReader.getFrameworkUrl() + href;
        } catch (Exception e) {
            throw new ExportManagerException("Cannot get framework url", e);
        }

        logger.info("url=" + url);
        GetMethod method = new GetMethod(url);

        method.setFollowRedirects(false);
        method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);

        // Execute the method with HttpClient.
        HttpClient client = new HttpClient();
        try {
            ProxyHelper.executeMethod(client, method);
        } catch (Exception e) {
            throw new ExportManagerException("Cannot execute HttpMethod", e);
        }

        int status = method.getStatusCode();
        logger.info("Status=" + status);

        if (status != 200)
            fileName += ".error" + status;

        byte[] responseBody;
        try {
            responseBody = method.getResponseBody();
        } catch (Exception e) {

            throw new ExportManagerException("Cannot get Response Body", e);

        }
        InputStream bis = new BufferedInputStream(new ByteArrayInputStream(responseBody));

        if (aos instanceof ZipOutputStream) {
            ZipEntry ze = new ZipEntry(fileName);
            ze.setSize(responseBody.length);
            try {
                ((ZipOutputStream) aos).putNextEntry(ze);
                writeFromStreamToStream(bis, aos);
                ((ZipOutputStream) aos).closeEntry();
            } catch (Exception e) {
                throw new ExportManagerException("zip2stream generation problem", e);
            }

        } else if (aos instanceof TarOutputStream) {
            TarEntry te = new TarEntry(fileName);
            te.setSize(responseBody.length);
            try {
                ((TarOutputStream) aos).putNextEntry(te);
                writeFromStreamToStream(bis, aos);
                ((TarOutputStream) aos).closeEntry();
            } catch (Exception e) {
                throw new ExportManagerException("tar2stream generation problem", e);
            }
        } else {
            throw new ExportManagerException("Unsupported archive output stream: " + aos.getClass());
        }
        try {
            bis.close();
        } catch (Exception e) {
            throw new ExportManagerException("Cannot close InputStream", e);
        }
    }

}