Search in sources :

Example 21 with MatchResult

use of org.apache.oro.text.regex.MatchResult in project tdi-studio-se by Talend.

the class WebServiceExpressionParser method parseInTableEntryLocations.

public Map<String, String> parseInTableEntryLocations(String expression) {
    // resultSet.clear();
    Map<String, String> map = new HashMap<String, String>();
    if (expression != null) {
        matcher.setMultiline(true);
        if (patternMatcherInput == null) {
            patternMatcherInput = new PatternMatcherInput(expression);
        } else {
            patternMatcherInput.setInput(expression);
        }
        recompilePatternIfNecessary(locationPattern);
        while (matcher.contains(patternMatcherInput, pattern)) {
            MatchResult matchResult = matcher.getMatch();
            map.put(matchResult.group(2), matchResult.group(1));
        // resultSet.add(map);
        }
    }
    // .toArray(new TableEntryLocation[0]);
    return map;
}
Also used : PatternMatcherInput(org.apache.oro.text.regex.PatternMatcherInput) HashMap(java.util.HashMap) MatchResult(org.apache.oro.text.regex.MatchResult)

Example 22 with MatchResult

use of org.apache.oro.text.regex.MatchResult in project tdi-studio-se by Talend.

the class JSONFileOutputStep1Form method addFieldsListeners.

