text:
package org.gw4e.eclipse.facade;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Generated;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
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.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.IAnnotationBinding;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMemberValuePairBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MemberValuePair;
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.NormalAnnotation;
import org.eclipse.jdt.core.dom.PackageDeclaration;
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.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.actions.OrganizeImportsAction;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.search.core.text.TextSearchEngine;
import org.eclipse.search.core.text.TextSearchMatchAccess;
import org.eclipse.search.core.text.TextSearchRequestor;
import org.eclipse.search.ui.text.FileTextSearchScope;
import org.eclipse.swt.widgets.Display;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import org.graphwalker.core.generator.PathGenerator;
import org.graphwalker.core.generator.PathGeneratorBase;
import org.graphwalker.core.machine.ExecutionContext;
import org.graphwalker.java.annotation.GraphWalker;
import org.graphwalker.java.annotation.Model;
import org.gw4e.eclipse.builder.Location;
import org.gw4e.eclipse.conversion.ClassExtension;
import org.gw4e.eclipse.refactoring.Helper;
import org.gw4e.eclipse.wizard.convert.AbstractPostConversion;

public class JDTManager {

	public static List<IFile> findAvailableExecutionContextAncestors(IFile file) {
		List<IFile> files = new ArrayList<IFile>();

		IResource[] roots = { file.getProject() };
		String[] fileNamePatterns = new String[] { "*.java" };
		FileTextSearchScope scope = FileTextSearchScope.newSearchScope(roots, fileNamePatterns, false);
		IPath path = Helper.buildGeneratedAnnotationValue(file);
		Pattern pattern = Pattern.compile(Helper.getGeneratedAnnotationRegExp(path));
		TextSearchRequestor collector = new TextSearchRequestor() {
			@Override
			public boolean acceptPatternMatch(TextSearchMatchAccess matchAccess) throws CoreException {
				IFile file = matchAccess.getFile();
				files.add(file);
				return true;
			}
		};
		TextSearchEngine.create().search(scope, collector, pattern, new NullProgressMonitor());
		return files;
	}

