org.eclipse.jem.workbench_2.0.400.v201104251400

16:45:21.216 INFO  jd.cli.Main - Decompiling org.eclipse.jem.workbench_2.0.400.v201104251400.jar
package org.eclipse.jem.internal.adapters.jdom;

import java.io.File;
import java.io.PrintStream;
import java.util.Map;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jem.internal.java.adapters.JavaReflectionAdaptor;
import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;
import org.eclipse.jem.java.Field;
import org.eclipse.jem.java.JavaClass;
import org.eclipse.jem.java.JavaRefFactory;
import org.eclipse.jem.java.JavaRefPackage;
import org.eclipse.jem.java.Method;
import org.eclipse.jem.java.internal.impl.JavaRefFactoryImpl;

public abstract class JDOMAdaptor
  extends JavaReflectionAdaptor
{
  protected static final JavaRefPackage JAVA_PACK = ;
  protected IJavaProject sourceProject;
  public static final int INVALID_LINENO = -1;
  protected final Integer fLINENOLock = new Integer(-1);
  private int fResolvedLineNo = -1;
  private int fResolvedColNo = -1;
  
  public JDOMAdaptor(Notifier target, IJavaProject workingProject)
  {
    super(target);
    setSourceProject(workingProject);
  }
  
  protected void clearSource() {}
  
  protected boolean isResourceLoaded()
  {
    Resource res = ((EObject)getTarget()).eResource();
    return (res != null) && (res.isLoaded());
  }
  
  private void computeLineOffset(int charOffset, IBuffer buffer)
  {
    fResolvedColNo = (fResolvedLineNo = -1);
    if (buffer == null) {
      return;
    }
    char[] charBuff = buffer.getCharacters();
    if (charBuff == null) {
      return;
    }
    int LineCount = 0;
    int ColNo = 0;
    for (int i = 0; i <= charOffset; i++)
    {
      ColNo++;
      if (charBuff[i] == '\r')
      {
        LineCount++;
        ColNo = 0;
        if (charBuff[(i + 1)] == '\n') {
          i++;
        }
      }
      else if (charBuff[i] == '\n')
      {
        LineCount++;
        ColNo = 0;
      }
    }
    fResolvedColNo = ColNo;
    fResolvedLineNo = LineCount;
  }
  
  public static String computeMethodID(IMethod jdomMethod)
  {
    return computeMethodID(jdomMethod, jdomMethod.getDeclaringType(), null);
  }
  
  public static String computeMethodID(IMethod jdomMethod, IType type, Map typeCache)
  {
    StringBuffer out = new StringBuffer();
    out.append(type.getTypeQualifiedName());
    out.append('.');
    out.append(jdomMethod.getElementName());
    out.append('(');
    String[] parmTypeNames = jdomMethod.getParameterTypes();
    for (int i = 0; i < parmTypeNames.length; i++)
    {
      String parmName = convertJDOMtypeName(parmTypeNames[i]);
      parmName = JDOMSearchHelper.getResolvedTypeName(parmName, type, typeCache);
      out.append(parmName);
      if (i < parmTypeNames.length - 1) {
        out.append(',');
      }
    }
    try
    {
      if (jdomMethod.isConstructor()) {
        out.append("_V");
      }
    }
    catch (JavaModelException localJavaModelException) {}
    return out.toString();
  }
  
  public static String computeMethodName(IMethod jdomMethod)
  {
    return jdomMethod.getElementName();
  }
  
  public void contentChanged()
  {
    synchronized (fLINENOLock)
    {
      fResolvedLineNo = -1;
      fResolvedColNo = -1;
    }
  }
  
  public static String convertJDOMtypeName(String jdomTypeName)
  {
    return signatureToString(jdomTypeName);
  }
  
  public Field createJavaField(IField jdomField, XMIResource resource)
  {
    String name = jdomField.getElementName();
    Field newField = getJavaFactory().createField();
    newField.setName(name);
    resource.setID(newField, ((JavaClass)getTarget()).getName() + '.' + name);
    return newField;
  }
  
  public Method createJavaMethod(IMethod jdomMethod, XMIResource resource)
  {
    Method newMethod = getJavaFactory().createMethod();
    
    newMethod.setName(computeMethodName(jdomMethod));
    resource.setID(newMethod, computeMethodID(jdomMethod, getType(), getTypeResolutionCache()));
    return newMethod;
  }
  
  protected IPath getBinaryPathFromQualifiedName(String qualifiedName)
  {
    return new Path(qualifiedName.replace('.', File.separatorChar) + ".class");
  }
  
  public IType getBinaryType(String qualifiedName)
  {
    try
    {
      if (getSourceProject() != null)
      {
        IJavaElement found = getSourceProject().findElement(getBinaryPathFromQualifiedName(qualifiedName));
        if (found != null) {
          return ((IClassFile)found).getType();
        }
      }
    }
    catch (JavaModelException jme)
    {
      System.out.println(ResourceHandler.getString("Error_Looking_Up_Type_ERROR_", new Object[] { qualifiedName, jme.getMessage() }));
    }
    return null;
  }
  
  public int getColNo()
  {
    synchronized (fLINENOLock)
    {
      if (fResolvedColNo == -1) {
        resolveLineColNo();
      }
    }
    return fResolvedColNo;
  }
  
  public int getLineNo()
  {
    synchronized (fLINENOLock)
    {
      if (fResolvedLineNo == -1) {
        resolveLineColNo();
      }
    }
    return fResolvedLineNo;
  }
  
  public abstract Object getReflectionSource();
  
  public static String getResolvedTypeName(String typeName, IType declaringType)
  {
    String name = typeName;
    try
    {
      name = JDOMSearchHelper.resolveSimpleTypeName(declaringType, typeName);
    }
    catch (JavaModelException localJavaModelException) {}
    return name;
  }
  
  protected IJavaProject getSourceProject()
  {
    return sourceProject;
  }
  
  protected abstract IType getType();
  
  protected abstract Map getTypeResolutionCache();
  
  public void releaseSourceType()
  {
    flushReflectedValuesIfNecessary(true);
  }
  
  public Notification releaseSourceTypeNoNotification()
  {
    return flushReflectedValuesIfNecessaryNoNotification(true);
  }
  
  private void resolveLineColNo()
  {
    IMember rs = (IMember)getReflectionSource();
    if (rs != null)
    {
      int offset = -1;
      try
      {
        ISourceRange sr = rs.getNameRange();
        if (sr.getLength() <= 0) {
          return;
        }
        offset = sr.getOffset();
      }
      catch (JavaModelException localJavaModelException1)
      {
        return;
      }
      ICompilationUnit cu = rs.getCompilationUnit();
      if (cu != null) {
        try
        {
          IBuffer buffer = cu.getBuffer();
          computeLineOffset(offset, buffer);
        }
        catch (JavaModelException localJavaModelException2) {}
      }
    }
  }
  
  protected void setSourceProject(IJavaProject workingProject)
  {
    sourceProject = workingProject;
  }
  
  public static String signatureToString(String signature)
    throws IllegalArgumentException
  {
    boolean hasDollar = signature.indexOf('$') != -1;
    
    String result = Signature.getTypeErasure(signature);
    result = Signature.toString(result);
    if (hasDollar)
    {
      int newPos = result.lastIndexOf(".");
      if (newPos != -1) {
        result = result.substring(0, newPos) + "$" + result.substring(newPos + 1);
      }
    }
    return result;
  }
  
  protected String typeNameFromSignature(String sig)
  {
    return typeNameFromSignature(sig, getType());
  }
  
  protected String typeNameFromSignature(String sig, IType parent)
  {
    return typeNameFromSignature(sig, parent, getTypeResolutionCache());
  }
  
  public static String typeNameFromSignature(String sig, IType parent, Map typeCache)
  {
    String componentSignature = Signature.getElementType(sig);
    int arrayDimensions = Signature.getArrayCount(sig);
    String result = JDOMSearchHelper.getResolvedTypeName(signatureToString(componentSignature), parent, typeCache);
    for (int i = 0; i < arrayDimensions; i++) {
      result = result + "[]";
    }
    return result;
  }
  
  /**
   * @deprecated
   */
  public IType getType(String qualifiedName)
  {
    return JDOMSearchHelper.findType(qualifiedName, false, getSourceProject(), this);
  }
}

