Example usage for java.util.regex Matcher groupCount

List of usage examples for java.util.regex Matcher groupCount

Introduction

In this page you can find the example usage for java.util.regex Matcher groupCount.

Prototype

public int groupCount() 

Source Link

Document

Returns the number of capturing groups in this matcher's pattern.

Usage

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Parse the change text of C line.//from   ww w  .java  2s . c  o  m
 *
 * @param forAddress Should parse for address or name?
 * @param changeText The change text of C line.
 * @return parsed string array with length 4.
 */
private static String[] captureChanges(boolean forAddress, String changeText) {
    String[] result = { "", "", "", "" };

    Matcher matcher = (forAddress ? ADDRESS_PATTERN : NAME_PATTERN).matcher(changeText);

    if (matcher.matches()) {
        int groupCount = matcher.groupCount();
        for (int i = 0; i < result.length; i++) {
            if (i + 1 <= groupCount) {
                String captured = matcher.group(i + 1);
                result[i] = captured == null ? result[i] : captured;
            }
        }
    }

    return result;
}

From source file:gtu._work.ui.RegexReplacer.java

/**
 * @param fromPattern//from   w ww.j  a va  2 s.  c o m
 *            ???pattern
 * @param toFormat
 *            ??pattern
 * @param replaceText
 *            ??
 */
String replacer(String fromPattern, String toFormat, String replaceText) {
    String errorRtn = replaceText.toString();
    try {
        int patternFlag = 0;

        // 
        if (multiLineCheckBox.isSelected()) {
            patternFlag = Pattern.DOTALL | Pattern.MULTILINE;
        }

        Pattern pattern = Pattern.compile(fromPattern, patternFlag);
        Matcher matcher = pattern.matcher(replaceText);

        StringBuffer sb = new StringBuffer();
        String tempStr = null;

        TradeOffConfig config = this.getTradeOffConfig();

        {
            int startPos = 0;
            for (; matcher.find();) {
                tempStr = toFormat.toString();
                sb.append(replaceText.substring(startPos, matcher.start()));

                // ----------------------------------------------
                if (StringUtils.isBlank(config.fremarkerKey)) {
                    // regex
                    for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                        System.out.println(ii + " -- " + matcher.group(ii));
                        tempStr = tempStr.replaceAll("#" + ii + "#",
                                Matcher.quoteReplacement(matcher.group(ii)));
                    }
                } else if (StringUtils.isNotBlank(config.fremarkerKey)) {
                    // freemarker
                    Map<String, Object> root = new HashMap<String, Object>();
                    TreeMap<Integer, Object> lstMap = new TreeMap<Integer, Object>();
                    for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                        lstMap.put(ii, matcher.group(ii));
                    }
                    root.put(StringUtils.trimToEmpty(config.fremarkerKey), lstMap.values());
                    System.out.println("template Map : " + root);
                    tempStr = FreeMarkerSimpleUtil.replace(tempStr, root);
                }
                // ----------------------------------------------

                sb.append(tempStr);
                startPos = matcher.end();
            }
            sb.append(replaceText.substring(startPos));
        }

        return sb.toString();
    } catch (Exception ex) {
        JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle());
        return errorRtn;
    }
}

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

/**
 * Returns {@code true} if the query content matches an SQL DELETE statement
 * syntax (see {@link #RX_DELETE}./*from ww w  .  j a  v  a  2  s  . c  o m*/
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL DELETE statement
 *         syntax
 * @since PROVISIONAL
 */
public boolean isRead(String code) {
    Matcher m1 = Pattern.compile(RX_FILE_URI).matcher(code);
    if (m1.matches()) {
        if (m1.groupCount() > 1 && m1.group(3) != null) {
            return false;
        }
        return true;
    }
    return false;
}

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

/**
 * Returns {@code true} if the query content matches an SQL DELETE statement
 * syntax (see {@link #RX_DELETE}./*  w  ww . j  a  va  2  s  .c om*/
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL DELETE statement
 *         syntax
 * @since PROVISIONAL
 */
