PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/netbeans-7.3/java.source/test/qa-functional/src/org/netbeans/test/java/Common.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 597 lines | 424 code | 68 blank | 105 comment | 35 complexity | eb82dc19501671681f03ee5330efdec9 MD5 | raw file
  1. /*
  2. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  3. *
  4. * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
  5. *
  6. * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
  7. * Other names may be trademarks of their respective owners.
  8. *
  9. * The contents of this file are subject to the terms of either the GNU
  10. * General Public License Version 2 only ("GPL") or the Common
  11. * Development and Distribution License("CDDL") (collectively, the
  12. * "License"). You may not use this file except in compliance with the
  13. * License. You can obtain a copy of the License at
  14. * http://www.netbeans.org/cddl-gplv2.html
  15. * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  16. * specific language governing permissions and limitations under the
  17. * License. When distributing the software, include this License Header
  18. * Notice in each file and include the License file at
  19. * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
  20. * particular file as subject to the "Classpath" exception as provided
  21. * by Oracle in the GPL Version 2 section of the License file that
  22. * accompanied this code. If applicable, add the following below the
  23. * License Header, with the fields enclosed by brackets [] replaced by
  24. * your own identifying information:
  25. * "Portions Copyrighted [year] [name of copyright owner]"
  26. *
  27. * Contributor(s):
  28. *
  29. * The Original Software is NetBeans. The Initial Developer of the Original
  30. * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
  31. * Microsystems, Inc. All Rights Reserved.
  32. *
  33. * If you wish your version of this file to be governed by only the CDDL
  34. * or only the GPL Version 2, indicate your decision by adding
  35. * "[Contributor] elects to include this software in this distribution
  36. * under the [CDDL or GPL Version 2] license." If you do not indicate a
  37. * single choice of license, a recipient has the option to distribute
  38. * your version of this file under either the CDDL, the GPL Version 2 or
  39. * to extend the choice of license to its licensees as provided above.
  40. * However, if you add GPL Version 2 code and therefore, elected the GPL
  41. * Version 2 license, then the option applies only if the new code is
  42. * made subject to such option by the copyright holder.
  43. */
  44. /*
  45. * Common.java
  46. *
  47. * Created on May 19, 2000, 1:56 PM
  48. */
  49. package org.netbeans.test.java;
  50. import com.sun.source.tree.AnnotationTree;
  51. import com.sun.source.tree.BlockTree;
  52. import com.sun.source.tree.ClassTree;
  53. import com.sun.source.tree.CompilationUnitTree;
  54. import com.sun.source.tree.ExpressionTree;
  55. import com.sun.source.tree.MethodTree;
  56. import com.sun.source.tree.ModifiersTree;
  57. import com.sun.source.tree.Tree;
  58. import com.sun.source.tree.Tree.Kind;
  59. import com.sun.source.tree.TypeParameterTree;
  60. import com.sun.source.tree.VariableTree;
  61. import java.io.IOException;
  62. import java.util.ArrayList;
  63. import java.util.Collections;
  64. import java.util.EnumSet;
  65. import java.util.HashMap;
  66. import java.util.LinkedList;
  67. import java.util.List;
  68. import java.util.Map;
  69. import java.util.Set;
  70. import java.util.TreeMap;
  71. import javax.lang.model.element.Modifier;
  72. import javax.lang.model.element.TypeElement;
  73. import javax.lang.model.type.TypeKind;
  74. import org.netbeans.api.java.classpath.ClassPath;
  75. import org.netbeans.api.java.source.CancellableTask;
  76. import org.netbeans.api.java.source.JavaSource;
  77. import org.netbeans.api.java.source.JavaSource.Phase;
  78. import org.netbeans.api.java.source.TreeMaker;
  79. import org.netbeans.api.java.source.TreeUtilities;
  80. import org.netbeans.api.java.source.WorkingCopy;
  81. import org.openide.filesystems.*;
  82. import org.openide.loaders.DataObject;
  83. //import org.openide.src.MethodParameter;
  84. //import org.openide.src.Type;
  85. /** Common static methods. Useful for creating new JavaElements
  86. * @author Jan Becicka
  87. * @version 1.1
  88. */
  89. public class Common extends Object {
  90. private static final String cr=System.getProperty("line.separator");
  91. private static final String METHODS = "newMethod";
  92. private static final String FIELDS = "newField";
  93. //private static final int DEFAULTMODIFIERS = Modifier.PUBLIC;
  94. private static final String DEFAULTBODY = "for (int i=0;i<100;i++){\n\tSystem.out.println(new Integer(i).toString());\n}\nreturn 0;\n";
  95. public static final String DEFAULTINITIALIZERBODY = "\n/*somebody*/\n";
  96. /** int parameter1
  97. */
  98. public static Map<String,String> PARS1;
  99. /** int parameter1, int parameter2
  100. */
  101. public static Map<String,String> PARS2;
  102. /** float parameter1, float parameter2, float parameter 3
  103. */
  104. public static Map<String,String> PARS3;
  105. static {
  106. PARS1 = new TreeMap<String, String>();
  107. PARS1.put("param1","int");
  108. PARS2 = new TreeMap<String, String>();
  109. PARS2.put("param1","int");
  110. PARS2.put("param2","int");
  111. PARS3 = new TreeMap<String, String>();
  112. PARS3.put("param1","float");
  113. PARS3.put("param2","int");
  114. PARS3.put("param3","String");
  115. }
  116. private static java.io.PrintWriter pw = null;
  117. public static void setPrintWriter(java.io.PrintWriter pr){
  118. pw=pr;
  119. }
  120. public Common() {
  121. }
  122. /** returns string from in and int
  123. * @param s
  124. * @param i
  125. * @return Makes String from String and int
  126. */
  127. public static String concat(String s, int i){
  128. return s+new Integer(i).toString();
  129. }
  130. /**
  131. * @param i
  132. * @return for i=1 "newMethod1"
  133. */
  134. static public String getMethodName(int i){
  135. return concat(METHODS,i);
  136. }
  137. /** Concats String and int
  138. * @param name
  139. * @param i
  140. * @return
  141. */
  142. public static String getFieldName(String name,int i){
  143. return concat(name,i);
  144. }
  145. /**
  146. * @param i
  147. * @return for i=1 "newField1"
  148. */
  149. public static String getFieldName(int i){
  150. return concat(FIELDS,i);
  151. }
  152. private static Tree getTreeForType(String paramType, TreeMaker make) {
  153. Tree param = null;
  154. try {
  155. param = make.PrimitiveType(TypeKind.valueOf(paramType.toUpperCase()));
  156. } catch (IllegalArgumentException iae) {
  157. param = make.Identifier(paramType);
  158. }
  159. return param;
  160. }
  161. public static MethodTree createMethod(TreeMaker make,String name, Map<String,String> params) {
  162. ModifiersTree methodModifiers = make.Modifiers(
  163. Collections.<Modifier>singleton(Modifier.PUBLIC),
  164. Collections.<AnnotationTree>emptyList()
  165. );
  166. List<VariableTree> paramList = new LinkedList<VariableTree>();
  167. for(String paramName: params.keySet()) {
  168. Tree paramType = getTreeForType(params.get(paramName), make);
  169. VariableTree parameter = make.Variable(
  170. make.Modifiers(
  171. Collections.<Modifier>emptySet(),
  172. Collections.<AnnotationTree>emptyList()
  173. ),
  174. paramName, // name
  175. paramType, // parameter type
  176. null // initializer - does not make sense in parameters.
  177. );
  178. paramList.add(parameter);
  179. }
  180. MethodTree newMethod = make.Method(
  181. methodModifiers, // public
  182. name, // name
  183. make.PrimitiveType(TypeKind.VOID), // return type "void"
  184. Collections.<TypeParameterTree>emptyList(), // type parameters - none
  185. paramList, // final ObjectOutput arg0
  186. Collections.<ExpressionTree>emptyList(), // throws
  187. "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
  188. null // default value - not applicable here, used by annotations
  189. );
  190. return newMethod;
  191. }
  192. public static void addMethod(JavaSource js,
  193. final String name,
  194. final Map<String,String> params,
  195. final String returnType,
  196. final Set<Modifier> modifiers) throws IOException {
  197. CancellableTask task = new CancellableTask<WorkingCopy>() {
  198. public void cancel() {
  199. throw new UnsupportedOperationException("Not supported yet.");
  200. }
  201. public void run(WorkingCopy workingCopy) throws Exception {
  202. workingCopy.toPhase(Phase.RESOLVED);
  203. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  204. TreeMaker make = workingCopy.getTreeMaker();
  205. ClassTree clazz = null;
  206. for (Tree typeDecl : cut.getTypeDecls()) {
  207. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  208. clazz = (ClassTree) typeDecl;
  209. }
  210. } // end for
  211. MethodTree newMethod = createMethod(make, name, params);
  212. newMethod = make.Method(make.Modifiers(modifiers),
  213. newMethod.getName(),
  214. getTreeForType(returnType, make),
  215. newMethod.getTypeParameters(),
  216. newMethod.getParameters(),
  217. newMethod.getThrows(),
  218. newMethod.getBody(),
  219. (ExpressionTree)newMethod.getDefaultValue());
  220. ClassTree modifiedClazz = make.addClassMember(clazz, newMethod);
  221. workingCopy.rewrite(clazz, modifiedClazz);
  222. }
  223. };
  224. js.runModificationTask(task).commit();
  225. }
  226. public static void addConstructor(JavaSource js, final Map<String,String> params) throws IOException {
  227. CancellableTask task = new CancellableTask<WorkingCopy>() {
  228. public void cancel() {
  229. throw new UnsupportedOperationException("Not supported yet.");
  230. }
  231. public void run(WorkingCopy workingCopy) throws Exception {
  232. workingCopy.toPhase(Phase.RESOLVED);
  233. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  234. TreeMaker make = workingCopy.getTreeMaker();
  235. ClassTree clazz = null;
  236. for (Tree typeDecl : cut.getTypeDecls()) {
  237. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  238. clazz = (ClassTree) typeDecl;
  239. }
  240. } // end for
  241. MethodTree newMethod = createMethod(make, "<init>", params);
  242. ClassTree modifiedClazz = make.addClassMember(clazz, newMethod);
  243. workingCopy.rewrite(clazz, modifiedClazz);
  244. }
  245. };
  246. js.runModificationTask(task).commit();
  247. }
  248. public static void removeConstructors(JavaSource js) throws IOException {
  249. CancellableTask task = new CancellableTask<WorkingCopy>() {
  250. public void cancel() {
  251. throw new UnsupportedOperationException("Not supported yet.");
  252. }
  253. ClassTree orig;
  254. public void run(WorkingCopy workingCopy) throws Exception {
  255. workingCopy.toPhase(Phase.RESOLVED);
  256. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  257. TreeMaker make = workingCopy.getTreeMaker();
  258. ClassTree clazz = null;
  259. for (Tree typeDecl : cut.getTypeDecls()) {
  260. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  261. clazz = (ClassTree) typeDecl;
  262. }
  263. } // end for
  264. orig = clazz;
  265. for(Tree el : clazz.getMembers()) {
  266. if(el.getKind().equals(Kind.METHOD)) {
  267. MethodTree method = (MethodTree) el;
  268. if(method.getName().toString().equals("<init>")) {
  269. clazz = make.removeClassMember(clazz, method);
  270. }
  271. }
  272. }
  273. workingCopy.rewrite(orig, clazz);
  274. }
  275. };
  276. js.runModificationTask(task).commit();
  277. }
  278. public static void addInitializer(JavaSource js, final boolean isStatic) throws IOException {
  279. CancellableTask task = new CancellableTask<WorkingCopy>() {
  280. public void cancel() {
  281. throw new UnsupportedOperationException("Not supported yet.");
  282. }
  283. public void run(WorkingCopy workingCopy) throws Exception {
  284. workingCopy.toPhase(Phase.RESOLVED);
  285. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  286. TreeMaker make = workingCopy.getTreeMaker();
  287. ClassTree clazz = null;
  288. for (Tree typeDecl : cut.getTypeDecls()) {
  289. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  290. clazz = (ClassTree) typeDecl;
  291. }
  292. } // end for
  293. BlockTree bt = make.Block(Collections.EMPTY_LIST, isStatic);
  294. ClassTree modifiedClazz = make.addClassMember(clazz, bt);
  295. workingCopy.rewrite(clazz,modifiedClazz);
  296. }
  297. };
  298. js.runModificationTask(task).commit();
  299. }
  300. public static void addExtendImplementClause(JavaSource js,final String superClass,final List<String> ifaces) throws IOException {
  301. CancellableTask task = new CancellableTask<WorkingCopy>() {
  302. public void cancel() {
  303. throw new UnsupportedOperationException("Not supported yet.");
  304. }
  305. public void run(WorkingCopy workingCopy) throws Exception {
  306. workingCopy.toPhase(Phase.RESOLVED);
  307. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  308. TreeMaker make = workingCopy.getTreeMaker();
  309. ClassTree clazz = null;
  310. for (Tree typeDecl : cut.getTypeDecls()) {
  311. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  312. clazz = (ClassTree) typeDecl;
  313. }
  314. } // end for
  315. ClassTree origClazz = clazz;
  316. for(String iface :ifaces) {
  317. TypeElement element = workingCopy.getElements().getTypeElement(iface);
  318. ExpressionTree implementsClause = implementsClause = make.QualIdent(element);
  319. clazz = make.addClassImplementsClause(clazz, implementsClause);
  320. }
  321. Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));
  322. clazz = make.Class(clazz.getModifiers(),
  323. clazz.getSimpleName(),
  324. clazz.getTypeParameters(),
  325. extendsTree,
  326. (List<ExpressionTree>) clazz.getImplementsClause(),
  327. clazz.getMembers());
  328. workingCopy.rewrite(origClazz,clazz);
  329. }
  330. };
  331. js.runModificationTask(task).commit();
  332. }
  333. /** Creates new Class from package
  334. * @param packageName destination
  335. * @param className name
  336. * @throws Exception
  337. * @return
  338. */
  339. public static void addImport(JavaSource js,final String importText,final boolean isStatic) throws IOException {
  340. CancellableTask task = new CancellableTask<WorkingCopy>() {
  341. public void cancel() {
  342. throw new UnsupportedOperationException("Not supported yet.");
  343. }
  344. public void run(WorkingCopy workingCopy) throws Exception {
  345. workingCopy.toPhase(Phase.RESOLVED);
  346. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  347. TreeMaker make = workingCopy.getTreeMaker();
  348. CompilationUnitTree copy = make.addCompUnitImport(cut,make.Import(make.Identifier(importText), isStatic));
  349. workingCopy.rewrite(cut, copy);
  350. }
  351. };
  352. js.runModificationTask(task).commit();
  353. }
  354. public static void setPackage(JavaSource js, final String pack) throws IOException {
  355. CancellableTask task = new CancellableTask<WorkingCopy>() {
  356. public void cancel() {
  357. throw new UnsupportedOperationException("Not supported yet.");
  358. }
  359. public void run(WorkingCopy workingCopy) throws Exception {
  360. workingCopy.toPhase(Phase.RESOLVED);
  361. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  362. TreeMaker make = workingCopy.getTreeMaker();
  363. CompilationUnitTree copy = make.CompilationUnit(make.Identifier(pack),cut.getImports(), cut.getTypeDecls(), cut.getSourceFile());
  364. workingCopy.rewrite(cut, copy);
  365. }
  366. };
  367. js.runModificationTask(task).commit();
  368. }
  369. public static FileObject createClass(FileObject target, String packageName, String className) throws Exception {
  370. DataObject dob = getSystemDO("Templates/Classes", "Class", "java");
  371. DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(target,packageName,null,null)), className);
  372. return mdob.getPrimaryFile();
  373. }
  374. /** Get a file object by name. */
  375. public static FileObject getFO(FileObject file, String pkg, String name, String ext) throws Exception {
  376. ClassPath cp=ClassPath.getClassPath(file, ClassPath.SOURCE);
  377. String nam=(pkg != null && pkg.length() > 0)?pkg:"";
  378. nam+=(name != null && name.length() > 0)?".":"";
  379. nam=nam.replace('.', '/');
  380. nam+=(name != null && name.length() > 0)?name:"";
  381. nam+=(ext != null && ext.length() > 0)?"."+ext:"";
  382. //check
  383. FileObject[] root=cp.getRoots();
  384. FileObject ret=cp.findResource(nam);
  385. return ret;
  386. }
  387. /** Get a data object by name. */
  388. public static DataObject getSystemDO(String pkg, String name, String ext) throws Exception {
  389. return DataObject.find(FileUtil.getConfigFile(pkg+"/"+name+"."+ext));
  390. }
  391. /** Compares two Arrays
  392. * @param l
  393. * @param r
  394. * @return
  395. */
  396. public static boolean arrayEquals(Object[] l,Object[] r) {
  397. if (l.length!=r.length) return false;
  398. for (int i=0; i < l.length; i++){
  399. if (!l[i].equals(r[i])) return false;
  400. }
  401. return true;
  402. }
  403. /** Removes time and author's name
  404. * @param result
  405. * @return
  406. */
  407. public static String unify(String result) {
  408. int left=result.indexOf("@author");
  409. int right=result.indexOf('\n',left);
  410. if (left > -1)
  411. result=result.substring(0,left+"@author".length())+result.substring(right);
  412. return result;
  413. }
  414. /**
  415. * @param str
  416. * @return
  417. */
  418. public static String firstCharToUpper(String str) {
  419. String first, rest;
  420. if( str==null || str.equals("") )
  421. return str;
  422. first = str.substring(0, 1).toUpperCase();
  423. rest = str.substring( 1 );
  424. return first+rest;
  425. }
  426. /**
  427. * @param str
  428. * @return
  429. */
  430. public static String firstCharToLower(String str) {
  431. String first, rest;
  432. if( str==null || str.equals("") )
  433. return( str );
  434. first = str.substring(0, 1).toLowerCase();
  435. rest = str.substring( 1 );
  436. return first+rest;
  437. }
  438. public static VariableTree createField(TreeMaker make,String name,Set<Modifier> modifiers, String type) {
  439. Tree fieldType = getTreeForType(type, make);
  440. VariableTree vt = make.Variable(
  441. make.Modifiers(modifiers),
  442. name,
  443. fieldType,
  444. null);
  445. return vt;
  446. }
  447. public static void addField(JavaSource js, final String name, final Set<Modifier> modifiers, final String type) throws IOException {
  448. CancellableTask task = new CancellableTask<WorkingCopy>() {
  449. public void cancel() {
  450. throw new UnsupportedOperationException("Not supported yet.");
  451. }
  452. public void run(WorkingCopy workingCopy) throws Exception {
  453. workingCopy.toPhase(Phase.RESOLVED);
  454. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  455. TreeMaker make = workingCopy.getTreeMaker();
  456. ClassTree clazz = null;
  457. for (Tree typeDecl : cut.getTypeDecls()) {
  458. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  459. clazz = (ClassTree) typeDecl;
  460. }
  461. } // end for
  462. VariableTree vt = createField(make, name, modifiers, type);
  463. ClassTree modifiedClazz = make.addClassMember(clazz, vt);
  464. workingCopy.rewrite(clazz, modifiedClazz);
  465. }
  466. };
  467. js.runModificationTask(task).commit();
  468. }
  469. public static ClassTree getClassTree(
  470. TreeMaker make,
  471. WorkingCopy workingCopy,
  472. String name,
  473. String superClass,
  474. List<ExpressionTree> implementsList,
  475. Set<Modifier> modifiers) {
  476. Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));
  477. Map<String,String> params = new HashMap<String, String>();
  478. params.put("param1", "String");
  479. MethodTree mt = Common.createMethod(make, "method", params);
  480. VariableTree vt = Common.createField(make, "variable", EnumSet.of(Modifier.PROTECTED), "double");
  481. List<Tree> members = new ArrayList<Tree>();
  482. members.add(mt);
  483. members.add(vt);
  484. members.add(make.Block(Collections.EMPTY_LIST, false));
  485. ClassTree innerClass = make.Class(
  486. make.Modifiers(modifiers),
  487. name,
  488. Collections.EMPTY_LIST,
  489. extendsTree,
  490. implementsList,
  491. members);
  492. return innerClass;
  493. }
  494. public static void addTopLevelClass(JavaSource js) throws IOException {
  495. CancellableTask task = new CancellableTask<WorkingCopy>() {
  496. public void cancel() {
  497. throw new UnsupportedOperationException("Not supported yet.");
  498. }
  499. public void run(WorkingCopy workingCopy) throws Exception {
  500. workingCopy.toPhase(Phase.RESOLVED);
  501. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  502. TreeMaker make = workingCopy.getTreeMaker();
  503. ClassTree clazz = getClassTree(make, workingCopy, "TopLevel", "java.util.List", Collections.<ExpressionTree>emptyList(), EnumSet.noneOf(Modifier.class));
  504. CompilationUnitTree copy = make.addCompUnitTypeDecl(cut, clazz);
  505. workingCopy.rewrite(cut, copy);
  506. }
  507. };
  508. js.runModificationTask(task).commit();
  509. }
  510. public static void addClassComment(JavaSource js, final String text) throws IOException {
  511. CancellableTask task = new CancellableTask<WorkingCopy>() {
  512. public void cancel() {
  513. throw new UnsupportedOperationException("Not supported yet.");
  514. }
  515. public void run(WorkingCopy workingCopy) throws Exception {
  516. workingCopy.toPhase(Phase.RESOLVED);
  517. CompilationUnitTree cut = workingCopy.getCompilationUnit();
  518. TreeMaker make = workingCopy.getTreeMaker();
  519. ClassTree clazz = null;
  520. for (Tree typeDecl : cut.getTypeDecls()) {
  521. if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
  522. clazz = (ClassTree) typeDecl;
  523. }
  524. } // end for
  525. }
  526. };
  527. js.runModificationTask(task).commit();
  528. }
  529. }