	/**
	 * @param elt
	 * @return
	 * @throws JavaModelException
	 */
	public static String getFullyQualifiedName(IJavaElement elt) throws JavaModelException {
		IPackageFragmentRoot[] roots = elt.getJavaProject().getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			if (roots[i].getPath().isPrefixOf(elt.getPath())) {
				IPath p = elt.getPath().makeRelativeTo(roots[i].getPath());
				return p.toString();
			}
		}
		return elt.getElementName();
	}

	public static String getJavaFullyQualifiedName(IJavaElement elt) throws JavaModelException {
		String name = getFullyQualifiedName(elt);
		name = name.split("\\.")[0];
		name = name.replaceAll("\\/", "\\.");
		return name;
	}

	/**
	 * Find the path of the graph model file that is the origin of the passed
	 * type The one which has been converted ..
	 *
	 * @param project
	 * @param itype
	 * @return
	 * @throws JavaModelException
	 */
	public static IPath getGraphModelPath(IProject project, IType itype) throws JavaModelException {
		IPath path = findPathInGeneratedAnnotation(project, itype);
		if (path == null) {
			path = findPathInStaticField(project, itype);
		}
		return path;
	}

	/**
	 * @param project
	 * @param itype
	 * @return
	 * @throws JavaModelException
	 */
	private static IPath findPathInGeneratedAnnotation(IProject project, IType itype) throws JavaModelException {
		ICompilationUnit cu = itype.getCompilationUnit();
		List<IAnnotationBinding> annotations = resolveAnnotation(cu, Generated.class).getAnnotations();
		if ((annotations != null) && (annotations.size() > 0)) {
			IAnnotationBinding ab = annotations.get(0);
			IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
			for (int i = 0; i < attributes.length; i++) {
				IMemberValuePairBinding attribut = attributes[i];
				if (attribut.getName().equalsIgnoreCase("value")) {
					Object[] o = (Object[]) attribut.getValue();
					if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) {
						try {
							IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim());
							return p;
						} catch (Exception e) {
							ResourceManager.logException(e);
							return null;
						}
					}
				}
			}
		}
		return null;
	}

	public static ICompilationUnit[] getOrCreateGeneratedTestInterfaces(IProject project)
			throws CoreException, FileNotFoundException {

		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		IPath folderForMain = project.getFullPath()
				.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), true));
		IPath folderForTest = project.getFullPath()
				.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), false));
		if (ResourceManager.getResource(folderForMain.toString()) == null
				&& ResourceManager.getResource(folderForTest.toString()) == null) {
			throw new IllegalStateException(
					"No target/generated-sources or target/generated-test-sources folders found");
		}

		// In main resource folder
		ICompilationUnit[] inMain = getExistingGeneratedTestInterfaces(project, true);
		// In test resource folder
		ICompilationUnit[] inTest = getExistingGeneratedTestInterfaces(project, false);
		ICompilationUnit[] ret = new ICompilationUnit[inMain.length+inTest.length];
		System.arraycopy(inMain, 0, ret, 0, inMain.length);
		System.arraycopy(inTest, 0, ret, inMain.length, inTest.length);
		return ret;
	}

	public static IPath guessPackageRootFragment(IProject project, boolean main)
			throws CoreException, FileNotFoundException {
		IPath folder = project.getFullPath()
				.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main));

		IResource interfaceFolder = ResourceManager.toResource(folder);
		List<IPath> paths = new ArrayList<IPath>();
		if (interfaceFolder != null) {
			interfaceFolder.accept(new IResourceVisitor() {
				@Override
				public boolean visit(IResource resource) throws CoreException {
					IJavaElement element = JavaCore.create(resource);
					if (element != null && element instanceof ICompilationUnit) {
						try {
							ICompilationUnit cu = (ICompilationUnit) element;
							CompilationUnit ast = parse(cu);
							ast.accept(new ASTVisitor() {
								public boolean visit(PackageDeclaration node) {
									PackageDeclaration decl = (PackageDeclaration) node;
									String pkgname = decl.getName().getFullyQualifiedName();
									int sizePath = pkgname.split("\\.").length;
									paths.add(resource.getParent().getFullPath().removeLastSegments(sizePath));
									return false;
								}
							});
						} catch (Exception e) {
							ResourceManager.logException(e);
						}
					}
					return true;
				}
			});
		}
		if (paths.size() == 0)
			return null;
		return paths.get(0);
	}

	/**
	 * @param project
	 * @return
	 * @throws CoreException
	 * @throws FileNotFoundException
	 */
	public static ICompilationUnit[] getExistingGeneratedTestInterfaces(IProject project, boolean main)
			throws CoreException, FileNotFoundException {
		IPath folder = project.getFullPath()
				.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main));
		List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();
		IResource interfaceFolder = ResourceManager.toResource(folder);
		if (interfaceFolder != null) {
			interfaceFolder.accept(new IResourceVisitor() {
				@Override
				public boolean visit(IResource resource) throws CoreException {
					IJavaElement element = JavaCore.create(resource);
					if (element != null && element instanceof ICompilationUnit) {
						try {
							ICompilationUnit cu = (ICompilationUnit) element;
							IType interf = cu.findPrimaryType();
							if (interf != null && interf.isInterface()) {
								units.add(cu);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					return true;
				}
			});
		}
		ICompilationUnit[] ret = new ICompilationUnit[units.size()];
		units.toArray(ret);
		return ret;
	}

	/**
	 * @param project
	 * @param itype
	 * @return
	 * @throws JavaModelException
	 */
	public static IPath findPathInModelAnnotation(IProject project, IType itype) throws JavaModelException {
		ICompilationUnit cu = itype.getCompilationUnit();
		List<IAnnotationBinding> annotations = resolveAnnotation(cu, Model.class).getAnnotations();
		if ((annotations != null) && (annotations.size() > 0)) {
			IAnnotationBinding ab = annotations.get(0);
			IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
			for (int i = 0; i < attributes.length; i++) {
				IMemberValuePairBinding attribut = attributes[i];
				if (attribut.getName().equalsIgnoreCase("value")) {
					Object[] o = (Object[]) attribut.getValue();
					if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) {
						try {
							IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim());
							return p;
						} catch (Exception e) {
							ResourceManager.logException(e);
							return null;
						}
					}
				}
			}
		}
		return null;
	}

	private static boolean isContext(ITypeBinding tbinding) {
		String executionContextClass = org.graphwalker.core.machine.ExecutionContext.class.getName();
		String contextClass = org.graphwalker.core.machine.Context.class.getName();
		while (tbinding != null) {
			String clazz = tbinding.getQualifiedName();
			if (executionContextClass.equals(clazz))
				return true;
			if (contextClass.equals(clazz))
				return true;
			ITypeBinding[] interfaces = tbinding.getInterfaces();
			for (int i = 0; i < interfaces.length; i++) {
				ITypeBinding interf = interfaces[i];
				if (contextClass.equals(interf.getQualifiedName()))
					return true;
			}
			tbinding = tbinding.getSuperclass();
		}
		return false;

	}

	private static boolean isTestBuilder(ITypeBinding tbinding) {

		String testBuilderClass = org.graphwalker.java.test.TestBuilder.class.getName();
		while (tbinding != null) {
			String clazz = tbinding.getQualifiedName();
			if (testBuilderClass.equals(clazz))
				return true;

		}
		return false;

	}

	public static AnnotationParsing findAnnotationParsingInGeneratedAnnotation(ICompilationUnit cu, String attribut) {
		AnnotationParsing annoParsing = resolveAnnotation(cu, Generated.class, attribut);
		return annoParsing;
	}

	/**
	 * @param cu
	 * @return
	 * @throws JavaModelException
	 */
	public static AnnotationParsing findAnnotationParsingInGraphWalkerAnnotation(ICompilationUnit cu, String attribut) {
		AnnotationParsing annoParsing = resolveAnnotation(cu, GraphWalker.class, attribut);
		return annoParsing;
	}

	public static AnnotationParsing findAnnotationParsingInModelAnnotation(ICompilationUnit cu, String attribut) {
		AnnotationParsing annoParsing = resolveAnnotation(cu, Model.class, attribut);
		return annoParsing;
	}

	/**
	 * @param cu
	 * @return
	 */
	public static String findPathGeneratorInGraphWalkerAnnotation(ICompilationUnit cu) {
		CompilationUnit ast = parse(cu);
		Map<String, String> ret = new HashMap<String, String>();
		ast.accept(new ASTVisitor() {
			public boolean visit(MemberValuePair node) {
				String name = node.getName().getFullyQualifiedName();
				if ("value".equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) {
					IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding();
					String qname = annoBinding.getAnnotationType().getQualifiedName();
					if (GraphWalker.class.getName().equals(qname)) {
						StringLiteral sl = (StringLiteral) node.getValue();
						ret.put("ret", sl.getLiteralValue());
					}
				}
				return true;
			}
		});
		return ret.get("ret");
	}

	/**
	 * @param project
	 * @param itype
	 * @return
	 */
	public static Set<String> findPathGeneratorClassInstanceCreation(IJavaProject project, IType itype) {
		Set<String> ret = new HashSet<String>();
		ICompilationUnit cu = itype.getCompilationUnit();
		CompilationUnit ast = parse(cu);

		ast.accept(new ASTVisitor() {
			public boolean visit(ClassInstanceCreation node) {
				Type createdType = node.getType();
				ITypeBinding binding = createdType.resolveBinding();
				IType boundType = (IType) binding.getJavaElement();
				try {
					IType execContextType = project.findType(PathGeneratorBase.class.getName());
					ITypeHierarchy th = boundType.newTypeHierarchy(null);
					if (th.contains(execContextType)) {
						int start = node.getStartPosition();
						int end = node.getLength();
						try {
							String code = cu.getSource().substring(start, start + end);
							ret.add(code);
						} catch (JavaModelException e) {
							ResourceManager.logException(e);
						}
					}
					;
				} catch (JavaModelException e) {
					ResourceManager.logException(e);
				}
				return true;
			}
		});
		return ret;
	}

	/**
	 * @param project
	 * @param itype
	 * @return
	 * @throws JavaModelException
	 */
	public static Map<String, List<String>> findSetPathGeneratorInvocation(IProject project, IType itype)
			throws JavaModelException {
		Map<String, List<String>> ret = new HashMap<String, List<String>>();
		ICompilationUnit cu = itype.getCompilationUnit();
		CompilationUnit ast = parse(cu);

		ast.accept(new ASTVisitor() {
			public boolean visit(MethodDeclaration node) {
				List<?> modifiers = (List<?>) node.getStructuralProperty(MethodDeclaration.MODIFIERS2_PROPERTY);
				for (Object modifier : modifiers) {
					if (modifier instanceof org.eclipse.jdt.core.dom.Annotation) {
						IAnnotationBinding annotationBinding = ((org.eclipse.jdt.core.dom.Annotation) modifier)
								.resolveAnnotationBinding();
						if (annotationBinding != null) {

							final String qualifiedName = annotationBinding.getAnnotationType().getQualifiedName();

							if ("org.junit.Test".equalsIgnoreCase(qualifiedName)) {
								Map<String, String> variables = new HashMap<String, String>();
								node.accept(new ASTVisitor() {
									public boolean visit(VariableDeclarationStatement node) {
										for (int i = 0; i < node.fragments().size(); ++i) {
											VariableDeclarationFragment frag = (VariableDeclarationFragment) node
													.fragments().get(i);
											if (isContext(node.getType().resolveBinding())) {
												Expression initializer = frag.getInitializer();
												JDTManager.ExpressionVisitor ev = new ExpressionVisitor(variables);
												initializer.accept(ev);
												if (ev.getValue() != null) {
													variables.put(frag.getName().getFullyQualifiedName(),
															ev.getValue());
												}
											}
										}
										return true;
									}

									public boolean visit(MethodInvocation node) {
										SimpleName simpleName = node.getName();

										IBinding bding = simpleName.resolveBinding();

										if (bding instanceof IMethodBinding) {
											IMethodBinding imb = (IMethodBinding) bding;

											// TestBuilder builder = new TestBuilder().addContext(context, MODEL_PATH, new RandomPath(new EdgeCoverage(100)));
											if ("addContext".equalsIgnoreCase(imb.getName())) {
												ITypeBinding[] arguments = imb.getParameterTypes();
												if (arguments.length == 3) {
													if (isTestBuilder(imb.getDeclaringClass()) &&
															PathGenerator.class.getName().equals(arguments[2].getQualifiedName())) {
														System.out.println("--->" + arguments[2].getQualifiedName());
														int start = node.getStartPosition();
														int end = node.getLength();
														try {
															String code = cu.getSource().substring(start, start + end);
															// System.out.println(code);
														} catch (JavaModelException e) {
															ResourceManager.logException(e);
														}
														List args = node.arguments();
														Expression argumentExpression = (Expression) args.get(2);
														ITypeBinding typeBinding = argumentExpression
																.resolveTypeBinding();
														String parameterName = "";
														if (typeBinding != null) {
															parameterName = argumentExpression.toString();
															JDTManager.ExpressionVisitor ev = new ExpressionVisitor(
																	variables);
															Expression expression = node.getExpression();
															expression.accept(ev);
															if (ev.getValue() != null) {
																// String contextClass = ev.getValue();
																String contextClass = itype.getFullyQualifiedName();

																List<String> generators = ret.get(contextClass);
																if (generators == null) {
																	generators = new ArrayList<String>();
																	ret.put(contextClass, generators);
																}

																if (!"null".equals(parameterName)
																		&& !generators.contains(parameterName)) {
																	generators.add(parameterName);
																	System.out.println("*** "  + parameterName);
																}
															}
														}
													}
												}
											}
											if ("setPathGenerator".equalsIgnoreCase(imb.getName())) {
												ITypeBinding[] arguments = imb.getParameterTypes();
												if (arguments.length == 1) {
													if (isContext(imb.getDeclaringClass())
															&& PathGenerator.class.getName()
																	.equals(arguments[0].getQualifiedName())
															&& isContext(imb.getReturnType())) {
														int start = node.getStartPosition();
														int end = node.getLength();
														try {
															String code = cu.getSource().substring(start, start + end);
															// System.out.println(code);
														} catch (JavaModelException e) {
															ResourceManager.logException(e);
														}
														List args = node.arguments();
														Expression argumentExpression = (Expression) args.get(0);
														ITypeBinding typeBinding = argumentExpression
																.resolveTypeBinding();
														String parameterName = "";
														if (typeBinding != null) {
															parameterName = argumentExpression.toString();
															JDTManager.ExpressionVisitor ev = new ExpressionVisitor(
																	variables);
															Expression expression = node.getExpression();
															expression.accept(ev);
															if (ev.getValue() != null) {
																String contextClass = ev.getValue();
																List<String> generators = ret.get(contextClass);
																if (generators == null) {
																	generators = new ArrayList<String>();
																	ret.put(contextClass, generators);
																}

																if (!"null".equals(parameterName)
																		&& !generators.contains(parameterName)) {
																	generators.add(parameterName);
																}
															}
														}
													}
												}
											}
										}
										return true;
									}
								});
							}
						}
					}
				}
				return true;
			}
		});
		return ret;
	}

	static class ExpressionVisitor extends ASTVisitor {
		String value;
		Map<String, String> variables;

		ExpressionVisitor(Map<String, String> variables) {
			this.variables = variables;
		}

		public String getValue() {
			return value;
		}

		public boolean visit(ClassInstanceCreation cic) {
			try {
				this.value = cic.getType().resolveBinding().getQualifiedName().toString();
			} catch (Throwable e) {
			}
			return false;
		}

		public boolean visit(MethodInvocation node) {
			try {
				SimpleName simpleName = node.getName();
				IBinding bding = simpleName.resolveBinding();
				if (bding instanceof IMethodBinding) {
					IMethodBinding imb = (IMethodBinding) bding;
					if (isContext(imb.getReturnType())) {
						this.value = imb.getReturnType().getQualifiedName().toString();
					}
				}
			} catch (Throwable e) {
			}
			return false;
		}

		public boolean visit(SimpleName node) {
			try {
				this.value = variables.get(node.getFullyQualifiedName());
			} catch (Throwable e) {
			}
			return true;
		}

	}

	public static Set<String> findGeneratorFactoryParseInvocation(IProject project, IType itype)
			throws JavaModelException {
		Set<String> ret = new HashSet<String>();
		ICompilationUnit cu = itype.getCompilationUnit();
		CompilationUnit ast = parse(cu);

		ast.accept(new ASTVisitor() {
			public boolean visit(MethodInvocation node) {
				SimpleName simpleName = node.getName();
				IBinding bding = simpleName.resolveBinding();
				if (bding instanceof IMethodBinding) {
					IMethodBinding imb = (IMethodBinding) bding;
					if ("parse".equalsIgnoreCase(imb.getName())) {
						ITypeBinding[] arguments = imb.getParameterTypes();
						if (arguments.length == 1) {
							if (String.class.getName().equals(arguments[0].getQualifiedName())
									&& PathGenerator.class.getName().equals(imb.getReturnType().getQualifiedName())) {
								int start = node.getStartPosition();
								int end = node.getLength();
								try {
									String code = cu.getSource().substring(start, start + end);
									// System.out.println(code);
								} catch (JavaModelException e) {
									ResourceManager.logException(e);
								}
								List args = node.arguments();
								Expression argumentExpression = (Expression) args.get(0);
								ITypeBinding typeBinding = argumentExpression.resolveTypeBinding();
								if (typeBinding != null) {
									if (argumentExpression instanceof StringLiteral) {
										StringLiteral sl = (StringLiteral) argumentExpression;
										String lv = sl.getLiteralValue();
										ret.add(lv);
									}
								}
							}
						}
					}
				}

				return true;
			}
		});
		return ret;
	}

	/**
	 * @param project
	 * @param itype
	 * @return
	 * @throws JavaModelException
	 */
	private static IPath findPathInStaticField(IProject project, IType itype) throws JavaModelException {
		List<IPath> wrapper = new ArrayList<IPath>();
		ICompilationUnit cu = itype.getCompilationUnit();
		CompilationUnit ast = parse(cu);
		ast.accept(new ASTVisitor() {
			public boolean visit(VariableDeclarationFragment node) {
				SimpleName simpleName = node.getName();
				IBinding bding = simpleName.resolveBinding();
				if (bding instanceof IVariableBinding) {
					IVariableBinding binding = (IVariableBinding) bding;
					String type = binding.getType().getBinaryName(); //
					String name = simpleName.getFullyQualifiedName();
					if ("MODEL_PATH".equals(name) && "java.nio.file.Path".equals(type)) {
						Expression expression = node.getInitializer();
						if (expression instanceof MethodInvocation) {
							MethodInvocation mi = (MethodInvocation) expression;
							if ("get".equals(mi.resolveMethodBinding().getName())
									&& "java.nio.file.Path".equals(mi.resolveTypeBinding().getBinaryName())) {
								StringLiteral sl = (StringLiteral) mi.arguments().get(0);
								String argument = sl.getLiteralValue();
								try {
									IPath p = ResourceManager.find(project, argument);
									wrapper.add(p);
								} catch (CoreException e) {
									ResourceManager.logException(e);
								}
							}
						}
					}
				}
				return true;
			}
		});
		if (wrapper.size() > 0)
			return wrapper.get(0);
		return null;
	}

	private static IType getClassesWithAnnotation(ICompilationUnit compilationUnit, Class annotationClass,
			String attributName, boolean valued) throws JavaModelException {
		List<IAnnotationBinding> annotations = resolveAnnotation(compilationUnit, annotationClass).getAnnotations();
		if ((annotations != null) && (annotations.size() > 0)) {
			IAnnotationBinding ab = annotations.get(0);
			IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
			for (int i = 0; i < attributes.length; i++) {
				IMemberValuePairBinding attribut = attributes[i];
				if (attribut.getName().equalsIgnoreCase(attributName)) {
					if (valued) {
						if (String.valueOf(attribut.getValue()).trim().length() > 0) {
							return compilationUnit.findPrimaryType();
						}
					} else {
						if (String.valueOf(attribut.getValue()).trim().length() == 0) {
							return compilationUnit.findPrimaryType();
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * @param projectName
	 * @return
	 * @throws JavaModelException
	 */
	private static List<IType> findClassesWithAnnotation(String projectName, Class annotationClass, String attributName,
			boolean valued) throws JavaModelException {
		List<IType> classList = new ArrayList<IType>();
		IProject project = ResourceManager.getProject(projectName);
		IJavaProject javaProject = JavaCore.create(project);
		IPackageFragment[] packages = javaProject.getPackageFragments();
		for (IPackageFragment packageFragment : packages) {
			for (final ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) {
				if (compilationUnit.exists()) {
					IType type = getClassesWithAnnotation(compilationUnit, annotationClass, attributName, valued);
					if (type != null)
						classList.add(type);
				}
			}
		}
		return classList;
	}

	/**
	 * @param compilationUnit
	 * @param progressMonitor
	 * @return
	 * @throws JavaModelException
	 */

	public static CompilationUnit parse(final ICompilationUnit cu) {
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(cu);
		parser.setResolveBindings(true);
		parser.setEnvironment(null, null, null, true);
		parser.setBindingsRecovery(true);
		final CompilationUnit ast = (CompilationUnit) parser.createAST(new NullProgressMonitor());

		return ast;
	}

	public static boolean hasStartableGraphWalkerAnnotation(Object receiver) {
		ICompilationUnit cu = null;
		if (receiver instanceof ICompilationUnit) {
			cu = (ICompilationUnit) receiver;
			List<IAnnotationBinding> annotations = resolveAnnotation(cu, GraphWalker.class).getAnnotations();
			if ((annotations != null) && annotations.size() > 0) {
				IAnnotationBinding ab = annotations.get(0);
				IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
				for (int i = 0; i < attributes.length; i++) {
					IMemberValuePairBinding attribut = attributes[i];
					if (attribut.getName().toLowerCase().equalsIgnoreCase("start")) {

						if (attribut.getValue() != null && String.valueOf(attribut.getValue()).trim().length() > 0) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	/**
	 * @param testInterface
	 * @return
	 * @throws JavaModelException
	 */
	public static boolean isGraphWalkerExecutionContextClass(ICompilationUnit unit) throws JavaModelException {
		IType[] types = unit.getAllTypes();

		if (types == null || types.length == 0) {
			ResourceManager.logInfo(unit.getJavaProject().getProject().getName(),
					"getAllTypes return null" + unit.getPath());
			return false;
		}
		IType execContextType = unit.getJavaProject().findType(ExecutionContext.class.getName());

		for (int i = 0; i < types.length; i++) {
			IType type = types[i];
			String typeNname = type.getFullyQualifiedName();
			String compilationUnitName = JDTManager.getJavaFullyQualifiedName(unit);
			if (typeNname.equals(compilationUnitName)) {
				try {
					ITypeHierarchy th = types[0].newTypeHierarchy(new NullProgressMonitor());
					return th.contains(execContextType);
				} catch (Exception e) {
					ResourceManager.logException(e);
				}
			}
		}
		return false;
	}

	/**
	 * @param receiver
	 * @return
	 * @throws JavaModelException
	 */
	public static String getGW4EGeneratedAnnotationValue(Object receiver, String attribut) {
		ICompilationUnit cu = null;
		if (receiver instanceof ICompilationUnit) {
			cu = (ICompilationUnit) receiver;
			List<IAnnotationBinding> annotations = resolveAnnotation(cu, Generated.class).getAnnotations();
			if ((annotations != null) && annotations.size() > 0) {
				IAnnotationBinding generated = annotations.get(0);
				IMemberValuePairBinding[] vpb = generated.getAllMemberValuePairs();
				for (int i = 0; i < vpb.length; i++) {
					IMemberValuePairBinding pair = vpb[i];
					if (attribut.equals(pair.getName())) {
						Object[] value = (Object[]) pair.getValue();
						if (value == null || value.length == 0)
							return null;
						return String.valueOf(value[0]);
					}
				}
			}
		}
		return null;
	}

	/**
	 * @param receiver
	 * @return
	 * @throws JavaModelException
	 */
	public static boolean hasGraphWalkerAnnotation(Object receiver) {
		ICompilationUnit cu = null;
		if (receiver instanceof ICompilationUnit) {
			cu = (ICompilationUnit) receiver;
			List<IAnnotationBinding> annotations = resolveAnnotation(cu, GraphWalker.class).getAnnotations();
			return ((annotations != null) && annotations.size() > 0);
		}
		return false;
	}

	public static AnnotationParsing resolveAnnotation(ICompilationUnit cu, Class inputClass) {
		return resolveAnnotation(cu, inputClass, "value");
	}

	/**
	 * @param cu
	 * @param annotationName
	 * @return
	 * @throws JavaModelException
	 */
	public static AnnotationParsing resolveAnnotation(ICompilationUnit cu, Class inputClass, final String attribut) {

		CompilationUnit ast = parse(cu);
		AnnotationParsing ret = new AnnotationParsing();
		String annotationName = inputClass.getName();
		ast.accept(new ASTVisitor() {
			public boolean visit(MemberValuePair node) {
				String name = node.getName().getFullyQualifiedName();
				if (attribut.equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) {
					IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding();
					String qname = annoBinding.getAnnotationType().getQualifiedName();
					if (inputClass.getName().equals(qname)) {
						int start = node.getStartPosition();
						int end = start + node.getLength();
						int lineNumber = ast.getLineNumber(start);
						Location location = new Location(lineNumber, start, end);
						ret.setLocation(location);
					}
				}
				return true;
			}

			public final boolean visit(final TypeDeclaration node) {
				List<?> modifiers = (List<?>) node.getStructuralProperty(TypeDeclaration.MODIFIERS2_PROPERTY);
				for (Object modifier : modifiers) {
					if (modifier instanceof org.eclipse.jdt.core.dom.Annotation) {
						IAnnotationBinding annotationBinding = ((org.eclipse.jdt.core.dom.Annotation) modifier)
								.resolveAnnotationBinding();

						if (annotationBinding != null) {
							final String qualifiedName = annotationBinding.getAnnotationType().getQualifiedName();
							if (annotationName.equalsIgnoreCase(qualifiedName))
								ret.add(annotationBinding);

						}
					}
				}
				return true;
			}
		});
		return ret;
	}

	/**
	 * @param projectName
	 * @return
	 * @throws JavaModelException
	 */
	public static List<IType> getStartableGraphWalkerClasses(String projectName) {
		try {

			return findClassesWithAnnotation(projectName, GraphWalker.class, "start", true);
		} catch (Exception e) {
			ResourceManager.logException(e);
			return new ArrayList<IType>();
		}
	}

	/**
	 * @param projectName
	 * @return
	 */
	public static List<IType> getOrphanGraphWalkerClasses(IType type, boolean hint) {
		try {
			IProject project = ResourceManager.getResource(type.getPath().toString()).getProject();
			String projectName = project.getName();

			List<IType> all = findClassesWithAnnotation(projectName, GraphWalker.class, "value", true);
			if (hint) {
				all = GraphWalkerFacade.getSharedContexts(project, type, all);
				all.remove(type);
			}

			Collections.sort(all, new Comparator() {
				@Override
				public int compare(Object o1, Object o2) {
					IType type1 = (IType) o1;
					IType type2 = (IType) o2;
					return type1.getFullyQualifiedName().compareTo(type2.getFullyQualifiedName());
				}
			});
			return all;
		} catch (Exception e) {
			ResourceManager.logException(e);
			return new ArrayList<IType>();
		}
	}

	/**
	 * Generate a test implementation if it does not exist
	 *
	 * @param implementationFolder
	 * @param implementationFragmentRoot
	 * @param targetPkg
	 * @param interfaceCompUnit
	 * @param monitor
	 * @throws CoreException
	 */
	public static IFile generateTestImplementation(TestResourceGeneration provider, IProgressMonitor monitor)
			throws Exception {

		IFile ifile = provider.toIFile();

		if (ifile.exists()) {
			JDTManager.rename(ifile, monitor);
			ifile.delete(true, monitor);
		}
		if (ifile.exists())
			return null;

		NewExecutionContextClassWizardPageRunner execRunner = new NewExecutionContextClassWizardPageRunner(provider,
				monitor);
		Display.getDefault().syncExec(execRunner);
		IPath path = execRunner.getType().getPath();
		IFile createdFile = (IFile) ResourceManager.getResource(path.toString());
		return createdFile;
	}

	/**
	 * Save the AST int he Compilation Unit
	 *
	 * @param testInterface
	 * @param rewrite
	 * @throws CoreException
	 */
	public static void save(CompilationUnit unit, ASTRewrite rewrite) throws CoreException {

		ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
		IPath path = unit.getJavaElement().getPath();
		try {
			bufferManager.connect(path, null);
			ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
			IDocument document = textFileBuffer.getDocument();
			TextEdit edit = rewrite.rewriteAST(document, null);
			edit.apply(document);
			textFileBuffer.commit(null /* ProgressMonitor */, true /* Overwrite */);
		} catch (Exception e) {
			ResourceManager.logException(e);
		} finally {
			// disconnect the path
			bufferManager.disconnect(path, null);
		}
	}

	/**
	 * @param cu
	 * @param rewrite
	 * @param ast
	 * @param pkgDeclaration
	 */
	private static void addPackageDeclaration(CompilationUnit cu, ASTRewrite rewrite, AST ast,
			String[] pkgDeclaration) {
		PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
		Name name = ast.newName(pkgDeclaration);
		packageDeclaration.setName(name);
		rewrite.set(cu, CompilationUnit.PACKAGE_PROPERTY, packageDeclaration, null);

	}

	/**
	 * @param file
	 * @param cu
	 * @param rewrite
	 * @param ast
	 * @throws JavaModelException
	 */
	private static void addPackageDeclarationIfNeeded(IFile file, CompilationUnit cu, ASTRewrite rewrite, AST ast)
			throws JavaModelException {
		IJavaProject javaProject = JavaCore.create(file.getProject());
		IClasspathEntry[] entries = javaProject.getRawClasspath();
		for (int i = 0; i < entries.length; i++) {
			IClasspathEntry entry = entries[i];
			if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
				if (entry.getPath().isPrefixOf(file.getFullPath())) {
					IPath path = file.getFullPath().makeRelativeTo(entry.getPath());
					path = path.removeLastSegments(1); // remove the file
														// name from the
														// path
					if (path.segmentCount() == 0)
						return; // no package declaration needs to be done
					int length = path.segmentCount();
					String[] pkgDeclaration = new String[length];
					for (int j = 0; j < length; j++) {
						pkgDeclaration[j] = path.segment(j);
					}
					addPackageDeclaration(cu, rewrite, ast, pkgDeclaration);
					return;
				}
			}

		}
	}

	/**
	 * Rename a class name into another name
	 *
	 * @param file
	 * @param oldClassname
	 * @param newName
	 * @param monitor
	 * @return
	 * @throws MalformedTreeException
	 * @throws BadLocationException
	 * @throws CoreException
	 */
	public static IFile renameClass(IFile file, String oldClassname, String newName, IProgressMonitor monitor)
			throws MalformedTreeException, BadLocationException, CoreException {
		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				try {

					ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
					CompilationUnit cu = parse(unit);
					AST ast = cu.getAST();
					ASTRewrite rewrite = ASTRewrite.create(ast);

					String classname = file.getName();
					classname = classname.substring(0, classname.indexOf("."));
					final String clazz = classname;
					ASTVisitor visitor = new ASTVisitor() {
						public boolean visit(SimpleName node) {
							String s = node.getIdentifier();
							if (oldClassname.equalsIgnoreCase(s)) {
								rewrite.replace(node, ast.newSimpleName(newName), null);
							}
							return true;
						}
					};
					cu.accept(visitor);

					addPackageDeclarationIfNeeded(file, cu, rewrite, ast);
					file.refreshLocal(IResource.DEPTH_ZERO, monitor);
					cu = parse(JavaCore.createCompilationUnitFrom(file));
					save(cu, rewrite);
				} catch (Exception e) {
					ResourceManager.logException(e);
				}
			}
		});
		return file;
	}

	/**
	 * @param ifile
	 * @param monitor
	 * @throws JavaModelException
	 */
	public static void rename(IFile ifile, IProgressMonitor monitor) throws JavaModelException {
		if (!ifile.getName().endsWith(".java"))
			return;
		ICompilationUnit unit = JavaCore.createCompilationUnitFrom(ifile);
		String name = ifile.getName();
		String[] segments = name.split("\\.");

		name = segments[0] + System.currentTimeMillis() + "." + segments[1];
		unit.rename(name, false, monitor);
		unit.close();
	}

	/**
	 * @param file
	 * @param info
	 * @param monitor
	 * @throws MalformedTreeException
	 * @throws BadLocationException
	 * @throws CoreException
	 */
	@SuppressWarnings("deprecation")
	public static void enrichClass(IFile file, TestResourceGeneration info, IProgressMonitor monitor)
			throws MalformedTreeException, BadLocationException, CoreException {
		ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file);
		try {

			String source = compilationUnit.getSource();

			Document document = new Document(source);
			compilationUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
			ASTParser parser = ASTParser.newParser(AST.JLS8);
			parser.setSource(compilationUnit);
			parser.setResolveBindings(true);
			CompilationUnit astRoot = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
			astRoot.recordModifications();
			final AST ast = astRoot.getAST();

			boolean[] hasGraphWalkerAnnotation = new boolean[1];
			boolean[] hasGeneratedAnnotation = new boolean[1];
			boolean[] hasStaticField = new boolean[1];
			// Add a System.out.println("xxx") statement to the methods
			astRoot.accept(new ASTVisitor() {
				@SuppressWarnings("unchecked")
				@Override
				public boolean visit(MethodDeclaration node) {
					if (info.isAppendSource())
						return false; // dont touch the existing code if we are
										// appending new source code.
					ExpressionStatement md = info.getClassExtension().getBodyMethod(node.getName().toString());
					ASTNode copiedNode = ASTNode.copySubtree(node.getAST(), md);
					node.setBody(ast.newBlock());
					node.getBody().statements().add(copiedNode);
					return false;
				}

				@Override
				public boolean visit(NormalAnnotation node) {
					if (!hasGeneratedAnnotation[0])
						hasGeneratedAnnotation[0] = (node.getTypeName().getFullyQualifiedName()
								.indexOf(Generated.class.getSimpleName()) != -1);
					if (!hasGraphWalkerAnnotation[0])
						hasGraphWalkerAnnotation[0] = (node.getTypeName().getFullyQualifiedName()
								.indexOf(GraphWalker.class.getSimpleName()) != -1);
					return true;
				}

				@Override
				public boolean visit(FieldDeclaration node) {
					if (!hasStaticField[0]) {
						VariableDeclarationFragment fragment = (VariableDeclarationFragment) node.fragments().get(0);
						hasStaticField[0] = fragment.getName().toString()
								.equals(ClassExtension.getStaticVariableName());
					}
					return true;
				}

			});

			final ImportRewrite importRewrite = ImportRewrite.create(astRoot, true);

			astRoot.accept(new ASTVisitor() {
				@SuppressWarnings("unchecked")
				@Override
				public boolean visit(TypeDeclaration node) {
					ITypeBinding binding = node.resolveBinding();

					// Add import for class annotation
					String[] imports = info.getClassExtension().getImports();
					List<String> allImports = new ArrayList<String>();
					for (int i = 0; i < imports.length; i++) {
						if (allImports.contains(imports[i]))
							continue;
						allImports.add(imports[i]);
					}
					// Add import for methods annotation & code
					for (int i = 0; i < info.getMethods().length; i++) {
						imports = info.getMethods()[i].getImports();
						for (int j = 0; j < imports.length; j++) {
							if (allImports.contains(imports[j]))
								continue;
							allImports.add(imports[j]);
						}
					}
					// Add import for methods annotation & code
					for (int i = 0; i < info.getMethods().length; i++) {
						imports = info.getMethods()[i].getStaticImports();
						for (int j = 0; j < imports.length; j++) {
							if (allImports.contains(imports[j]))
								continue;
							allImports.add(imports[j]);
						}
					}

					ASTNode copiedNode = null;
					Collections.sort(allImports);
					Iterator<String> iterator = allImports.iterator();
					while (iterator.hasNext()) {
						String imp = (String) iterator.next();
						importRewrite.addImport(imp);
					}
					// Add Generated annotation
					if (!hasGeneratedAnnotation[0]) {
						NormalAnnotation annotation = info.getClassExtension().getGeneratedClassAnnotation();
						if (annotation != null) {
							copiedNode = ASTNode.copySubtree(node.getAST(), annotation);
							node.modifiers().add(0, copiedNode);
						}
					}
					// Add graphwalker annotation
					if (!hasGraphWalkerAnnotation[0]) {
						NormalAnnotation annotation = info.getClassExtension().getGraphWalkerClassAnnotation();
						if (annotation != null) {
							copiedNode = ASTNode.copySubtree(node.getAST(), annotation);
							node.modifiers().add(1, copiedNode);
						}
					}

					if (!hasStaticField[0]) {
						FieldDeclaration field = info.getClassExtension().getField();
						if (field != null) {
							copiedNode = ASTNode.copySubtree(node.getAST(), field);
							node.bodyDeclarations().add(0, copiedNode);
						}
					}

					List<IFile> additionals = info.getAdditionalContexts();
					List<String> temp = new ArrayList<String>();
					for (IFile iFile : additionals) {
						try {
							AbstractPostConversion converter = GraphWalkerContextManager
									.getDefaultGraphConversion(iFile, false);
							temp.add(converter.getQualifiedNameForImplementation());

						} catch (CoreException e) {
							ResourceManager.logException(e);
						}
					}
					String[] adds = new String[temp.size()];
					temp.toArray(adds);
					// add helper hook & test methods
					for (int i = 0; i < info.getMethods().length; i++) {
						try {
							MethodDeclaration methodDeclaration = info.getMethods()[i].getMethodDeclaration(adds,
									node.getName().toString());
							if (methodDeclaration == null)
								continue;

							copiedNode = ASTNode.copySubtree(node.getAST(), methodDeclaration);
							node.bodyDeclarations().add(copiedNode);
						} catch (Exception e) {
							ResourceManager.logException(e);
						}
					}

					return super.visit(node);
				}
			});

			TextEdit rewrite = astRoot.rewrite(document, compilationUnit.getJavaProject().getOptions(true));
			rewrite.apply(document);

			TextEdit rewriteImports = importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
			rewriteImports.apply(document);

			String newSource = document.get();

			compilationUnit.getBuffer().setContents(newSource);

			compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, new SubProgressMonitor(monitor, 1));
			compilationUnit.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
		} finally {
			compilationUnit.discardWorkingCopy();
			monitor.done();
		}

	}

	/**
	 * @param file
	 * @param info
	 * @param monitor
	 * @throws MalformedTreeException
	 * @throws BadLocationException
	 * @throws CoreException
	 */
	@SuppressWarnings("deprecation")
	public static void addGeneratedAnnotation(IFile file, IFile graphFile, IProgressMonitor monitor)
			throws MalformedTreeException, BadLocationException, CoreException {
		ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file);
		try {

			String source = compilationUnit.getSource();
			Document document = new Document(source);
			compilationUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
			ASTParser parser = ASTParser.newParser(AST.JLS8);
			parser.setSource(compilationUnit);
			parser.setResolveBindings(true);
			CompilationUnit astRoot = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
			astRoot.recordModifications();

			final ImportRewrite importRewrite = ImportRewrite.create(astRoot, true);
			importRewrite.addImport("javax.annotation.Generated");

			astRoot.accept(new ASTVisitor() {
				@SuppressWarnings("unchecked")
				@Override
				public boolean visit(TypeDeclaration node) {
					ASTNode copiedNode = null;
					// Add Generated annotation
					ClassExtension ce;
					try {
						ce = new ClassExtension(false, false, false, false, false, false, "", "", null, false, false,
								"", "", "", graphFile);
						NormalAnnotation annotation = ce.getGeneratedClassAnnotation();
						if (annotation != null) {
							copiedNode = ASTNode.copySubtree(node.getAST(), annotation);
							node.modifiers().add(0, copiedNode);
						}
					} catch (JavaModelException e) {
						ResourceManager.logException(e);
					}

					return super.visit(node);
				}
			});

			TextEdit rewrite = astRoot.rewrite(document, compilationUnit.getJavaProject().getOptions(true));
			rewrite.apply(document);

			TextEdit rewriteImports = importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
			rewriteImports.apply(document);

			String newSource = document.get();
			compilationUnit.getBuffer().setContents(newSource);

			compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, new SubProgressMonitor(monitor, 1));
			compilationUnit.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
		} finally {
			compilationUnit.discardWorkingCopy();
			monitor.done();
		}
		// WorkbenchFacade.JDTManager.reorganizeImport(compilationUnit);
	}

	/**
	 * @param project
	 * @param targetSite
	 * @throws CoreException
	 */
	private static void organizeImports(final ICompilationUnit cu, final IWorkbenchSite targetSite)
			throws CoreException {
		Runnable job = new Runnable() {
			@Override
			public void run() {
				OrganizeImportsAction org = new OrganizeImportsAction(targetSite);
				org.run(cu);
				try {
					if (cu.isWorkingCopy())
						cu.commitWorkingCopy(true, new NullProgressMonitor ());
				} catch (JavaModelException e) {
					ResourceManager.logException(e);
				}
				try {
					cu.getCorrespondingResource().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor ());
				} catch (Exception e) {
				}
			}
		};
		Display.getDefault().syncExec(job);
	}

	/**
	 * @param project
	 */
	public static void reorganizeImport(final ICompilationUnit cu) {

		Display.getDefault().syncExec(() -> {
			try {
				IWorkbenchWindow iww = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
				if (iww == null)
					return;
				IPartService partService = iww.getPartService();
				if (partService == null)
					return;
				IWorkbenchPart wp = partService.getActivePart();
				if (wp == null)
					return;
				IWorkbenchPartSite targetSite = wp.getSite();
				if (targetSite == null)
					return;
				organizeImports(cu, targetSite);
			} catch (Exception e) {
				ResourceManager.logException(e);
			}
		});
	}

	/**
	 * Format a Unit Source Code
	 *
	 * @param testInterface
	 * @param monitor
	 * @throws CoreException
	 */
	@SuppressWarnings("unchecked")
	public static void formatUnitSourceCode(IFile file, IProgressMonitor monitor) throws CoreException {
		@SuppressWarnings("rawtypes")
		SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
		ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
		subMonitor.split(50);
		ICompilationUnit workingCopy = unit.getWorkingCopy(monitor);

		Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

		options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
		options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);

		options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
				DefaultCodeFormatterConstants.createAlignmentValue(true,
						DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
						DefaultCodeFormatterConstants.INDENT_ON_COLUMN));

		final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
		ISourceRange range = unit.getSourceRange();
		TextEdit formatEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(),
				range.getOffset(), range.getLength(), 0, null);
		subMonitor.split(30);
		if (formatEdit != null /* && formatEdit.hasChildren()*/) {
			workingCopy.applyTextEdit(formatEdit, monitor);
			workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
			workingCopy.commitWorkingCopy(true, null);
			workingCopy.discardWorkingCopy();
		}
		file.refreshLocal(IResource.DEPTH_INFINITE, subMonitor);
		subMonitor.split(20);
	}

	/**
	 * Return a java model
	 *
	 * @return
	 */
	public static IJavaModel getJavaModel() {
		return JavaCore.create(ResourceManager.getWorkspaceRoot());
	}

	/**
	 *
	 * Open a default editor
	 *
	 * @param resource
	 * @throws FileNotFoundException
	 */
	public static void openDefaultEditor(final IResource resource) {
		openEditor(resource, "org.eclipse.ui.DefaultTextEditor", null);
	}

	/**
	 *
	 * Open an editor
	 *
	 * @param resource
	 * @throws FileNotFoundException
	 */
	public static void openEditor(final IResource resource, IWorkbenchWindow aww) {
		openEditor(resource, null, aww);
	}

	/**
	 * Open an editor
	 *
	 * @param resource
	 * @param editorId
	 */
	public static void openEditor(final IResource resource, String editorId, IWorkbenchWindow aww) {
		openFileEditor(resource, editorId, aww);
	}

	/**
	 * Open an editor
	 *
	 * @param resource
	 * @param extension
	 * @param editor
	 * @throws FileNotFoundException
	 */
	public static void openFileEditor(final IResource resource, String editorId, IWorkbenchWindow window) {
		try {
			Display.getDefault().syncExec(() -> {
				IWorkbenchWindow[] ww = new IWorkbenchWindow[] { window };
				if (resource == null)
					return;
				if (resource.getType() != IResource.FILE) {
					return;
				}
				IFile file = (IFile) resource;
				if (!file.exists())
					return;
				if (ww[0] == null) {
					ww[0] = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
				}

				if (ww[0] == null) {
					return;
				}
				final IWorkbenchPage activePage = ww[0].getActivePage();
				try {
					if (editorId == null) {
						if (file.getFileExtension().equals("java")) {
							IDE.openEditor(activePage, file, JavaUI.ID_CU_EDITOR, true);
						} else {
							IDE.openEditor(activePage, file, "org.eclipse.ui.DefaultTextEditor", true);
						}
					} else {
						IDE.openEditor(activePage, file, editorId, true);
					}
				} catch (Throwable e) {
					ResourceManager.logException(e);
				}
				BasicNewResourceWizard.selectAndReveal(resource, activePage.getWorkbenchWindow());
			});
		} catch (Exception e) {
			ResourceManager.logException(e);
		}
	}

	/**
	 * Adapt the passed object to an IProject
	 *
	 * @param receiver
	 * @return
	 */
	public static IProject toJavaProject(Object receiver) {
		IProject project = null;
		if (receiver instanceof IProject) {
			project = (IProject) receiver;
		}
		if (receiver instanceof IJavaProject) {
			project = ((IJavaProject) receiver).getProject();
		} else if (receiver instanceof IAdaptable) {
			project = (IProject) ((IAdaptable) receiver).getAdapter(IProject.class);
		}
		return project;
	}

	public static IPackageFragment getPackageFragment(IFile file) throws JavaModelException {
		IPackageFragmentRoot root1 = JDTManager.findPackageFragmentRoot(file.getProject(), file.getFullPath());
		IPath path = file.getParent().getFullPath().makeRelativeTo(root1.getPath());
		IPackageFragment pf =root1.getPackageFragment(path.toString().replace("/", "."));
		return pf;
	}

	/**
	 * Return a package fragment with the passed path
	 *
	 * @param project
	 * @param path
	 * @return
	 * @throws JavaModelException
	 */
	public static IPackageFragmentRoot getPackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
		IJavaProject javaProject = JavaCore.create(project);
		IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			if (roots[i].getPath().equals(path))
				return roots[i];
		}
		return null;
	}

	public static IPackageFragmentRoot findPackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
		IJavaProject javaProject = JavaCore.create(project);
		IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			if (roots[i].getPath().isPrefixOf(path))
				return roots[i];
		}
		return null;
	}

	public static IPath removePackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
		IJavaProject javaProject = JavaCore.create(project);
		IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			if (roots[i].getPath().isPrefixOf(path))
				return path.makeRelativeTo(roots[i].getPath());
		}
		return null;
	}

	public static boolean validateClassName(String name) {
		String temp = name + ".java";
		IStatus status = JavaConventions.validateCompilationUnitName(temp, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8);
		boolean b = (status.getCode() == IStatus.OK);
		return b;
	}
}


