geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From lin...@apache.org
Subject svn commit: r582932 [2/3] - in /geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources: ./ META-INF/ schema/ src/ src/org/ src/org/apache/ src/org/apache/geronimo/ src/org/apache/geronimo/devtools/ src/org/apache/geronimo/devtools...
Date Mon, 08 Oct 2007 18:50:56 GMT
Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/NodesVisitor.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/NodesVisitor.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/NodesVisitor.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/NodesVisitor.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,370 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.geronimo.devtools.j2g.sources.dependence;
+
+
+import java.io.File;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.geronimo.devtools.j2g.common.FatalToolException;
+import org.apache.geronimo.devtools.j2g.common.IOutput;
+import org.apache.geronimo.devtools.j2g.common.Tool;
+import org.apache.geronimo.devtools.j2g.common.ToolConstants;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.Expression;
+import org.eclipse.jdt.core.dom.IBinding;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.ImportDeclaration;
+import org.eclipse.jdt.core.dom.MethodDeclaration;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.Name;
+import org.eclipse.jdt.core.dom.QualifiedName;
+import org.eclipse.jdt.core.dom.QualifiedType;
+import org.eclipse.jdt.core.dom.SimpleName;
+import org.eclipse.jdt.core.dom.SimpleType;
+import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
+import org.eclipse.jdt.core.dom.Type;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+
+
+/**
+ * Visitor for ASTNode. Finds types dependencies and reports to tool output.
+ */
+public class NodesVisitor extends ASTVisitor {
+	/**
+	 * Tool output.
+	 */
+	private IOutput out;
+
+	/**
+	 * Current compilation unit.
+	 */
+	private CompilationUnit unit;
+
+	/**
+	 * Set of declared variables.
+	 */
+	private Set vars;
+
+	/**
+	 * Set of already picked libraries.
+	 */
+	private Set linkedLibs;
+
+	/**
+	 * Set of declared classes in imports.
+	 */
+	private Set imports;
+
+	/**
+	 * 
+	 */
+	
+	private boolean wrongApiUsing;
+
+	/**
+	 * Constructor.
+	 * 
+	 * @param unit
+	 *            compilation unit which will be visited.
+	 * @param out
+	 * @param visitDocTypes
+	 */
+	public NodesVisitor(CompilationUnit unit) {
+		super(false);
+		this.out = Tool.getCurrent().getOutput();
+		this.unit = unit;
+		vars = new HashSet();
+		linkedLibs = new HashSet();
+		imports = new HashSet();
+		wrongApiUsing = false;
+		
+		List compUnitList = unit.imports();
+		Iterator listIter = compUnitList.iterator();
+		while (listIter.hasNext()) {
+			ImportDeclaration impDec = (ImportDeclaration)listIter.next();
+			if (impDec.getName().isQualifiedName()) {
+				QualifiedName qualifiedName = (QualifiedName) impDec.getName();
+				String className = qualifiedName.getName().getIdentifier();
+				imports.add(className);
+			}
+			else {
+				SimpleName simpleName = (SimpleName) impDec.getName();
+				imports.add(simpleName.getIdentifier());
+			}
+		}
+	}
+
+	/**
+	 * Solves binding and if it's corressponds to Geronimo repository library
+	 * warns about it.
+	 * 
+	 * @param binding
+	 * @throws FatalToolException
+	 */
+	private void solveBinding(IBinding binding, String name) {
+		if (binding instanceof ITypeBinding) {
+			try {
+				String linkedJarName = binding.getJavaElement().getPath().toFile().getName();
+				if (linkedJarName.startsWith(ToolConstants.GERONIMO_REP)) {
+					File lib = binding.getJavaElement().getUnderlyingResource().getRawLocation().toFile();
+					String artifactName = getGeronimoArtifactName(lib);
+					if (!linkedLibs.contains(lib.getName()) && !DependenceJavaMigration.getDefaultLibs().contains(artifactName)) {
+						out.warn(NodesVisitor.class.getSimpleName(), "You should add a '" + artifactName + "' dependency.");
+						linkedLibs.add(lib.getName());
+					}
+				}
+			} catch (JavaModelException e) {
+				out.fatal(NodesVisitor.class.getSimpleName(), "Cannot get access to library for resolve name'" + name + "'.");
+			}
+		}
+	}
+
+	/**
+	 * Visits {@link ImportDeclaration} and trying to resolve binding.
+	 */
+	public boolean visit(ImportDeclaration importDeclaration) {
+		if (importDeclaration.resolveBinding() != null) {
+			String name = importDeclaration.getName().getFullyQualifiedName();
+			solveBinding(importDeclaration.resolveBinding(), name);
+		}
+		else {
+			printImportError(importDeclaration.getName().getFullyQualifiedName(), importDeclaration.getStartPosition());
+			if (importDeclaration.getName().isQualifiedName()) {
+				QualifiedName qualifiedName = (QualifiedName) importDeclaration.getName();
+				String className = qualifiedName.getName().getIdentifier();
+				imports.add(className);
+			}
+			else {
+				SimpleName simpleName = (SimpleName) importDeclaration.getName();
+				imports.add(simpleName.getIdentifier());
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Visits {@link QualifiedType} and trying to resolve binding.
+	 */
+	public boolean visit(QualifiedType qualifiedType) {
+		if (qualifiedType.resolveBinding() != null) {
+			String name = qualifiedType.getName().getFullyQualifiedName();
+			solveBinding(qualifiedType.resolveBinding(), name);
+			return true;
+		}
+		else {
+			Type qualifier = qualifiedType.getQualifier();
+			if (qualifier instanceof QualifiedType) {
+				if (visit((QualifiedType) qualifier)) {
+					printTypeError(qualifiedType.getName().getFullyQualifiedName(), qualifiedType.getStartPosition());
+				}
+			}
+			else {
+				if (visit((SimpleType) qualifier)) {
+					printTypeError(qualifiedType.getName().getFullyQualifiedName(), qualifiedType.getStartPosition());
+				}
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Visits {@link SimpleType} and trying to resolve binding.
+	 */
+	public boolean visit(SimpleType simpleType) {
+		if (simpleType.resolveBinding() != null) {
+			String name = simpleType.getName().getFullyQualifiedName(); 
+			solveBinding(simpleType.resolveBinding(), name );
+		}
+		else {
+			printTypeError(simpleType.getName().getFullyQualifiedName(), simpleType.getStartPosition());
+		}
+		return false;
+	}
+
+	/**
+	 * Visits {@link QualifiedName} and trying to resolve binding.
+	 */
+	public boolean visit(QualifiedName qualifiedName) {
+		if (qualifiedName.resolveBinding() != null) {
+			String name = qualifiedName.getFullyQualifiedName();
+			solveBinding(qualifiedName.resolveBinding(), name);
+			return true;
+		}
+		else {
+			Name qualifiedPart = qualifiedName.getQualifier();
+			if (qualifiedPart instanceof QualifiedName) {
+				if (visit((QualifiedName) qualifiedPart)) {
+					printTypeError(qualifiedName.getFullyQualifiedName(), qualifiedName.getStartPosition());
+				}
+				return false;
+			}
+			else {
+				if (qualifiedPart.resolveBinding() != null) {
+					printTypeError(qualifiedName.getFullyQualifiedName(), qualifiedName.getStartPosition());
+				}
+				else {
+					if (!isDeclaredVar(qualifiedPart.toString())) {
+						printTypeError(qualifiedPart.getFullyQualifiedName(), qualifiedPart.getStartPosition());
+					}
+				}
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Visits {@link MethodDeclaration} and trying to resolve binding.
+	 */
+	public boolean visit(MethodDeclaration method) {
+		List names = method.thrownExceptions();
+		if (names != null) {
+			Iterator iter = names.iterator();
+			while (iter.hasNext()) {
+				Name name = (Name) iter.next();
+				if (name.resolveBinding() != null) {
+					String nameStr = name.getFullyQualifiedName();
+					solveBinding(name.resolveBinding(), nameStr);
+				}
+				else {
+					printTypeError(name.getFullyQualifiedName(), name.getStartPosition());
+				}
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * Visits {@link MethodInvocation} and trying to resolve binding.
+	 */
+	public boolean visit(MethodInvocation methodInvocation) {
+		Expression expr = methodInvocation.getExpression();
+		if (expr == null) {
+			if (methodInvocation.resolveMethodBinding() == null) {
+				printTypeError(methodInvocation.getName().getFullyQualifiedName(), methodInvocation.getStartPosition());
+			}
+		}
+		else {
+			if (expr.resolveTypeBinding() != null) {
+				String name = expr.toString();
+				solveBinding(expr.resolveTypeBinding(), name);
+			}
+			else {
+				if (expr instanceof MethodInvocation) {
+					visit((MethodInvocation) expr);
+				}
+				else if (expr instanceof QualifiedName) {
+					visit((QualifiedName) expr);
+				}
+				else if (expr instanceof SimpleName) {
+					if (!isDeclaredVar(expr.toString())) {
+						SimpleName simpleName = (SimpleName) expr;
+						printTypeError(simpleName.getFullyQualifiedName(), expr.getStartPosition());
+					}
+				}
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * Visits {@link SingleVariableDeclaration} and adds variable name to the
+	 * list.
+	 */
+	public boolean visit(SingleVariableDeclaration declaration) {
+		vars.add(declaration.getName().toString());
+		return true;
+	}
+
+	/**
+	 * Visits {@link VariableDeclarationFragment} and adds variable name to the
+	 * list.
+	 */
+	public boolean visit(VariableDeclarationFragment declaration) {
+		vars.add(declaration.getName().toString());
+		return true;
+	}
+
+	/**
+	 * @param name
+	 *            simple name.
+	 * @return <code>true</code> if it is declared variable and
+	 *         <code>false</code> if not.
+	 */
+	private boolean isDeclaredVar(String name) {
+		return vars.contains(name);
+	}
+
+	/**
+	 * Prints error about not resolved name.
+	 * 
+	 * @param name
+	 *            not resolved name.
+	 * @param position
+	 *            start position in source file.
+	 */
+	private void printTypeError(String name, int position) {
+		if (!imports.contains(name)) {
+			out.error(NodesVisitor.class.getSimpleName(), "The name '" + name + "' cannot be resolved.", unit.getLineNumber(position), unit.getColumnNumber(position));
+			wrongApiUsing = true;
+		}
+	}
+
+	/**
+	 * Prints error about not resolved import.
+	 * 
+	 * @param name
+	 *            import name.
+	 * @param position
+	 *            start position in source file.
+	 */
+	private void printImportError(String name, int position) {
+		wrongApiUsing = true;
+		out.error(NodesVisitor.class.getSimpleName(), "The import '" + name + "' cannot be resolved.", unit.getLineNumber(position), unit.getColumnNumber(position));
+	}
+	
+	/**
+	 * Constructs Geronimo artifact name from repository library file.
+	 * 
+	 * @param libFullName
+	 *            full path to the repository library.
+	 * @return Geronimo artifact name.
+	 */
+	private String getGeronimoArtifactName(File libFullName) {
+		String fullName = libFullName.getAbsolutePath();
+		String geronimoRep = ToolConstants.GERONIMO_REPOSITORY_FOLDER + File.separator;
+		String name = fullName.substring(fullName.lastIndexOf(geronimoRep) + geronimoRep.length());
+		name = name.substring(0, name.indexOf(libFullName.getName()));
+		name = name.replace(File.separatorChar, ToolConstants.GERONIMO_SEPARATOR_CHAR);
+		String extension = fullName.substring(fullName.lastIndexOf('.') + 1);
+		return name + extension;
+	}
+	
+	/**
+	 * @return true if source uses proprietary api.
+	 */
+	public boolean isSourceValid(){
+		return !wrongApiUsing;
+	}
+	
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/NodesVisitor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Anybody.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Anybody.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Anybody.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Anybody.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,60 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+/*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.security.Principal;
+
+public class Anybody
+    implements Comparable, Principal
+{
+
+    public Anybody()
+    {
+    }
+
+    public int hashCode()
+    {
+        return ANYBODY.hashCode();
+    }
+
+    public String getName()
+    {
+        return ANYBODY;
+    }
+
+    public String toString()
+    {
+        return ANYBODY;
+    }
+
+    public boolean equals(Object another)
+    {
+        return true;
+    }
+
+    public int compareTo(Object o)
+    {
+        return 0;
+    }
+
+    public static final String ANYBODY = "<ANYBODY>";
+    public static final Anybody ANYBODY_PRINCIPAL = new Anybody();
+
+}
\ No newline at end of file

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Anybody.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/DigestCallback.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/DigestCallback.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/DigestCallback.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/DigestCallback.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,32 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+/*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.security.MessageDigest;
+import java.util.Map;
+
+public interface DigestCallback {
+
+  public abstract void init(Map map);
+
+  public abstract void preDigest(MessageDigest digest);
+
+  public abstract void postDigest(MessageDigest digest);
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/DigestCallback.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoLoginModule.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoLoginModule.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoLoginModule.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoLoginModule.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,352 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+/*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.FailedLoginException;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.spi.LoginModule;
+
+import org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal;
+import org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal;
+
+public abstract class GeronimoLoginModule implements LoginModule {
+
+	protected Subject subject;
+
+	protected CallbackHandler callbackHandler;
+
+	protected Map sharedState;
+
+	protected Map options;
+
+	protected boolean useFirstPass;
+
+	protected boolean loginOk;
+
+	protected String principalClassName;
+
+	protected Principal unauthenticatedIdentity;
+
+	private Principal identity;
+
+	private char passport[];
+
+	private String algorithm;
+
+	private String charset;
+
+	private String encoding;
+
+	private boolean ignorePasswordCase;
+
+	protected final static int USERNAME_POS = 0;
+
+	protected final static int PASSWORD_POS = 1;
+
+	public GeronimoLoginModule() {
+		algorithm = null;
+		charset = null;
+		encoding = null;
+	}
+
+	public boolean abort() throws LoginException {
+		return true;
+	}
+
+	public boolean commit() throws LoginException {
+		if (!loginOk) {
+			return false;
+		}
+		Set heads = subject.getPrincipals();
+		Principal identity = getIdentity();
+		heads.add(identity);
+		Group roleSets[] = getRoleSets();
+		for (int i = 0; i < roleSets.length; i++) {
+			Group group = roleSets[i];
+			String name = group.getName();
+			Group subjectGroup = createGroup(name, heads);
+			Principal role;
+			Enumeration members = group.members();
+			while (members.hasMoreElements()) {
+				role = (Principal) members.nextElement();
+				subjectGroup.addMember(role);
+				if(name.equals("Roles")){
+					heads.add(new GeronimoGroupPrincipal(role.getName()));
+				}
+			}
+		}
+		return true;
+	}
+
+	protected Principal getIdentity() {
+		return identity;
+	}
+
+	public void initialize(Subject subject, CallbackHandler callbackHandler,
+			Map sharedState, Map options) {
+		this.subject = subject;
+		this.callbackHandler = callbackHandler;
+		this.sharedState = sharedState;
+		this.options = options;
+		String passwordStacking = (String) options.get("password-stacking");
+		if (passwordStacking != null
+				&& passwordStacking.equalsIgnoreCase("useFirstPass")) {
+			useFirstPass = true;
+		}
+		principalClassName = (String) options.get("principalClass");
+		String name = (String) options.get("unauthenticatedIdentity");
+		if (name != null) {
+			try {
+				unauthenticatedIdentity = createIdentity(name);
+			} catch (Exception e) {
+			}
+		}
+		algorithm = (String) options.get("hashAlgorithm");
+		if (algorithm != null) {
+			encoding = (String) options.get("hashEncoding");
+			if (encoding == null) {
+				encoding = "BASE64";
+			}
+			charset = (String) options.get("hashCharset");
+		}
+		String flag = (String) options.get("ignorePasswordCase");
+		ignorePasswordCase = Boolean.valueOf(flag).booleanValue();
+	}
+
+	public boolean login() throws LoginException {
+		loginOk = false;
+		if (useFirstPass) {
+			Object identity = sharedState.get("javax.security.auth.login.name");
+			Object credential = sharedState
+					.get("javax.security.auth.login.password");
+			if (identity != null && credential != null) {
+				loginOk = true;
+			}
+		}
+		if (loginOk) {
+			Object username = sharedState.get("javax.security.auth.login.name");
+			if (username instanceof Principal) {
+				identity = (Principal) username;
+			} else {
+				try {
+					identity = createIdentity(username.toString());
+				} catch (Exception e) {
+					throw new LoginException("Failed to create principal: "
+							+ e.getMessage());
+				}
+			}
+			Object password = sharedState
+					.get("javax.security.auth.login.password");
+
+			if (password != null) {
+				if (password instanceof char[]) {
+					passport = (char[]) password;
+				} else {
+					passport = password.toString().toCharArray();
+				}
+			}
+			return true;
+		}
+		loginOk = false;
+
+		String username = null;
+		String password = null;
+
+		String[] usernameAndPassword = getUsernameAndPassword();
+
+		username = usernameAndPassword[USERNAME_POS];
+		password = usernameAndPassword[PASSWORD_POS];
+		if (username == null && password == null) {
+			identity = unauthenticatedIdentity;
+		}
+		if (identity == null) {
+			try {
+				identity = createIdentity(username);
+			} catch (Exception e) {
+				throw new LoginException("Failed to create principal: "
+						+ e.getMessage());
+			}
+			if (algorithm != null) {
+				password = createPasswordHash(username, password);
+			}
+			String expectedPassword = getUsersPassword();
+			if (!validatePassword(password, expectedPassword)) {
+				throw new FailedLoginException(
+						"Password Incorrect/Password Required");
+			}
+		}
+		if (getUseFirstPass()) {
+			sharedState.put("javax.security.auth.login.name", username);
+			sharedState.put("javax.security.auth.login.password", passport);
+		}
+		loginOk = true;
+		return loginOk;
+	}
+
+	protected String[] getUsernameAndPassword() throws LoginException {
+		String usernamePassword[] = { null, null };
+		if (callbackHandler == null) {
+			throw new LoginException(
+					"Error occurs: there are no CallbackHandler available to get information about authentication");
+		}
+		String username = null;
+		String password = null;
+		try {
+			Callback callbacks[] = { new NameCallback("Username: "), new PasswordCallback("Password: ", false) };
+			callbackHandler.handle(callbacks);
+			NameCallback nameCallback = (NameCallback) callbacks[0];
+			PasswordCallback passwordCallback = (PasswordCallback) callbacks[1];
+			username = nameCallback.getName();
+			char helperPassword[] = passwordCallback.getPassword();
+			if (helperPassword != null) {
+				passport = new char[helperPassword.length];
+				System.arraycopy(helperPassword, 0, passport, 0,
+						helperPassword.length);
+				passwordCallback.clearPassword();
+				password = new String(passport);
+			}
+		} catch (IOException ioe) {
+			throw new LoginException(ioe.toString());
+		} catch (UnsupportedCallbackException uce) {
+			throw new LoginException("CallbackHandler does not support: "
+					+ uce.getCallback());
+		}
+		usernamePassword[USERNAME_POS] = username;
+		usernamePassword[PASSWORD_POS] = password;
+		return usernamePassword;
+	}
+
+	protected boolean validatePassword(String inputPassword,
+			String expectedPassword) {
+		if (inputPassword == null || expectedPassword == null) {
+			return false;
+		}
+		return ignorePasswordCase ? inputPassword
+				.equalsIgnoreCase(expectedPassword) : inputPassword
+				.equals(expectedPassword);
+	}
+
+	protected String createPasswordHash(String username, String password) {
+		DigestCallback callback = null;
+		String callbackClassName = (String) options.get("digestCallback");
+		if (callbackClassName != null) {
+			try {
+				Class callbackClass = loadSomeClass(callbackClassName);
+				callback = (DigestCallback) callbackClass.newInstance();
+			} catch (Exception e) {
+				SecurityException securityExeption = new SecurityException(
+						"Cannot load DigestCallback");
+				securityExeption.initCause(e);
+				throw securityExeption;
+			}
+			HashMap optionsMap = new HashMap(options);
+			optionsMap.put("javax.security.auth.login.name", username);
+			optionsMap.put("javax.security.auth.login.password", password);
+			callback.init(optionsMap);
+		}
+
+		return PasswordHasher.calculateHash(algorithm, encoding, charset,
+				username, password, callback);
+	}
+
+	protected boolean getUseFirstPass() {
+		return useFirstPass;
+	}
+
+	protected Principal getUnauthenticatedIdentity() {
+		return unauthenticatedIdentity;
+	}
+
+	protected Object getCredentials() {
+		return passport;
+	}
+
+	public boolean logout() throws LoginException {
+		Principal identity = getIdentity();
+		Set principals = subject.getPrincipals();
+		principals.remove(identity);
+		return true;
+	}
+
+	protected Principal createIdentity(String username) throws Exception {
+		Principal principal = null;
+		if (principalClassName != null) {
+			Class loadedClass = loadSomeClass(principalClassName);
+			Class signatures[] = { java.lang.String.class };
+			Constructor constructorInstance = loadedClass
+					.getConstructor(signatures);
+			Object argumentsForConstructor[] = { username };
+			principal = (Principal) constructorInstance
+					.newInstance(argumentsForConstructor);
+		} else {
+			principal = new GeronimoUserPrincipal(username);
+		}
+		return principal;
+	}
+
+	private Class loadSomeClass(String classname) throws ClassNotFoundException {
+		ClassLoader loader = Thread.currentThread().getContextClassLoader();
+		return loader.loadClass(classname);
+	}
+
+	protected String getUsername() {
+		return (getIdentity() != null) ? getIdentity().getName() : null;
+	}
+
+	protected Group createGroup(String name, Set principals) {
+		Group roles = null;
+		Iterator principalsIter = principals.iterator();
+		while (principalsIter.hasNext()) {
+			Object next = principalsIter.next();
+			if (next instanceof Group) {
+				Group nextGroup = (Group) next;
+				if (nextGroup.getName().equals(name)) {
+					roles = nextGroup;
+					break;
+				}
+			}
+		}
+		if (roles == null) {
+			roles = new GeronimoSimpleGroup(name);
+			principals.add(roles);
+		}
+		return roles;
+	}
+
+	protected abstract String getUsersPassword() throws LoginException;
+
+	protected abstract Group[] getRoleSets() throws LoginException;
+}
\ No newline at end of file

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoLoginModule.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoSimpleGroup.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoSimpleGroup.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoSimpleGroup.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoSimpleGroup.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,97 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+ /*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal;
+
+public class GeronimoSimpleGroup extends GeronimoGroupPrincipal implements Group {
+
+	/**
+	 * Serial ID.
+	 */
+	private static final long serialVersionUID = 4220122854158936883L;
+
+	private HashMap members;
+
+	public GeronimoSimpleGroup(String name) {
+		super(name);
+		members = new HashMap(3);
+	}
+
+	public boolean addMember(Principal user) {
+		boolean isMember = members.containsKey(user);
+		if (!isMember) {
+			members.put(user, user);
+		}
+		return !isMember;
+	}
+
+	public boolean isMember(Principal member) {
+		boolean isMember = members.containsKey(member);
+		if (!isMember) {
+			isMember = member instanceof Anybody;
+			if (!isMember && (member instanceof Nobody)) {
+				return false;
+			}
+		}
+
+		if (!isMember) {
+			Collection values = members.values();
+			Iterator iter = values.iterator();
+			do {
+				if (isMember || !iter.hasNext()) {
+					break;
+				}
+				Object next = iter.next();
+				if (next instanceof Group) {
+					Group group = (Group) next;
+					isMember = group.isMember(member);
+				}
+			} while (true);
+		}
+		return isMember;
+	}
+
+	public Enumeration members() {
+		return Collections.enumeration(members.values());
+	}
+
+	public boolean removeMember(Principal user) {
+		return (members.remove(user) != null);
+	}
+
+	public String toString() {
+		String tmp = new String(getName());
+		tmp.concat("(MEMBERS:");
+		for (Iterator iter = members.keySet().iterator(); iter.hasNext(); tmp.concat(",")) {
+			tmp.concat(iter.next().toString());
+		}
+		tmp.concat(")");
+		return tmp.toString();
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/GeronimoSimpleGroup.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Nobody.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Nobody.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Nobody.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Nobody.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,51 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+ /*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.security.Principal;
+
+public class Nobody implements Comparable, Principal {
+	public static final String NOBODY = "<NOBODY>";
+
+	public static final Nobody NOBODY_PRINCIPAL = new Nobody();
+
+	public Nobody() {
+	}
+
+	public int hashCode() {
+		return NOBODY.hashCode();
+	}
+
+	public String getName() {
+		return NOBODY;
+	}
+
+	public String toString() {
+		return NOBODY;
+	}
+
+	public boolean equals(Object another) {
+		return false;
+	}
+
+	public int compareTo(Object o) {
+		return 1;
+	}
+}
\ No newline at end of file

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/Nobody.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/PasswordHasher.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/PasswordHasher.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/PasswordHasher.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/PasswordHasher.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,103 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+ /*
+ * Auto-generated by J2G Migration. 
+ */
+package org.apache.geronimo.devtools.j2g.sources.dependence.compatibility;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+
+import org.apache.geronimo.util.encoders.Base64Encoder;
+
+public class PasswordHasher {
+	
+	private final static String HEX_ENC = "HEX";
+	private final static String ISO_ENC = "ISO-8859-1";
+	private final static String BASE_64_ENC = "BASE64";
+	
+	public static String calculateHash(String algorithm, String encoding, String charset, String username, String password, DigestCallback callback) {
+		String passwordHash = null;
+		byte passBytes[];
+		try {
+			if (charset == null) {
+				passBytes = password.getBytes();
+			}
+			else {
+				passBytes = password.getBytes(charset);
+			}
+		} catch (UnsupportedEncodingException uee) {
+			passBytes = password.getBytes();
+		}
+		try {
+			MessageDigest mesDigest = MessageDigest.getInstance(algorithm);
+			if (callback != null) {
+				callback.preDigest(mesDigest);
+			}
+			mesDigest.update(passBytes);
+			if (callback != null) {
+				callback.postDigest(mesDigest);
+			}
+			byte hash[] = mesDigest.digest();
+			if (encoding.equalsIgnoreCase(HEX_ENC)) {
+				passwordHash = base16Encoding(hash);
+			} else if (encoding.equalsIgnoreCase(BASE_64_ENC)) {
+				passwordHash = base64Encoding(hash);
+			}
+		} catch (Exception e) {}
+		return passwordHash;
+	}
+
+	private static String base16Encoding(byte encodedChain[]) {
+		StringBuffer buffer = new StringBuffer(encodedChain.length * 2);
+		for (int i = 0; i < encodedChain.length; i++) {
+			byte nextByte = encodedChain[i];
+			char nextChar = (char) (nextByte >> 4 & 0xf);
+			if (nextChar > '\t') {
+				nextChar = (char) ((nextChar - 10) + 97);
+			}
+			else {
+				nextChar += '0';
+			}
+			buffer.append(nextChar);
+			nextChar = (char) (nextByte & 0xf);
+			if (nextChar > '\t') {
+				nextChar = (char) ((nextChar - 10) + 97);
+			}
+			else {
+				nextChar += '0';
+			}
+			buffer.append(nextChar);
+		}
+		return buffer.toString();
+	}
+
+	private static String base64Encoding(byte bytes[]) {
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		Base64Encoder encoder = new Base64Encoder();
+		try {
+			encoder.encode(bytes, 0, bytes.length, out);
+		} catch (IOException e) {}
+		String result = null;
+		try {
+			result = out.toString(ISO_ENC);
+		} catch (UnsupportedEncodingException e) {}
+		return result;
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/dependence/compatibility/PasswordHasher.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/AbsoluteNameSolver.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/AbsoluteNameSolver.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/AbsoluteNameSolver.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/AbsoluteNameSolver.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,469 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.devtools.j2g.sources.environment;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.geronimo.devtools.j2g.common.IOutput;
+import org.apache.geronimo.devtools.j2g.common.Tool;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.Node;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.SAXReader;
+import org.dom4j.io.XMLWriter;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.Type;
+
+
+/**
+ * Provides a mechanism to solve absolute JNDI name used in javax.naming.lookup
+ * method.
+ */
+public class AbsoluteNameSolver {
+	/** Static couner for generating valid ejb names. */
+	private static int counter = 0;
+
+	/** Property file with EJB interfaces */
+	public final static String INTERFACES_PROP_FILENAME = "beans-interfaces.properties";
+	public final static String INTERFACES_PROP_DIRECTORY = System.getenv("ECLIPSE_HOME")+"/plugins/org.apache.geronimo.devtools.j2g.sources.environment/";
+
+	/** Property file with paths for searching types in jboss.xml */
+	public final static String BEANS_TYPES_PROP_FILENAME = "beans-types.properties";
+	public final static String BEANS_TYPES_PROP_DIRECTORY = System.getenv("ECLIPSE_HOME")+"/plugins/org.apache.geronimo.devtools.j2g.sources.environment/";
+
+	/**
+	 * Property file with paths for searching home and remote interfaces in
+	 * ejb-jar.xml
+	 */
+	public final static String BEANS_REFS_PROP_FILENAME = "beans-references.properties";
+	public final static String BEANS_REFS_PROP_DIRECTORY = System.getenv("ECLIPSE_HOME")+"/plugins/org.apache.geronimo.devtools.j2g.sources.environment/";
+
+	/** References in ejb-jar.xml to be found */
+	private final static String[] EJB_REFS = { "ejb-ref", "ejb-local-ref",
+			"resource-ref", "resource-env-ref" };
+
+	/** Separator string for XPath */
+	private final static String XPATH_SEPARATOR = "/";
+
+	/** Separator string for XPath for access elements by non-full names. */
+	private final static String DOUBLE_XPATH_SEPARATOR = "//";
+
+	/** Ejb classname element int ejb-jar.xml */
+	private final static String EJB_CLASS_ELM = "ejb-class";
+
+	/** Ejb name element. */
+	private final static String EJB_NAME_ELM = "ejb-name";
+
+	/** Ejb reference element for add references to ejb-jar.xml */
+	private final static String EJB_REF_ELM = "ejb-ref";
+
+	/** Ejb reference element for add references to ejb-jar.xml */
+	private final static String EJB_LOCAL_REF_ELM = "ejb-local-ref";
+
+	/** Ejb reference JNDI name element. */
+	private final static String EJB_REF_NAME_ELM = "ejb-ref-name";
+
+	/** Ejb reference type element. (Session | Entity) */
+	private final static String EJB_REF_TYPE_ELM = "ejb-ref-type";
+
+	/** Ejb link element. */
+	private final static String EJB_LINK_ELM = "ejb-link";
+
+	/** Base name for generating full ejb reference name. */
+	private final static String BASE_JNDI_NAME = "ejb/";
+
+	/** Session reference type */
+	private final static String SESSION_TYPE = "Session";
+
+	/** Entity reference type */
+	private final static String ENTITY_TYPE = "Entity";
+
+	/** Property file with EJB interfaces */
+	public static Properties interfaces;
+
+	/** Property file with paths for searching types in jboss.xml */
+	private static Properties beansTypes;
+
+	/**
+	 * Property file with paths for searching home and remote interfaces in
+	 * ejb-jar.xml
+	 */
+	private static Properties beansRefs;
+
+	/** Home interface suffix */
+	private final static String HOME_INTERFACE_SUFFIX = "-home";
+
+	/** XPath to session elements. */
+	private final static String SESSION_XPATH = "/ejb-jar/enterprise-beans/session/";
+
+	/** XPath to entity elements */
+	private final static String ENTITY_XPATH = "/ejb-jar/enterprise-beans/entity/";
+
+	/** Full qualified classname for current class */
+	private String qualifiedClassName;
+
+	/** Superinterfaces for current class. */
+	private List superInterfaces;
+
+	/** Output */
+	private IOutput out;
+
+	/** Current compilation unit */
+	private CompilationUnit unit;
+
+	/** SAX reader */
+	private SAXReader xmlReader;
+
+	/** XPath path for class */
+	private String pathForClass;
+
+	/**
+	 * Constructor.
+	 * 
+	 * @param qualifiedClassName
+	 *            full qualified class name which defined in compilation unit.
+	 * @param unit
+	 *            compilation unit.
+	 * @param superIterfaces
+	 *            super interfaces implemented by class which defined in
+	 *            compilation unit.
+	 * @throws NameSolvingException
+	 */
+	public AbsoluteNameSolver(String qualifiedClassName, List superIterfaces,
+			CompilationUnit unit) throws NameSolvingException {
+		this.out = Tool.getCurrent().getOutput();
+		this.qualifiedClassName = qualifiedClassName;
+		this.superInterfaces = superIterfaces;
+		this.unit = unit;
+		pathForClass = getPathForClass();
+		xmlReader = new SAXReader(true);
+	}
+
+	/**
+	 * Tries to find already existing references to current class. If none
+	 * found, tries to resolve type of the current ejb and to add ejb reference
+	 * for current absolute name.
+	 * 
+	 * @param absoluteName
+	 *            absolute name which should be solved.
+	 * @param position
+	 *            position in compilation unit.
+	 * @param ejbJar
+	 *            existed ejb-jar.xml descriptor. (META-INF/ejb-jar.xml)
+	 * @param jbossXml
+	 *            existed jboss.xml descriptor. (META-INf/jboss.xml)
+	 * @return JNDI name in local context which was referenced in ejb-jar
+	 *         descriptor.
+	 * @throws NameSolvingException
+	 *             if any errors occurs while solving absolute names.
+	 */
+	public String solveName(String absoluteName, int position, File ejbJar,
+			File jbossXml) throws NameSolvingException {
+		loadProperties();
+		if (pathForClass != null) {
+			Document ejbJarDoc = null;
+			try {
+				ejbJarDoc = xmlReader.read(ejbJar);
+			} catch (DocumentException ex) {
+				throw new NameSolvingException(
+						"Error occured while reading xml descriptor "
+								+ jbossXml.getAbsolutePath()
+								+ ". It is possible that the migrator cannot download the xml schema or the xml file has incorrect syntax. Nested exception:"
+								+ ex.getMessage());
+			}
+
+			List nodes = ejbJarDoc.selectNodes(pathForClass + XPATH_SEPARATOR
+					+ EJB_CLASS_ELM);
+			Iterator nodesIter = nodes.iterator();
+			Node ejbJarNode = null;
+			while (nodesIter.hasNext()) {
+				Node node = (Node) nodesIter.next();
+				if (qualifiedClassName.equals(node.getStringValue().trim())) {
+					ejbJarNode = node.getParent();
+					for (int i = 0; i < EJB_REFS.length; i++) {
+						List refsNodes = ejbJarNode
+								.selectNodes(DOUBLE_XPATH_SEPARATOR
+										+ EJB_REFS[i]);
+						if (!refsNodes.isEmpty()) {
+							Iterator references = refsNodes.iterator();
+
+							while (references.hasNext()) {
+								Node referenceNode = (Node) references.next();
+								String refName = getNodeValueByName(
+										referenceNode, EJB_REF_NAME_ELM);
+								if (refName != null
+										&& absoluteName.equals(refName.trim())) {
+									out
+											.warn(AbsoluteNameSolver.class.getSimpleName(), 
+													"Cannot add reference to the absolute name '"
+															+ absoluteName
+															+ "' because the reference in ejb-jar.xml descriptor to current class is already defined.",
+													unit
+															.getLineNumber(position),
+													unit
+															.getColumnNumber(position));
+									return null;
+								}
+							}
+						}
+					}
+					break;
+				}
+			}
+			if (ejbJarNode != null) {
+				Document jbossXmlDoc = null;
+				try {
+					jbossXmlDoc = xmlReader.read(jbossXml);
+				} catch (DocumentException ex) {
+					throw new NameSolvingException(
+							"Error occured while reading xml descriptor "
+									+ jbossXml.getAbsolutePath()
+									+ ". It is possible that the migrator cannot download the xml schema or the xml file has incorrect syntax. Nested exception:"
+									+ ex.getMessage());
+				}
+				Enumeration paths = beansTypes.keys();
+				while (paths.hasMoreElements()) {
+					String path = (String) paths.nextElement();
+					List findedNodes = jbossXmlDoc.selectNodes(path);
+					Iterator findedNodesIter = findedNodes.iterator();
+					while (findedNodesIter.hasNext()) {
+						Node jbossXmlNode = (Node) findedNodesIter.next();
+						if (absoluteName.equals(jbossXmlNode.getStringValue()
+								.trim())) {
+							String type = beansTypes.getProperty(path);
+							String ejbName = getNodeValueByName(
+									jbossXmlNode.getParent(), EJB_NAME_ELM)
+									.trim();
+							Node referenceNode = null;
+							String ejbRefType = null;
+							List sessionNodes = ejbJarDoc
+									.selectNodes(SESSION_XPATH + EJB_NAME_ELM);
+							Iterator sessionNodesIter = sessionNodes.iterator();
+							while (sessionNodesIter.hasNext()) {
+								Node ejbNameNode = (Node) sessionNodesIter
+										.next();
+								if (ejbName
+										.equals(ejbNameNode.getStringValue())) {
+									referenceNode = ejbNameNode.getParent();
+									ejbRefType = SESSION_TYPE;
+									break;
+								}
+							}
+							if (ejbRefType == null) {
+								List entityNodes = ejbJarDoc
+										.selectNodes(ENTITY_XPATH
+												+ EJB_NAME_ELM);
+								Iterator entityNodesIter = entityNodes
+										.iterator();
+								while (entityNodesIter.hasNext()) {
+									Node ejbNameNode = (Node) entityNodesIter
+											.next();
+									if (ejbName.equals(ejbNameNode
+											.getStringValue())) {
+										referenceNode = ejbNameNode.getParent();
+										ejbRefType = ENTITY_TYPE;
+										break;
+									}
+								}
+							}
+							if (referenceNode != null) {
+								String homeIterfacePath = beansRefs
+										.getProperty(type
+												+ HOME_INTERFACE_SUFFIX);
+								String homeIterface = getNodeValueByName(
+										referenceNode, homeIterfacePath);
+								String objectIterfacePath = beansRefs
+										.getProperty(type);
+								String objectIterface = getNodeValueByName(
+										referenceNode, objectIterfacePath);
+								Element ejbJarElement = (Element) ejbJarNode;
+								Element ejbRef = null;
+								if (objectIterfacePath.equals("remote")) {
+									ejbRef = ejbJarElement
+											.addElement(EJB_REF_ELM);
+								} else {
+									ejbRef = ejbJarElement
+											.addElement(EJB_LOCAL_REF_ELM);
+								}
+
+								String refName = generateNewRefName();
+								ejbRef.addElement(EJB_REF_NAME_ELM).addText(
+										refName);
+								ejbRef.addElement(EJB_REF_TYPE_ELM).addText(
+										ejbRefType);
+								ejbRef.addElement(homeIterfacePath).addText(
+										homeIterface);
+								ejbRef.addElement(objectIterfacePath).addText(
+										objectIterface);
+								ejbRef.addElement(EJB_LINK_ELM)
+										.addText(ejbName);
+								serializetoXML(ejbJar, ejbJarDoc);
+								return refName;
+							} else {
+								out.error(AbsoluteNameSolver.class.getSimpleName(), "Cannot find the EJB definition in ejb-jar.xml to create a reference for it.");
+							}
+						}
+					}
+				}
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Generates new names for ejb references. It looks like
+	 * 'ejb/SimpleClassName_x'
+	 * 
+	 * @return new generated reference name.
+	 */
+	private String generateNewRefName() {
+		String simpleClassName = qualifiedClassName
+				.substring(qualifiedClassName.lastIndexOf(".") + 1);
+		return BASE_JNDI_NAME + simpleClassName + "_" + (counter++);
+	}
+
+	/**
+	 * Saves document to file.
+	 * 
+	 * @param xmlFile
+	 *            destination file.
+	 * @param doc
+	 *            xml document.
+	 * @throws NameSolvingException
+	 *             if cannot save document.
+	 */
+	private void serializetoXML(File xmlFile, Document doc)
+			throws NameSolvingException {
+		try {
+			OutputStream output = new FileOutputStream(xmlFile);
+			OutputFormat outformat = OutputFormat.createPrettyPrint();
+			XMLWriter writer = new XMLWriter(output, outformat);
+			writer.write(doc);
+			writer.flush();
+		} catch (Exception ex) {
+			throw new NameSolvingException(
+					"Error occurs while xml descriptors saving.", ex);
+		}
+	}
+
+	/**
+	 * Gets string value of element in node by it name.
+	 * 
+	 * @param parent
+	 *            parent node.
+	 * @param name
+	 *            element name.
+	 * @return string value of element in node.
+	 */
+	private String getNodeValueByName(Node parent, String name) {
+		Node node = parent.selectSingleNode(name);
+		if (node != null) {
+			return node.getStringValue();
+		}
+		return null;
+	}
+
+	/**
+	 * Gets XPath where need to search already defined references for current
+	 * class defined in current compilation unit and determines type of
+	 * reference required for current class.
+	 * 
+	 * @return XPath in ejb-jar.xml descriptor.
+	 * @throws NameSolvingException
+	 *             if cannot load properties files.
+	 */
+	private String getPathForClass() throws NameSolvingException {
+		loadProperties();
+		Enumeration enumeration = interfaces.keys();
+		while (enumeration.hasMoreElements()) {
+			String ejbInterface = (String) enumeration.nextElement();
+			Iterator types = superInterfaces.iterator();
+			while (types.hasNext()) {
+				Type superType = (Type) types.next();
+				ITypeBinding bind = superType.resolveBinding();
+				if (bind != null
+						&& bind.getQualifiedName().equals(ejbInterface)) {
+					String path = interfaces.getProperty(ejbInterface);
+					return path;
+				}
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * @return true if class is an EJB bean.
+	 */
+	public boolean isEjbBeanClass() {
+		return (pathForClass != null);
+	}
+
+	/**
+	 * Loads all necessary properties files.
+	 * 
+	 * @throws NameSolvingException
+	 *             if cannot load one or more properts files.
+	 */
+	private void loadProperties() throws NameSolvingException {
+		if (interfaces == null) {
+			interfaces = new Properties();
+			try {
+				File propertyFile = new File(INTERFACES_PROP_DIRECTORY + INTERFACES_PROP_FILENAME);
+				interfaces.load(new FileInputStream(propertyFile));
+			} catch (IOException ex) {
+				throw new NameSolvingException(
+						"Cannot read system property file: " + INTERFACES_PROP_FILENAME,
+						ex);
+			}
+		}
+
+		if (beansTypes == null) {
+			beansTypes = new Properties();
+			try {
+				File propertyFile = new File(BEANS_TYPES_PROP_DIRECTORY + BEANS_TYPES_PROP_FILENAME);
+				beansTypes.load(new FileInputStream(propertyFile));
+			} catch (IOException ex) {
+				throw new NameSolvingException(
+						"Cannot read system property file: " + BEANS_TYPES_PROP_FILENAME,
+						ex);
+			}
+		}
+
+		if (beansRefs == null) {
+			beansRefs = new Properties();
+			try {
+				File propertyFile = new File(BEANS_REFS_PROP_DIRECTORY + BEANS_REFS_PROP_FILENAME);
+				beansRefs.load(new FileInputStream(propertyFile));
+			} catch (IOException ex) {
+				throw new NameSolvingException(
+						"Cannot read system property file: " + BEANS_REFS_PROP_FILENAME,
+						ex);
+			}
+		}
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/AbsoluteNameSolver.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/BlockVisitor.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/BlockVisitor.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/BlockVisitor.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/BlockVisitor.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,464 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.geronimo.devtools.j2g.sources.environment;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.geronimo.devtools.j2g.common.FatalToolException;
+import org.apache.geronimo.devtools.j2g.common.IOutput;
+import org.apache.geronimo.devtools.j2g.common.Tool;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.Assignment;
+import org.eclipse.jdt.core.dom.CastExpression;
+import org.eclipse.jdt.core.dom.ClassInstanceCreation;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.Expression;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.SimpleName;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.core.dom.Type;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+
+
+/**
+ * The algorithm of work as follows: <br>
+ * 1. Searches invocations of the <code>javax.naming.Context#lookup</code> method; <br>
+ * 
+ * 2. If the lookup meets the following conditions: <br>
+ * a) It is performed from an EJB;<br>
+ * b) JNDI name is a string constant;<br>
+ * c) JNDI name is a path in the EJB environment (starts with "java:comp/env" or equals to
+ * "java:comp/UserTransaction", "java:comp/ORB" );<br>
+ * then the plug-in considers this lookup as correct. <br>
+ * 
+ * 3. If the lookup meets the following conditions: <br>
+ * a) It is performed from an EJB;<br>
+ * b) JNDI name is a string constant;<br>
+ * c) JNDI name is a full direct path;<br>
+ * d) EJB does not have any environment references; <br>
+ * then the plug-in should add the resource reference in the EJB component's deployment descriptor
+ * and replace the use of a direct name with this name from the component's environment.<br>
+ * 
+ * 4. Otherwise the plug-in outputs a warning message that the lookup might be incorrect.
+ */
+public class BlockVisitor extends ASTVisitor {
+
+	/** Lookup method simple name. */
+	private final static String LOOKUP_METHOD_NAME = "lookup";
+
+	/** Full qualified name for Context interface. */
+	private final static String CONTEXT_INTERFACE_NAME = "javax.naming.Context";
+
+	/** Full qualified name for InitialContext class. */
+	private final static String INIT_CONTEXT_CLASSNAME = "javax.naming.InitialContext";
+
+	/** Initial context. */
+	private final static String INITIAL_CONTEXT = "";
+
+	/** Compilation unit. */
+	private CompilationUnit unit;
+
+	/** Tool output. */
+	private IOutput out;
+
+	/** HashMap for the context variables. */
+	private HashMap varsMap;
+
+	/** Solver for absolute JNDI names used in lookup methods. */
+	private AbsoluteNameSolver solver;
+
+	/** Allowed objects for JNDI lookup. */
+	private final static String[] ALLOWED_OBJECTS = { "java:comp/UserTransaction", "java:comp/ORB" };
+
+	/** Local context. */
+	private final static String LOCAL_CONTEXT = "java:comp/env/";
+
+	/** Meta-inf directory default name. */
+	public final static String META_INF_DIR = "META-INF";
+
+	/** EJB deployment descriptor default filename. */
+	public final static String EJB_JAR_FILE = "ejb-jar.xml";
+
+	/** JBoss descriptor default filename. */
+	public final static String JBOSS_XML_FILE = "jboss.xml";
+
+	/** Last catched string literal for lookup method. */
+	private StringLiteral lastStrLiteral;
+
+	/**
+	 * Visitor constructor. Setups compilation unit and output.
+	 * @param unit current compilation unit.
+	 * @param solver initialized absolute names solver for visiting class.
+	 */
+	public BlockVisitor(CompilationUnit unit, AbsoluteNameSolver solver) {
+		super(false);
+		this.unit = unit;
+		this.solver = solver;
+		varsMap = new HashMap();
+		out = Tool.getCurrent().getOutput();
+	}
+
+	/**
+	 * Checks method and if it is a javax.naming.Context#lookup resolves and analizes context.
+	 * @param methodInvocation method invocation.
+	 */
+	public boolean visit(MethodInvocation methodInvocation) {
+		int position = methodInvocation.getStartPosition();
+		if (isLookupMethodInvocation(methodInvocation)) {
+			String jndiName = getLookupArgument(methodInvocation);
+			try {
+				analizeLookupJNDIName(jndiName, position);
+			} catch (FatalToolException ex) {
+				out.error(BlockVisitor.class.getSimpleName(), "Cannot check correctness of lookup method using: " + ex.getMessage(), unit.getLineNumber(position), unit.getColumnNumber(position));
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * If it's an assign for a variable which type is javax.naming.Context then analizes correctness
+	 * of initializer and puts variable assignment to the varsMap.
+	 * @param assignment assignment.
+	 */
+	public boolean visit(Assignment assignment) {
+		Expression leftSide = assignment.getLeftHandSide();
+		if (leftSide instanceof SimpleName) {
+			SimpleName varName = (SimpleName) leftSide;
+			if (isValidType(varName)) {
+				Expression rightSide = assignment.getRightHandSide();
+				ASTNode parent = getParentBlock(assignment);
+				int exprEnd = parent.getStartPosition() + parent.getLength();
+				if (isValidContextInitializer(rightSide)) {
+					String key = varName.getIdentifier();
+					VarContext var = new VarContext(INITIAL_CONTEXT, exprEnd, true);
+					varsMap.put(key, var);
+					return false;
+				}
+				else {
+					String cast = checkCastToContext(rightSide);
+					if (cast != null) {
+						String key = varName.getIdentifier();
+						VarContext var = new VarContext(cast, exprEnd, true);
+						varsMap.put(key, var);
+						return false;
+					}
+					else {
+						String key = varName.getIdentifier();
+						VarContext var = new VarContext(INITIAL_CONTEXT, exprEnd, false);
+						varsMap.put(key, var);
+						return true;
+					}
+				}
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * If it's the declaration of the variable which type is javax.naming.Context and initializer
+	 * not null then analizes it correctness and puts variable assignment to the varsMap.
+	 * @param fragment variable declaration fragment.
+	 */
+	public boolean visit(VariableDeclarationFragment fragment) {
+		Expression initializer = fragment.getInitializer();
+		if (initializer != null) {
+			SimpleName varName = fragment.getName();
+			if (isValidType(varName)) {
+				ASTNode parent = getParentBlock(fragment);
+				int exprEnd = parent.getStartPosition() + parent.getLength();
+				if (isValidContextInitializer(initializer)) {
+					String key = varName.getIdentifier();
+					VarContext var = new VarContext(INITIAL_CONTEXT, exprEnd, true);
+					varsMap.put(key, var);
+					return false;
+				}
+				else {
+					String cast = checkCastToContext(fragment.getInitializer());
+					if (cast != null) {
+						String key = varName.getIdentifier();
+						VarContext var = new VarContext(cast, exprEnd, true);
+						varsMap.put(key, var);
+						return false;
+					}
+					else {
+						String key = varName.getIdentifier();
+						VarContext var = new VarContext(INITIAL_CONTEXT, exprEnd, false);
+						varsMap.put(key, var);
+						return true;
+					}
+				}
+			}
+			else {
+				return true;
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Checks that expression is a creation of <code>InitailContext</code> class instance without
+	 * parameters.
+	 * @param expr initializer expression.
+	 * @return true if expr looks like this <code>new InitialContext()</code>.
+	 */
+	private boolean isValidContextInitializer(Expression expr) {
+		if (expr instanceof ClassInstanceCreation) {
+			ClassInstanceCreation instanceCreation = (ClassInstanceCreation) expr;
+			Type type = instanceCreation.getType();
+			ITypeBinding typeBind = type.resolveBinding();
+			if (typeBind.getQualifiedName().equals(INIT_CONTEXT_CLASSNAME)) {
+				if (instanceCreation.arguments().isEmpty()) {
+					return true;
+				}
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Checks that expression has <code>javax.naming.Context</code> type or its type implements
+	 * that interface.
+	 * 
+	 * @param expr expression which will be checked.
+	 * @return true if expression has <code>javax.naming.Context</code> type or its type
+	 *         implements that interface.
+	 */
+	private boolean isValidType(Expression expr) {
+		ITypeBinding bind = expr.resolveTypeBinding();
+		if (bind != null) {
+			if (bind.getQualifiedName().equals(CONTEXT_INTERFACE_NAME)) {
+				return true;
+			}
+			else {
+				ITypeBinding[] interfaces = bind.getInterfaces();
+				for (int i = 0; i < interfaces.length; i++) {
+					if (interfaces[i].getQualifiedName().equals(CONTEXT_INTERFACE_NAME)) {
+						return true;
+					}
+				}
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * Checks that expression is cast object returned by <code>javax.naming.Context#lookup</code>
+	 * method to the <code>javax.naming.Context</code> type.
+	 * 
+	 * @param expr expression which will be checked.
+	 * @return JNDI name for Context presented by cast or <code>null</code> if it cannot be
+	 *         unambiguously resolved or if expression is invalid.
+	 */
+	private String checkCastToContext(Expression expr) {
+		if (expr != null && isValidType(expr)) {
+			if (expr instanceof CastExpression) {
+				CastExpression castExpr = (CastExpression) expr;
+				Expression castArg = castExpr.getExpression();
+				if (castArg instanceof MethodInvocation) {
+					MethodInvocation invocation = (MethodInvocation) castArg;
+					if (isLookupMethodInvocation(invocation)) {
+						String name = getLookupArgument(invocation);
+						return name;
+					}
+					else {
+						return null;
+					}
+
+				}
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Checks a javax.naming.Context#lookup method invocation and tries to resolve context.
+	 * @param invocation lookup method invocation node.
+	 * @return JNDI name for object returned by lookup method or <code>null</code> if it cannot be
+	 *         unambiguously resolved or it is not lookup method.
+	 */
+	private String getLookupArgument(MethodInvocation invocation) {
+		Expression expr = invocation.getExpression();
+		String history = getExpressionHistory(expr);
+		if (history != null) {
+			List arguments = invocation.arguments();
+			if (arguments.size() != 0) {
+				Expression arg = (Expression) arguments.get(0);
+				if (arg instanceof StringLiteral) {
+					StringLiteral literal = (StringLiteral) arg;
+					String resultContext = history + literal.getLiteralValue();
+					this.lastStrLiteral = literal;
+					return resultContext;
+				}
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Checks is it lookup method or not.
+	 * @param invocation method invocation node.
+	 * @return <code>true</code> if it is a javax.naming.Context#lookup and <code>false</code>
+	 *         in another cases.
+	 */
+	private boolean isLookupMethodInvocation(MethodInvocation invocation) {
+		if (invocation.getName().getIdentifier().equals(LOOKUP_METHOD_NAME)) {
+			Expression expr = invocation.getExpression();
+			if (isValidType(expr)) {
+				return true;
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * If expr is a variable then gets variable context from varsMap and returns its value if it's
+	 * correct.
+	 * @param expr which type is a <code>javax.naming.Context</code>.
+	 * @return JNDI name presented by this expression or <code>null</code> if it cannot be
+	 *         unambiguously resolved
+	 */
+	private String getExpressionHistory(Expression expr) {
+		if (expr instanceof SimpleName) {
+			SimpleName name = (SimpleName) expr;
+			String varName = name.getIdentifier();
+			VarContext var = (VarContext) varsMap.get(varName);
+			if (var != null && var.isValid() && var.getAreaEnd() > name.getStartPosition()) {
+				return var.getJNDIName();
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Gets parent node for a variable declaration fragment.
+	 * @param fragment
+	 * @return parent block for the specified <code>VariableDeclarationFragment</code>.
+	 */
+	private ASTNode getParentBlock(VariableDeclarationFragment fragment) {
+		return fragment.getParent().getParent().getParent();
+	}
+
+	/**
+	 * Gets parent node for an assignment.
+	 * @param assignment
+	 * @return parent block for the specified <code>Assignment</code>.
+	 */
+	private ASTNode getParentBlock(Assignment assignment) {
+		return assignment.getParent().getParent();
+	}
+
+	/**
+	 * Checks the correctness of the JNDI name.
+	 * @param name JNDI name.
+	 * @param position position in the source file.
+	 * @throws FatalToolException if any exceptions occurs while checks JNDI name.
+	 */
+	private void analizeLookupJNDIName(String name, int position) throws FatalToolException {
+		if (name != null) {
+			if (!isValidJNDIName(name)) {
+				String literalValue = lastStrLiteral.getLiteralValue();
+				if (literalValue.equals(name)) {
+					String solvedName = solveAbsoluteName(name, position);
+					if (solvedName != null) {
+						String localJNDIName = LOCAL_CONTEXT + solvedName;
+						out.info(BlockVisitor.class.getSimpleName(), "A reference to the current EJB was added to " + EJB_JAR_FILE + " deployment descriptor. Use of direct name '" + name + "' was replaced by '" + localJNDIName + "' local name.", unit.getLineNumber(position), unit.getColumnNumber(position));
+						lastStrLiteral.setLiteralValue(localJNDIName);
+						return;
+					} 
+					else {
+						out.warn(BlockVisitor.class.getSimpleName(), "Use of an absolute JNDI name might be incorrect.", unit.getLineNumber(position), unit.getColumnNumber(position));
+						return;
+					}
+				}
+			} else{
+				return;
+			}
+			
+		} 
+		out.warn(BlockVisitor.class.getSimpleName(), "Lookup use might be incorrect.", unit.getLineNumber(position), unit.getColumnNumber(position));
+	}
+
+	/**
+	 * Tries to find META-INF/ejb-jar.xml and META-INF/jboss.xml descriptors and if its exests tries
+	 * to add references for JNDI name to its.
+	 * @param absoluteName absolute JNDI name.
+	 * @param position position in the source file.
+	 * @return JNDI name in local context or null if cannot unambiguously solve references.
+	 * @throws FatalToolException if any errors occurs while solving name.
+	 */
+	private String solveAbsoluteName(String absoluteName, int position) throws FatalToolException {
+		if (solver.isEjbBeanClass()) {
+			try {
+				String pack = unit.getPackage().getName().getFullyQualifiedName().replace('.', File.separatorChar);
+				String unitFile = unit.getJavaElement().getUnderlyingResource().getRawLocation().toFile().getAbsolutePath();
+				String rootDir = unitFile.substring(0, unitFile.lastIndexOf(pack));
+				File metaInfDir = new File(rootDir + META_INF_DIR);
+				if (metaInfDir.exists() && metaInfDir.isDirectory()) {
+					File ejbJar = new File(metaInfDir, EJB_JAR_FILE);
+					File jbossXml = new File(metaInfDir, JBOSS_XML_FILE);
+					if (ejbJar.exists()) {
+						if (jbossXml.exists()) {
+							String solvedName = solver.solveName(absoluteName, position, ejbJar, jbossXml);
+							return solvedName;
+						}
+						else {
+							out.error(BlockVisitor.class.getSimpleName(), "Cannot add reference for absolute name '" + absoluteName + "' : cannot find " + jbossXml.getAbsolutePath() + " file.", unit.getLineNumber(position), unit.getColumnNumber(position));
+						}
+					}
+					else {
+						out.error(BlockVisitor.class.getSimpleName(), "Cannot add reference for absolute name '" + absoluteName + "' : cannot find " + ejbJar.getAbsolutePath() + " file.", unit.getLineNumber(position), unit.getColumnNumber(position));
+					}
+
+				}
+				else {
+					out.error(BlockVisitor.class.getSimpleName(), "Cannot add reference for absolute name '" + absoluteName + "' : cannot find " + metaInfDir.getAbsolutePath() + " directory.", unit.getLineNumber(position), unit.getColumnNumber(position));
+					return null;
+				}
+
+			} catch (JavaModelException ex) {
+				throw new FatalToolException("Cannot access to source file.", ex);
+			} catch (NameSolvingException ex) {
+				out.error(BlockVisitor.class.getSimpleName(), "Cannot add reference for absolute name '" + absoluteName + "' :" + ex.getMessage());
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Checks correctness of constant JNDI name.
+	 * @param name JNDI name.
+	 * @return true if it's correct JNDI name (Starts with 'java:comp/env/' or equals to allowed
+	 *         strings).
+	 */
+	private boolean isValidJNDIName(String name) {
+		if (name.startsWith(LOCAL_CONTEXT)) {
+			return true;
+		}
+		for (int i = 0; i < ALLOWED_OBJECTS.length; i++) {
+			if (ALLOWED_OBJECTS[i].equals(name)) {
+				return true;
+			}
+		}
+		return false;
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/BlockVisitor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/EjbEnvJavaMigration.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/EjbEnvJavaMigration.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/EjbEnvJavaMigration.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/EjbEnvJavaMigration.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,66 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.geronimo.devtools.j2g.sources.environment;
+
+import org.apache.geronimo.devtools.j2g.common.IJavaMigration;
+import org.apache.geronimo.devtools.j2g.common.IOutput;
+import org.apache.geronimo.devtools.j2g.common.Tool;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+
+
+/**
+ * @see IJavaMigration
+ */
+public class EjbEnvJavaMigration implements IJavaMigration {
+	/**
+	 * Plug-in name.
+	 */
+	private final static String PLUGIN_NAME = "EJB environment plug-in";
+
+	/**
+	 * Tool output.
+	 */
+	private IOutput out;
+
+	/**
+	 * Finds access of a component to the named object in the source code outside of its own
+	 * environment and tries to ascertain is it correct or not.
+	 * @param source compilation unit for migration.
+	 * @throws JavaModelException
+	 */
+	public boolean migrate(ASTNode source) {
+		out = Tool.getCurrent().getOutput();
+		if (source instanceof CompilationUnit) {
+			CompilationUnit unit = (CompilationUnit) source;
+			out.info(EjbEnvJavaMigration.class.getSimpleName(), "[" + PLUGIN_NAME + "] " + "Migration started: " + unit.getJavaElement().getElementName());
+			long initialChanges = unit.getAST().modificationCount();
+			MethodsVisitor methodsVisitor = new MethodsVisitor(unit);
+			unit.accept(methodsVisitor);
+			//methodsVisitor.visit(unit); 
+			long finalChanges = unit.getAST().modificationCount();
+			out.info(EjbEnvJavaMigration.class.getSimpleName(), "[" + PLUGIN_NAME + "] " + "Migration finished: " + unit.getJavaElement().getElementName());
+			return initialChanges != finalChanges;
+		}
+		else {
+			out.error(EjbEnvJavaMigration.class.getSimpleName(), "[" + PLUGIN_NAME + "] " + "Wrong type of source node.");
+		}
+		return false;
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/EjbEnvJavaMigration.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/MethodsVisitor.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/MethodsVisitor.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/MethodsVisitor.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/MethodsVisitor.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,83 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.geronimo.devtools.j2g.sources.environment;
+
+import java.util.List;
+
+import org.apache.geronimo.devtools.j2g.common.Tool;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.Block;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.MethodDeclaration;
+import org.eclipse.jdt.core.dom.SimpleName;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+
+
+/**
+ * Visits types declarations, creates absolute name solvers and then visits methods declarations of
+ * these types. For each method declaration creates and starts {@link BlockVisitor}.
+ */
+public class MethodsVisitor extends ASTVisitor {
+	/** Compilation unit. */
+	private CompilationUnit unit;
+
+	/** Solver for absolute JNDI names. */
+	private AbsoluteNameSolver solver;
+
+	/**
+	 * Constructor.
+	 * @param unit compilation unit.
+	 */
+	public MethodsVisitor(CompilationUnit unit) {
+		super(false);
+		this.unit = unit;
+	}
+
+	/**
+	 * Creates absolute names solver for this type declaration.
+	 * @param declaration type declaration.
+	 */
+	public boolean visit(TypeDeclaration declaration) {
+		List superInterfaces = declaration.superInterfaceTypes();
+		SimpleName className = declaration.getName();
+		ITypeBinding bind = className.resolveTypeBinding();
+		String qualifiedName = bind.getQualifiedName();
+		try {
+			solver = new AbsoluteNameSolver(qualifiedName, superInterfaces, unit);
+			return true;
+		} catch (NameSolvingException e) {
+			Tool.getCurrent().getOutput().fatal(MethodsVisitor.class.getSimpleName(), "Internal error occured. " + e.getMessage());
+		}
+		return false;
+	}
+
+	/**
+	 * Creates and starts {@link BlockVisitor} if method is not empty.
+	 * @param methodDeclaration method declaration.
+	 */
+	public boolean visit(MethodDeclaration methodDeclaration) {
+		Block block = methodDeclaration.getBody();
+		if (block != null) {
+			BlockVisitor blockVisitor = new BlockVisitor(unit, solver);
+			methodDeclaration.accept(blockVisitor);
+			//blockVisitor.visit(block); 
+		}
+		return false;
+	}
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/MethodsVisitor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/NameSolvingException.java
URL: http://svn.apache.org/viewvc/geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/NameSolvingException.java?rev=582932&view=auto
==============================================================================
--- geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/NameSolvingException.java (added)
+++ geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/NameSolvingException.java Mon Oct  8 11:50:53 2007
@@ -0,0 +1,60 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.geronimo.devtools.j2g.sources.environment;
+
+/**
+ * Exception that indicates exceptions occurs while AbsoluteNameSolver works.
+ */
+public class NameSolvingException extends Exception {
+
+	/** Serial version UID */
+	private static final long serialVersionUID = 1419666308972177554L;
+
+	/**
+	 * Constructor.
+	 */
+	public NameSolvingException() {
+		super();
+	}
+
+	/**
+	 * Constructor.
+	 * @param msg message.
+	 */
+	public NameSolvingException(String msg) {
+		super(msg);
+	}
+
+	/**
+	 * Constructor.
+	 * @param cause cause.
+	 */
+	public NameSolvingException(Throwable cause) {
+		super(cause);
+	}
+
+	/**
+	 * Constructor.
+	 * @param msg message.
+	 * @param cause cause.
+	 */
+	public NameSolvingException(String msg, Throwable cause) {
+		super(msg, cause);
+	}
+
+}

Propchange: geronimo/devtools/j2g/trunk/plugins/org.apache.geronimo.devtools.j2g.sources/src/org/apache/geronimo/devtools/j2g/sources/environment/NameSolvingException.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message