/* Location:
 * Qualified Name:     org.eclipse.jem.internal.adapters.jdom.JDOMAdaptor
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.eclipse.jem.internal.adapters.jdom;

import java.io.File;
import java.io.PrintStream;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;

public class JDOMClassFinder
{
  private static JDOMClassFinder instance;
  
  protected IPath getBinaryPathFromQualifiedName(String qualifiedName)
  {
    return new Path(qualifiedName.replace('.', File.separatorChar) + ".class");
  }
  
  public IType getBinaryType(String qualifiedName)
  {
    IJavaElement found = getJavaElement(qualifiedName);
    if (found != null) {
      return ((IClassFile)found).getType();
    }
    return null;
  }
  
  public IJavaElement getJavaElement(String qualifiedName)
  {
    try
    {
      if (getSourceProject() != null) {
        return getSourceProject().findElement(getPathFromQualifiedName(qualifiedName));
      }
    }
    catch (JavaModelException jme)
    {
      System.out.println(ResourceHandler.getString("Error_Looking_Up_Type_ERROR_", new Object[] { qualifiedName, jme.getMessage() }));
    }
    return null;
  }
  
  protected IPath getPathFromQualifiedName(String qualifiedName)
  {
    return new Path(qualifiedName.replace('.', File.separatorChar) + ".java");
  }
  
  protected IJavaProject getSourceProject()
  {
    return null;
  }
  
  public IType getType(String qualifiedName)
  {
    IJavaElement found = getJavaElement(qualifiedName);
    if (found != null)
    {
      if ((found instanceof IClassFile)) {
        return ((IClassFile)found).getType();
      }
      if ((found instanceof ICompilationUnit))
      {
        ICompilationUnit foundCU = (ICompilationUnit)found;
        
        String cuMainTypeName = foundCU.getElementName();
        cuMainTypeName = cuMainTypeName.substring(0, cuMainTypeName.length() - 5);
        return foundCU.getType(cuMainTypeName);
      }
    }
    return null;
  }
  
  public static JDOMClassFinder instance()
  {
    if (instance == null) {
      instance = new JDOMClassFinder();
    }
    return instance;
  }
}

/* Location:
 * Qualified Name:     org.eclipse.jem.internal.adapters.jdom.JDOMClassFinder
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.eclipse.jem.internal.adapters.jdom;

import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;

public class JDOMSearchHelper
{
  private static final String RESOLVED_NAME = " :: RESOLVED_NAME :: ";
  private static final String PERIOD = ".";
  private static final String BOOLEAN = "boolean";
  private static final String BYTE = "byte";
  private static final String CHAR = "char";
  private static final String SHORT = "short";
  private static final String INT = "int";
  private static final String LONG = "long";
  private static final String FLOAT = "float";
  private static final String DOUBLE = "double";
  private static final String VOID = "void";
  
  private static String[][] getTypeNameInfo(IType type, String simpleName, boolean isForReflection)
    throws JavaModelException
  {
    String[][] result = (String[][])null;
    
    String typeName = simpleName;
    if (type != null)
    {
      if (isForReflection) {
        typeName = typeName.replace('.', '$');
      }
      int index = typeName.indexOf("$");
      if (index > 0)
      {
        String declaringName = typeName.substring(0, index);
        result = type.resolveType(declaringName);
        if (result != null)
        {
          if (isForReflection) {
            result[0][1] = result[0][1].replace('.', '$');
          }
          int tmp89_88 = 1; String[] tmp89_87 = result[0];tmp89_87[tmp89_88] = (tmp89_87[tmp89_88] + typeName.substring(index, typeName.length()));
        }
      }
      else
      {
        index = typeName.indexOf("[");
        if (index > 0)
        {
          String declaringName = typeName.substring(0, index);
          result = type.resolveType(declaringName);
          if (result != null) {
            result[0][1] = (result[0][1] + typeName.substring(index));
          }
        }
        else
        {
          result = type.resolveType(typeName);
        }
      }
    }
    return result;
  }
  
  public static final boolean isPrimitive(String type)
  {
    return ("boolean".equals(type)) || ("int".equals(type)) || ("char".equals(type)) || ("short".equals(type)) || ("long".equals(type)) || ("float".equals(type)) || ("double".equals(type)) || ("byte".equals(type));
  }
  
  public static final boolean isPrimitiveOrVoid(String type)
  {
    return (isPrimitive(type)) || (isVoid(type));
  }
  
  public static final boolean isVoid(String type)
  {
    return "void".equals(type);
  }
  
  public static boolean matchTypeSignatures(IType type, String signature1, String signature2)
    throws JavaModelException
  {
    return matchTypeSignatures(type, signature1, signature2, null);
  }
  
  public static boolean matchTypeSignatures(IType type, String signature1, String signature2, Map resolvedNameCache)
    throws JavaModelException
  {
    boolean result = false;
    String sig1 = signature1;
    String sig2 = signature2;
    if (Signature.getArrayCount(sig1) == Signature.getArrayCount(sig2))
    {
      sig1 = Signature.getElementType(sig1);
      sig2 = Signature.getElementType(sig2);
      if (((sig1.indexOf('.') == -1 ? 1 : 0) ^ (sig2.indexOf('.') == -1 ? 1 : 0)) == 0)
      {
        result = Signature.toString(sig1).equals(Signature.toString(sig2));
      }
      else if (((sig1.charAt(0) == 'Q') || (sig1.charAt(0) == 'L')) && ((sig2.charAt(0) == 'Q') || (sig2.charAt(0) == 'L')))
      {
        String qualifiedName = null;
        String simpleName = null;
        if (sig1.indexOf('.') == -1)
        {
          qualifiedName = Signature.toString(sig2);
          simpleName = Signature.toString(sig1);
        }
        else
        {
          qualifiedName = Signature.toString(sig1);
          simpleName = Signature.toString(sig2);
        }
        result = qualifiedName.equals(resolveSimpleTypeName(type, simpleName, resolvedNameCache));
      }
    }
    return result;
  }
  
  private static boolean needsToResolveName(IType type, String simpleName, boolean isForReflection)
  {
    boolean retVal = false;
    if (type != null) {
      retVal = (!type.isBinary()) && ((isForReflection) || (simpleName.indexOf(".") <= -1)) && (!isPrimitiveOrVoid(simpleName));
    }
    return retVal;
  }
  
  public static String resolveSimpleTypeName(IType type, String simpleName)
    throws JavaModelException
  {
    return resolveSimpleTypeName(type, simpleName, null);
  }
  
  public static String resolveSimpleTypeName(IType type, String simpleName, Map resolvedNameCache)
    throws JavaModelException
  {
    return resolveSimpleTypeName(type, simpleName, resolvedNameCache, false);
  }
  
  public static String resolveSimpleTypeName(IType type, String simpleName, Map resolvedNameCache, boolean isForReflection)
    throws JavaModelException
  {
    if (!needsToResolveName(type, simpleName, isForReflection)) {
      return simpleName;
    }
    String key = null;String qualifiedName = null;
    if (resolvedNameCache != null)
    {
      key = type.getFullyQualifiedName() + " :: RESOLVED_NAME :: " + simpleName;
      qualifiedName = (String)resolvedNameCache.get(key);
    }
    if (qualifiedName == null)
    {
      String[][] result = getTypeNameInfo(type, simpleName, isForReflection);
      if (result != null)
      {
        String packName = result[0][0];
        if (packName.length() == 0)
        {
          qualifiedName = result[0][1];
          if (isForReflection) {
            qualifiedName = qualifiedName.replace('.', '$');
          }
        }
        else
        {
          StringBuffer b = new StringBuffer();
          b.append(result[0][0]).append(".");
          String typeName = result[0][1];
          if (isForReflection) {
            typeName = typeName.replace('.', '$');
          }
          b.append(typeName);
          qualifiedName = b.toString();
        }
      }
      else
      {
        qualifiedName = simpleName;
      }
      if (resolvedNameCache != null) {
        resolvedNameCache.put(key, qualifiedName);
      }
    }
    return qualifiedName;
  }
  
  public static IMethod searchForMatchingMethod(IType type, String methodName, String[] parmSigs)
    throws JavaModelException
  {
    return searchForMatchingMethod(type, methodName, parmSigs, null);
  }
  
  public static IMethod searchForMatchingMethod(IType type, String methodName, String[] parmSigs, Map resolvedNameCache)
    throws JavaModelException
  {
    IMethod[] allMethods = type.getMethods();
    List candidateMethods = new ArrayList();
    for (int i = 0; i < allMethods.length; i++)
    {
      int parmSigsLength = parmSigs != null ? parmSigs.length : 0;
      if ((allMethods[i].getElementName().equals(methodName)) && (allMethods[i].getNumberOfParameters() == parmSigsLength)) {
        candidateMethods.add(allMethods[i]);
      }
    }
    IMethod next = null;
    String[] nextParmSigs = (String[])null;
    boolean found = false;
    Iterator candidateIter = candidateMethods.iterator();
    int i;
    for (; (!found) && (candidateIter.hasNext()); (found) && (i < nextParmSigs.length))
    {
      next = (IMethod)candidateIter.next();
      nextParmSigs = next.getParameterTypes();
      found = true;
      i = 0; continue;
      found &= matchTypeSignatures(type, parmSigs[i], nextParmSigs[i], resolvedNameCache);i++;
    }
    return found ? next : null;
  }
  
  protected static Object[] findActualJavaElement(String qualifiedName, IJavaProject javaProject, JDOMAdaptor adaptor)
  {
    Object[] result = new Object[2];
    if (adaptor == null) {
      result[1] = qualifiedName;
    } else {
      result[1] = getResolvedTypeName(qualifiedName, adaptor.getType(), adaptor.getTypeResolutionCache());
    }
    result[0] = findJavaElement((String)result[1], javaProject, adaptor);
    if (result[0] == null) {
      findInnerJavaElement(result, javaProject, adaptor);
    }
    return result;
  }
  
  protected static void findInnerJavaElement(Object[] info, IJavaProject javaProject, JDOMAdaptor adaptor)
  {
    String qualifiedName = (String)info[1];
    int index = qualifiedName.lastIndexOf(".");
    if (index > 0)
    {
      String innerName = qualifiedName.substring(0, index);
      String pkgName = innerName;
      innerName = innerName + "$";
      innerName = innerName + qualifiedName.substring(index + 1, qualifiedName.length());
      if (adaptor != null)
      {
        innerName = getResolvedTypeName(innerName, adaptor.getType(), adaptor.getTypeResolutionCache());
        if (qualifiedName.equals(innerName)) {
          return;
        }
      }
      info[1] = innerName;
      info[0] = findJavaElement(innerName, javaProject, adaptor);
      if ((javaProject.getProject().isAccessible()) && (info[0] == null))
      {
        index = innerName.lastIndexOf(".");
        if ((index > 0) && (innerName.substring(0, index).equals(pkgName))) {
          return;
        }
        findInnerJavaElement(info, javaProject, adaptor);
      }
    }
  }
  
  protected static IJavaElement findJavaElement(String qualifiedName, IJavaProject javaProject, JDOMAdaptor adaptor)
  {
    try
    {
      if (javaProject != null) {
        return javaProject.findType(qualifiedName);
      }
    }
    catch (JavaModelException jme)
    {
      System.out.println(ResourceHandler.getString("Error_Looking_Up_Type_ERROR_", new Object[] { qualifiedName, jme.getMessage() }));
    }
    return null;
  }
  
  protected static IPath getPathFromQualifiedName(String qualifiedName)
  {
    return new Path(qualifiedName.replace('.', File.separatorChar) + ".java");
  }
  
  public static String getResolvedTypeName(String typeName, IType declaringType, Map typeCache)
  {
    String name = typeName;
    try
    {
      name = resolveSimpleTypeName(declaringType, typeName, typeCache, true);
    }
    catch (JavaModelException localJavaModelException) {}
    return name;
  }
  
  public static IType findType(String qualifiedName, boolean useAdvancedForInners, IJavaProject javaProject, JDOMAdaptor adaptor)
  {
    IJavaElement found = null;
    String resolvedName = qualifiedName;
    if (useAdvancedForInners)
    {
      Object[] result = findActualJavaElement(qualifiedName, javaProject, adaptor);
      found = (IJavaElement)result[0];
      resolvedName = (String)result[1];
    }
    else
    {
      found = findJavaElement(qualifiedName, javaProject, adaptor);
    }
    if (found != null)
    {
      if ((found instanceof IClassFile)) {
        return ((IClassFile)found).getType();
      }
      if ((found instanceof ICompilationUnit))
      {
        ICompilationUnit foundCU = (ICompilationUnit)found;
        
        String cuMainTypeName = foundCU.getElementName();
        cuMainTypeName = cuMainTypeName.substring(0, cuMainTypeName.length() - 5);
        return foundCU.getType(cuMainTypeName);
      }
      if ((found instanceof IType))
      {
        IType type = (IType)found;
        if (!type.getFullyQualifiedName('$').equals(resolvedName))
        {
          int index = resolvedName.lastIndexOf('$');
          if (index > -1) {
            return type.getType(resolvedName.substring(index + 1, resolvedName.length()));
          }
          return type;
        }
        return type;
      }
    }
    return null;
  }
  
  public static IType findType(String packageName, String qualifiedTypeName, IJavaProject javaProject)
  {
    try
    {
      if (javaProject != null) {
        return javaProject.findType(packageName, qualifiedTypeName.replace('$', '.'));
      }
    }
    catch (JavaModelException jme)
    {
      System.out.println(ResourceHandler.getString("Error_Looking_Up_Type_ERROR_", new Object[] { packageName + "." + qualifiedTypeName, jme.getMessage() }));
    }
    return null;
  }
}

/* Location:
 * Qualified Name:     org.eclipse.jem.internal.adapters.jdom.JDOMSearchHelper
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.eclipse.jem.internal.adapters.jdom;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.core.resources.IResource;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jem.internal.java.adapters.IJavaClassAdaptor;
import org.eclipse.jem.internal.java.adapters.JavaReflectionAdapterFactory;
import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;
import org.eclipse.jem.internal.plugin.JavaPlugin;
import org.eclipse.jem.java.Field;
import org.eclipse.jem.java.InheritanceCycleException;
import org.eclipse.jem.java.JavaClass;
import org.eclipse.jem.java.JavaPackage;
import org.eclipse.jem.java.JavaRefFactory;
import org.eclipse.jem.java.Method;
import org.eclipse.jem.java.TypeKind;
import org.eclipse.jem.java.internal.impl.JavaClassImpl;
import org.eclipse.jem.util.TimerTests;
import org.eclipse.jem.util.UIContextDetermination;
import org.eclipse.jem.util.logger.proxy.Logger;

public class JavaClassJDOMAdaptor
  extends JDOMAdaptor
  implements IJavaClassAdaptor
{
  private static final String OBJECT_TYPE_NAME = "java.lang.Object";
  public static final String REFLECT_CLASS = "Reflect JDOM Class";
  public static final String REFLECT_METHODS = "Reflect all JDOM methods for a class";
  public static final String REFLECT_FIELDS = "Reflect all JDOM fields for a class";
  protected IType sourceType = null;
  protected JavaReflectionAdapterFactory adapterFactory;
  private Map typeResolutionCache = new HashMap(25);
  private boolean hasReflectedFields;
  private boolean isReflectingFields;
  private boolean hasReflectedMethods;
  private boolean isReflectingMethods;
  
  public JavaClassJDOMAdaptor(Notifier target, IJavaProject workingProject, JavaReflectionAdapterFactory inFactory)
  {
    super(target, workingProject);
    setAdapterFactory(inFactory);
  }
  
  private Map existingFields = new HashMap();
  
  protected boolean addFields()
  {
    IField[] fields = (IField[])null;
    try
    {
      fields = getSourceType().getFields();
    }
    catch (JavaModelException e)
    {
      Logger.getLogger().log(e, Level.WARNING);
      return false;
    }
    XMIResource resource = (XMIResource)getJavaClassTarget().eResource();
    Field field = null;
    JavaFieldJDOMAdaptor adapter = null;
    Map newExisting = new HashMap(fields.length);
    List newFields = new ArrayList();
    for (int i = 0; i < fields.length; i++)
    {
      IField ifield = fields[i];
      field = (Field)existingFields.remove(ifield);
      if (field != null)
      {
        newExisting.put(ifield, field);
        
        adapter = (JavaFieldJDOMAdaptor)EcoreUtil.getExistingAdapter(field, "JavaReflection");
        if (adapter == null) {
          adapter = (JavaFieldJDOMAdaptor)getAdapterFactory().adaptNew(field, "JavaReflection");
        } else {
          adapter.flushReflectedValuesIfNecessaryNoNotification(true);
        }
        adapter.setSourceField(ifield);
      }
      else
      {
        field = createJavaField(ifield, resource);
        newExisting.put(ifield, field);
        newFields.add(field);
        adapter = (JavaFieldJDOMAdaptor)getAdapterFactory().adaptNew(field, "JavaReflection");
        if (adapter != null) {
          adapter.setSourceField(ifield);
        }
      }
    }
    BasicEList fieldsList = (BasicEList)getJavaClassTarget().getFieldsGen();
    if (!existingFields.isEmpty())
    {
      URI baseURI = resource.getURI();
      Collection toDelete = existingFields.values();
      for (Iterator itr = toDelete.iterator(); itr.hasNext();)
      {
        InternalEObject m = (InternalEObject)itr.next();
        String id = resource.getID(m);
        if (id != null) {
          m.eSetProxyURI(baseURI.appendFragment(id));
        }
      }
      fieldsList.removeAll(toDelete);
    }
    if (!newFields.isEmpty()) {
      fieldsList.addAllUnique(newFields);
    }
    existingFields = newExisting;
    return true;
  }
  
  private Map existingMethods = new HashMap();
  protected boolean flushAndClearCachedModelObject;
  
  protected boolean addMethods()
  {
    IMethod[] methods = (IMethod[])null;
    try
    {
      methods = getSourceType().getMethods();
    }
    catch (JavaModelException e)
    {
      Logger.getLogger().log(e, Level.WARNING);
      return false;
    }
    XMIResource resource = (XMIResource)getJavaClassTarget().eResource();
    Method method = null;
    JavaMethodJDOMAdaptor adapter = null;
    Map newExisting = new HashMap(methods.length);
    List newMethods = new ArrayList();
    for (int i = 0; i < methods.length; i++)
    {
      IMethod im = methods[i];
      method = (Method)existingMethods.remove(im);
      if (method != null)
      {
        newExisting.put(im, method);
        adapter = (JavaMethodJDOMAdaptor)retrieveAdaptorFrom(method);
        if (adapter != null)
        {
          adapter.flushReflectedValuesIfNecessaryNoNotification(true);
          adapter.setSourceMethod(im);
        }
      }
      else
      {
        method = createJavaMethod(im, resource);
        newExisting.put(im, method);
        newMethods.add(method);
        
        adapter = (JavaMethodJDOMAdaptor)getAdapterFactory().adaptNew(method, "JavaReflection");
        if (adapter != null) {
          adapter.setSourceMethod(methods[i]);
        }
      }
    }
    BasicEList methodsList = (BasicEList)getJavaClassTarget().getMethodsGen();
    if (!existingMethods.isEmpty())
    {
      URI baseURI = resource.getURI();
      Collection toDelete = existingMethods.values();
      for (Iterator itr = toDelete.iterator(); itr.hasNext();)
      {
        InternalEObject m = (InternalEObject)itr.next();
        String id = resource.getID(m);
        if (id != null) {
          m.eSetProxyURI(baseURI.appendFragment(id));
        }
      }
      methodsList.removeAll(toDelete);
    }
    if (!newMethods.isEmpty()) {
      methodsList.addAllUnique(newMethods);
    }
    existingMethods = newExisting;
    return true;
  }
  
  protected void clearSource()
  {
    sourceType = null;
  }
  
  protected boolean flushFields()
  {
    existingFields.clear();
    XMIResource res = (XMIResource)getJavaClassTarget().eResource();
    URI baseURI = res.getURI();
    List fields = getJavaClassTarget().getFieldsGen();
    int msize = fields.size();
    for (int i = 0; i < msize; i++)
    {
      InternalEObject f = (InternalEObject)fields.get(i);
      String id = res.getID(f);
      if (id != null) {
        f.eSetProxyURI(baseURI.appendFragment(id));
      }
    }
    fields.clear();
    return true;
  }
  
  protected boolean flushImplements()
  {
    getJavaClassTarget().getImplementsInterfacesGen().clear();
    return true;
  }
  
  protected boolean flushMethods()
  {
    existingMethods.clear();
    XMIResource res = (XMIResource)getJavaClassTarget().eResource();
    URI baseURI = res.getURI();
    List methods = getJavaClassTarget().getMethodsGen();
    int msize = methods.size();
    for (int i = 0; i < msize; i++)
    {
      InternalEObject m = (InternalEObject)methods.get(i);
      String id = res.getID(m);
      if (id != null) {
        m.eSetProxyURI(baseURI.appendFragment(id));
      }
    }
    methods.clear();
    return true;
  }
  
  protected boolean flushModifiers()
  {
    JavaClass javaClassTarget = (JavaClass)getTarget();
    javaClassTarget.setAbstract(false);
    javaClassTarget.setFinal(false);
    javaClassTarget.setPublic(false);
    javaClassTarget.setKind(TypeKind.UNDEFINED_LITERAL);
    return true;
  }
  
  protected boolean flushInnerClasses()
  {
    getJavaClassTarget().getDeclaredClassesGen().clear();
    return true;
  }
  
  protected boolean flushReflectedValues(boolean clearCachedModelObject)
  {
    flushAndClearCachedModelObject = clearCachedModelObject;
    return true;
  }
  
  private void flushNow()
  {
    if (flushAndClearCachedModelObject) {
      setSourceType(null);
    }
    typeResolutionCache.clear();
    flushModifiers();
    flushSuper();
    flushImplements();
    if (flushAndClearCachedModelObject)
    {
      flushMethods();
      flushFields();
    }
    hasReflectedMethods = false;
    hasReflectedFields = false;
    
    flushInnerClasses();
    flushAndClearCachedModelObject = false;
  }
  
  protected void postFlushReflectedValuesIfNecessary(boolean isExisting)
  {
    getJavaClassTarget().setReflected(false);
    super.postFlushReflectedValuesIfNecessary(isExisting);
  }
  
  protected boolean flushSuper()
  {
    List targetSupers = getJavaClassTarget().primGetESuperTypes();
    targetSupers.clear();
    return true;
  }
  
  protected JavaReflectionAdapterFactory getAdapterFactory()
  {
    return adapterFactory;
  }
  
  protected IType getBinaryType()
  {
    return getBinaryType(((JavaClass)getTarget()).getQualifiedName());
  }
  
  protected JavaClassImpl getJavaClassTarget()
  {
    return (JavaClassImpl)getTarget();
  }
  
  public Object getReflectionSource()
  {
    return getSourceType();
  }
  
  public boolean hasCachedReflectionSource()
  {
    return sourceType != null;
  }
  
  public IType getSourceType()
  {
    if ((sourceType == null) || (flushAndClearCachedModelObject))
    {
      JavaClassImpl javaClass = (JavaClassImpl)getTarget();
      sourceType = JDOMSearchHelper.findType(javaClass.getJavaPackage().getName(), javaClass.primGetName(), getSourceProject());
      if (hasValidReflection()) {
        flushReflectedValuesIfNecessaryNoNotification(false);
      }
    }
    return sourceType;
  }
  
  protected IType getType()
  {
    return getSourceType();
  }
  
  protected Map getTypeResolutionCache()
  {
    return typeResolutionCache;
  }
  
  public Object getValueIn(EObject object, EObject attribute)
  {
    return super.getValueIn(object, attribute);
  }
  
  public boolean isSourceTypeFromBinary()
  {
    if (getSourceType() == null) {
      return false;
    }
    return getSourceType().isBinary();
  }
  
  protected JavaClass reflectJavaClass(String qualifiedName)
  {
    IType type = JDOMSearchHelper.findType(qualifiedName, true, getSourceProject(), this);
    if (type != null) {
      return reflectJavaClass(type);
    }
    return createJavaClassRef(qualifiedName);
  }
  
  protected JavaClass reflectJavaClass(IType aType)
  {
    if (aType != null)
    {
      JavaClass javaClass = (JavaClass)JavaRefFactory.eINSTANCE.reflectType(aType.getFullyQualifiedName(), (EObject)getTarget());
      if (javaClass != null)
      {
        JavaClassJDOMAdaptor adaptor = (JavaClassJDOMAdaptor)EcoreUtil.getAdapter(javaClass.eAdapters(), "JavaReflection");
        if (adaptor != null) {
          adaptor.setSourceType(aType);
        }
      }
      return javaClass;
    }
    return null;
  }
  
  public boolean reflectValues()
  {
    if (hasFlushed) {
      flushNow();
    }
    super.reflectValues();
    boolean isHeadless = UIContextDetermination.getCurrentContext() == 102;
    if (canReflect())
    {
      TimerTests.basicTest.startCumulativeStep("Reflect JDOM Class");
      try
      {
        ICompilationUnit cu = getSourceType().getCompilationUnit();
        boolean isWC = cu != null ? cu.isWorkingCopy() : false;
        IResource res = isWC ? getSourceType().getResource() : null;
        if ((!isWC) || ((res != null) && (res.isAccessible())))
        {
          setModifiers();
          setNaming();
          try
          {
            setSuper();
          }
          catch (InheritanceCycleException e)
          {
            JavaPlugin.getDefault().getLogger().log(e);
          }
          setImplements();
          reflectInnerClasses();
          setDeclaringClass();
          if (isHeadless)
          {
            registerWithFactory();
            return true;
          }
        }
      }
      finally
      {
        TimerTests.basicTest.stopCumulativeStep("Reflect JDOM Class");
      }
      jsr -13;
    }
    if (isHeadless) {
      return false;
    }
    registerWithFactory();
    return true;
  }
  
  protected void setDeclaringClass()
  {
    IType declaringType = getSourceType().getDeclaringType();
    if (declaringType != null)
    {
      ResourceSet set = getTargetResource().getResourceSet();
      String packageName = declaringType.getPackageFragment().getElementName();
      JavaClassImpl declaringClass = (JavaClassImpl)JavaRefFactory.eINSTANCE.reflectType(packageName, declaringType.getTypeQualifiedName(), set);
      declaringClass.getDeclaredClasses();
    }
  }
  
  private boolean canReflect()
  {
    return (isResourceLoaded()) && (getSourceProject() != null) && (getSourceType() != null) && (getSourceType().exists());
  }
  
  public synchronized boolean reflectFieldsIfNecessary()
  {
    if ((reflectValuesIfNecessary()) && (canReflect()))
    {
      if ((!hasReflectedFields) && (!isReflectingFields))
      {
        isReflectingFields = true;
        try
        {
          TimerTests.basicTest.startCumulativeStep("Reflect all JDOM fields for a class");
          addFields();
          hasReflectedFields = true;
        }
        catch (Exception e)
        {
          hasReflectedFields = false;
          Logger logger = Logger.getLogger();
          if (logger.isLoggingLevel(Level.WARNING))
          {
            logger.log(ResourceHandler.getString("Failed_reflecting_values_ERROR_"), Level.WARNING);
            logger.logWarning(e);
          }
        }
        finally
        {
          isReflectingFields = false;
          TimerTests.basicTest.stopCumulativeStep("Reflect all JDOM fields for a class");
        }
      }
      return hasReflectedFields;
    }
    return false;
  }
  
  public synchronized boolean reflectMethodsIfNecessary()
  {
    if ((reflectValuesIfNecessary()) && (canReflect()))
    {
      if ((!hasReflectedMethods) && (!isReflectingMethods))
      {
        isReflectingMethods = true;
        try
        {
          TimerTests.basicTest.startCumulativeStep("Reflect all JDOM methods for a class");
          hasReflectedMethods = addMethods();
        }
        catch (Exception e)
        {
          hasReflectedMethods = false;
          Logger logger = Logger.getLogger();
          if (logger.isLoggingLevel(Level.WARNING))
          {
            logger.log(ResourceHandler.getString("Failed_reflecting_values_ERROR_"), Level.WARNING);
            logger.logWarning(e);
          }
        }
        finally
        {
          isReflectingMethods = false;
          if (!hasReflected) {
            flushMethods();
          }
          TimerTests.basicTest.stopCumulativeStep("Reflect all JDOM methods for a class");
        }
      }
      return hasReflectedMethods;
    }
    return false;
  }
  
  private void registerWithFactory()
  {
    getAdapterFactory().registerReflection(getJavaClassTarget().getQualifiedNameForReflection(), this);
  }
  
  public void notifyChanged(Notification notification)
  {
    if ((notification.getEventType() == 8) && 
      (notification.getOldValue() == this) && 
      (notification.getNotifier() == getTarget())) {
      getAdapterFactory().unregisterReflection(getJavaClassTarget().getQualifiedNameForReflection());
    }
  }
  
  protected void setAdapterFactory(JavaReflectionAdapterFactory inFactory)
  {
    adapterFactory = inFactory;
  }
  
  protected void setImplements()
  {
    try
    {
      String[] interfaceNames = getSourceType().getSuperInterfaceNam
1 2 3 4

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd