List of usage examples for org.eclipse.jdt.internal.compiler.env NameEnvironmentAnswer NameEnvironmentAnswer
public NameEnvironmentAnswer(ReferenceBinding binding, ModuleBinding module)
From source file:br.com.objectos.code.StandardPackageName.java
License:Apache License
private NameEnvironmentAnswer answer(InputStream in, String filename) throws ClassFormatException, IOException { ClassFileReader reader = ClassFileReader.read(in, filename); return new NameEnvironmentAnswer(reader, null); }
From source file:com.codenvy.ide.ext.java.server.internal.core.builder.ClasspathDirectory.java
License:Open Source License
public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) { if (!doesFileExist(binaryFileName, qualifiedPackageName, qualifiedBinaryFileName)) return null; // most common case ClassFileReader reader = null;//from w w w. j a va 2s . c o m try { reader = Util.newClassFileReader(this.binaryFolder.getFile(new Path(qualifiedBinaryFileName))); } catch (CoreException e) { return null; } catch (ClassFormatException e) { return null; } catch (IOException e) { return null; } if (reader != null) { if (this.accessRuleSet == null) return new NameEnvironmentAnswer(reader, null); String fileNameWithoutExtension = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - SuffixConstants.SUFFIX_CLASS.length); return new NameEnvironmentAnswer(reader, this.accessRuleSet.getViolatedRestriction(fileNameWithoutExtension.toCharArray())); } return null; }
From source file:com.codenvy.ide.ext.java.server.internal.core.builder.ClasspathJar.java
License:Open Source License
public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) { if (!isPackage(qualifiedPackageName)) return null; // most common case try {/*from w w w . j a v a 2 s. c om*/ ClassFileReader reader = ClassFileReader.read(this.zipFile, qualifiedBinaryFileName); if (reader != null) { if (this.accessRuleSet == null) return new NameEnvironmentAnswer(reader, null); String fileNameWithoutExtension = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - SuffixConstants.SUFFIX_CLASS.length); return new NameEnvironmentAnswer(reader, this.accessRuleSet.getViolatedRestriction(fileNameWithoutExtension.toCharArray())); } } catch (IOException | ClassFormatException e) { // treat as if class file is missing } return null; }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.ClasspathSourceDirectory.java
License:Open Source License
public NameEnvironmentAnswer findClass(String sourceFileWithoutExtension, String qualifiedPackageName, String qualifiedSourceFileWithoutExtension) { SimpleLookupTable dirTable = directoryTable(qualifiedPackageName); if (dirTable != null && dirTable.elementSize > 0) { File file = (File) dirTable.get(sourceFileWithoutExtension); if (file != null) { return new NameEnvironmentAnswer(new ResourceCompilationUnit(file), null /* no access restriction */); }/*from w ww . ja va2 s . c o m*/ } return null; }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.JavaSearchNameEnvironment.java
License:Open Source License
private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) { String binaryFileName = null, qBinaryFileName = null, sourceFileName = null, qSourceFileName = null, qPackageName = null;/*from ww w . j a v a 2s. co m*/ NameEnvironmentAnswer suggestedAnswer = null; for (int i = 0, length = this.locations.length; i < length; i++) { ClasspathLocation location = this.locations[i]; NameEnvironmentAnswer answer; if (location instanceof ClasspathSourceDirectory) { if (sourceFileName == null) { qSourceFileName = qualifiedTypeName; // doesn't include the file extension sourceFileName = qSourceFileName; qPackageName = ""; //$NON-NLS-1$ if (qualifiedTypeName.length() > typeName.length) { int typeNameStart = qSourceFileName.length() - typeName.length; qPackageName = qSourceFileName.substring(0, typeNameStart - 1); sourceFileName = qSourceFileName.substring(typeNameStart); } } ICompilationUnit workingCopy = (ICompilationUnit) this.workingCopies.get(qualifiedTypeName); if (workingCopy != null) { answer = new NameEnvironmentAnswer(workingCopy, null /*no access restriction*/); } else { answer = location.findClass(sourceFileName, // doesn't include the file extension qPackageName, qSourceFileName); // doesn't include the file extension } } else { if (binaryFileName == null) { qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class; binaryFileName = qBinaryFileName; qPackageName = ""; //$NON-NLS-1$ if (qualifiedTypeName.length() > typeName.length) { int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class" qPackageName = qBinaryFileName.substring(0, typeNameStart - 1); binaryFileName = qBinaryFileName.substring(typeNameStart); } } answer = location.findClass(binaryFileName, qPackageName, qBinaryFileName); } if (answer != null) { if (!answer.ignoreIfBetter()) { if (answer.isBetter(suggestedAnswer)) return answer; } else if (answer.isBetter(suggestedAnswer)) // remember suggestion and keep looking suggestedAnswer = answer; } } if (suggestedAnswer != null) // no better answer was found return suggestedAnswer; return null; }
From source file:com.codenvy.ide.ext.java.server.internal.core.SearchableEnvironment.java
License:Open Source License
/** * Returns the given type in the the given package if it exists, * otherwise <code>null</code>. */// w w w . j ava2s . co m protected NameEnvironmentAnswer find(String typeName, String packageName) { if (packageName == null) packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; if (this.owner != null) { String source = this.owner.findSource(typeName, packageName); if (source != null) { ICompilationUnit cu = new BasicCompilationUnit(source.toCharArray(), CharOperation.splitOn('.', packageName.toCharArray()), typeName + Util.defaultJavaExtension()); return new NameEnvironmentAnswer(cu, null); } } NameLookup.Answer answer = this.nameLookup.findType(typeName, packageName, false/*exact match*/, NameLookup.ACCEPT_ALL, this.checkAccessRestrictions); if (answer != null) { // construct name env answer if (answer.type instanceof BinaryType) { // BinaryType try { return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) answer.type).getElementInfo(), answer.restriction); } catch (JavaModelException npe) { // fall back to using owner } } else { //SourceType try { // retrieve the requested type SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) answer.type) .getElementInfo(); ISourceType topLevelType = sourceType; while (topLevelType.getEnclosingType() != null) { topLevelType = topLevelType.getEnclosingType(); } // find all siblings (other types declared in same unit, since may be used for name resolution) IType[] types = sourceType.getHandle().getCompilationUnit().getTypes(); ISourceType[] sourceTypes = new ISourceType[types.length]; // in the resulting collection, ensure the requested type is the first one sourceTypes[0] = sourceType; int length = types.length; for (int i = 0, index = 1; i < length; i++) { ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo(); if (!otherType.equals(topLevelType) && index < length) // check that the index is in bounds (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62861) sourceTypes[index++] = otherType; } return new NameEnvironmentAnswer(sourceTypes, answer.restriction); } catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit) answer.type.getParent(), answer.restriction); } // no usable answer } } } return null; }
From source file:com.google.gwt.dev.javac.CompiledClass.java
License:Open Source License
NameEnvironmentAnswer getNameEnvironmentAnswer() {
if (nameEnvironmentAnswer == null) {
try {/* w ww .j a va2 s .c om*/
ClassFileReader cfr = new ClassFileReader(getBytes(), unit.getDisplayLocation().toCharArray(),
true);
nameEnvironmentAnswer = new NameEnvironmentAnswer(cfr, null);
} catch (ClassFormatException e) {
throw new RuntimeException("Unexpectedly unable to parse class file", e);
}
}
return nameEnvironmentAnswer;
}
From source file:com.mysema.codegen.ECJEvaluatorFactory.java
License:Apache License
protected void compile(String source, ClassType projectionType, String[] names, Type[] types, String id, Map<String, Object> constants) throws IOException { // create source source = createSource(source, projectionType, names, types, id, constants); // compile/*from w ww . ja v a2s . co m*/ final char[] targetContents = source.toCharArray(); final String targetName = id; final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() { @Override public char[] getContents() { return targetContents; } @Override public char[] getMainTypeName() { int dot = targetName.lastIndexOf('.'); if (dot > 0) return targetName.substring(dot + 1).toCharArray(); else return targetName.toCharArray(); } @Override public char[][] getPackageName() { StringTokenizer tok = new StringTokenizer(targetName, "."); char[][] result = new char[tok.countTokens() - 1][]; for (int j = 0; j < result.length; j++) { result[j] = tok.nextToken().toCharArray(); } return result; } @Override public char[] getFileName() { return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray()); } @Override public boolean ignoreOptionalProblems() { return true; } } }; INameEnvironment env = new INameEnvironment() { private String join(char[][] compoundName, char separator) { if (compoundName == null) { return ""; } else { List<String> parts = Lists.newArrayListWithCapacity(compoundName.length); for (char[] part : compoundName) { parts.add(new String(part)); } return Joiner.on(separator).join(parts); } } @Override public NameEnvironmentAnswer findType(char[][] compoundTypeName) { return findType(join(compoundTypeName, '.')); } @Override public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { return findType(CharOperation.arrayConcat(packageName, typeName)); } private boolean isClass(String result) { if (Strings.isNullOrEmpty(result)) { return false; } // if it's the class we're compiling, then of course it's a class if (result.equals(targetName)) { return true; } InputStream is = null; try { // if this is a class we've already compiled, it's a class is = loader.getResourceAsStream(result); if (is == null) { // use our normal class loader now... String resourceName = result.replace('.', '/') + ".class"; is = parentClassLoader.getResourceAsStream(resourceName); if (is == null && !result.contains(".")) { // we couldn't find the class, and it has no package; is it a core class? is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName); } } return is != null; } finally { if (is != null) { try { is.close(); } catch (IOException ex) { } } } } @Override public boolean isPackage(char[][] parentPackageName, char[] packageName) { // if the parent is a class, the child can't be a package String parent = join(parentPackageName, '.'); if (isClass(parent)) return false; // if the child is a class, it's not a package String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName); return !isClass(qualifiedName); } @Override public void cleanup() { } private NameEnvironmentAnswer findType(String className) { String resourceName = className.replace('.', '/') + ".class"; InputStream is = null; try { // we're only asking ECJ to compile a single class; we shouldn't need this if (className.equals(targetName)) { return new NameEnvironmentAnswer(targetCompilationUnits[0], null); } is = loader.getResourceAsStream(resourceName); if (is == null) { is = parentClassLoader.getResourceAsStream(resourceName); } if (is != null) { ClassFileReader cfr = new ClassFileReader(ByteStreams.toByteArray(is), className.toCharArray(), true); return new NameEnvironmentAnswer(cfr, null); } else { return null; } } catch (ClassFormatException ex) { throw new RuntimeException(ex); } catch (IOException e) { throw new RuntimeException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } }; ICompilerRequestor requestor = new ICompilerRequestor() { @Override public void acceptResult(CompilationResult result) { if (result.hasErrors()) { for (CategorizedProblem problem : result.getProblems()) { if (problem.isError()) { problemList.add(problem.getMessage()); } } } else { for (ClassFile clazz : result.getClassFiles()) { try { MemJavaFileObject jfo = (MemJavaFileObject) fileManager.getJavaFileForOutput( StandardLocation.CLASS_OUTPUT, new String(clazz.fileName()), JavaFileObject.Kind.CLASS, null); OutputStream os = jfo.openOutputStream(); os.write(clazz.getBytes()); } catch (IOException ex) { throw new RuntimeException(ex); } } } } }; problemList.clear(); IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems(); IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); try { //Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true); Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory); compiler.compile(targetCompilationUnits); if (!problemList.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String problem : problemList) { sb.append("\t").append(problem).append("\n"); } throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString()); } } catch (RuntimeException ex) { // if we encountered an IOException, unbox and throw it; // if we encountered a ClassFormatException, box it as an IOException and throw it // otherwise, it's a legit RuntimeException, // not one of our checked exceptions boxed as unchecked; just rethrow Throwable cause = ex.getCause(); if (cause != null) { if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof ClassFormatException) { throw new IOException(cause); } } throw ex; } }
From source file:com.opensymphony.webwork.util.classloader.compilers.eclipse.EclipseJavaCompiler.java
License:Apache License
public void compile(final String[] pClazzNames, final ResourceReader pReader, final ResourceStore pStore, final CompilationProblemHandler pProblemHandler) { final Map settingsMap = settings.getMap(); final Set clazzIndex = new HashSet(); ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length]; for (int i = 0; i < compilationUnits.length; i++) { final String clazzName = pClazzNames[i]; compilationUnits[i] = new CompilationUnit(pReader, clazzName); clazzIndex.add(clazzName);//w w w. j a v a 2 s. com log.debug("compiling " + clazzName); } final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final INameEnvironment nameEnvironment = new INameEnvironment() { public NameEnvironmentAnswer findType(final char[][] compoundTypeName) { final StringBuffer result = new StringBuffer(); for (int i = 0; i < compoundTypeName.length; i++) { if (i != 0) { result.append('.'); } result.append(compoundTypeName[i]); } return findType(result.toString()); } public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) { final StringBuffer result = new StringBuffer(); for (int i = 0; i < packageName.length; i++) { result.append(packageName[i]); result.append('.'); } result.append(typeName); return findType(result.toString()); } private NameEnvironmentAnswer findType(final String clazzName) { byte[] clazzBytes = pStore.read(clazzName); if (clazzBytes != null) { // log.debug("loading from store " + clazzName); final char[] fileName = clazzName.toCharArray(); try { final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final ClassFormatException e) { log.error("wrong class format", e); } } else { if (pReader.isAvailable(clazzName.replace('.', '/') + ".java")) { log.debug("compile " + clazzName); ICompilationUnit compilationUnit = new CompilationUnit(pReader, clazzName); return new NameEnvironmentAnswer(compilationUnit, null); } final String resourceName = clazzName.replace('.', '/') + ".class"; final InputStream is = this.getClass().getClassLoader().getResourceAsStream(resourceName); if (is != null) { final byte[] buffer = new byte[8192]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length); int count; try { while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); clazzBytes = baos.toByteArray(); final char[] fileName = clazzName.toCharArray(); ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final IOException e) { log.error("could not read class", e); } catch (final ClassFormatException e) { log.error("wrong class format", e); } finally { try { baos.close(); } catch (final IOException oe) { log.error("could not close output stream", oe); } try { is.close(); } catch (final IOException ie) { log.error("could not close input stream", ie); } } } } return null; } private boolean isPackage(final String clazzName) { final String resourceName = clazzName.replace('.', '/') + ".class"; final URL resource = this.getClass().getClassLoader().getResource(resourceName); return resource == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { final StringBuffer result = new StringBuffer(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i != 0) { result.append('.'); } result.append(parentPackageName[i]); } } if (Character.isUpperCase(packageName[0])) { return false; } if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(packageName); return isPackage(result.toString()); } public void cleanup() { } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { if (result.hasProblems()) { if (pProblemHandler != null) { final IProblem[] problems = result.getProblems(); for (int i = 0; i < problems.length; i++) { final IProblem problem = problems[i]; pProblemHandler.handle(new EclipseCompilationProblem(problem)); } } } if (!result.hasErrors()) { final ClassFile[] clazzFiles = result.getClassFiles(); for (int i = 0; i < clazzFiles.length; i++) { final ClassFile clazzFile = clazzFiles[i]; final char[][] compoundName = clazzFile.getCompoundName(); final StringBuffer clazzName = new StringBuffer(); for (int j = 0; j < compoundName.length; j++) { if (j != 0) { clazzName.append('.'); } clazzName.append(compoundName[j]); } pStore.write(clazzName.toString(), clazzFile.getBytes()); } } } }; pProblemHandler.onStart(); try { final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory); compiler.compile(compilationUnits); } finally { pProblemHandler.onStop(); } }
From source file:io.takari.maven.plugins.compile.jdt.classpath.ClasspathDirectory.java
License:Open Source License
@Override public NameEnvironmentAnswer findType(String packageName, String binaryFileName, AccessRestriction accessRestriction) { try {/*w w w . jav a 2 s. c om*/ String qualifiedFileName = packageName + "/" + binaryFileName; File classFile = new File(file, qualifiedFileName).getCanonicalFile(); if (classFile.isFile() && matchQualifiedName(classFile, qualifiedFileName)) { ClassFileReader reader = ClassFileReader.read(classFile, false); if (reader != null) { return new NameEnvironmentAnswer(reader, accessRestriction); } } } catch (ClassFormatException | IOException e) { // treat as if class file is missing } return null; }