text:
//--------------------------------------------------------------------------------
// GLContext.cpp
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// includes
//--------------------------------------------------------------------------------
#include <unistd.h>
#include "GLContext.h"
#include "gl3stub.h"

namespace ndk_helper {

//--------------------------------------------------------------------------------
// eGLContext
//--------------------------------------------------------------------------------
const int32_t SWAPINTERVAL_DEFAULT = 1;

//--------------------------------------------------------------------------------
// Ctor
//--------------------------------------------------------------------------------
GLContext::GLContext()
    : window_(nullptr), display_(EGL_NO_DISPLAY), surface_(EGL_NO_SURFACE),
      context_(EGL_NO_CONTEXT), screen_width_(0), screen_height_(0),
      msaa_size_(1), restoreInterval_(false),
      swapInterval_(SWAPINTERVAL_DEFAULT), gles_initialized_(false),
      egl_context_initialized_(false), es3_supported_(false), gl_version_(0),
      context_valid_(false) {}

void GLContext::InitGLES() {
  if (gles_initialized_)
    return;
  //
  //Initialize OpenGL ES 3 if available
  //
  const char *versionStr = (const char *)glGetString(GL_VERSION);
  if (strstr(versionStr, "OpenGL ES 3.") && gl3stubInit()) {
    es3_supported_ = true;
    gl_version_ = 3.0f;
  } else {
    gl_version_ = 2.0f;
  }

  gles_initialized_ = true;
}

//--------------------------------------------------------------------------------
// Dtor
//--------------------------------------------------------------------------------
GLContext::~GLContext() { Terminate(); }

bool GLContext::Init(ANativeWindow *window, const int32_t msaa) {
  if (egl_context_initialized_)
    return true;

  //
  //Initialize EGL
  //
  window_ = window;
  msaa_size_ = msaa;
  InitEGLSurface();
  InitEGLContext();
  InitGLES();

  egl_context_initialized_ = true;

  return true;
}

bool GLContext::InitEGLSurface() {
  display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  eglInitialize(display_, 0, 0);

  /*
   * Here specify the attributes of the desired configuration.
   * Below, we select an EGLConfig with at least 8 bits per color
   * component compatible with on-screen windows
   */
  const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                             EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                             EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8,
                             EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE,
                             24,
//                             EGL_COLORSPACE, EGL_COLORSPACE_sRGB,
//                             EGL_COLORSPACE, EGL_COLORSPACE_LINEAR,
                             EGL_SAMPLES, msaa_size_, EGL_NONE };
  color_size_ = 8;
  depth_size_ = 24;

  EGLint num_configs;
  eglChooseConfig(display_, attribs, &config_, 1, &num_configs);
  LOGI("Found %d configs", num_configs);

  if (msaa_size_ > 1 && !num_configs) {
    LOGW("No EGL config with MSAA");
    //Fall back to non MSAA
    const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                               EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                               EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE,
                               8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8,
                               EGL_DEPTH_SIZE, 24, EGL_NONE };
    msaa_size_ = 1;
    eglChooseConfig(display_, attribs, &config_, 1, &num_configs);
  }

  if (!num_configs) {
    LOGW("No 24bit depth buffer");

    //Fall back to 16bit depth buffer
    const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                               EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                               EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE,
                               8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8,
                               EGL_DEPTH_SIZE, 16, EGL_NONE };
    eglChooseConfig(display_, attribs, &config_, 1, &num_configs);
    depth_size_ = 16;
  }

  if (!num_configs) {
    LOGW("Unable to retrieve EGL config");
    return false;
  }

  surface_ = eglCreateWindowSurface(display_, config_, window_, NULL);
  eglQuerySurface(display_, surface_, EGL_WIDTH, &screen_width_);
  eglQuerySurface(display_, surface_, EGL_HEIGHT, &screen_height_);

  /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
   * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
   * As soon as we picked a EGLConfig, we can safely reconfigure the
   * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
  EGLint format;
  eglGetConfigAttrib(display_, config_, EGL_NATIVE_VISUAL_ID, &format);
  ANativeWindow_setBuffersGeometry(window_, 0, 0, format);

  return true;
}

bool GLContext::InitEGLContext() {
  const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION,
                                     2, //Request opengl ES2.0
                                     EGL_NONE };
  context_ = eglCreateContext(display_, config_, NULL, context_attribs);

  if (eglMakeCurrent(display_, surface_, surface_, context_) == EGL_FALSE) {
    LOGW("Unable to eglMakeCurrent");
    return false;
  }

  context_valid_ = true;
  return true;
}

EGLint GLContext::Swap() {
  bool b = eglSwapBuffers(display_, surface_);
  if (!b) {
    EGLint err = eglGetError();
    if (err == EGL_BAD_SURFACE) {
      //Recreate surface
      InitEGLSurface();
      err = EGL_SUCCESS; //Still consider glContext is valid
    } else if (err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT) {
      //Context has been lost!!
      context_valid_ = false;
      Terminate();
      InitEGLContext();
    }

    return err;
  }
  if (restoreInterval_ && swapInterval_ != SWAPINTERVAL_DEFAULT) {
    eglSwapInterval(display_, swapInterval_); //Restore Swap interval
  }
  return EGL_SUCCESS;
}

void GLContext::Terminate() {
  if (display_ != EGL_NO_DISPLAY) {
    eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    if (context_ != EGL_NO_CONTEXT) {
      eglDestroyContext(display_, context_);
    }

    if (surface_ != EGL_NO_SURFACE) {
      eglDestroySurface(display_, surface_);
    }
    eglTerminate(display_);
  }

  display_ = EGL_NO_DISPLAY;
  context_ = EGL_NO_CONTEXT;
  surface_ = EGL_NO_SURFACE;
  context_valid_ = false;

}

EGLint GLContext::Resume(ANativeWindow *window) {
  if (egl_context_initialized_ == false) {
    Init(window, msaa_size_);
    return EGL_SUCCESS;
  }

  int32_t original_widhth = screen_width_;
  int32_t original_height = screen_height_;

  //Create surface
  window_ = window;
  surface_ = eglCreateWindowSurface(display_, config_, window_, NULL);
  eglQuerySurface(display_, surface_, EGL_WIDTH, &screen_width_);
  eglQuerySurface(display_, surface_, EGL_HEIGHT, &screen_height_);

  if (screen_width_ != original_widhth || screen_height_ != original_height) {
    //Screen resized
    LOGI("Screen resized");
  }

  if (eglMakeCurrent(display_, surface_, surface_, context_) == EGL_TRUE)
    return EGL_SUCCESS;

  EGLint err = eglGetError();
  LOGW("Unable to eglMakeCurrent %d", err);

  if (err == EGL_CONTEXT_LOST) {
    //Recreate context
    LOGI("Re-creating egl context");
    InitEGLContext();
  } else {
    //Recreate surface
    Terminate();
    InitEGLSurface();
    InitEGLContext();
  }

  return err;
}

void GLContext::Suspend() {
  if (surface_ != EGL_NO_SURFACE) {
    eglDestroySurface(display_, surface_);
    surface_ = EGL_NO_SURFACE;
  }
  restoreInterval_ = true;
}

bool GLContext::Invalidate() {
  Terminate();

  egl_context_initialized_ = false;
  return true;
}

bool GLContext::CheckExtension(const char *extension) {
  if (extension == NULL)
    return false;

  std::string extensions = std::string((char *)glGetString(GL_EXTENSIONS));
  std::string str = std::string(extension);
  str.append(" ");

  size_t pos = 0;
  if (extensions.find(extension, pos) != std::string::npos) {
    return true;
  }

  return false;
}

} //namespace ndkHelper

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sis.cloud.aws.s3;

import java.util.List;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.stream.Stream;
import java.util.function.Function;
import java.util.function.Consumer;

/**
 * A list in which values are derived from another list using a given function.
 * The conversion is done the fly every times an element is accessed.
 * Consequently, this wrapper should be used only for elements that are cheap to wrap.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.2
 *
 * @param  <S>  type of elements in the source list.
 * @param  <E>  type of elements in this list.
 *
 * @since 1.2
 * @module
 */
final class DerivedList<S,E> extends AbstractList<E> {
    /**
     * The list of source elements.
     */
    private final List<S> source;

    /**
     * The function for deriving an element in this list from an element in the source list.
     */
    private final Function<S,E> adapter;

    /**
     * Creates a new derived list wrapping the given list.
     *
     * @param  source   the list of source elements.
     * @param  adapter  the function for deriving an element in this list from an element in the source list.
     */
    DerivedList(final List<S> source, final Function<S,E> adapter) {
        this.source  = source;
        this.adapter = adapter;
    }

    /**
     * Delegates to the wrapped list.
     */
    @Override public boolean   isEmpty()        {return source.isEmpty();}
    @Override public int       size()           {return source.size();}
    @Override public E         get(int i)       {return adapter.apply(source.get(i));}
    @Override public E         remove(int i)    {return adapter.apply(source.remove(i));}
    @Override public Stream<E> stream()         {return source.stream().map(adapter);};
    @Override public Stream<E> parallelStream() {return source.parallelStream().map(adapter);};

