Example usage for java.util.regex Matcher reset

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

Introduction

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

Prototype

public Matcher reset() 

Source Link

Document

Resets this matcher.

Usage

From source file:com.boylesoftware.web.impl.AbstractRouterConfiguration.java

@Override
public RouterRequest findRoute(final HttpServletRequest request, final HttpServletResponse response)
        throws MethodNotAllowedException, ServletException {

    // check if we have mappings
    if (this.mappings.length == 0)
        return null;

    // try to find the matching route mapping
    final Lock readLock = this.mappingsLock.readLock();
    readLock.lock();//from   w ww  .j  a  v a2  s. co  m
    try {

        // test request URI against the mappings
        RouteImpl mapping = this.mappings[0];
        final String requestURI = request.getRequestURI();
        // TODO: reusable matcher?
        final Matcher m = mapping.getURIPattern().matcher(requestURI);
        int mappingInd = 0;
        do {

            // try to match the mapping
            if (m.matches()) {

                // log the match
                if (this.log.isDebugEnabled())
                    this.log.debug("found mapping for URI " + requestURI + " on attempt " + (mappingInd + 1));

                // move the mapping higher if matched more frequently
                final long numMatched = mapping.incrementNumMatched();
                if (mappingInd > 0) {
                    final RouteImpl prevMapping = this.mappings[mappingInd - 1];
                    if (numMatched > prevMapping.getNumMatched()) {
                        final Lock writeLock = this.mappingsLock.writeLock();
                        readLock.unlock();
                        writeLock.lock();
                        try {
                            this.mappings[mappingInd] = prevMapping;
                            this.mappings[mappingInd - 1] = mapping;
                        } finally {
                            readLock.lock();
                            writeLock.unlock();
                        }
                    }
                }

                // wrap the request
                final RouterRequestImpl routerRequest = this.routerRequestPool.getSync();
                boolean success = false;
                try {

                    // initialize the router request
                    routerRequest.wrap(request, response, mapping, this.isAuthenticationRequired(requestURI));

                    // add parameters made from the URI components
                    final int numURIParams = m.groupCount();
                    for (int i = 0; i < numURIParams; i++) {
                        final String uriParamName = mapping.getURIParamName(i);
                        if (uriParamName != null)
                            routerRequest.addParameter(uriParamName, m.group(i + 1));
                    }

                    // convert flash attributes cookie to request attributes
                    routerRequest.flashCookieToAttributes();

                    // return the router request
                    success = true;
                    return routerRequest;

                } finally {
                    if (!success)
                        routerRequest.recycle();
                }
            }

            // next mapping for next iteration
            if (++mappingInd >= this.mappings.length)
                break;
            mapping = this.mappings[mappingInd];

            // reuse the matcher
            m.reset();
            m.usePattern(mapping.getURIPattern());

        } while (true);

    } finally {
        readLock.unlock();
    }

    // no mapping matched
    return null;
}

From source file:org.jmlspecs.util.QDoxUtil.java

