Java Code Examples for org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader

The following examples show how to use org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: xtext-extras   Source File: InMemoryJavaCompiler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
  try {
    final Function1<char[], String> _function = (char[] it) -> {
      return String.valueOf(it);
    };
    String _join = IterableExtensions.join(ListExtensions.<char[], String>map(((List<char[]>)Conversions.doWrapArray(compoundTypeName)), _function), "/");
    final String fileName = (_join + ".class");
    boolean _containsKey = this.cache.containsKey(fileName);
    if (_containsKey) {
      return this.cache.get(fileName);
    }
    final URL url = this.classLoader.getResource(fileName);
    if ((url == null)) {
      this.cache.put(fileName, null);
      return null;
    }
    final ClassFileReader reader = ClassFileReader.read(url.openStream(), fileName);
    final NameEnvironmentAnswer result = new NameEnvironmentAnswer(reader, null);
    this.cache.put(fileName, result);
    return result;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 2
@Override
public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
  try {
    final Function1<char[], String> _function = (char[] it) -> {
      return String.valueOf(it);
    };
    String _join = IterableExtensions.join(ListExtensions.<char[], String>map(((List<char[]>)Conversions.doWrapArray(compoundTypeName)), _function), "/");
    final String fileName = (_join + ".class");
    boolean _containsKey = this.cache.containsKey(fileName);
    if (_containsKey) {
      return this.cache.get(fileName);
    }
    final URL url = this.classLoader.getResource(fileName);
    if ((url == null)) {
      this.cache.put(fileName, null);
      return null;
    }
    final ClassFileReader reader = ClassFileReader.read(url.openStream(), fileName);
    final NameEnvironmentAnswer result = new NameEnvironmentAnswer(reader, null);
    this.cache.put(fileName, result);
    return result;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 3
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException {
	JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
	ZipFile zip = null;
	try {
		zip = root.getJar();
		String entryName = Util.concatWith(pkg.names, getElementName(), '/');
		ZipEntry ze = zip.getEntry(entryName);
		if (ze != null) {
			byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
			String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName;
			return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize);
		}
	} finally {
		JavaModelManager.getJavaModelManager().closeZipFile(zip);
	}
	return null;
}
 
Example 4
Map<String, String> gleanNamedType(File classfile) throws IOException {
  // use jdt class reader to avoid extra runtime dependency, otherwise could use asm

  try {
    ClassFileReader type = ClassFileReader.read(classfile);
    IBinaryAnnotation[] annotations = type.getAnnotations();
    if (annotations != null) {
      for (IBinaryAnnotation annotation : annotations) {
        if ("Ljavax/inject/Named;".equals(new String(annotation.getTypeName()))) {
          return Collections.singletonMap(new String(type.getName()).replace('/', '.'), null);
        }
      }
    }
  } catch (ClassFormatException e) {
    // silently ignore classes we can't read/parse
  }

  return null;
}
 
Example 5
Source Project: jetbrick-template-1x   Source File: JdtCompiler.java    License: Apache License 2.0 6 votes vote down vote up
private NameEnvironmentAnswer findType(String className) {
    if (className.equals(source.getQualifiedClassName())) {
        return new NameEnvironmentAnswer(new CompilationUnit(source), null);
    }

    InputStream is = null;
    try {
        String resourceName = className.replace('.', '/') + ".class";
        is = classLoader.getResourceAsStream(resourceName);
        if (is != null) {
            byte[] bytes = IoUtils.toByteArray(is);
            char[] fileName = resourceName.toCharArray();
            ClassFileReader classFileReader = new ClassFileReader(bytes, fileName, true);
            return new NameEnvironmentAnswer(classFileReader, null);
        }
    } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
        log.error("Compilation error", e);
    } finally {
        IoUtils.closeQuietly(is);
    }
    return null;
}
 
