List of usage examples for org.apache.commons.lang3 StringUtils replaceOnce
public static String replaceOnce(final String text, final String searchString, final String replacement)
Replaces a String with another String inside a larger String, once.
A null reference passed to this method is a no-op.
StringUtils.replaceOnce(null, *, *) = null StringUtils.replaceOnce("", *, *) = "" StringUtils.replaceOnce("any", null, *) = "any" StringUtils.replaceOnce("any", *, null) = "any" StringUtils.replaceOnce("any", "", *) = "any" StringUtils.replaceOnce("aba", "a", null) = "aba" StringUtils.replaceOnce("aba", "a", "") = "ba" StringUtils.replaceOnce("aba", "a", "z") = "zba"
From source file:org.gsweb.components.util.ComponentResourceUtils.java
public static String getScriptFunctionNameForXhrMain(String functionName) { if (StringUtils.isBlank(functionName)) { return ""; }/* w ww . j av a 2 s . c o m*/ functionName = functionName.trim(); if (functionName.indexOf(";") > -1) { functionName = StringUtils.replaceOnce(functionName, ";", ""); } if (functionName.indexOf(")") == -1) { functionName = functionName + "()"; } return functionName; }
From source file:org.gsweb.components.util.ComponentResourceUtils.java
public static String getScriptFunctionNameForGridParams(String functionName) { if (StringUtils.isBlank(functionName)) { return ""; }/*from w w w.ja va2s . com*/ functionName = functionName.trim(); if (functionName.indexOf(";") > -1) { functionName = StringUtils.replaceOnce(functionName, ";", ""); } return functionName; }
From source file:org.icatproject.idav.methods.AbstractMethod.java
/** * Return the relative path associated with this servlet. * /*from ww w .j a va2s .c o m*/ * @param request * The servlet request we are processing */ protected String getRelativePath(HttpServletRequest request) { // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute("javax.servlet.include.request_uri") != null) { String result = (String) request.getAttribute("javax.servlet.include.path_info"); // if (result == null) // result = (String) request // .getAttribute("javax.servlet.include.servlet_path"); if ((result == null) || (result.equals(""))) result = "/"; return (result); } // KP 17/07/15 - added this section because previously the simple // solution of using request.getPathInfo() was being used but // this starts to fall over when you use special (but legal) // characters in your folder and filenames // we should aim to cope with all of these if at all possible // LOG.trace("getPathInfo: [" + request.getPathInfo() + "]"); // LOG.trace("getPathTranslated: [" + request.getPathTranslated() + "]"); // LOG.trace("getContextPath: [" + request.getContextPath() + "]"); // LOG.trace("getQueryString: [" + request.getQueryString() + "]"); // LOG.trace("getRequestURI: [" + request.getRequestURI() + "]"); // LOG.trace("getRequestURL: [" + request.getRequestURL() + "]"); String requestURI = request.getRequestURI(); String contextPath = request.getContextPath(); if (contextPath != null) { // remove the context path from the request URI requestURI = StringUtils.replaceOnce(requestURI, contextPath, ""); } // I think Windows is not encoding the "+" in folder/file names // so we need to encode this first otherwise it gets changed to a // space by the URLDecoder requestURI = StringUtils.replace(requestURI, "+", "%2B"); try { requestURI = URLDecoder.decode(requestURI, "UTF-8"); } catch (UnsupportedEncodingException e) { // this should never happen - the w3c recommends that UTF-8 encoding is used // see http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars } LOG.trace("Correct requestURI is: [" + requestURI + "]"); String result = requestURI; // end of section added by KP // No, extract the desired path directly from the request // KP 17/07/15 - I commented out the line below but // the 3 lines below that were already commented out //String result = request.getPathInfo(); // if (result == null) { // result = request.getServletPath(); // } if ((result == null) || (result.equals(""))) { result = "/"; } return (result); }
From source file:org.jmlspecs.ajmlrac.TransPostExpression2.java
/** * Translates a JML old expression, <code>self</code>, enclosed in * quantifiers. The translation generates code that evaluates the * old expression for each combination of bound variables of * quantifiers and stores the result to a private cache. The original * old expression is replaced with cache lookup code. * /*from w ww. j a va 2 s.co m*/ * <pre><jml> * requires !quantifiers.isEmpty(); * //assignable oldExprs; * </jml></pre> */ private void oldExpressionInQuantifiers(JmlSpecExpressionWrapper self) { JExpression expr = self.specExpression(); CType type = expr.getApparentType(); String mapVar = varGen.freshOldVar(); // cache variable // statements for evaluating old expression, E, of type T. // T v = T_init; // v = [[E]] // mapVar.put(key, v); String var = oldVarGen.freshVar(); String key = buildKey(); // coerce to type TN_JMLVALUE with appropriate guard against // undefinedness. // RacNode stmt = new TransOldExpression(oldVarGen,context,expr,var,typeDecl).stmt(); TransExpression2 tr = new TransExpression2(oldVarGen, context, expr, var, typeDecl, errorType); RacNode stmt = tr.stmt(false); if (!tr.isProperlyEvaluated()) { throw tr.reportedException; } // stmt = RacParser.parseStatement( // //"try {\n" + // " " + TransUtils.toString(type) + " " + var + " = " + // TransUtils.defaultValue(type) + ";\n" + // "$0\n" + // " " + mapVar + ".put(" + key + ", " +TN_JMLVALUE+ ".ofObject(" + // TransUtils.wrapValue(type, var) + "));"/* + // "}\n" + // "catch (JMLNonExecutableException jml$e0) {\n" + // " " + mapVar + ".put(" + key + // ", " +TN_JMLVALUE+ ".ofNonExecutable());\n" + // "}" + // "catch (java.lang.Exception jml$e0) {\n" + // " " + mapVar + ".put(" + key + // ", " +TN_JMLVALUE+ ".ofUndefined());\n" + // "}"*/, // stmt.incrIndent()); // iteration of the statement over bound variables // try { // TransQuantifiedExpression trans = null; // // As the variable quantifiers is a stack, the translation // // should be done in the reverse order, i.e., from the // // inner to outer quantifiers. Thanks to Peter Chan for // // reporting this error. // for (int i = quantifiers.size() - 1; i >= 0; i--) { // trans = new TransQuantifiedExpression(varGen, context, // (JmlSpecQuantifiedExpression)quantifiers.get(i), // null, this); // stmt = trans.generateLoop(stmt); // } // } catch (NonExecutableQuantifierException e) { // /* // // contextual interpretation of non-executable expression // if (context.enabled() && type.isBoolean()) { // RETURN_RESULT(RacParser.parseStatement( // "// from a non_executable, boolean, JML clause\n" + // context.angelicValue(GET_ARGUMENT()) + ";")); // } else { // nonExecutableExpression(); // } // return;*/ // throw(new NotImplementedExpressionException(self.getTokenReference(), "The old expression in this quantifier")); // } // piggyback cache declaration in the name field // stmt.setVarDecl(PreValueVars.createVar(forStatic, // "JMLOldExpressionCache", // mapVar, // "new JMLOldExpressionCache()")); // oldExprs.add(stmt); List fieldsName = new ArrayList(); HashMap fieldsMap = new HashMap(); String[] fields = tr.stmtAsString().split(" "); if ((tr.stmtAsString().contains("[") && tr.stmtAsString().contains("]"))) { for (int i = 0; i < fields.length; i++) { if (fields[i].contains("this.") || fields[i].contains(typeDecl.getCClass().getJavaName() + ".")) { String fieldName = fields[i].replaceAll("\\[(.)+\\]", "").split(" ")[0].replace("(", "") .replace(")", ""); JFieldDeclarationType[] typeFields = typeDecl.fields(); for (int l = 0; l < typeFields.length; l++) { JVariableDefinition varDef = typeFields[l].variable(); if (("this." + varDef.ident()).equals(fieldName)) { fieldsName.add(fieldName); } } } } for (Iterator iterator = fieldsName.iterator(); iterator.hasNext();) { String currentField = (String) iterator.next(); fieldsMap.put( currentField.replace("this.", "").replace(typeDecl.getCClass().getJavaName() + ".", ""), mapVar); currentField = currentField.replace("this.", "object$rac."); oldVarDecl.add(TransUtils.toString(type) + "[] " + mapVar + ";"); oldExprs.add(mapVar + " = new " + type + "[" + currentField + ".length];\n" + " " + "System.arraycopy(" + currentField + ", 0, " + mapVar + ", 0, " + currentField + ".length );"); mapVar = varGen.freshOldVar(); } } else { for (int i = 0; i < fields.length; i++) { if (fields[i].contains("this.") || fields[i].contains(typeDecl.getCClass().getJavaName() + ".")) { String fieldName = fields[i]; if (fieldName.startsWith("(")) { // fieldName = fieldName.replaceFirst("(", ""); fieldName = StringUtils.replaceOnce(fieldName, "(", ""); } if (fieldName.startsWith("this.")) { fieldName = fieldName.replaceFirst("this.", ""); fieldName = fieldName.replace(".", "_"); fieldsName.add("this." + fieldName.split("_")[0]); } else if (fieldName.startsWith(typeDecl.getCClass().getJavaName() + ".")) { fieldName = fieldName.replaceFirst(typeDecl.getCClass().getJavaName() + ".", ""); fieldName = fieldName.replace(".", "_"); fieldsName.add(typeDecl.getCClass().getJavaName() + "." + fieldName.split("_")[0]); } } } for (Iterator iterator = fieldsName.iterator(); iterator.hasNext();) { String currentField = (String) iterator.next(); fieldsMap.put( currentField.replace("this.", "").replace(typeDecl.getCClass().getJavaName() + ".", ""), mapVar); currentField = currentField.replace("this.", "object$rac."); oldVarDecl.add("java.util.Collection " + mapVar + ";"); oldExprs.add(mapVar + " = new java.util.HashSet();\n" + " " + mapVar + ".addAll(" + currentField + ");"); mapVar = varGen.freshOldVar(); } } // replace the old expr with cache lookup code // RacNode result = RacParser.parseStatement( // "if (" + mapVar + ".containsKey(" + key + ")) {\n" + // " " + GET_ARGUMENT() + " = " + // TransUtils.unwrapObject(type, // "((" +TN_JMLVALUE+ ")" +mapVar+ ".get(" +key+ ")).value()") // + ";\n" + // "} else {\n" + // " throw JMLChecker.ANGELIC_EXCEPTION;\n" + // "}"); // String result = TransUtils.unwrapObject(type,"((" +TN_JMLVALUE+ ")" +mapVar+ ".get(" +key+ ")).value()"); String result = tr.stmtAsString().replace("this.", "").replace(typeDecl.getCClass().getJavaName() + ".", ""); for (Iterator iterator = fieldsMap.keySet().iterator(); iterator.hasNext();) { String currentKey = (String) iterator.next(); if (result.contains(currentKey)) { result = result.replace(currentKey, (String) fieldsMap.get(currentKey)); } } RETURN_RESULT(result); }
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();/*w w w . j ava2s . co m*/ 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.jmlspecs.util.QDoxUtil.java
private static String stripMethBodies(String fileAsString, List<JavaMethod> javaDeclMeths, List<String> fileMeths) { int indexMeth = 0; for (Iterator<String> iterator = fileMeths.iterator(); iterator.hasNext();) { String returnTypeDefaultValue = ""; String currentMeth = iterator.next(); String currentMethStrippedBody = ""; currentMethStrippedBody = currentMeth; JavaMethod javaMeth = javaDeclMeths.get(indexMeth); if (((javaMeth.getReturnType() != null) && !(javaMeth.isConstructor()))) { if (!QDoxUtil.defaultValue(javaMeth.getReturnType().getFullyQualifiedName()).equals("")) { // if(!isJMLFile){ returnTypeDefaultValue = "return " + QDoxUtil.defaultValue(javaMeth.getReturnType().getFullyQualifiedName()) + ";"; // } }// w w w .j a va2s . c o m } if (!currentMeth.equals("")) { int openBraceIndex = currentMeth.indexOf('{'); if (openBraceIndex != -1) { String tmp = ""; StringBuffer linesToAppend = new StringBuffer(""); tmp = currentMeth.substring(openBraceIndex + 1); int newLineCount = QDoxUtil.getLineNumbersQtd(tmp); // if(!isJMLFile){ linesToAppend.append("{"); // } // else{ // linesToAppend.append(";"); // } linesToAppend.append(QDoxUtil.getNewLinesCaracter(newLineCount)); linesToAppend.append(returnTypeDefaultValue); // if(!isJMLFile){ linesToAppend.append("}"); // } // currentMethStrippedBody = currentMeth.replaceAll("\\{[\\w\\W]*\\}", linesToAppend.toString()); String body = currentMeth.substring(openBraceIndex, currentMeth.lastIndexOf("}") + 1); currentMethStrippedBody = currentMeth.replace(body, linesToAppend.toString()); fileAsString = StringUtils.replaceOnce(fileAsString, currentMeth, currentMethStrippedBody); } } indexMeth++; } return fileAsString; }
From source file:org.jmlspecs.util.QDoxUtil.java
private static String getFileMethDeclsProcessed(String fileAsString, List<JavaMethod> javaDeclMeths, List<String> fileMeths, File file) throws PositionedError { int indexMeth = 0; for (Iterator<String> iterator = fileMeths.iterator(); iterator.hasNext();) { String currentMethErasure = ""; String currentMethErasureTmp = ""; String currentMeth = iterator.next(); JavaMethod javaMeth = javaDeclMeths.get(indexMeth); if (javaMeth.getAnnotations().length > 0) { // processing method annotations including parameter ones String currentMethAnnoProcessed = QDoxUtil.removeNonJMLAnnotationParameters(currentMeth); fileAsString = StringUtils.replaceOnce(fileAsString, currentMeth, currentMethAnnoProcessed); currentMeth = currentMethAnnoProcessed; }/*from www. j a v a 2s .c o m*/ currentMethErasureTmp = currentMeth; JavaClass onwerType = javaMeth.getParentClass(); HashMap<String, String> genericAndErasureTypeParameters = QDoxUtil .getGenericAndErasureTypeParametersForMethod(onwerType, javaMeth); Set<String> genericTypes = genericAndErasureTypeParameters.keySet(); for (Iterator<String> iterator2 = genericTypes.iterator(); iterator2.hasNext();) { String genericType = iterator2.next(); String erasureType = genericAndErasureTypeParameters.get(genericType); currentMethErasureTmp = currentMethErasureTmp.replaceAll("(\\b)" + genericType + "(\\b)", erasureType); currentMethErasure = currentMethErasureTmp; } indexMeth++; if (!currentMethErasure.equals("")) { // means that we have generic type parameters if (currentMethErasure.contains("<") && currentMethErasure.contains(">")) { int lp = currentMethErasure.lastIndexOf('('); String currentMethErasurePreArgs = currentMethErasure.substring(0, lp); String currentMethErasureArgs = currentMethErasure.substring(lp); String currentMethPreArgsWithoutDiamond = currentMethErasurePreArgs .replaceAll("\\<[\\w\\W]*\\>", ""); String currentMethArgsWithoutDiamond = currentMethErasureArgs; currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replaceAll("\\<[\\w\\W]*\\>", ""); while (currentMethArgsWithoutDiamond.contains("<")) { int lD = currentMethArgsWithoutDiamond.indexOf("<"); int rD = currentMethArgsWithoutDiamond.indexOf(">"); if (lD > rD) { // currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replaceFirst(">", ""); currentMethArgsWithoutDiamond = StringUtils.replaceOnce(currentMethArgsWithoutDiamond, ">", ""); lD = currentMethArgsWithoutDiamond.indexOf("<"); rD = currentMethArgsWithoutDiamond.indexOf(">"); } String diamond = currentMethArgsWithoutDiamond.substring(lD, (rD + 1)); currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replace(diamond, ""); } if (currentMethArgsWithoutDiamond.contains(">")) { currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replace(">", ""); // removing any residual from generics --- [[[hemr]]] } currentMethErasure = currentMethErasure .replace(currentMethErasurePreArgs, currentMethPreArgsWithoutDiamond) .replace(currentMethErasureArgs, currentMethArgsWithoutDiamond); } fileAsString = StringUtils.replaceOnce(fileAsString, currentMeth, currentMethErasure); // handling crosscutting specs JavaClass ownerType = javaMeth.getParentClass(); QDoxUtil.handlingCrosscutSpecs(file, javaMeth, currentMethErasure, ownerType); } else { // means that we have generic type parameters if (currentMeth.contains("<") && currentMeth.contains(">")) { String currentMethTmp = currentMeth; int lp = currentMeth.lastIndexOf('('); String currentMethPreArgs = currentMethTmp.substring(0, lp); String currentMethArgs = currentMethTmp.substring(lp); String currentMethPreArgsWithoutDiamond = currentMethPreArgs.replaceAll("\\<[\\w\\W]*\\>", ""); String currentMethArgsWithoutDiamond = currentMethArgs; currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replaceAll("\\<[\\w\\W]*\\>", ""); while (currentMethArgsWithoutDiamond.contains("<")) { int lD = currentMethArgsWithoutDiamond.indexOf("<"); int rD = currentMethArgsWithoutDiamond.indexOf(">"); if (lD > rD) { // currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replaceFirst(">", ""); currentMethArgsWithoutDiamond = StringUtils.replaceOnce(currentMethArgsWithoutDiamond, ">", ""); lD = currentMethArgsWithoutDiamond.indexOf("<"); rD = currentMethArgsWithoutDiamond.indexOf(">"); } String diamond = currentMethArgsWithoutDiamond.substring(lD, (rD + 1)); currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replace(diamond, ""); } if (currentMethArgsWithoutDiamond.contains(">")) { currentMethArgsWithoutDiamond = currentMethArgsWithoutDiamond.replace(">", ""); // removing any residual from generics --- [[[hemr]]] } currentMethTmp = currentMethTmp.replace(currentMethPreArgs, currentMethPreArgsWithoutDiamond) .replace(currentMethArgs, currentMethArgsWithoutDiamond); fileAsString = StringUtils.replaceOnce(fileAsString, currentMeth, currentMethTmp); // handling crosscutting specs JavaClass ownerType = javaMeth.getParentClass(); QDoxUtil.handlingCrosscutSpecs(file, javaMeth, currentMethTmp, ownerType); } else { // means that we have a method in a .jml file // handling crosscutting specs JavaClass ownerType = javaMeth.getParentClass(); QDoxUtil.handlingCrosscutSpecs(file, javaMeth, currentMeth, ownerType); } } } return fileAsString; }
From source file:org.jmlspecs.util.QDoxUtil.java
private static String getFileEnumTypeErasureProcessingAsString(StringBuffer bufferedFile, String fileAsString, List<JavaClass> javaDeclEnumTypes) throws IOException { BufferedReader buffer = null; String line = ""; List<com.github.antlrjavaparser.api.body.EnumDeclaration> javaDeclEnumTypes2 = QDoxUtil .getAllDeclaredJavaEnumConstantsInFile(fileAsString); fileAsString = fileAsString.replace("enum ", "final class "); // handling enumeration fields for (int i = 0; i < javaDeclEnumTypes.size(); i++) { JavaClass enumType = javaDeclEnumTypes.get(i); com.github.antlrjavaparser.api.body.EnumDeclaration enumType2 = javaDeclEnumTypes2.get(i); List<JavaField> enumTypeFields = QDoxUtil.getADeclaredJavaEnumerationFieldsInEnumType(enumType); if (enumTypeFields.size() > 0) { String enumFieldsConverted = QDoxUtil .getADeclaredJavaEnumerationFieldsInEnumTypeAsErasure(enumType); List<String> listEnumConstLineNumbers = getEnumConstantLineNumbersPerEnumDecl(enumType2); buffer = new BufferedReader(new StringReader(fileAsString)); bufferedFile.delete(0, (bufferedFile.length() - 1)); // resetting buffer line = buffer.readLine();//from w w w . j av a 2 s . co m int lineStart = enumType2.getBeginLine(); int lineEnd = enumType2.getEndLine(); int lineNumber = 1; String lastLine = ""; while (line != null) { if (listEnumConstLineNumbers.get(listEnumConstLineNumbers.size() - 1).equals(lineNumber + "")) { lastLine = "/* " + line + " */#"; fileAsString = StringUtils.replaceOnce(fileAsString, line, lastLine); } else if (listEnumConstLineNumbers.contains(lineNumber + "")) { String lineProcessed = "/* " + line + " */"; fileAsString = StringUtils.replaceOnce(fileAsString, line, lineProcessed); } line = buffer.readLine(); lineNumber++; } buffer.close(); fileAsString = StringUtils.replaceOnce(fileAsString, lastLine, lastLine.replace("#", enumFieldsConverted)); } } return fileAsString; }
From source file:org.jmlspecs.util.QDoxUtil.java
private static String handleConstructDeclInJMLFileMode(StringBuffer bufferedFile, String fileAsString, List<JavaMethod> javaDeclMeths) throws IOException { BufferedReader buffer;/* ww w . j a v a 2s .c o m*/ String line; for (Iterator<JavaMethod> iterator = javaDeclMeths.iterator(); iterator.hasNext();) { JavaMethod javaMethod = iterator.next(); if (!javaMethod.isConstructor()) { continue; } int lineNumber = javaMethod.getLineNumber(); buffer = new BufferedReader(new StringReader(fileAsString)); line = buffer.readLine(); int fileLineNumber = 1; boolean canStart = false; while (line != null) { if (lineNumber == fileLineNumber) { canStart = true; } if (canStart) { bufferedFile.append(line); bufferedFile.append("\n"); JavaDocBuilder qDoxJavaMethodParser = new JavaDocBuilder(); try { qDoxJavaMethodParser.addSource(new StringReader( "public class JMethodParser{\n" + bufferedFile.toString() + "\n}")); if (qDoxJavaMethodParser.getClassByName("JMethodParser").getMethods().length == 1) { // if match the wanted contructor if (line.contains(";")) { String lineProcessed = line.replace(";", ""); fileAsString = StringUtils.replaceOnce(fileAsString, bufferedFile.toString(), bufferedFile.toString().replace(line, lineProcessed) + "{}"); } bufferedFile.delete(0, (bufferedFile.length() - 1)); break; } } catch (com.thoughtworks.qdox.parser.ParseException e) { // continue if it is not a valid method or constructor... [[[hemr]]] } } line = buffer.readLine(); fileLineNumber++; } } return fileAsString; }
From source file:org.jmlspecs.util.QDoxUtil.java
private static String removeNonJMLAnnotationParameters(String currentMethTmp) { String currentMethTmp2 = currentMethTmp; Pattern tmpPattern = Pattern.compile("/\\*(.|\\s)*@(.|\\s)*\\*/"); Matcher tmpMatcher = tmpPattern.matcher(currentMethTmp2); while (tmpMatcher.find()) { currentMethTmp2 = currentMethTmp2.replace(tmpMatcher.group(), ""); }// w ww . j av a 2 s . c om Pattern annoPattern = Pattern.compile("@(\\s)*(.)*(\\s)*(\\((.)*\\))"); Matcher annoMatcher = annoPattern.matcher(currentMethTmp2); while (annoMatcher.find()) { String group = annoMatcher.group(); char[] groupAsChar = group.toCharArray(); boolean canCheck = false; boolean foundAt = false; StringBuffer matchedAnnotation = new StringBuffer(""); for (int i = 0; i < groupAsChar.length; i++) { if (groupAsChar[i] == '(') { canCheck = true; } if (groupAsChar[i] == '@') { foundAt = true; } if (foundAt) { matchedAnnotation.append(groupAsChar[i]); } if (canCheck) { if (QDoxUtil.isParenBalanced(matchedAnnotation.toString())) { // if is not JML annotation, we remove it... if (!isJMLAnnotation(matchedAnnotation.toString())) { currentMethTmp = StringUtils.replaceOnce(currentMethTmp, matchedAnnotation.toString(), ""); } matchedAnnotation = new StringBuffer(""); canCheck = false; foundAt = false; } } } } return currentMethTmp; }