@Override
protected void addFieldsListeners() {
    jsonFilePath.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            if (jsonFilePath.getResult() == null) {
                return;
            }
            String text = jsonFilePath.getText();
            if (isContextMode()) {
                ContextType contextType = ConnectionContextHelper.getContextTypeForContextMode(connectionItem.getConnection(), true);
                text = TalendQuoteUtils.removeQuotes(ConnectionContextHelper.getOriginalValue(contextType, text));
            }
            // getConnection().setJSONFilePath(PathUtils.getPortablePath(JSONXsdFilePath.getText()));
            if (JSONFileOutputStep1Form.this.tempPath == null) {
                JSONFileOutputStep1Form.this.tempPath = JSONUtil.changeJsonToXml(text);
            }
            File file = new File(text);
            if (file.exists()) {
                List<ATreeNode> treeNodes = new ArrayList<ATreeNode>();
                valid = treePopulator.populateTree(JSONUtil.changeJsonToXml(text), treeNode);
                checkFieldsValue();
                if (!valid) {
                    return;
                }
                if (treeNodes.size() > 0) {
                    treeNode = treeNodes.get(0);
                }
                updateConnection(text);
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    jsonFilePath.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent event) {
            String text = jsonFilePath.getText();
            if (isContextMode()) {
                ContextType contextType = ConnectionContextHelper.getContextTypeForContextMode(connectionItem.getConnection(), true);
                text = TalendQuoteUtils.removeQuotes(ConnectionContextHelper.getOriginalValue(contextType, text));
            }
            if (getConnection().getJSONFilePath() != null && !getConnection().getJSONFilePath().equals(text)) {
                getConnection().getLoop().clear();
                getConnection().getRoot().clear();
                getConnection().getGroup().clear();
                xsdPathChanged = true;
            } else {
                xsdPathChanged = false;
            }
            if (Path.fromOSString(jsonFilePath.getText()).toFile().isFile()) {
                getConnection().setJSONFilePath(PathUtils.getPortablePath(jsonFilePath.getText()));
            } else {
                getConnection().setJSONFilePath(jsonFilePath.getText());
            }
            // updateConnection(text);
            StringBuilder fileContent = new StringBuilder();
            BufferedReader in = null;
            File file = null;
            if (tempJSONPath != null && getConnection().getFileContent() != null && getConnection().getFileContent().length > 0 && !isModifing) {
                file = new File(tempJSONPath);
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e2) {
                        ExceptionHandler.process(e2);
                    }
                    FileOutputStream outStream;
                    try {
                        outStream = new FileOutputStream(file);
                        outStream.write(getConnection().getFileContent());
                        outStream.close();
                    } catch (FileNotFoundException e1) {
                        ExceptionHandler.process(e1);
                    } catch (IOException e) {
                        ExceptionHandler.process(e);
                    }
                }
            } else {
                file = new File(text);
            }
            String str;
            try {
                Charset guessCharset = CharsetToolkit.guessEncoding(file, 4096);
                in = new BufferedReader(new InputStreamReader(new FileInputStream(file), guessCharset.displayName()));
                while ((str = in.readLine()) != null) {
                    fileContent.append(str + "\n");
                    // for encoding
                    if (str.contains("encoding")) {
                        String regex = "^<\\?JSON\\s*version=\\\"[^\\\"]*\\\"\\s*encoding=\\\"([^\\\"]*)\\\"\\?>$";
                        Perl5Compiler compiler = new Perl5Compiler();
                        Perl5Matcher matcher = new Perl5Matcher();
                        Pattern pattern = null;
                        try {
                            pattern = compiler.compile(regex);
                            if (matcher.contains(str, pattern)) {
                                MatchResult matchResult = matcher.getMatch();
                                if (matchResult != null) {
                                    encoding = matchResult.group(1);
                                }
                            }
                        } catch (MalformedPatternException malE) {
                            ExceptionHandler.process(malE);
                        }
                    }
                }
                fileContentText.setText(new String(fileContent));
            } catch (Exception e) {
                String msgError = "File" + " \"" + jsonFilePath.getText().replace("\\\\", "\\") + "\"\n";
                if (e instanceof FileNotFoundException) {
                    msgError = msgError + "is not found";
                } else if (e instanceof EOFException) {
                    msgError = msgError + "have an incorrect character EOF";
                } else if (e instanceof IOException) {
                    msgError = msgError + "is locked by another soft";
                } else {
                    msgError = msgError + "doesn't exist";
                }
                fileContentText.setText(msgError);
                if (!isReadOnly()) {
                    updateStatus(IStatus.ERROR, msgError);
                }
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception exception) {
                    ExceptionHandler.process(exception);
                }
            }
            if (getConnection().getEncoding() == null || "".equals(getConnection().getEncoding())) {
                getConnection().setEncoding(encoding);
                if (encoding != null && !"".equals(encoding)) {
                    encodingCombo.setText(encoding);
                } else {
                    encodingCombo.setText("UTF-8");
                }
            }
            // }
            if (file.exists()) {
                valid = treePopulator.populateTree(JSONUtil.changeJsonToXml(text), treeNode);
                updateConnection(text);
            }
            checkFieldsValue();
            isModifing = true;
        }
    });
    encodingCombo.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            getConnection().setEncoding(encodingCombo.getText());
            checkFieldsValue();
        }
    });
    commonNodesLimitation.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            String str = commonNodesLimitation.getText();
            if ((!str.matches("\\d+")) || (Integer.valueOf(str) < 0)) {
                commonNodesLimitation.setText(String.valueOf(treePopulator.getLimit()));
                labelLimitation.setToolTipText(MessageFormat.format(Messages.JSONLimitToolTip, commonNodesLimitation.getText()));
            } else {
                treePopulator.setLimit(Integer.valueOf(str));
                labelLimitation.setToolTipText(MessageFormat.format(Messages.JSONLimitToolTip, str));
            }
            if (JSONFileOutputStep1Form.this.tempPath == null) {
                JSONFileOutputStep1Form.this.tempPath = JSONUtil.changeJsonToXml(jsonFilePath.getText());
            }
            File file = new File(JSONFileOutputStep1Form.this.tempPath);
            if (file.exists()) {
                valid = treePopulator.populateTree(JSONFileOutputStep1Form.this.tempPath, treeNode);
            }
            checkFieldsValue();
        }
    });
    commonNodesLimitation.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
        }

        @Override
        public void focusLost(FocusEvent e) {
            commonNodesLimitation.setText(String.valueOf(TreePopulator.getLimit()));
            labelLimitation.setToolTipText(MessageFormat.format(Messages.JSONLimitToolTip, commonNodesLimitation.getText()));
        }
    });
    outputFilePath.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            getConnection().setOutputFilePath(PathUtils.getPortablePath(outputFilePath.getText()));
            checkFieldsValue();
        }
    });
}
Also used : ModifyListener(org.eclipse.swt.events.ModifyListener) FileNotFoundException(java.io.FileNotFoundException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult) FocusEvent(org.eclipse.swt.events.FocusEvent) ModifyEvent(org.eclipse.swt.events.ModifyEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) EOFException(java.io.EOFException) List(java.util.List) ArrayList(java.util.ArrayList) EList(org.eclipse.emf.common.util.EList) MalformedPatternException(org.apache.oro.text.regex.MalformedPatternException) ContextType(org.talend.designer.core.model.utils.emf.talendfile.ContextType) Perl5Compiler(org.apache.oro.text.regex.Perl5Compiler) Pattern(org.apache.oro.text.regex.Pattern) InputStreamReader(java.io.InputStreamReader) Charset(java.nio.charset.Charset) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) MalformedPatternException(org.apache.oro.text.regex.MalformedPatternException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) PersistenceException(org.talend.commons.exception.PersistenceException) ATreeNode(org.talend.datatools.xml.utils.ATreeNode) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) RecordFile(orgomg.cwm.resource.record.RecordFile) File(java.io.File) FocusListener(org.eclipse.swt.events.FocusListener) SelectionListener(org.eclipse.swt.events.SelectionListener)