Example 6
Source Project: xtext-extras   Source File: InMemoryJavaCompiler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
  try {
    final Function1<char[], String> _function = (char[] it) -> {
      return String.valueOf(it);
    };
    String _join = IterableExtensions.join(ListExtensions.<char[], String>map(((List<char[]>)Conversions.doWrapArray(packageName)), _function), "/");
    String _plus = (_join + "/");
    String _valueOf = String.valueOf(typeName);
    String _plus_1 = (_plus + _valueOf);
    final String fileName = (_plus_1 + ".class");
    boolean _containsKey = this.cache.containsKey(fileName);
    if (_containsKey) {
      return this.cache.get(fileName);
    }
    final URL url = this.classLoader.getResource(fileName);
    if ((url == null)) {
      this.cache.put(fileName, null);
      return null;
    }
    final ClassFileReader reader = ClassFileReader.read(url.openStream(), fileName);
    final NameEnvironmentAnswer result = new NameEnvironmentAnswer(reader, null);
    this.cache.put(fileName, result);
    return result;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 7
@Override
public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
  try {
    final Function1<char[], String> _function = (char[] it) -> {
      return String.valueOf(it);
    };
    String _join = IterableExtensions.join(ListExtensions.<char[], String>map(((List<char[]>)Conversions.doWrapArray(packageName)), _function), "/");
    String _plus = (_join + "/");
    String _valueOf = String.valueOf(typeName);
    String _plus_1 = (_plus + _valueOf);
    final String fileName = (_plus_1 + ".class");
    boolean _containsKey = this.cache.containsKey(fileName);
    if (_containsKey) {
      return this.cache.get(fileName);
    }
    final URL url = this.classLoader.getResource(fileName);
    if ((url == null)) {
      this.cache.put(fileName, null);
      return null;
    }
    final ClassFileReader reader = ClassFileReader.read(url.openStream(), fileName);
    final NameEnvironmentAnswer result = new NameEnvironmentAnswer(reader, null);
    this.cache.put(fileName, result);
    return result;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 8
IMethod createBinaryMethodHandle(IType type, char[] methodSelector, char[][] argumentTypeNames) {
	ClassFileReader reader = MatchLocator.classFileReader(type);
	if (reader != null) {
		IBinaryMethod[] methods = reader.getMethods();
		if (methods != null) {
			int argCount = argumentTypeNames == null ? 0 : argumentTypeNames.length;
			nextMethod : for (int i = 0, methodsLength = methods.length; i < methodsLength; i++) {
				IBinaryMethod binaryMethod = methods[i];
				char[] selector = binaryMethod.isConstructor() ? type.getElementName().toCharArray() : binaryMethod.getSelector();
				if (CharOperation.equals(selector, methodSelector)) {
					char[] signature = binaryMethod.getGenericSignature();
					if (signature == null) signature = binaryMethod.getMethodDescriptor();
					char[][] parameterTypes = Signature.getParameterTypes(signature);
					if (argCount != parameterTypes.length) continue nextMethod;
					if (argumentTypeNames != null) {
						for (int j = 0; j < argCount; j++) {
							char[] parameterTypeName = ClassFileMatchLocator.convertClassFileFormat(parameterTypes[j]);
							if (!CharOperation.endsWith(Signature.toCharArray(Signature.getTypeErasure(parameterTypeName)), CharOperation.replaceOnCopy(argumentTypeNames[j], '$', '.')))
								continue nextMethod;
							parameterTypes[j] = parameterTypeName;
						}
					}
					return (IMethod) createMethodHandle(type, new String(selector), CharOperation.toStrings(parameterTypes));
				}
			}
		}
	}
	return null;
}
 
Example 9
private String getSourceFileName() {
	if (this.sourceFileName != null) return this.sourceFileName;

	this.sourceFileName = NO_SOURCE_FILE_NAME;
	if (this.openable.getSourceMapper() != null) {
		BinaryType type = (BinaryType) ((ClassFile) this.openable).getType();
		ClassFileReader reader = MatchLocator.classFileReader(type);
		if (reader != null) {
			String fileName = type.sourceFileName(reader);
			this.sourceFileName = fileName == null ? NO_SOURCE_FILE_NAME : fileName;
		}
	}
	return this.sourceFileName;
}
 
Example 10
public ImportReference[] buildImports(ClassFileReader reader) {
	// add remaining references to the list of type names
	// (code extracted from BinaryIndexer#extractReferenceFromConstantPool(...))
	int[] constantPoolOffsets = reader.getConstantPoolOffsets();
	int constantPoolCount = constantPoolOffsets.length;
	for (int i = 0; i < constantPoolCount; i++) {
		int tag = reader.u1At(constantPoolOffsets[i]);
		char[] name = null;
		switch (tag) {
			case ClassFileConstants.MethodRefTag :
			case ClassFileConstants.InterfaceMethodRefTag :
				int constantPoolIndex = reader.u2At(constantPoolOffsets[i] + 3);
				int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 3)];
				name = reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
				break;
			case ClassFileConstants.ClassTag :
				utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[i] + 1)];
				name = reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
				break;
		}
		if (name == null || (name.length > 0 && name[0] == '['))
			break; // skip over array references
		this.typeNames.add(CharOperation.splitOn('/', name));
	}

	// convert type names into import references
	int typeNamesLength = this.typeNames.size();
	ImportReference[] imports = new ImportReference[typeNamesLength];
	char[][][] set = this.typeNames.set;
	int index = 0;
	for (int i = 0, length = set.length; i < length; i++) {
		char[][] typeName = set[i];
		if (typeName != null) {
			imports[index++] = new ImportReference(typeName, new long[typeName.length]/*dummy positions*/, false/*not on demand*/, 0);
		}
	}
	return imports;
}
 
Example 11
public static ClassFileReader newClassFileReader(IResource resource) throws CoreException, ClassFormatException, IOException {
	InputStream in = null;
	try {
		in = ((IFile) resource).getContents(true);
		return ClassFileReader.read(in, resource.getFullPath().toString());
	} finally {
		if (in != null)
			in.close();
	}
}
 
Example 12
public static int getExtraFlags(ClassFileReader reader) {
	int extraFlags = 0;
	
	if (reader.isNestedType()) {
		extraFlags |= ExtraFlags.IsMemberType;
	}
	
	if (reader.isLocal()) {
		extraFlags |= ExtraFlags.IsLocalType;
	}
	
	IBinaryNestedType[] memberTypes = reader.getMemberTypes();
	int memberTypeCounter = memberTypes == null ? 0 : memberTypes.length;
	if (memberTypeCounter > 0) {
		done : for (int i = 0; i < memberTypeCounter; i++) {
			int modifiers = memberTypes[i].getModifiers();
			// if the member type is static and not private
			if ((modifiers & ClassFileConstants.AccStatic) != 0 && (modifiers & ClassFileConstants.AccPrivate) == 0) {
				extraFlags |= ExtraFlags.HasNonPrivateStaticMemberTypes;
				break done;
			}
		}
		
	}
	
	return extraFlags;
}
 
Example 13
Source Project: actframework   Source File: AppCompiler.java    License: Apache License 2.0 5 votes vote down vote up
private NameEnvironmentAnswer findType(String type) {
    try {
        byte[] bytes;
        Source source;
        if (Act.isDev()) {
            source = classLoader.source(type);
            if (null != source) {
                return new NameEnvironmentAnswer(source.compilationUnit(), null);
            }
        }
        bytes = classLoader.enhancedBytecode(type);
        if (bytes != null) {
            ClassFileReader classFileReader = new ClassFileReader(bytes, type.toCharArray(), true);
            return new NameEnvironmentAnswer(classFileReader, null);
        } else {
            if (type.startsWith("org.osgl") || type.startsWith("java.") || type.startsWith("javax.")) {
                return null;
            }
        }
        if (Act.isDev()) {
            return null;
        }
        source = classLoader.source(type);
        if (null == source) {
            return null;
        } else {
            return new NameEnvironmentAnswer(source.compilationUnit(), null);
        }
    } catch (ClassFormatException e) {
        throw E.unexpected(e);
    }
}
 
Example 14
Source Project: takari-lifecycle   Source File: CompilerJdt.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private byte[] digestClassFile(File outputFile, byte[] definition) {
  try {
    ClassFileReader reader = new ClassFileReader(definition, outputFile.getAbsolutePath().toCharArray());
    return digester.digest(reader);
  } catch (ClassFormatException e) {
    // ignore this class
  }
  return null;
}
 
Example 15
Source Project: takari-lifecycle   Source File: ClasspathJar.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public NameEnvironmentAnswer findType(String packageName, String typeName, AccessRestriction accessRestriction) {
  try {
    String qualifiedFileName = packageName + "/" + typeName + SUFFIX_STRING_class;
    ClassFileReader reader = ClassFileReader.read(this.zipFile, qualifiedFileName);
    if (reader != null) {
      return new NameEnvironmentAnswer(reader, accessRestriction);
    }
  } catch (ClassFormatException | IOException e) {
    // treat as if class file is missing
  }
  return null;
}
 
Example 16
@Override
public NameEnvironmentAnswer findType(String packageName, String typeName, AccessRestriction accessRestriction) {
  try {
    Path classFile = getFile(packageName, typeName);
    if (classFile != null) {
      try (InputStream is = Files.newInputStream(classFile)) {
        return new NameEnvironmentAnswer(ClassFileReader.read(is, classFile.getFileName().toString(), false), accessRestriction);
      }
    }
  } catch (ClassFormatException | IOException e) {
    // treat as if type is missing
  }
  return null;
}
 
Example 17
private char[] extractClassName(int[] constantPoolOffsets, ClassFileReader reader, int index) {
	// the entry at i has to be a field ref or a method/interface method ref.
	int class_index = reader.u2At(constantPoolOffsets[index] + 1);
	int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[class_index] + 1)];
	return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
}
 
Example 18
private char[] extractName(int[] constantPoolOffsets, ClassFileReader reader, int index) {
	int nameAndTypeIndex = reader.u2At(constantPoolOffsets[index] + 3);
	int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[nameAndTypeIndex] + 1)];
	return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
}
 
Example 19
private char[] extractClassReference(int[] constantPoolOffsets, ClassFileReader reader, int index) {
	// the entry at i has to be a class ref.
	int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[index] + 1)];
	return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
}
 
Example 20
/**
 * Extract all type, method, field and interface method references from the constant pool
 */
private void extractReferenceFromConstantPool(byte[] contents, ClassFileReader reader) throws ClassFormatException {
	int[] constantPoolOffsets = reader.getConstantPoolOffsets();
	int constantPoolCount = constantPoolOffsets.length;
	for (int i = 1; i < constantPoolCount; i++) {
		int tag = reader.u1At(constantPoolOffsets[i]);
		/**
		 * u1 tag
		 * u2 class_index
		 * u2 name_and_type_index
		 */
		char[] name = null;
		char[] type = null;
		switch (tag) {
			case ClassFileConstants.FieldRefTag :
				// add reference to the class/interface and field name and type
				name = extractName(constantPoolOffsets, reader, i);
				addFieldReference(name);
				break;
			case ClassFileConstants.MethodRefTag :
				// add reference to the class and method name and type
			case ClassFileConstants.InterfaceMethodRefTag :
				// add reference to the interface and method name and type
				name = extractName(constantPoolOffsets, reader, i);
				type = extractType(constantPoolOffsets, reader, i);
				if (CharOperation.equals(INIT, name)) {
					// get class name and see if it's a local type or not
					char[] className = extractClassName(constantPoolOffsets, reader, i);
					boolean localType = false;
					if (className !=  null) {
						for (int c = 0, max = className.length; c < max; c++) {
							switch (className[c]) {
								case '/':
									className[c] = '.';
									break;
								case '$':
									localType = true;
									break;
							}
						}
					}
					// add a constructor reference, use class name to extract arg count if it's a local type to remove synthetic parameter
					addConstructorReference(className, extractArgCount(type, localType?className:null));
				} else {
					// add a method reference
					addMethodReference(name, extractArgCount(type, null));
				}
				break;
			case ClassFileConstants.ClassTag :
				// add a type reference
				name = extractClassReference(constantPoolOffsets, reader, i);
				if (name.length > 0 && name[0] == '[')
					break; // skip over array references
				name = replace('/', '.', name); // so that it looks like java.lang.String
				addTypeReference(name);

				// also add a simple reference on each segment of the qualification (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24741)
				char[][] qualification = CharOperation.splitOn('.', name);
				for (int j = 0, length = qualification.length; j < length; j++) {
					addNameReference(qualification[j]);
				}
				break;
		}
	}
}
 
Example 21
private char[] extractType(int[] constantPoolOffsets, ClassFileReader reader, int index) {
	int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 3);
	int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 3)];
	return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
}