    /**
     * Returns a view of the portion of this list.
     */
    @Override public List<E> subList(int fromIndex, int toIndex) {
        return new DerivedList<>(source.subList(fromIndex, toIndex), adapter);
    }

    /**
     * Applies the given action on all elements in the list.
     */
    @Override public void forEach(final Consumer<? super E> action) {
        source.forEach(adapt(adapter, action));
    }

    /**
     * Creates a consumer of {@code <S>} which will delegate to a consumer of {@code <E>} objects.
     * This is used for allowing {@code forEach(…)} methods to delegate to underlying source.
     */
    private static <S,E> Consumer<S> adapt(final Function<S,E> adapter, final Consumer<? super E> action) {
        return (e) -> action.accept(adapter.apply(e));
    }

    /**
     * An iterator over the elements in the source list,
     * converted on-the-fly to elements of type {@code <E>}.
     */
    private static final class Iter<S,E> implements Iterator<E> {
        /** The iterator over source elements. */
        private final Iterator<S> source;

        /** The function for deriving an element in this list from an element in the source list. */
        private final Function<S,E> adapter;

        /** Creates a new iterator wrapping the given source. */
        Iter(final Iterator<S> source, final Function<S,E> adapter) {
            this.source  = source;
            this.adapter = adapter;
        }

        /** Delegates to the wrapped iterator. */
        @Override public boolean hasNext() {return source.hasNext();}
        @Override public E       next()    {return adapter.apply(source.next());}
        @Override public void    remove()  {source.remove();}

        /** Applies the given action on all remaining elements in the iterator. */
        @Override public void forEachRemaining(final Consumer<? super E> action) {
            source.forEachRemaining(adapt(adapter, action));
        }
    }
}


text:
use mentat_core::{
    Binding,
    TypedValue,
};

/// The result you get from a 'rel' query, like:
///
/// ```edn
/// [:find ?person ?name
///  :where [?person :person/name ?name]]
/// ```
///
/// There are three ways to get data out of a `RelResult`:
/// - By iterating over rows as slices. Use `result.rows()`. This is efficient and is
///   recommended in two cases:
///   1. If you don't need to take ownership of the resulting values (e.g., you're comparing
///      or making a modified clone).
///   2. When the data you're retrieving is cheap to clone. All scalar values are relatively
///      cheap: they're either small values or `Rc`.
/// - By direct reference to a row by index, using `result.row(i)`. This also returns
///   a reference.
/// - By consuming the results using `into_iter`. This allocates short-lived vectors,
///   but gives you ownership of the enclosed `TypedValue`s.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RelResult<T> {
    pub width: usize,
    pub values: Vec<T>,
}

pub type StructuredRelResult = RelResult<Binding>;