public static String getTypeErasureForTypeDeclsInFile(File file, boolean isGenericSource)
        throws FileNotFoundException, IOException, PositionedError {
    BufferedReader buffer = null;
    StringBuffer bufferedFile = null;
    String fileAsString = "";
    String line = "";

    bufferedFile = new StringBuffer("");
    buffer = new BufferedReader(new FileReader(file));
    line = buffer.readLine();//from   w ww .jav  a2s .com
    while (line != null) {
        bufferedFile.append(line);
        bufferedFile.append("\n");
        line = buffer.readLine();
    }
    buffer.close();
    fileAsString = bufferedFile.toString();

    AspectUtil.getInstance().addJavaFileAsString(fileAsString);
    JavaDocBuilder qDoxFile = new JavaDocBuilder();
    qDoxFile.addSource(new FileReader(file));

    // handling JavaDocTags in File
    List<DocletTag> javaMethsWithDocletTagsFile = QDoxUtil.getAllJavaDocTagsInFile(qDoxFile);
    if (javaMethsWithDocletTagsFile.size() > 0) {
        buffer = new BufferedReader(new StringReader(fileAsString));
        StringBuffer fileAsStringJavaDocProcessed = new StringBuffer("");
        line = buffer.readLine();
        int fileLineNumber = 1;
        while (line != null) {
            // if any
            String jmlClause = QDoxUtil.getJavaDocTagAsJMLClause(javaMethsWithDocletTagsFile, fileLineNumber);
            fileAsStringJavaDocProcessed.append(line).append(jmlClause);
            fileAsStringJavaDocProcessed.append("\n");
            line = buffer.readLine();
            fileLineNumber++;
        }
        buffer.close();
        fileAsString = StringUtils.replaceOnce(fileAsString, fileAsString,
                fileAsStringJavaDocProcessed.toString());
    }

    // handling javadoc tags in Java types that should be shifted
    List<JavaClass> javaDeclTypeWithJavadocTags = QDoxUtil
            .getAllDeclaredJavaTypesWithJavaDocTagsInFile(qDoxFile);
    for (Iterator<JavaClass> iterator = javaDeclTypeWithJavadocTags.iterator(); iterator.hasNext();) {
        JavaClass javaTypeWithJavadoc = iterator.next();
        String jmlClausesToShift = QDoxUtil.getJavaDocTagAsJMLClauseForTypeToShift(
                QDoxUtil.getAllJavaDocTagsInAJavaTypedDecl(javaTypeWithJavadoc));
        if (jmlClausesToShift.equals("")) {
            continue;
        }
        buffer = new BufferedReader(new StringReader(fileAsString));
        int lineStart = javaTypeWithJavadoc.getLineNumber();
        int fileLineNumber = 1;
        StringBuffer TypeDeclUtilOpenBrace = new StringBuffer("");
        line = buffer.readLine();
        fileLineNumber = 1;
        while (line != null) {
            if (fileLineNumber >= lineStart) {
                if (line.contains("{")) {
                    int indexOpenBrace = line.indexOf('{');
                    String lineTmp = line.substring(0, (indexOpenBrace + 1));
                    TypeDeclUtilOpenBrace.append(lineTmp);
                    break;
                } else {
                    TypeDeclUtilOpenBrace.append(line);
                    TypeDeclUtilOpenBrace.append("\n");
                }
            }
            line = buffer.readLine();
            fileLineNumber++;
        }
        buffer.close();
        String TypeDeclUtilOpenBraceStr = TypeDeclUtilOpenBrace.toString().trim();
        // processing java field tags
        // placing them where the JML compiler can understand - [[[hemr]]]
        fileAsString = StringUtils.replaceOnce(fileAsString, TypeDeclUtilOpenBraceStr,
                TypeDeclUtilOpenBraceStr + jmlClausesToShift);
    } // end for

    // handling javadoc tags in Java fields that should be shifted
    List<JavaField> javaDeclFieldsWithJavadocTags = QDoxUtil
            .getAllDeclaredJavaFieldsWithJavaDocTagsInFile(qDoxFile);
    for (Iterator<JavaField> iterator = javaDeclFieldsWithJavadocTags.iterator(); iterator.hasNext();) {
        JavaField javaFieldWithJavadoc = iterator.next();
        String jmlClausesToShift = QDoxUtil.getJavaDocTagAsJMLClauseForFieldToShift(
                QDoxUtil.getAllJavaDocTagsInAJavaFieldDecl(javaFieldWithJavadoc));
        if (jmlClausesToShift.equals("")) {
            continue;
        }
        buffer = new BufferedReader(new StringReader(fileAsString));
        int lineStart = javaFieldWithJavadoc.getLineNumber();
        int fileLineNumber = 1;
        StringBuffer fieldDecl = new StringBuffer("");
        line = buffer.readLine();
        fileLineNumber = 1;
        while (line != null) {
            if (fileLineNumber >= lineStart) {
                if (line.contains(";")) {
                    int indexSemiColon = line.lastIndexOf(';');
                    fieldDecl.append(line.substring(0, indexSemiColon + 1));
                    break;
                } else {
                    fieldDecl.append(line);
                    fieldDecl.append("\n");
                }
            }
            line = buffer.readLine();
            fileLineNumber++;
        }
        buffer.close();
        String fieldDeclStr = fieldDecl.toString().trim();
        // processing java field tags
        // placing them where the JML compiler can understand - [[[hemr]]]
        fileAsString = StringUtils.replaceOnce(fileAsString, fieldDeclStr, fieldDeclStr + jmlClausesToShift);
    } // end for

    // Generic Source or any Java 5+ features (hopefully :-)
    if (isGenericSource) {
        String actualFileAsString = fileAsString;
        bufferedFile.delete(0, (bufferedFile.length() - 1)); // reset for later use

        // handling enum types
        List<JavaClass> javaDeclEnumTypes = QDoxUtil.getAllDeclaredJavaEnumTypesInFile(qDoxFile);
        if (javaDeclEnumTypes.size() > 0) {
            fileAsString = QDoxUtil.getFileEnumTypeErasureProcessingAsString(bufferedFile, actualFileAsString,
                    javaDeclEnumTypes);
        }

        // collecting all methods that lexically occur within a file
        bufferedFile.delete(0, (bufferedFile.length() - 1)); // reset for later use
        List<JavaMethod> javaDeclMeths = QDoxUtil.getAllDeclaredJavaMethodsInFile(qDoxFile);
        if (file.getCanonicalPath().endsWith(".jml")) {
            actualFileAsString = QDoxUtil.handleConstructDeclInJMLFileMode(bufferedFile, actualFileAsString,
                    javaDeclMeths);
        }
        List<com.github.antlrjavaparser.api.body.BodyDeclaration> members = QDoxUtil
                .getAllDeclaredJavaMethodsInFile(actualFileAsString);
        List<String> fileMeths = QDoxUtil.getAllJavaMethodDeclLexicallyInFile(bufferedFile, actualFileAsString,
                javaDeclMeths, members);

        if (fileMeths.size() != javaDeclMeths.size()) {
            System.out.println("file = " + file.getCanonicalPath());
            System.out.println("processed ---> " + fileMeths.size());
            System.out.println("really contains = " + javaDeclMeths.size());
        }

        fileAsString = QDoxUtil.stripMethBodies(fileAsString, javaDeclMeths, fileMeths); // method bodies stripped... [[[hemr]]]

        //         eliminating the pattern --> default {return null;};
        fileAsString = fileAsString.replaceAll("default(\\s)*\\{(\\s)*return [\\w;]+(\\s)*\\};", ";");

        // handling annotated Java fields
        List<JavaField> javaDeclAnnotatedFields = QDoxUtil.getAllDeclaredAnnotatedJavaFieldsInFile(qDoxFile);
        List<com.github.antlrjavaparser.api.body.FieldDeclaration> javaDeclAnnotatedFields2 = QDoxUtil
                .getAllDeclaredAnnotatedJavaFieldsInFile(actualFileAsString);
        for (int i = 0; i < javaDeclAnnotatedFields.size(); i++) {
            JavaField annotatedJavaField = javaDeclAnnotatedFields.get(i);
            com.github.antlrjavaparser.api.body.FieldDeclaration annotatedJavaField2 = javaDeclAnnotatedFields2
                    .get(i);

            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer annotationArea = new StringBuffer("");
            StringBuffer annotationAreaCommented = new StringBuffer("");
            int lineStart = annotatedJavaField2.getAnnotations().get(0).getBeginLine();
            int lineEnd = annotatedJavaField2.getAnnotations()
                    .get(annotatedJavaField2.getAnnotations().size() - 1).getEndLine();
            line = buffer.readLine();
            int fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber >= lineStart) {
                    if (fileLineNumber == lineEnd) {
                        annotationArea.append(line);
                        annotationAreaCommented
                                .append("/*" + fileLineNumber + "*/" + "/* " + line.replace("@", "#") + "*/");
                        break;
                    } else {
                        annotationArea.append(line);
                        annotationArea.append("\n");
                        annotationAreaCommented
                                .append("/*" + fileLineNumber + "*/" + "/* " + line.replace("@", "#") + "*/");
                        annotationAreaCommented.append("\n");
                    }
                }
                line = buffer.readLine();
                fileLineNumber++;
            } // end while
            buffer.close();
            // pre field annotations if any
            StringBuffer fieldDeclAnnotations = new StringBuffer("");
            if (annotationArea.toString().contains("@SpecPublic")) {
                fieldDeclAnnotations.append("spec_public ");
            }
            if (annotationArea.toString().contains("@SpecProtected")) {
                fieldDeclAnnotations.append("spec_protected ");
            }
            if (annotationArea.toString().contains("@NonNull")) {
                fieldDeclAnnotations.append("non_null ");
            }
            if (annotationArea.toString().contains("@Nullable")) {
                fieldDeclAnnotations.append("nullable ");
            }
            if (annotationArea.toString().contains("@Model")) {
                fieldDeclAnnotations.append("model ");
            }

            // processing java field annotations
            String annotationAreaCommentedStr = QDoxUtil.getFieldAnnotationAreaCommentedProcessedWithJML(
                    annotatedJavaField, annotationAreaCommented.toString());

            // doing the replacement
            int newLineEnd = annotatedJavaField2.getEndLine();
            lineStart = lineEnd;
            lineEnd = newLineEnd;
            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer fileAsStringReplacement = new StringBuffer("");
            line = buffer.readLine();
            fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber == (lineStart + 1)) {
                    // placing them where the JML compiler can understand - [[[hemr]]]
                    fileAsStringReplacement
                            .append("/*@  " + fieldDeclAnnotations.toString() + "@*/" + " " + line);
                    fileAsStringReplacement.append("\n");
                } else if (fileLineNumber == (lineEnd)) { // getting the end of field line
                    // placing them where the JML compiler can understand - [[[hemr]]]
                    fileAsStringReplacement.append(line + annotationAreaCommentedStr);
                    fileAsStringReplacement.append("\n");
                } else {
                    fileAsStringReplacement.append(line);
                    fileAsStringReplacement.append("\n");
                }
                line = buffer.readLine();
                fileLineNumber++;
            } // end while
            buffer.close();

            fileAsString = fileAsStringReplacement.toString();
            // updating the current field annotations in the file
            // removing field annotations
            fileAsString = StringUtils.replaceOnce(fileAsString, annotationArea.toString(), "");
        } // end for

        // handling annotated Java Methods
        List<String> javaDeclMethsAnnotationArea = new ArrayList<String>();
        List<JavaMethod> javaDeclAnnotatedMeths = QDoxUtil.getAllDeclaredAnnotatedJavaMethodsInFile(qDoxFile);
        List<com.github.antlrjavaparser.api.body.BodyDeclaration> javaDeclAnnotatedMeths2 = QDoxUtil
                .getAllDeclaredAnnotatedJavaMethodsInFile(actualFileAsString);
        for (int i = 0; i < javaDeclAnnotatedMeths.size(); i++) {
            JavaMethod annotatedJavaMethod = javaDeclAnnotatedMeths.get(i);
            com.github.antlrjavaparser.api.body.BodyDeclaration annotatedJavaMethod2 = javaDeclAnnotatedMeths2
                    .get(i);

            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer annotationArea = new StringBuffer("");
            StringBuffer annotationAreaCommented = new StringBuffer("");
            int lineStart = annotatedJavaMethod2.getAnnotations().get(0).getBeginLine();
            int lineEnd = annotatedJavaMethod2.getAnnotations()
                    .get(annotatedJavaMethod2.getAnnotations().size() - 1).getEndLine();
            line = buffer.readLine();
            int fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber >= lineStart) {
                    if (fileLineNumber == lineEnd) {
                        annotationArea.append(line);
                        annotationArea.append("\n");
                        annotationAreaCommented.append("/*" + fileLineNumber + "*/" + "/* " + line + "*/");
                        annotationAreaCommented.append("\n");
                        break;
                    } else {
                        annotationArea.append(line);
                        annotationArea.append("\n");
                        annotationAreaCommented.append("/*" + fileLineNumber + "*/" + "/* " + line + "*/");
                        annotationAreaCommented.append("\n");
                    }
                }
                line = buffer.readLine();
                fileLineNumber++;
            } // end while
              // processing java method annotations
            String annotationAreaCommentedStr = QDoxUtil.getMethodAnnotationAreaCommentedProcessedWithJML(
                    annotatedJavaMethod, annotationAreaCommented);

            // updating the current meth annotations in the file
            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer fileStartCurrentMeth = new StringBuffer("");

            lineStart = annotatedJavaMethod.getLineNumber();
            lineEnd = annotatedJavaMethod2.getEndLine();
            line = buffer.readLine();
            fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber >= lineStart) {
                    if (fileLineNumber == lineEnd) {
                        fileStartCurrentMeth.append(line);
                        fileStartCurrentMeth.append("\n");
                        break;
                    } else {
                        fileStartCurrentMeth.append(line);
                        fileStartCurrentMeth.append("\n");
                    }

                }
                line = buffer.readLine();
                fileLineNumber++;
            }
            String fileAsStringTmp = StringUtils.replaceOnce(fileStartCurrentMeth.toString(),
                    annotationArea.toString(), annotationAreaCommentedStr.toString());
            fileAsString = StringUtils.replaceOnce(fileAsString, fileStartCurrentMeth.toString(),
                    fileAsStringTmp);
            javaDeclMethsAnnotationArea.add(annotationAreaCommentedStr);
        } // end for

        // handling annotated Java Types
        List<JavaClass> javaDeclAnnotatedTypes = QDoxUtil.getAllDeclaredAnnotatedJavaTypesInFile(qDoxFile);
        List<com.github.antlrjavaparser.api.body.TypeDeclaration> javaDeclAnnotatedTypes2 = QDoxUtil
                .getAllDeclaredAnnotatedJavaTypesInFile(actualFileAsString);
        for (int i = 0; i < javaDeclAnnotatedTypes.size(); i++) {
            JavaClass annotatedJavaType = javaDeclAnnotatedTypes.get(i);
            com.github.antlrjavaparser.api.body.TypeDeclaration annotatedJavaType2 = javaDeclAnnotatedTypes2
                    .get(i);
            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer annotationArea = new StringBuffer("");
            StringBuffer annotationAreaCommented = new StringBuffer("");
            int lineStart = annotatedJavaType2.getAnnotations().get(0).getBeginLine();
            int lineEnd = annotatedJavaType2.getAnnotations()
                    .get(annotatedJavaType2.getAnnotations().size() - 1).getEndLine();
            //            System.out.println("lineStart = "+lineStart);
            //            System.out.println("lineEnd = "+lineEnd);
            line = buffer.readLine();
            int fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber >= lineStart) {
                    if (fileLineNumber == lineEnd) {
                        annotationArea.append(line);
                        annotationArea.append("\n");
                        annotationAreaCommented
                                .append("/*" + fileLineNumber + "*/" + "/* " + line.replace("@", "#") + "*/");
                        annotationAreaCommented.append("\n");
                        break;
                    } else {
                        annotationArea.append(line);
                        annotationArea.append("\n");
                        annotationAreaCommented
                                .append("/*" + fileLineNumber + "*/" + "/* " + line.replace("@", "#") + "*/");
                        annotationAreaCommented.append("\n");
                    }
                }
                line = buffer.readLine();
                fileLineNumber++;
            } // end while

            // selecting the entire type decl
            buffer = new BufferedReader(new StringReader(fileAsString));
            StringBuffer typeDecl = new StringBuffer("");
            int newEnd = annotatedJavaType2.getEndLine();
            lineStart = lineEnd + 1;
            lineEnd = newEnd;
            //            System.out.println("lineStart<new> = "+lineStart);
            //            System.out.println("lineEnd<new> = "+lineEnd);
            line = buffer.readLine();
            fileLineNumber = 1;
            while (line != null) {
                if (fileLineNumber >= lineStart) {
                    if (fileLineNumber == lineEnd) {
                        typeDecl.append(line);
                        typeDecl.append("\n");
                    } else {
                        typeDecl.append(line);
                        typeDecl.append("\n");
                    }
                }
                line = buffer.readLine();
                fileLineNumber++;
            }

            String typeJMLAnno = "";
            if (annotationArea.toString().contains("@NonNullByDefault")) {
                typeJMLAnno = "/*@ non_null_by_default @*/";
            }
            if (annotationArea.toString().contains("@NullableByDefault")) {
                typeJMLAnno = "/*@ nullable_by_default @*/" + typeJMLAnno;
            }
            if (annotationArea.toString().contains("@SpecPublic")) {
                typeJMLAnno = "/*@ spec_public @*/" + typeJMLAnno;
            }
            if (annotationArea.toString().contains("@SpecProtected")) {
                typeJMLAnno = "/*@ spec_protected @*/" + typeJMLAnno;
            }

            // processing java type annotations
            String annotationAreaCommentedStr = QDoxUtil.getTypeAnnotationAreaCommentedProcessedWithJML(
                    annotatedJavaType, annotationAreaCommented.toString());

            // placing them where the JML compiler can understand - [[[hemr]]]
            String typeDeclStr = StringUtils.replaceOnce(typeDecl.toString(), "{",
                    "{" + annotationAreaCommentedStr);

            // updating the current type annotations in the file
            // removing type annotations
            fileAsString = StringUtils.replaceOnce(fileAsString, annotationArea.toString(), typeJMLAnno);
            fileAsString = StringUtils.replaceOnce(fileAsString, typeDecl.toString(), typeDeclStr);
        } // end for

        //         // collecting all methods that lexically occur within a file
        bufferedFile.delete(0, (bufferedFile.length() - 1)); // reset for later use
        javaDeclMeths = QDoxUtil.getAllDeclaredJavaMethodsInFile(qDoxFile);
        fileMeths = QDoxUtil.getAllJavaMethodDeclLexicallyInFile(bufferedFile, fileAsString, javaDeclMeths,
                members);
        //            System.out.println("fileMeths = "+fileMeths.size());
        //         for (Iterator<String> iterator = fileMeths.iterator(); iterator.hasNext();) {
        //            String currentMeth = iterator.next();
        //            System.out.println("matchedMeth = "+currentMeth);
        //         }
        fileAsString = QDoxUtil.getFileMethDeclsProcessed(fileAsString, javaDeclMeths, fileMeths, file);

        // final issues about JML type annotations
        Pattern jmlAnnoPattern = Pattern.compile("@(\\s)*Pure(\\b)(\\s)*(\\((\\s)*\\))?");
        Matcher jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ pure @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        jmlAnnoMatcher.reset();
        jmlAnnoPattern = Pattern.compile("@(\\s)*Helper(\\b)(\\s)*(\\((\\s)*\\))?");
        jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ helper @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        jmlAnnoMatcher.reset();
        jmlAnnoPattern = Pattern.compile("@(\\s)*Nullable(\\b)(\\s)*(\\((\\s)*\\))?");
        jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ nullable @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        jmlAnnoMatcher.reset();
        jmlAnnoPattern = Pattern.compile("@(\\s)*NonNull(\\b)(\\s)*(\\((\\s)*\\))?");
        jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ non_null @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        jmlAnnoMatcher.reset();
        jmlAnnoPattern = Pattern.compile("@(\\s)*SpecPublic(\\b)(\\s)*(\\((\\s)*\\))?");
        jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ spec_public @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        jmlAnnoMatcher.reset();
        jmlAnnoPattern = Pattern.compile("@(\\s)*SpecProtected(\\b)(\\s)*(\\((\\s)*\\))?");
        jmlAnnoMatcher = jmlAnnoPattern.matcher(fileAsString);
        while (jmlAnnoMatcher.find()) {
            int numberOfNewLines = QDoxUtil.getLineNumbersQtd(jmlAnnoMatcher.group());
            fileAsString = StringUtils.replaceOnce(fileAsString, jmlAnnoMatcher.group(),
                    "/*@ spec_protected @*/" + QDoxUtil.getNewLinesCaracter(numberOfNewLines));
        }
        fileAsString = fileAsString.replaceAll("/\\*(\\s)*/\\*@", "/*@");
        fileAsString = fileAsString.replaceAll("@\\*/(\\s)*\\*/", "@*/");
        // final issues due to annotation types support
        fileAsString = fileAsString.replace("@interface", "interface");
        //         fileAsString = fileAsString.replaceAll("\"[\\w\"\\s+\\{\\}\\(\\)\\.]*(\\b)default(\\b)[\\w\"\\s+\\{\\}\\(\\)\\.]*\"", "\"\""); // improve! [[[hemr]]] **

        Pattern defaultTextPattern = Pattern
                .compile("\"[\\w\"\\s+\\{\\}\\(\\)\\.]*(\\b)default(\\b)[\\@\\-\\w\"\\s+\\{\\}\\(\\)\\.]*\"");
        Matcher defaultTextMatcher = defaultTextPattern.matcher(fileAsString);
        while (defaultTextMatcher.find()) {
            fileAsString = StringUtils.replaceOnce(fileAsString, defaultTextMatcher.group(),
                    defaultTextMatcher.group().replace("default", ""));
        }

        // handling default stmt in annotation types
        fileAsString = fileAsString
                .replaceAll("(\\b)default(\\b)(\\s)*[\\@\\-\\w\"\\s+\\{\\}\\(\\)\\.]*(\\s)*;", ";");

        // handling static imports to support java 5 mode
        Pattern staticImportPattern = Pattern.compile("import static (.)*;");
        Matcher staticImportMatcher = staticImportPattern.matcher(fileAsString);
        while (staticImportMatcher.find()) {
            String staticImport = staticImportMatcher.group();
            staticImport = staticImport.substring(0, staticImport.lastIndexOf(".")).replace("static ", "")
                    + ";";
            fileAsString = StringUtils.replaceOnce(fileAsString, staticImportMatcher.group(), staticImport);
        }

        // handling standard Java 5 annotations
        if (fileAsString.contains("@Inherited")) {
            fileAsString = fileAsString.replaceAll("@Inherited((\\s)*\\((\\s)*\\))?", "");
        }

        if (fileAsString.contains("@Override")) {
            fileAsString = fileAsString.replaceAll("@Override((\\s)*\\((\\s)*\\))?", "");
        }

        if (fileAsString.contains("@Deprecated")) {
            fileAsString = fileAsString.replaceAll("@Deprecated((\\s)*\\((\\s)*\\))?", "");
        }

        if (fileAsString.contains("@SuppressWarnings")) {
            fileAsString = fileAsString.replaceAll("@SuppressWarnings((\\s)*\\(\"(.)*\"\\))?", "");
            fileAsString = fileAsString.replaceAll("@SuppressWarnings((\\s)*\\((\\s)*\\))?", "");
        }

        // handling dot dot dot in Java 5
        if (fileAsString.contains("...")) {
            fileAsString = fileAsString.replace("...", "[]");
        }

    } // final generic treatment

    // for debuggin purposes remove the following comment - [[[hemr]]]
    //      System.err.println(fileAsString);
    return fileAsString;
}

From source file:org.infoglue.deliver.util.CacheController.java

private static boolean cacheNewResult(PageInvoker pageInvoker, GeneralCacheAdministrator cacheAdministrator,
        String pageKey, String value) {
    /*/*from  www  . ja  v a 2  s.  c o m*/
    int argumentCount = StringUtils.countMatches(pageKey, "&");
    if(argumentCount > 4)
    {
       logger.error("Skipping caching as we don't cache url:s with more than 3 params:" + pageKey);
       return false;
    }
    argumentCount = StringUtils.countMatches(pageKey, "/");
    if(argumentCount > 7)
    {
       logger.error("Skipping caching as we don't cache url:s with more than 7 slashes:" + pageKey);
       return false;
    }
    */

    boolean isCached = false;

    String pageCacheExtraName = "pageCacheExtra";
    if (!pageInvoker.getTemplateController().getIsPageCacheDisabled()
            && !pageInvoker.getDeliveryContext().getDisablePageCache()) //Caching page if not disabled
    {
        Integer newPageCacheTimeout = pageInvoker.getDeliveryContext().getPageCacheTimeout();
        if (newPageCacheTimeout == null)
            newPageCacheTimeout = pageInvoker.getTemplateController().getPageCacheTimeout();

        //String[] allUsedEntitiesCopy = pageInvoker.getDeliveryContext().getAllUsedEntities().clone();
        List<String> allUsedEntitiesSet = pageInvoker.getDeliveryContext().getAllUsedEntitiesAsSet();
        //String[] allUsedEntitiesCopy = allUsedEntitiesSet.toArray(new String[0]);
        //System.out.println("allUsedEntitiesSet:" + allUsedEntitiesSet.size());

        String pageCacheExclusionsRegexp = null;
        Integer pageCacheMaxGroups = 500;
        try {
            Map cacheSettings = CmsPropertyHandler.getCacheSettings();
            //System.out.println("cacheSettings:" + cacheSettings);
            if (cacheSettings != null) {
                pageCacheExclusionsRegexp = (String) cacheSettings.get("PAGE_CACHE_EXCLUSIONS");
                String pageCacheMaxGroupsString = (String) cacheSettings.get("PAGE_CACHE_MAX_GROUPS");
                if (pageCacheMaxGroupsString != null)
                    pageCacheMaxGroups = new Integer(pageCacheMaxGroupsString);

                if (pageCacheExclusionsRegexp != null && !pageCacheExclusionsRegexp.equals(""))
                    pattern = Pattern.compile(pageCacheExclusionsRegexp);
            }
        } catch (Exception e) {
            logger.warn("cacheSettings was null:" + e.getMessage(), e);
        }
        if (logger.isInfoEnabled()) {
            logger.info("pageCacheExclusionsRegexp:" + pageCacheExclusionsRegexp);
            logger.info("pageCacheMaxGroups:" + pageCacheMaxGroups);
        }

        boolean detailedRelations = true;
        if (allUsedEntitiesSet.size() > pageCacheMaxGroups)
            detailedRelations = false;

        //System.out.println("detailedRelations:" + detailedRelations);
        //System.out.println("allUsedEntitiesSet:" + allUsedEntitiesSet.size());

        Object extraData = pageInvoker.getDeliveryContext().getExtraData();
        List<String> allUsedEntitiesFilteredCopy = new ArrayList<String>();
        for (String s : allUsedEntitiesSet) {
            if (detailedRelations) {
                if (s.startsWith("content_") && s.indexOf("_", 8) > -1) {
                    //allUsedEntitiesFilteredCopy.add(getPooledString(s.hashCode()));
                    allUsedEntitiesFilteredCopy.add(s); //(getPooledString(s.hashCode()));
                    //System.out.println("Added: " + s);
                } else if (s.startsWith("siteNode_"))
                    allUsedEntitiesFilteredCopy.add(s);
                else if (s.startsWith("selectiveCacheUpdateNonApplicable"))
                    allUsedEntitiesFilteredCopy.add(s);
            } else {
                if (s.startsWith("content_") && s.indexOf("_", 8) == -1) {
                    allUsedEntitiesFilteredCopy.add(s);
                    //allUsedEntitiesFilteredCopy.add(s); //getPooledString(s.hashCode()));
                    //System.out.println("Added: " + s);
                } else if (s.startsWith("siteNode_"))
                    allUsedEntitiesFilteredCopy.add(s);
                else if (s.startsWith("selectiveCacheUpdateNonApplicable"))
                    allUsedEntitiesFilteredCopy.add(s);
            }
        }
        //System.out.println("allUsedEntitiesFilteredCopy:" + allUsedEntitiesFilteredCopy.size());

        try {
            logger.info("pageCacheExclusionsRegexp:" + pageCacheExclusionsRegexp);
            logger.info("pageCacheMaxGroups:" + pageCacheMaxGroups);

            if (pattern != null) {
                Matcher matcher = pattern.matcher(pageKey);
                if (matcher.find()) {
                    logger.info("Skipping caching key 1:" + pageKey);
                    return false;
                }
                if (pageCacheMaxGroups != null && !pageCacheMaxGroups.equals("")
                        && allUsedEntitiesFilteredCopy.size() > pageCacheMaxGroups) {
                    logger.info("Skipping caching key 2:" + pageKey);
                    return false;
                }
                matcher.reset();
            }
        } catch (Exception e) {
            logger.warn("cacheSettings was null:" + e.getMessage(), e);
        }

        String[] allUsedEntitiesCopy = allUsedEntitiesFilteredCopy.toArray(new String[0]);
        //System.out.println("allUsedEntitiesCopy:" + allUsedEntitiesCopy.length);
        logger.info("allUsedEntitiesCopy:" + allUsedEntitiesCopy.length);
        logger.info("Caching:" + pageKey);

        synchronized (cacheAdministrator) {
            byte[] compressedData = compressionHelper.compress(value);
            //logger.info("Compressing page for pageCache took " + (System.currentTimeMillis() - startCompression) + " with a compressionFactor of " + (this.pageString.length() / compressedData.length));
            if (pageInvoker.getTemplateController().getOperatingMode().intValue() == 3
                    && !CmsPropertyHandler.getLivePublicationThreadClass()
                            .equalsIgnoreCase("org.infoglue.deliver.util.SelectiveLivePublicationThread")) {
                PageCacheHelper.getInstance().cachePageString(pageKey, compressedData);
                //cacheAdministrator.putInCache(pageKey, compressedData, allUsedEntitiesCopy);
                isCached = true;
                //CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey, extraData, allUsedEntitiesCopy, false);
                //CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey + "_pageCacheTimeout", newPageCacheTimeout, allUsedEntitiesCopy, false);    
            } else {
                //FIX THE part above as well
                //System.out.println("Caching in pageCache");
                PageCacheHelper.getInstance().cachePageString(pageKey, compressedData);
                //cacheAdministrator.putInCache(pageKey, compressedData, allUsedEntitiesCopy);
                isCached = true;

                /*
                if(pageInvoker.getTemplateController().getHttpServletRequest().getParameter("listMostUsed") != null)
                {
                   System.out.println("These contents were used before:" + ContentDeliveryController.mostUsedContentIds.size());
                   Map<Integer,Integer> contentIds = ContentDeliveryController.mostUsedContentIds;
                   for(Integer contentId : contentIds.keySet())
                   {
                      if(contentIds.get(contentId) > 3)
                System.out.println("" + contentId + ":" + contentIds.get(contentId));
                   }
                }
                */
                if (pageInvoker.getTemplateController().getHttpServletRequest()
                        .getParameter("listEntities") != null) {
                    List<String> debug = Arrays.asList(allUsedEntitiesCopy);
                    Collections.sort(debug);
                    for (String s : debug) {
                        System.out.println("s:" + s);
                    }
                }

                CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey, extraData, null, false);
                CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey + "_pageCacheTimeout",
                        newPageCacheTimeout, null, false);
                //CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey + "_entities", allUsedEntitiesCopy, null, false);
                String allUsedEntitiesCopyAsString = StringUtils.join(allUsedEntitiesCopy, "|");
                if (logger.isInfoEnabled()) {
                    logger.info("pageKey:" + pageKey);
                    logger.info("allUsedEntitiesCopyAsString:" + allUsedEntitiesCopyAsString);
                }

                if (CmsPropertyHandler.getOperatingMode().equals("0")) {
                    CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey + "_entitiesAsByte",
                            allUsedEntitiesCopyAsString);
                } else {
                    byte[] compressedAllUsedEntitiesCopyAsString = compressionHelper
                            .compress(allUsedEntitiesCopyAsString);
                    CacheController.cacheObjectInAdvancedCache(pageCacheExtraName, pageKey + "_entitiesAsByte",
                            compressedAllUsedEntitiesCopyAsString);
                }
            }
        }
    } else {
        if (logger.isInfoEnabled())
            logger.info(
                    "Page caching was disabled for the page " + pageInvoker.getDeliveryContext().getSiteNodeId()
                            + " with pageKey " + pageInvoker.getDeliveryContext().getPageKey()
                            + " - modifying the logic to enable page caching would boast performance.");
    }
    return isCached;
}