Example 23 with MatchResult

use of org.apache.oro.text.regex.MatchResult in project jmeter by apache.

the class TestHTTPSamplersAgainstHttpMirrorServer method getPositionOfBody.

private int getPositionOfBody(String stringToCheck) {
    Perl5Matcher localMatcher = JMeterUtils.getMatcher();
    // The headers and body are divided by a blank line
    String regularExpression = "^.$";
    Pattern pattern = JMeterUtils.getPattern(regularExpression, Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.MULTILINE_MASK);
    PatternMatcherInput input = new PatternMatcherInput(stringToCheck);
    while (localMatcher.contains(input, pattern)) {
        MatchResult match = localMatcher.getMatch();
        return match.beginOffset(0);
    }
    // No divider was found
    return -1;
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) PatternMatcherInput(org.apache.oro.text.regex.PatternMatcherInput) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult)

Example 24 with MatchResult

use of org.apache.oro.text.regex.MatchResult in project jmeter by apache.

the class RegexExtractor method process.

/**
     * Parses the response data using regular expressions and saving the results
     * into variables for use later in the test.
     *
     * @see org.apache.jmeter.processor.PostProcessor#process()
     */
@Override
public void process() {
    initTemplate();
    JMeterContext context = getThreadContext();
    SampleResult previousResult = context.getPreviousResult();
    if (previousResult == null) {
        return;
    }
    log.debug("RegexExtractor processing result");
    // Fetch some variables
    JMeterVariables vars = context.getVariables();
    String refName = getRefName();
    int matchNumber = getMatchNumber();
    final String defaultValue = getDefaultValue();
    if (defaultValue.length() > 0 || isEmptyDefaultValue()) {
        // Only replace default if it is provided or empty default value is explicitly requested
        vars.put(refName, defaultValue);
    }
    Perl5Matcher matcher = JMeterUtils.getMatcher();
    String regex = getRegex();
    Pattern pattern = null;
    try {
        pattern = JMeterUtils.getPatternCache().getPattern(regex, Perl5Compiler.READ_ONLY_MASK);
        List<MatchResult> matches = processMatches(pattern, regex, previousResult, matchNumber, vars);
        int prevCount = 0;
        String prevString = vars.get(refName + REF_MATCH_NR);
        if (prevString != null) {
            // ensure old value is not left defined
            vars.remove(refName + REF_MATCH_NR);
            try {
                prevCount = Integer.parseInt(prevString);
            } catch (NumberFormatException nfe) {
                log.warn("Could not parse number: '{}'", prevString);
            }
        }
        // Number of refName_n variable sets to keep
        int matchCount = 0;
        try {
            MatchResult match;
            if (matchNumber >= 0) {
                // Original match behaviour
                match = getCorrectMatch(matches, matchNumber);
                if (match != null) {
                    vars.put(refName, generateResult(match));
                    saveGroups(vars, refName, match);
                } else {
                    // refname has already been set to the default (if present)
                    removeGroups(vars, refName);
                }
            } else // < 0 means we save all the matches
            {
                // remove any single matches
                removeGroups(vars, refName);
                matchCount = matches.size();
                // Save the count
                vars.put(refName + REF_MATCH_NR, Integer.toString(matchCount));
                for (int i = 1; i <= matchCount; i++) {
                    match = getCorrectMatch(matches, i);
                    if (match != null) {
                        final String refName_n = new StringBuilder(refName).append(UNDERSCORE).append(i).toString();
                        vars.put(refName_n, generateResult(match));
                        saveGroups(vars, refName_n, match);
                    }
                }
            }
            // Remove any left-over variables
            for (int i = matchCount + 1; i <= prevCount; i++) {
                final String refName_n = new StringBuilder(refName).append(UNDERSCORE).append(i).toString();
                vars.remove(refName_n);
                removeGroups(vars, refName_n);
            }
        } catch (RuntimeException e) {
            log.warn("Error while generating result");
        }
    } catch (MalformedCachePatternException e) {
        log.error("Error in pattern: '{}'", regex);
    } finally {
        JMeterUtils.clearMatcherMemory(matcher, pattern);
    }
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult)