public boolean isWrite(String code) {
    Matcher m1 = Pattern.compile(RX_FILE_URI).matcher(code);
    if (m1.matches()) {
        if (m1.groupCount() > 1 && m1.group(3) != null && m1.group(3).equals(WRITE)) {
            return true;
        }
        return false;
    }
    return false;
}

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

/**
 * Returns {@code true} if the query content matches an SQL DELETE statement
 * syntax (see {@link #RX_DELETE}./* w  w  w .  java 2  s.c  o m*/
 * 
 * @param code
 *          stored code (with YADA markup)
 * @return {@code true} if the query content matches an SQL DELETE statement
 *         syntax
 * @since PROVISIONAL
 */
public boolean isAppend(String code) {
    Matcher m1 = Pattern.compile(RX_FILE_URI).matcher(code);
    if (m1.matches()) {
        if (m1.groupCount() > 1 && m1.group(3) != null && m1.group(3).equals(APPEND)) {
            return true;
        }
        return false;
    }
    return false;
}

From source file:com.joliciel.talismane.parser.ParserRegexBasedCorpusReaderImpl.java

@Override
public boolean hasNextConfiguration() {
    MONITOR.startTask("hasNextConfiguration");
    try {/*from  w  ww.j a va 2 s.  c  o m*/
        if (maxSentenceCount > 0 && sentenceCount >= maxSentenceCount) {
            // we've reached the end, do nothing
        } else {
            while (configuration == null) {
                List<ParseDataLine> dataLines = new ArrayList<ParseDataLine>();
                List<LexicalEntry> lexicalEntries = new ArrayList<LexicalEntry>();
                boolean hasLine = false;
                if (!this.hasNextLine())
                    break;

                int sentenceStartLineNumber = lineNumber;
                while (configuration == null) {
                    // break out when there's no next line & nothing in the buffer to process
                    if (!this.hasNextLine() && !hasLine)
                        break;

                    String line = "";
                    if (this.hasNextLine())
                        line = this.nextLine().replace("\r", "");

                    lineNumber++;
                    if (line.trim().length() == 0) {
                        if (!hasLine)
                            continue;

                        // end of sentence
                        totalSentenceCount++;
                        if (LOG.isTraceEnabled())
                            LOG.trace("totalSentenceCount: " + totalSentenceCount);

                        // check cross-validation
                        if (crossValidationSize > 0) {
                            boolean includeMe = true;
                            if (includeIndex >= 0) {
                                if (totalSentenceCount % crossValidationSize != includeIndex) {
                                    includeMe = false;
                                }
                            } else if (excludeIndex >= 0) {
                                if (totalSentenceCount % crossValidationSize == excludeIndex) {
                                    includeMe = false;
                                }
                            }
                            if (!includeMe) {
                                dataLines = new ArrayList<ParseDataLine>();
                                lexicalEntries = new ArrayList<LexicalEntry>();
                                hasLine = false;
                                continue;
                            }
                        }

                        // construct the configuration
                        if (dataLines.size() > 0) {
                            boolean badConfig = false;
                            for (ParseDataLine dataLine : dataLines) {
                                badConfig = !this.checkDataLine(dataLine);
                                if (badConfig) {
                                    dataLines = new ArrayList<ParseDataLine>();
                                    hasLine = false;
                                    break;
                                }
                            }

                            if (!badConfig) {
                                PretokenisedSequence tokenSequence = this.getTokeniserService()
                                        .getEmptyPretokenisedSequence();

                                int maxIndex = 0;
                                for (ParseDataLine dataLine : dataLines) {
                                    Token token = tokenSequence.addToken(dataLine.getWord());
                                    dataLine.setToken(token);
                                    if (dataLine.getIndex() > maxIndex)
                                        maxIndex = dataLine.getIndex();
                                    token.setFileName(dataLine.getOriginalFileName());
                                    token.setLineNumber(dataLine.getOriginalLineNumber());
                                    token.setColumnNumber(dataLine.getOriginalColumnNumber());
                                }
                                LOG.debug("Sentence " + (sentenceCount + 1) + ": " + tokenSequence.getText());

                                tokenSequence.cleanSlate();

                                // first apply the token filters - which might replace the text of an individual token
                                // with something else
                                if (tokenFilterWrapper == null) {
                                    tokenFilterWrapper = this.getTokenFilterService()
                                            .getTokenSequenceFilter(this.tokenFilters);
                                }
                                tokenFilterWrapper.apply(tokenSequence);

                                for (TokenSequenceFilter tokenFilter : this.tokenSequenceFilters) {
                                    tokenFilter.apply(tokenSequence);
                                }

                                if (tokenSequence.getTokensAdded().size() > 0) {
                                    // create an empty data line for each empty token that was added by the filters
                                    List<ParseDataLine> newDataLines = new ArrayList<ParseDataLine>();
                                    int i = 0;
                                    ParseDataLine lastDataLine = null;
                                    for (Token token : tokenSequence) {
                                        if (tokenSequence.getTokensAdded().contains(token)) {
                                            ParseDataLine emptyDataLine = new ParseDataLine();
                                            emptyDataLine.setToken(token);
                                            emptyDataLine.setWord("");
                                            emptyDataLine.setIndex(++maxIndex);
                                            if (lastDataLine != null)
                                                emptyDataLine.setLineNumber(lastDataLine.getLineNumber());
                                            else
                                                emptyDataLine.setLineNumber(sentenceStartLineNumber);
                                            newDataLines.add(emptyDataLine);
                                        } else {
                                            lastDataLine = dataLines.get(i++);
                                            newDataLines.add(lastDataLine);
                                        }
                                    }
                                    dataLines = newDataLines;
                                }

                                boolean hasSkip = false;
                                for (int i = 0; i < dataLines.size(); i++) {
                                    this.updateDataLine(dataLines, i);
                                    ParseDataLine dataLine = dataLines.get(i);
                                    if (dataLine.getWord().equals("") && dataLine.getPosTagCode().equals(""))
                                        dataLine.setSkip(true);
                                    if (dataLine.isSkip())
                                        hasSkip = true;
                                }

                                if (hasSkip) {
                                    List<ParseDataLine> newDataLines = new ArrayList<ParseDataLine>();
                                    for (ParseDataLine dataLine : dataLines) {
                                        if (dataLine.isSkip()) {
                                            tokenSequence.removeEmptyToken(dataLine.getToken());
                                        } else {
                                            newDataLines.add(dataLine);
                                        }
                                    }
                                    dataLines = newDataLines;
                                }

                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Data lines after update:");
                                    for (ParseDataLine dataLine : dataLines) {
                                        LOG.trace(dataLine.toString());
                                    }
                                }

                                PosTagSequence posTagSequence = this.getPosTaggerService()
                                        .getPosTagSequence(tokenSequence, tokenSequence.size());
                                Map<Integer, PosTaggedToken> idTokenMap = new HashMap<Integer, PosTaggedToken>();
                                int i = 0;
                                int lexicalEntryIndex = 0;
                                PosTagSet posTagSet = TalismaneSession.getPosTagSet();
                                for (ParseDataLine dataLine : dataLines) {
                                    Token token = tokenSequence.get(i);

                                    PosTag posTag = null;
                                    try {
                                        posTag = posTagSet.getPosTag(dataLine.getPosTagCode());
                                    } catch (UnknownPosTagException upte) {
                                        throw new TalismaneException("Unknown posTag on line "
                                                + dataLine.getLineNumber() + ": " + dataLine.getPosTagCode());
                                    }
                                    Decision<PosTag> posTagDecision = posTagSet.createDefaultDecision(posTag);
                                    PosTaggedToken posTaggedToken = this.getPosTaggerService()
                                            .getPosTaggedToken(token, posTagDecision);
                                    if (LOG.isTraceEnabled()) {
                                        LOG.trace(posTaggedToken.toString());
                                    }

                                    posTaggedToken.setComment(dataLine.getPosTagComment());

                                    // set the lexical entry if we have one
                                    if (this.lexicalEntryReader != null) {
                                        List<LexicalEntry> lexicalEntrySet = new ArrayList<LexicalEntry>(1);
                                        if (!tokenSequence.getTokensAdded().contains(token)) {
                                            lexicalEntrySet.add(lexicalEntries.get(lexicalEntryIndex++));
                                        }
                                        posTaggedToken.setLexicalEntries(lexicalEntrySet);
                                    }
                                    posTagSequence.addPosTaggedToken(posTaggedToken);
                                    idTokenMap.put(dataLine.getIndex(), posTaggedToken);
                                    i++;
                                }

                                for (PosTagSequenceFilter posTagSequenceFilter : this.posTagSequenceFilters) {
                                    posTagSequenceFilter.apply(posTagSequence);
                                }

                                PosTaggedToken rootToken = posTagSequence.prependRoot();
                                idTokenMap.put(0, rootToken);

                                Set<DependencyArc> dependencies = new TreeSet<DependencyArc>();
                                for (ParseDataLine dataLine : dataLines) {
                                    PosTaggedToken head = idTokenMap.get(dataLine.getGovernorIndex());
                                    PosTaggedToken dependent = idTokenMap.get(dataLine.getIndex());
                                    DependencyArc arc = this.getParserService().getDependencyArc(head,
                                            dependent, dataLine.getDependencyLabel());
                                    if (LOG.isTraceEnabled())
                                        LOG.trace(arc);
                                    dependencies.add(arc);
                                    arc.setComment(dataLine.getDependencyComment());
                                }

                                configuration = this.getParserService().getInitialConfiguration(posTagSequence);
                                if (this.predictTransitions) {
                                    TransitionSystem transitionSystem = TalismaneSession.getTransitionSystem();
                                    transitionSystem.predictTransitions(configuration, dependencies);
                                } else {
                                    for (DependencyArc arc : dependencies) {
                                        configuration.addDependency(arc.getHead(), arc.getDependent(),
                                                arc.getLabel(), null);
                                    }
                                }
                                sentenceCount++;
                            } // is the configuration a valid one
                        } // have we data lines?
                    } else {
                        // add a token to the current sentence
                        hasLine = true;
                        Matcher matcher = this.getPattern().matcher(line);
                        if (!matcher.matches())
                            throw new TalismaneException("Didn't match pattern \"" + regex + "\" on line "
                                    + lineNumber + ": " + line);

                        if (matcher.groupCount() != placeholderIndexMap.size()) {
                            throw new TalismaneException(
                                    "Expected " + placeholderIndexMap.size() + " matches (but found "
                                            + matcher.groupCount() + ") on line " + lineNumber);
                        }

                        int index = Integer.parseInt(matcher.group(placeholderIndexMap.get(INDEX_PLACEHOLDER)));
                        String rawWord = matcher.group(placeholderIndexMap.get(TOKEN_PLACEHOLDER));
                        String word = this.readWord(rawWord);
                        String posTagCode = matcher.group(placeholderIndexMap.get(POSTAG_PLACEHOLDER));
                        String depLabel = matcher.group(placeholderIndexMap.get(LABEL_PLACEHOLDER));
                        if (depLabel.equals("_"))
                            depLabel = "";
                        int governorIndex = Integer
                                .parseInt(matcher.group(placeholderIndexMap.get(GOVERNOR_PLACEHOLDER)));

                        ParseDataLine dataLine = new ParseDataLine();
                        dataLine.setLineNumber(this.lineNumber);
                        dataLine.setIndex(index);
                        dataLine.setWord(word);
                        dataLine.setPosTagCode(posTagCode);
                        dataLine.setDependencyLabel(depLabel);
                        dataLine.setGovernorIndex(governorIndex);
                        if (placeholderIndexMap.containsKey(FILENAME_PLACEHOLDER))
                            dataLine.setOriginalFileName(
                                    matcher.group(placeholderIndexMap.get(FILENAME_PLACEHOLDER)));
                        if (placeholderIndexMap.containsKey(ROW_PLACEHOLDER))
                            dataLine.setOriginalLineNumber(
                                    Integer.parseInt(matcher.group(placeholderIndexMap.get(ROW_PLACEHOLDER))));
                        if (placeholderIndexMap.containsKey(COLUMN_PLACEHOLDER))
                            dataLine.setOriginalColumnNumber(Integer
                                    .parseInt(matcher.group(placeholderIndexMap.get(COLUMN_PLACEHOLDER))));
                        if (placeholderIndexMap.containsKey(POSTAG_COMMENT_PLACEHOLDER))
                            dataLine.setPosTagComment(
                                    matcher.group(placeholderIndexMap.get(POSTAG_COMMENT_PLACEHOLDER)));
                        if (placeholderIndexMap.containsKey(DEP_COMMENT_PLACEHOLDER))
                            dataLine.setDependencyComment(
                                    matcher.group(placeholderIndexMap.get(DEP_COMMENT_PLACEHOLDER)));

                        dataLines.add(dataLine);

                        if (this.lexicalEntryReader != null) {
                            LexicalEntry lexicalEntry = this.lexicalEntryReader.readEntry(line);
                            lexicalEntries.add(lexicalEntry);
                        }
                    }
                }
            } // is configuration still null?
        } // have we reached the max sentence count?

        return configuration != null;
    } finally {
        MONITOR.endTask("hasNextConfiguration");
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static Object str2RegExp(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    String[] strArr = null;//  w  w w .j ava 2 s.  co m
    if (ArgList.length == 2) {
        try {
            if (isNull(ArgList, new int[] { 0, 1 }))
                return null;
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return undefinedValue;
            String strToMatch = (String) ArgList[0];
            Pattern p = Pattern.compile((String) ArgList[1]);
            Matcher m = p.matcher(strToMatch);
            if (m.matches() && m.groupCount() > 0) {
                strArr = new String[m.groupCount()];
                for (int i = 1; i <= m.groupCount(); i++) {
                    strArr[i - 1] = m.group(i);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
    } else {
        throw new RuntimeException("The function call str2RegExp requires 2 arguments.");
    }
    return strArr;
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object str2RegExp(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    String[] strArr = null;/*from ww  w  .ja  v a2 s  .  c om*/
    if (ArgList.length == 2) {
        try {
            if (isNull(ArgList, new int[] { 0, 1 }))
                return null;
            else if (isUndefined(ArgList, new int[] { 0, 1 }))
                return Context.getUndefinedValue();
            String strToMatch = Context.toString(ArgList[0]);
            Pattern p = Pattern.compile(Context.toString(ArgList[1]));
            Matcher m = p.matcher(strToMatch);
            if (m.matches() && m.groupCount() > 0) {
                strArr = new String[m.groupCount()];
                for (int i = 1; i <= m.groupCount(); i++) {
                    strArr[i - 1] = m.group(i);
                }
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call str2RegExp requires 2 arguments.");
    }
    return strArr;
}

From source file:com.codeasylum.stress.api.HttpTask.java

@Override
public void execute(long timeDifferential, int hostIndex, String hostId, Ouroboros ouroboros,
        ExchangeTransport exchangeTransport) throws IOException, ScriptInterpolationException {

    if (isEnabled() && ouroboros.isEnabled()) {

        HttpUriRequest httpRequest;//from   w w  w.j  ava 2  s  .c  o m
        ResponseCarrier responseCarrier;
        URI requestURI;
        StringBuilder uriBuilder;
        String requestMimeType;
        String requestCharSet;
        String requestBody;
        boolean validated = true;
        long startTime;

        if ((portAttribute.getScript() == null) || (portAttribute.getScript().length() == 0)) {
            throw new TaskExecutionException("The %s(%s) has no http port value configured",
                    HttpTask.class.getSimpleName(), getName());
        }

        uriBuilder = new StringBuilder("http://").append(serverAttribute.get(this)).append(':')
                .append(portAttribute.get(this)).append('/').append(pathAttribute.get(this));
        try {
            requestURI = new URI(uriBuilder.toString());
        } catch (URISyntaxException uriSyntaxException) {
            throw new TaskExecutionException(uriSyntaxException,
                    "The %s(%s) has been configured with a malformed URI(%s)", HttpTask.class.getSimpleName(),
                    getName(), uriBuilder.toString());
        }

        if ((requestMimeType = contentTypeAttribute.get(this)) != null) {

            int semiColonPos;

            if ((semiColonPos = requestMimeType.indexOf(';')) < 0) {
                requestCharSet = "utf-8";
            } else {

                int equalsPos;

                if ((equalsPos = requestMimeType.indexOf('=', semiColonPos + 1)) <= 0) {
                    throw new TaskExecutionException(
                            "The %s(%s) contains an improperly formatted content type(%s)",
                            HttpTask.class.getSimpleName(), getName(), requestMimeType);
                }

                requestCharSet = requestMimeType.substring(equalsPos + 1);
                requestMimeType = requestMimeType.substring(0, semiColonPos);
            }
        } else {
            requestMimeType = "text/plain";
            requestCharSet = "utf-8";
        }

        switch (httpMethod) {
        case GET:
            if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'GET' method, but has been configured with body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpGet(requestURI);
            break;
        case PUT:
            if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'PUT' method, but has not been configured with any body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpPut(requestURI);
            ((HttpPut) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet));
            break;
        case POST:
            if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'POST' method, but has not been configured with any body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpPost(requestURI);
            ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet));
            break;
        case DELETE:
            if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'DELETE' method, but has been configured with body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpDelete(requestURI);
            break;
        default:
            throw new UnknownSwitchCaseException(httpMethod.name());
        }

        httpRequest.setHeader("Content-Type", requestMimeType + ";charset=" + requestCharSet);

        startTime = System.currentTimeMillis();
        try {
            responseCarrier = httpClient.execute(httpRequest, new ResponseHandler<ResponseCarrier>() {

                @Override
                public ResponseCarrier handleResponse(HttpResponse response) throws IOException {

                    HttpEntity entity;
                    Header contentTypeHeader = response.getFirstHeader("Content-Type");
                    String responseMimeType;
                    String responseCharSet;

                    if ((contentTypeHeader != null)
                            && ((responseMimeType = contentTypeHeader.getValue()) != null)) {

                        int semiColonPos;

                        if ((semiColonPos = responseMimeType.indexOf(';')) < 0) {
                            responseCharSet = "utf-8";
                        } else {

                            int equalsPos;

                            if ((equalsPos = responseMimeType.indexOf('=', semiColonPos + 1)) <= 0) {
                                throw new TaskExecutionException(
                                        "Improperly formatted content type(%s) in response", responseMimeType);
                            }

                            responseCharSet = responseMimeType.substring(equalsPos + 1);
                            responseMimeType = responseMimeType.substring(0, semiColonPos);
                        }
                    } else {
                        responseMimeType = "text/plain";
                        responseCharSet = "utf-8";

                    }

                    return new ResponseCarrier(System.currentTimeMillis(),
                            response.getStatusLine().getStatusCode(), responseMimeType, responseCharSet,
                            ((entity = response.getEntity()) == null) ? null : EntityUtils.toByteArray(entity));
                }
            });

            if (!regexpMap.isEmpty()) {

                Matcher regexpMatcher;
                String responseBody = (responseCarrier.getRawResponse() == null) ? null
                        : new String(responseCarrier.getRawResponse(), responseCarrier.getResponseCharSet());

                for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) {
                    PropertyContext.removeKeysStartingWith(regexpEntry.getKey());

                    if (responseBody != null) {
                        if ((regexpMatcher = Pattern.compile(
                                PROPERTY_EXPANDER.expand(regexpEntry.getValue(), PropertyContext.getMap()))
                                .matcher(responseBody)).find()) {
                            PropertyContext.put(regexpEntry.getKey(), "true");
                            for (int groupIndex = 0; groupIndex <= regexpMatcher.groupCount(); groupIndex++) {
                                PropertyContext.put(regexpEntry.getKey() + '.' + groupIndex,
                                        regexpMatcher.group(groupIndex));
                            }
                        } else {
                            PropertyContext.put(regexpEntry.getKey(), "false");
                        }
                    }
                }
            }

            if (!validationMap.isEmpty()) {
                for (Map.Entry<String, String> validationEntry : validationMap.entrySet()) {
                    if (!PropertyContext.valueEquals(validationEntry.getKey(), validationEntry.getValue())) {
                        validated = false;
                        break;
                    }
                }
            }

            if ((responseKey != null) && (responseKey.length() > 0)) {
                PropertyContext.put(responseKey, new String(responseCarrier.getRawResponse()));
            }

            exchangeTransport.send(new HttpExchange(validated && (responseCarrier.getResponseCode() == 200),
                    hostId, getName(), startTime + timeDifferential,
                    responseCarrier.getResponseTimestamp() + timeDifferential,
                    responseCarrier.getResponseCode(), requestMimeType, requestCharSet, requestBody,
                    responseCarrier.getResponseMimeType(), responseCarrier.getResponseCharSet(),
                    responseCarrier.getRawResponse()));
        } catch (Exception exception) {
            exchangeTransport.send(new HttpExchange(false, hostId, getName(), startTime + timeDifferential,
                    System.currentTimeMillis() + timeDifferential, 503, requestMimeType, requestCharSet,
                    requestBody, "text/plain", "utf-8",
                    StackTraceUtilities.obtainStackTraceAsString(exception).getBytes()));

            if (!regexpMap.isEmpty()) {
                for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) {
                    PropertyContext.removeKeysStartingWith(regexpEntry.getKey());
                }
            }

            if ((responseKey != null) && (responseKey.length() > 0)) {
                PropertyContext.remove(responseKey);
            }
        }
    }
}

From source file:com.thoughtworks.go.config.CachedGoConfigIntegrationTest.java

@Test
public void shouldFailWhenTryingToAddPipelineWithTheSameNameAsAnotherPipelineDefinedRemotely_EntitySave()
        throws Exception {
    assertThat(configWatchList.getCurrentConfigRepos().size()).isEqualTo(1);
    repoConfigDataSource.onCheckoutComplete(configRepo.getMaterialConfig(), externalConfigRepo,
            latestModification);//from   ww w .j a va  2s. c o m
    assertThat(cachedGoConfig.currentConfig().hasPipelineNamed(new CaseInsensitiveString("pipe1"))).isTrue();

    PipelineConfig dupPipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("pipe1",
            "ut", "www.spring.com");
    try {
        goConfigDao.updateConfig(
                new CreatePipelineConfigCommand(goConfigService, dupPipelineConfig, Username.ANONYMOUS,
                        new DefaultLocalizedOperationResult(), "default", externalArtifactsService),
                Username.ANONYMOUS);
        fail("Should have thrown");
    } catch (RuntimeException ex) {
        PipelineConfig pipe1 = goConfigService.pipelineConfigNamed(new CaseInsensitiveString("pipe1"));
        String errorMessage = dupPipelineConfig.errors().on(PipelineConfig.NAME);
        assertThat(errorMessage).contains(
                "You have defined multiple pipelines named 'pipe1'. Pipeline names must be unique. Source(s):");
        Matcher matcher = Pattern.compile("^.*\\[(.*),\\s(.*)\\].*$").matcher(errorMessage);
        assertThat(matcher.matches()).isTrue();
        assertThat(matcher.groupCount()).isEqualTo(2);
        List<String> expectedSources = asList(dupPipelineConfig.getOriginDisplayName(),
                pipe1.getOriginDisplayName());
        List<String> actualSources = new ArrayList<>();
        for (int i = 1; i <= matcher.groupCount(); i++) {
            actualSources.add(matcher.group(i));
        }
        assertThat(actualSources.size()).isEqualTo(expectedSources.size());
        assertThat(actualSources.containsAll(expectedSources)).isTrue();
    }
}