impl<T> RelResult<T> {
    pub fn empty(width: usize) -> RelResult<T> {
        RelResult {
            width: width,
            values: Vec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn row_count(&self) -> usize {
        self.values.len() / self.width
    }

    pub fn rows(&self) -> ::std::slice::Chunks<T> {
        // TODO: Nightly-only API `exact_chunks`. #47115.
        self.values.chunks(self.width)
    }

    pub fn row(&self, index: usize) -> Option<&[T]> {
        let end = self.width * (index + 1);
        if end > self.values.len() {
            None
        } else {
            let start = self.width * index;
            Some(&self.values[start..end])
        }
    }
}

#[test]
fn test_rel_result() {
    let empty = StructuredRelResult::empty(3);
    let unit = StructuredRelResult {
        width: 1,
        values: vec![TypedValue::Long(5).into()],
    };
    let two_by_two = StructuredRelResult {
        width: 2,
        values: vec![TypedValue::Long(5).into(), TypedValue::Boolean(true).into(),
                     TypedValue::Long(-2).into(), TypedValue::Boolean(false).into()],
    };

    assert!(empty.is_empty());
    assert!(!unit.is_empty());
    assert!(!two_by_two.is_empty());

    assert_eq!(empty.row_count(), 0);
    assert_eq!(unit.row_count(), 1);
    assert_eq!(two_by_two.row_count(), 2);

    assert_eq!(empty.row(0), None);
    assert_eq!(unit.row(1), None);
    assert_eq!(two_by_two.row(2), None);

    assert_eq!(unit.row(0), Some(vec![TypedValue::Long(5).into()].as_slice()));
    assert_eq!(two_by_two.row(0), Some(vec![TypedValue::Long(5).into(), TypedValue::Boolean(true).into()].as_slice()));
    assert_eq!(two_by_two.row(1), Some(vec![TypedValue::Long(-2).into(), TypedValue::Boolean(false).into()].as_slice()));

    let mut rr = two_by_two.rows();
    assert_eq!(rr.next(), Some(vec![TypedValue::Long(5).into(), TypedValue::Boolean(true).into()].as_slice()));
    assert_eq!(rr.next(), Some(vec![TypedValue::Long(-2).into(), TypedValue::Boolean(false).into()].as_slice()));
    assert_eq!(rr.next(), None);
}

// Primarily for testing.
impl From<Vec<Vec<TypedValue>>> for RelResult<Binding> {
    fn from(src: Vec<Vec<TypedValue>>) -> Self {
        if src.is_empty() {
            RelResult::empty(0)
        } else {
            let width = src.get(0).map(|r| r.len()).unwrap_or(0);
            RelResult {
                width: width,
                values: src.into_iter().flat_map(|r| r.into_iter().map(|v| v.into())).collect(),
            }
        }
    }
}

pub struct SubvecIntoIterator<T> {
    width: usize,
    values: ::std::vec::IntoIter<T>,
}

impl<T> Iterator for SubvecIntoIterator<T> {
    // TODO: this is a good opportunity to use `SmallVec` instead: most queries
    // return a handful of columns.
    type Item = Vec<T>;
    fn next(&mut self) -> Option<Self::Item> {
        let result: Vec<_> = (&mut self.values).take(self.width).collect();
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }
}

impl<T> IntoIterator for RelResult<T> {
    type Item = Vec<T>;
    type IntoIter = SubvecIntoIterator<T>;

    fn into_iter(self) -> Self::IntoIter {
        SubvecIntoIterator {
            width: self.width,
            values: self.values.into_iter(),
        }
    }
}


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/style/style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">


text:
from __future__ import unicode_literals

from contextlib import contextmanager

from web.security import when
from web.security.predicate import always, never

@contextmanager
def must_be_called(n=None):
	"""Ensure the target function is called.

	If an `n` value is supplied, ensure the target is called that many times.
	"""
	called = []

	def must_call(context=None):
		called.append(context)

	yield must_call

	if n is None:
		assert len(called) > 0, "Predicate that must be called, was not."

	else:
		assert len(called) == n, "Predicate that must be called " + str(n) + " times was called " + \
				str(len(called)) + " times."

@contextmanager
def must_not_be_called():
	"""Ensure the target function is never called."""
	called = []

	def must_not_call(context=None):
		called.append(context)

	yield must_not_call

	assert len(called) == 0, "Predicate that must not be called, was."

class MockController:
	def __init__(self, context):
		self._ctx = context

	def test(self):
		return None

	def allowed(self):
		class secret(dict):
			__acl__ = [always]
		return secret(value=27)

	def forbidden(self):
		class secret(dict):
			__acl__ = [never]
		return secret(value=27)

@when(always)
class Grant(MockController):
	pass

@when(always)
class EarlyGrant(MockController):
	@when(never)
	def test(self):
		return None

@when(never)
class EarlyDeny(MockController):
	@when(always)
	def test(self):
		return None

@when(never)
class Nuke(MockController):
	@when(inherit=False)
	def test(self):
		return None


text:
using System;
using System.Web.UI;

namespace Hotcakes.Commerce.Content
{
    public class NotifyClickControl : UserControl
    {
        public event EventHandler<ClickedEventArgs> Clicked;

        protected bool NotifyClicked(string data)
        {
            var args = new ClickedEventArgs(data);
            if (Clicked != null)
            {
                Clicked(this, args);
            }
            return !args.ErrorOccurred;
        }

        protected bool NotifyClicked()
        {
            var args = new ClickedEventArgs();
            if (Clicked != null)
            {
                Clicked(this, args);
            }
            return !args.ErrorOccurred;
        }

        public class ClickedEventArgs : EventArgs
        {
            private string _info = string.Empty;

            public ClickedEventArgs()
            {
                ErrorOccurred = false;
            }

            public ClickedEventArgs(string data)
            {
                ErrorOccurred = false;
                if (data != null)
                {
                    _info = data;
                }
            }

            public string Info
            {
                get { return _info; }
                set { _info = value; }
            }

            public bool ErrorOccurred { get; set; }
        }
    }
}


text:
Clazz.declarePackage ("J.jvxl.readers");
Clazz.load (["J.jvxl.readers.IsoFxyReader"], "J.jvxl.readers.IsoFxyzReader", null, function () {
c$ = Clazz.decorateAsClass (function () {
this.$data = null;
Clazz.instantialize (this, arguments);
}, J.jvxl.readers, "IsoFxyzReader", J.jvxl.readers.IsoFxyReader);
Clazz.makeConstructor (c$,
function () {
Clazz.superConstructor (this, J.jvxl.readers.IsoFxyzReader, []);
});
Clazz.overrideMethod (c$, "setup",
function (isMapData) {
if (this.params.functionInfo.size () > 5) this.$data = this.params.functionInfo.get (5);
this.setupType ("functionXYZ");
}, "~B");
Clazz.defineMethod (c$, "getValue",
function (x, y, z) {
return (this.$data == null ? this.evaluateValue (x, y, z) : this.$data[x][y][z]);
}, "~N,~N,~N");
});


text:
This page was generated with Wiki Builder. Do not change the format!

## Info

## Schema
* **Schema Type:** Array
* **Type:** array
* **Array Contents:** [[PeriodType|Destiny-HistoricalStats-Definitions-PeriodType]]:Enum

## Example
```javascript
[
   // Type: [[PeriodType|Destiny-HistoricalStats-Definitions-PeriodType]]:Enum
    0
]

```

## References
1. https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-PeriodType[].html#schema_Destiny-HistoricalStats-Definitions-PeriodType[]


text:
/**
 * @file msoSlinkMS.c
 *
 */

/*** Copyright (c), University of North Carolina            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/

/**
 * @file  msoSlinkMS.c
 *
 */

#include "msoDriversMS.h"
#include <strings.h>

extern int rsDataObjWrite (rsComm_t *rsComm,
			   openedDataObjInp_t *dataObjWriteInp,
			   bytesBuf_t *dataObjWriteInpBBuf);
extern int rsDataObjRead (rsComm_t *rsComm,
			  openedDataObjInp_t *dataObjReadInp,
			  bytesBuf_t *dataObjReadOutBBuf);
extern int rsDataObjOpen (rsComm_t *rsComm, dataObjInp_t *dataObjInp);
extern int rsDataObjClose (rsComm_t *rsComm, openedDataObjInp_t *dataObjCloseInp);
extern int rsDataObjCreate (rsComm_t *rsComm, dataObjInp_t *dataObjInp);

/**
 * \fn msiobjget_slink(msParam_t*  inRequestPath, msParam_t* inFileMode, msParam_t* inFileFlags, msParam_t* inCacheFilename,  ruleExecInfo_t* rei )
 *
 * \brief Gets an SLINK object
 *
 * \module msoDrivers_slink
 *
 * \since 3.0
 *
 * \author  Arcot Rajasekar
 * \date    2011
 *
 * \usage See clients/icommands/test/rules3.0/
 *
 * \param[in] inRequestPath - a STR_MS_T request string to external resource
 * \param[in] inFileMode - a STR_MS_T mode of cache file creation
 * \param[in] inFileFlags - a STR_MS_T flags for cache file creation
 * \param[in] inCacheFilename - a STR_MS_T cache file name (full path)
 * \param[in,out] rei - The RuleExecInfo structure that is automatically
 *    handled by the rule engine. The user does not include rei as a
 *    parameter in the rule invocation.
 *
 * \DolVarDependence none
 * \DolVarModified none
 * \iCatAttrDependence none
 * \iCatAttrModified none
 * \sideeffect none
 *
 * \return integer
 * \retval 0 on success
 * \pre none
 * \post none
 * \sa none
**/

int
msiobjget_slink(msParam_t*  inRequestPath, msParam_t* inFileMode,
	       msParam_t* inFileFlags, msParam_t* inCacheFilename,
	       ruleExecInfo_t* rei )
{

  char *locStr;
  int mode, flags;
  char *cacheFilename;
  char *str, *t;
  int status, bytesRead, bytesWritten;
  int destFd, i;
  rsComm_t *rsComm;

  dataObjInp_t dataObjInp;
  int objFD;
  openedDataObjInp_t dataObjReadInp;
  openedDataObjInp_t dataObjCloseInp;
  bytesBuf_t readBuf;

  RE_TEST_MACRO( "    Calling msiobjget_slink" );

  /*  check for input parameters */
  if (inRequestPath ==  NULL ||
      strcmp(inRequestPath->type , STR_MS_T) != 0 ||
      inRequestPath->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  if (inFileMode ==  NULL ||
      strcmp(inFileMode->type , STR_MS_T) != 0 ||
      inFileMode->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  if (inFileFlags ==  NULL ||
      strcmp(inFileFlags->type , STR_MS_T) != 0 ||
      inFileFlags->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  if (inCacheFilename ==  NULL ||
      strcmp(inCacheFilename->type , STR_MS_T) != 0 ||
      inCacheFilename->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  /*  coerce input to local variables */
  str = strdup((char *) inRequestPath->inOutStruct);
  if ((t = strstr(str, ":")) != NULL)
    locStr = t+1;
  else {
    free(str);
    return(USER_INPUT_FORMAT_ERR);
  }

  cacheFilename = (char *) inCacheFilename->inOutStruct;
  mode  = atoi((char *) inFileMode->inOutStruct);
  flags = atoi((char *) inFileFlags->inOutStruct);
  rsComm = rei->rsComm;

  /* Do the processing */
  bzero (&dataObjInp, sizeof (dataObjInp));
  bzero (&dataObjReadInp, sizeof (dataObjReadInp));
  bzero (&dataObjCloseInp, sizeof (dataObjCloseInp));
  bzero (&readBuf, sizeof (readBuf));

  dataObjInp.openFlags = O_RDONLY;
  rstrcpy(dataObjInp.objPath, locStr, MAX_NAME_LEN);
  free(str);

  objFD = rsDataObjOpen (rsComm, &dataObjInp);
  if (objFD < 0) {
    printf("msigetobj_slink: Unable to open file %s:%i\n", dataObjInp.objPath,objFD);
    return(objFD);
  }

  destFd = open (cacheFilename, O_WRONLY | O_CREAT | O_TRUNC, mode);
  if (destFd < 0) {
    status = UNIX_FILE_OPEN_ERR - errno;
    printf (
	    "msigetobj_slink: open error for cacheFilename %s, status = %d",
	    cacheFilename, status);
    return status;
  }

  dataObjReadInp.l1descInx = objFD;
  dataObjCloseInp.l1descInx = objFD;

  readBuf.len = MAX_SZ_FOR_SINGLE_BUF;
  readBuf.buf = (char *)malloc(readBuf.len);
  dataObjReadInp.len = readBuf.len;

  while ((bytesRead = rsDataObjRead (rsComm, &dataObjReadInp, &readBuf)) > 0) {
    bytesWritten = write (destFd, readBuf.buf, bytesRead);
    if (bytesWritten != bytesRead ) {
      free(readBuf.buf);
      close (destFd);
      rsDataObjClose (rsComm, &dataObjCloseInp);
      printf(
	     "msigetobj_slink: In Cache File %s bytesWritten %d != returned objLen %i\n",
	     cacheFilename, bytesWritten, bytesRead);
      return SYS_COPY_LEN_ERR;
    }
  }
  free(readBuf.buf);
  close (destFd);
  i = rsDataObjClose (rsComm, &dataObjCloseInp);

  return(i);

}

/**
 * \fn msiobjput_slink(msParam_t*  inMSOPath, msParam_t*  inCacheFilename,  msParam_t*  inFileSize, ruleExecInfo_t* rei )
 *
 * \brief Puts an SLINK object
 *
 * \module msoDrivers_slink
 *
 * \since 3.0
 *
 * \author  Arcot Rajasekar
 * \date    2011
 *
 * \usage See clients/icommands/test/rules3.0/
 *
 * \param[in] inMSOPath - a STR_MS_T path string to external resource
 * \param[in] inCacheFilename - a STR_MS_T cache file containing data to be written out
 * \param[in] inFileSize - a STR_MS_T size of inCacheFilename
 * \param[in,out] rei - The RuleExecInfo structure that is automatically
 *    handled by the rule engine. The user does not include rei as a
 *    parameter in the rule invocation.
 *
 * \DolVarDependence none
 * \DolVarModified none
 * \iCatAttrDependence none
 * \iCatAttrModified none
 * \sideeffect none
 *
 * \return integer
 * \retval 0 on success
 * \pre none
 * \post none
 * \sa none
**/

int
msiobjput_slink(msParam_t*  inMSOPath, msParam_t*  inCacheFilename,
	       msParam_t*  inFileSize, ruleExecInfo_t* rei )
{

  char *reqStr;
  char *str, *t;
  char *cacheFilename;
  rodsLong_t dataSize;
  int status, i;
  int srcFd;
  char *myBuf;
  int bytesRead;
  openedDataObjInp_t dataObjWriteInp;
  int bytesWritten;
  openedDataObjInp_t dataObjCloseInp;
  dataObjInp_t dataObjInp;
  int outDesc;
  bytesBuf_t writeBuf;
  int writeBufLen;
  rsComm_t *rsComm;

  RE_TEST_MACRO( "    Calling msiobjput_slink" );

  /*  check for input parameters */
  if (inMSOPath ==  NULL ||
      strcmp(inMSOPath->type , STR_MS_T) != 0 ||
      inMSOPath->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  if (inCacheFilename ==  NULL ||
      strcmp(inCacheFilename->type , STR_MS_T) != 0 ||
      inCacheFilename->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  if (inFileSize ==  NULL ||
      strcmp(inFileSize->type , STR_MS_T) != 0 ||
      inFileSize->inOutStruct == NULL)
    return(USER_PARAM_TYPE_ERR);

  /*  coerce input to local variables */
  str = strdup((char *) inMSOPath->inOutStruct);
  if ((t = strstr(str, ":")) != NULL)
    reqStr = t+1;
  else {
    free(str);
    return(USER_INPUT_FORMAT_ERR);
  }

  cacheFilename = (char *) inCacheFilename->inOutStruct;
  dataSize  = atol((char *) inFileSize->inOutStruct);
  rsComm = rei->rsComm;

  /* Read the cache and Do the upload*/
  srcFd = open (cacheFilename, O_RDONLY, 0);
  if (srcFd < 0) {
    status = UNIX_FILE_OPEN_ERR - errno;
    printf ("msiputobj_slink: open error for %s, status = %d\n",
	    cacheFilename, status);
    free(str);
    return status;
  }

  bzero (&dataObjInp, sizeof(dataObjInp_t));
  bzero(&dataObjWriteInp, sizeof (dataObjWriteInp));
  bzero(&dataObjCloseInp, sizeof (dataObjCloseInp));

  rstrcpy(dataObjInp.objPath, reqStr, MAX_NAME_LEN);
  addKeyVal (&dataObjInp.condInput, FORCE_FLAG_KW, "");
  free(str);

  outDesc = rsDataObjCreate (rsComm, &dataObjInp);
  if (outDesc < 0) {
    printf ("msiputobj_slink: Unable to open file %s:%i\n", dataObjInp.objPath,outDesc);
    return(outDesc);
  }

  dataObjWriteInp.l1descInx = outDesc;
  dataObjCloseInp.l1descInx = outDesc;

  if (dataSize > MAX_SZ_FOR_SINGLE_BUF)
    writeBufLen = MAX_SZ_FOR_SINGLE_BUF;
  else
    writeBufLen = dataSize;

  myBuf = (char *) malloc (writeBufLen);
  writeBuf.buf = myBuf;

  while ( (bytesRead = read(srcFd, (void *) myBuf, writeBufLen)) > 0) {
    writeBuf.len = bytesRead;
    dataObjWriteInp.len = bytesRead;
    bytesWritten = rsDataObjWrite(rsComm, &dataObjWriteInp, &writeBuf);
    if (bytesWritten != bytesRead) {
      free(myBuf);
      close (srcFd);
      rsDataObjClose (rsComm, &dataObjCloseInp);
      printf ("msiputobj_slink: Write Error: bytesRead %d != bytesWritten %d\n",
	      bytesRead, bytesWritten);
      return SYS_COPY_LEN_ERR;
    }
  }
  free(myBuf);
  close (srcFd);
  i = rsDataObjClose (rsComm, &dataObjCloseInp);

  return(i);
}


text:
package kuberuntime

import (
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/stretchr/testify/assert"
	"testing"
)

func TestVerifyRunAsNonRoot(t *testing.T) {
	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			UID:       "12345678",
			Name:      "bar",
			Namespace: "new",
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:            "foo",
					Image:           "busybox",
					ImagePullPolicy: v1.PullIfNotPresent,
					Command:         []string{"testCommand"},
					WorkingDir:      "testWorkingDir",
				},
			},
		},
	}

	rootUser := int64(0)
	runAsNonRootTrue := true
	runAsNonRootFalse := false
	imageRootUser := int64(0)
	imageNonRootUser := int64(123)
	for _, test := range []struct {
		desc      string
		sc        *v1.SecurityContext
		imageUser int64
		fail      bool
	}{
		{
			desc:      "Pass if SecurityContext is not set",
			sc:        nil,
			imageUser: imageRootUser,
			fail:      false,
		},
		{
			desc: "Pass if RunAsNonRoot is not set",
			sc: &v1.SecurityContext{
				RunAsUser: &rootUser,
			},
			imageUser: imageRootUser,
			fail:      false,
		},
		{
			desc: "Pass if RunAsNonRoot is false (image user is root)",
			sc: &v1.SecurityContext{
				RunAsNonRoot: &runAsNonRootFalse,
			},
			imageUser: imageRootUser,
			fail:      false,
		},
		{
			desc: "Pass if RunAsNonRoot is false (RunAsUser is root)",
			sc: &v1.SecurityContext{
				RunAsNonRoot: &runAsNonRootFalse,
				RunAsUser:    &rootUser,
			},
			imageUser: imageNonRootUser,
			fail:      false,
		},
		{
			desc: "Fail if container's RunAsUser is root and RunAsNonRoot is true",
			sc: &v1.SecurityContext{
				RunAsNonRoot: &runAsNonRootTrue,
				RunAsUser:    &rootUser,
			},
			imageUser: imageNonRootUser,
			fail:      true,
		},
		{
			desc: "Fail if image's user is root and RunAsNonRoot is true",
			sc: &v1.SecurityContext{
				RunAsNonRoot: &runAsNonRootTrue,
			},
			imageUser: imageRootUser,
			fail:      true,
		},
	} {
		pod.Spec.Containers[0].SecurityContext = test.sc
		uid := int64(0)
		err := verifyRunAsNonRoot(pod, &pod.Spec.Containers[0], &uid, "")
		if test.fail {
			assert.Error(t, err, test.desc)
		} else {
			assert.NoError(t, err, test.desc)
		}
	}
}


text:
/*
   ARPACK++ v1.2 2/18/2000
   c++ interface to ARPACK code.

   MODULE DSVD2.cc.
   Example program that illustrates how to determine the largest
   singular values of an out-of-core dense matrix using arpack++.

   1) Problem description:

      In this example, Arpack++ is called to solve the symmetric problem:

                             (A'*A)*v = sigma*v

      where A is an m by n real matrix.
      This formulation is appropriate when m >= n.
      The roles of A and A' must be reversed in the case that m < n.

   2) Data structure used to represent the matrix:

      Because m >> n in this example, A is supposed to be stored
      row-wise in a file. Since this program is intended to show
      how to find the singular values of an out-of-core matrix, A
      will be loaded by blocks. This means that only part of the
      matrix will be stored in vector called A, and the contents
      of this vector will be changed several times while performing
      the matrix-vector product y <- Ax.

   3) Included header files:

      File             Contents
      -----------      --------------------------------------------
      ardnsmat.h       The ARdsNonSymMatrix class definition.
      arssym.h         The ARSymStdEig class definition.

   4) ARPACK Authors:

      Richard Lehoucq
      Kristyn Maschhoff
      Danny Sorensen
      Chao Yang
      Dept. of Computational & Applied Mathematics
      Rice University
      Houston, Texas
*/

#include "arssym.h"
#include "ardnsmat.h"
#include "iostream.h"
#include <math.h>

int main()
{

  // Defining variables;

  int     i;
  double* svalue = new double[4];

  // Using ARdsNonSymMatrix to store matrix data and to
  // perform the product A'Ax (LU decomposition is not used).

  ARdsNonSymMatrix<double, double> A("matrix.dat", 250);

  // Defining what we need: eigenvalues with largest magnitude.

  ARSymStdEig<double, ARdsNonSymMatrix<double, double> >
    dprob(A.ncols(), 4L, &A, &ARdsNonSymMatrix<double, double>::MultMtMv);

  // Finding eigenvalues.

  dprob.Eigenvalues(svalue);

  // Calculating singular values.

  for (i=0; i<4; i++) {
    svalue[i] = sqrt(svalue[i]);
  }

  // Printing some information about the problem.

  cout << endl << "Testing ARPACK++ class ARSymStdEig" << endl;
  cout << "Obtaining singular values by solving (A'*A)*v = sigma*v" << endl;
  cout << endl << "greatest singular values: " << endl;
  for (i=0; i<4; i++) {
    cout << "  sigma [" << i+1 << "]: " << svalue[i] << endl;
  }

} // main.


text:
package org.antlr.analysis;

import org.antlr.tool.Grammar;
import org.antlr.misc.Utils;

import java.util.HashSet;
import java.util.Set;

/** A module to perform optimizations on DFAs.
 *
 *  I could more easily (and more quickly) do some optimizations (such as
 *  PRUNE_EBNF_EXIT_BRANCHES) during DFA construction, but then it
 *  messes up the determinism checking.  For example, it looks like
 *  loop exit branches are unreachable if you prune exit branches
 *  during DFA construction and before determinism checks.
 *
 *  In general, ANTLR's NFA->DFA->codegen pipeline seems very robust
 *  to me which I attribute to a uniform and consistent set of data
 *  structures.  Regardless of what I want to "say"/implement, I do so
 *  within the confines of, for example, a DFA.  The code generator
 *  can then just generate code--it doesn't have to do much thinking.
 *  Putting optimizations in the code gen code really starts to make
 *  it a spagetti factory (uh oh, now I'm hungry!).  The pipeline is
 *  very testable; each stage has well defined input/output pairs.
 *
 *  ### Optimization: PRUNE_EBNF_EXIT_BRANCHES
 *
 *  There is no need to test EBNF block exit branches.  Not only is it
 *  an unneeded computation, but counter-intuitively, you actually get
 *  better errors. You can report an error at the missing or extra
 *  token rather than as soon as you've figured out you will fail.
 *
 *  Imagine optional block "( DOT CLASS )? SEMI".  ANTLR generates:
 *
 *  int alt=0;
 *  if ( input.LA(1)==DOT ) {
 *      alt=1;
 *  }
 *  else if ( input.LA(1)==SEMI ) {
 *      alt=2;
 *  }
 *
 *  Clearly, since Parser.match() will ultimately find the error, we
 *  do not want to report an error nor do we want to bother testing
 *  lookahead against what follows the (...)?  We want to generate
 *  simply "should I enter the subrule?":
 *
 *  int alt=2;
 *  if ( input.LA(1)==DOT ) {
 *      alt=1;
 *  }
 *
 *  NOTE 1. Greedy loops cannot be optimized in this way.  For example,
 *  "(greedy=false:'x'|.)* '\n'".  You specifically need the exit branch
 *  to tell you when to terminate the loop as the same input actually
 *  predicts one of the alts (i.e., staying in the loop).
 *
 *  NOTE 2.  I do not optimize cyclic DFAs at the moment as it doesn't
 *  seem to work. ;)  I'll have to investigate later to see what work I
 *  can do on cyclic DFAs to make them have fewer edges.  Might have
 *  something to do with the EOT token.
 *
 *  ### PRUNE_SUPERFLUOUS_EOT_EDGES
 *
 *  When a token is a subset of another such as the following rules, ANTLR
 *  quietly assumes the first token to resolve the ambiguity.
 *
 *  EQ			: '=' ;
 *  ASSIGNOP	: '=' | '+=' ;
 *
 *  It can yield states that have only a single edge on EOT to an accept
 *  state.  This is a waste and messes up my code generation. ;)  If
 *  Tokens rule DFA goes
 *
 * 		s0 -'='-> s3 -EOT-> s5 (accept)
 *
 *  then s5 should be pruned and s3 should be made an accept.  Do NOT do this
 *  for keyword versus ID as the state with EOT edge emanating from it will
 *  also have another edge.
 *
 *  ### Optimization: COLLAPSE_ALL_INCIDENT_EDGES
 *
 *  Done during DFA construction.  See method addTransition() in
 *  NFAToDFAConverter.
 *
 *  ### Optimization: MERGE_STOP_STATES
 *
 *  Done during DFA construction.  See addDFAState() in NFAToDFAConverter.
 */
public class DFAOptimizer {
	public static boolean PRUNE_EBNF_EXIT_BRANCHES = true;
	public static boolean PRUNE_TOKENS_RULE_SUPERFLUOUS_EOT_EDGES = true;
	public static boolean COLLAPSE_ALL_PARALLEL_EDGES = true;
	public static boolean MERGE_STOP_STATES = true;

	/** Used by DFA state machine generator to avoid infinite recursion
	 *  resulting from cycles int the DFA.  This is a set of int state #s.
	 */
	protected Set visited = new HashSet();

    protected Grammar grammar;

    public DFAOptimizer(Grammar grammar) {
		this.grammar = grammar;
    }

	public void optimize() {
		// optimize each DFA in this grammar
		for (int decisionNumber=1;
			 decisionNumber<=grammar.getNumberOfDecisions();
			 decisionNumber++)
		{
			DFA dfa = grammar.getLookaheadDFA(decisionNumber);
			optimize(dfa);
		}
	}

	protected void optimize(DFA dfa) {
		if ( dfa==null ) {
			return; // nothing to do
		}
		/*
		System.out.println("Optimize DFA "+dfa.decisionNFAStartState.decisionNumber+
						   " num states="+dfa.getNumberOfStates());
		*/
		//long start = System.currentTimeMillis();
		if ( PRUNE_EBNF_EXIT_BRANCHES && dfa.canInlineDecision() ) {
			visited.clear();
			int decisionType =
				dfa.getNFADecisionStartState().decisionStateType;
			if ( dfa.isGreedy() &&
				 (decisionType==NFAState.OPTIONAL_BLOCK_START ||
				 decisionType==NFAState.LOOPBACK) )
			{
				optimizeExitBranches(dfa.startState);
			}
		}
		// If the Tokens rule has syntactically ambiguous rules, try to prune
		if ( PRUNE_TOKENS_RULE_SUPERFLUOUS_EOT_EDGES &&
			 dfa.isTokensRuleDecision() &&
			 dfa.probe.stateToSyntacticallyAmbiguousTokensRuleAltsMap.size()>0 )
		{
			visited.clear();
			optimizeEOTBranches(dfa.startState);
		}

		/* ack...code gen needs this, cannot optimize
		visited.clear();
		unlinkUnneededStateData(dfa.startState);
		*/
		//long stop = System.currentTimeMillis();
		//System.out.println("minimized in "+(int)(stop-start)+" ms");
    }

	protected void optimizeExitBranches(DFAState d) {
		Integer sI = Utils.integer(d.stateNumber);
		if ( visited.contains(sI) ) {
			return; // already visited
		}
		visited.add(sI);
		int nAlts = d.dfa.getNumberOfAlts();
		for (int i = 0; i < d.getNumberOfTransitions(); i++) {
			Transition edge = (Transition) d.transition(i);
			DFAState edgeTarget = ((DFAState)edge.target);
			/*
			System.out.println(d.stateNumber+"-"+
							   edge.label.toString(d.dfa.nfa.grammar)+"->"+
							   edgeTarget.stateNumber);
			*/
			// if target is an accept state and that alt is the exit alt
			if ( edgeTarget.isAcceptState() &&
				edgeTarget.getUniquelyPredictedAlt()==nAlts)
			{
				/*
				System.out.println("ignoring transition "+i+" to max alt "+
					d.dfa.getNumberOfAlts());
				*/
				d.removeTransition(i);
				i--; // back up one so that i++ of loop iteration stays within bounds
			}
			optimizeExitBranches(edgeTarget);
		}
	}

	protected void optimizeEOTBranches(DFAState d) {
		Integer sI = Utils.integer(d.stateNumber);
		if ( visited.contains(sI) ) {
			return; // already visited
		}
		visited.add(sI);
		for (int i = 0; i < d.getNumberOfTransitions(); i++) {
			Transition edge = (Transition) d.transition(i);
			DFAState edgeTarget = ((DFAState)edge.target);
			/*
			System.out.println(d.stateNumber+"-"+
							   edge.label.toString(d.dfa.nfa.grammar)+"->"+
							   edgeTarget.stateNumber);
			*/
			// if only one edge coming out, it is EOT, and target is accept prune
			if ( PRUNE_TOKENS_RULE_SUPERFLUOUS_EOT_EDGES &&
				edgeTarget.isAcceptState() &&
				d.getNumberOfTransitions()==1 &&
				edge.label.isAtom() &&
				edge.label.getAtom()==Label.EOT )
			{
				//System.out.println("state "+d+" can be pruned");
				// remove the superfluous EOT edge
				d.removeTransition(i);
				d.setAcceptState(true); // make it an accept state
				// force it to uniquely predict the originally predicted state
				d.cachedUniquelyPredicatedAlt =
					edgeTarget.getUniquelyPredictedAlt();
				i--; // back up one so that i++ of loop iteration stays within bounds
			}
			optimizeEOTBranches(edgeTarget);
		}
	}

	/** Walk DFA states, unlinking the nfa configs and whatever else I
	 *  can to reduce memory footprint.
	protected void unlinkUnneededStateData(DFAState d) {
		Integer sI = Utils.integer(d.stateNumber);
		if ( visited.contains(sI) ) {
			return; // already visited
		}
		visited.add(sI);
		d.nfaConfigurations = null;
		for (int i = 0; i < d.getNumberOfTransitions(); i++) {
			Transition edge = (Transition) d.transition(i);
			DFAState edgeTarget = ((DFAState)edge.target);
			unlinkUnneededStateData(edgeTarget);
		}
	}
	 */

}