Example 25 with MatchResult

use of org.apache.oro.text.regex.MatchResult in project jmeter by apache.

the class RenderAsRegexp method process.

private String process(String textToParse) {
    Perl5Matcher matcher = new Perl5Matcher();
    PatternMatcherInput input = new PatternMatcherInput(textToParse);
    PatternCacheLRU pcLRU = new PatternCacheLRU();
    Pattern pattern;
    try {
        pattern = pcLRU.getPattern(regexpField.getText(), Perl5Compiler.READ_ONLY_MASK);
    } catch (MalformedCachePatternException e) {
        return e.toString();
    }
    List<MatchResult> matches = new LinkedList<>();
    while (matcher.contains(input, pattern)) {
        matches.add(matcher.getMatch());
    }
    // Construct a multi-line string with all matches
    StringBuilder sb = new StringBuilder();
    final int size = matches.size();
    sb.append("Match count: ").append(size).append("\n");
    for (int j = 0; j < size; j++) {
        MatchResult mr = matches.get(j);
        final int groups = mr.groups();
        for (int i = 0; i < groups; i++) {
            sb.append("Match[").append(j + 1).append("][").append(i).append("]=").append(mr.group(i)).append("\n");
        }
    }
    return sb.toString();
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) PatternMatcherInput(org.apache.oro.text.regex.PatternMatcherInput) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult) LinkedList(java.util.LinkedList) PatternCacheLRU(org.apache.oro.text.PatternCacheLRU)

Aggregations

MatchResult (org.apache.oro.text.regex.MatchResult)25 PatternMatcherInput (org.apache.oro.text.regex.PatternMatcherInput)16 Perl5Matcher (org.apache.oro.text.regex.Perl5Matcher)15 Pattern (org.apache.oro.text.regex.Pattern)14 ArrayList (java.util.ArrayList)10 MalformedCachePatternException (org.apache.oro.text.MalformedCachePatternException)4 Perl5Compiler (org.apache.oro.text.regex.Perl5Compiler)4 MalformedURLException (java.net.MalformedURLException)3 HashMap (java.util.HashMap)3 SampleResult (org.apache.jmeter.samplers.SampleResult)3 MalformedPatternException (org.apache.oro.text.regex.MalformedPatternException)3 PatternMatcher (org.apache.oro.text.regex.PatternMatcher)3 BufferedReader (java.io.BufferedReader)2 EOFException (java.io.EOFException)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 InputStreamReader (java.io.InputStreamReader)2 Charset (java.nio.charset.Charset)2