package com.zxin.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;

@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    // 超时配置
    @HystrixCommand
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {
        if (number % 2 == 0) {
            return "success";
        }
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://1

    }

    private String fallback() {
        return "太拥挤了, 请稍后再试~~";
    }

    private String defaultFallback() {
        return "默认提示：太拥挤了, 请稍后再试~~";
    }
}


if (number % 2 == 0) {
            return "success";
        }

package com.zxin.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;

@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    // 超时配置
    @HystrixCommand
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder", Arrays.asList("157875196366160022"), String.class);
    }

    private String fallback() {
        return "太拥挤了, 请稍后再试~~";
    }

    private String defaultFallback() {
        return "默认提示：太拥挤了, 请稍后再试~~";
    }
}


package org.jfugue;

/**
 * This is the base class for the JFugue elements, including Voice, Instrument,
 * Note, Controller, and Tempo. It requires that elements be able to return a
 * Music String representation of their settings.
 *
 * @author David Koelle
 * @version 2.0
 * @version 4.0 - Added getVerifyString()
 * @version 4.0.3 - Now extends Serializable
 */
public interface JFugueElement {

    /**
     * Returns the Music String representing this element and all of its
     * settings.
     *
     * @return the Music String for this element
     */

    /**
     * Returns a verification string, which should contain a String
     * representation of all of the aspects of the given element. This should be
     * in the following form: Thing: key=value, key=value, key=value,... For
     * example: Note: value=60, duration=0.25
     *
     * @version 4.0
     */
    public String getVerifyString();
}


@SuppressWarnings("unchecked")
    @Override
    protected Pair<Object, Object> retrieveMetadata(ViewerCell cell)

/*
 *
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://example.com>.
 *
 * Contributors:
 *     HUMBOLDT EU Integrated Project #030962
 *     Data Harmonisation Panel <http://www.dhpanel.eu>
 */
package eu.esdihumboldt.hale.ui.views.data.internal.explore;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerCell;
import eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;
import eu.esdihumboldt.util.Pair;

/**
 * Provides metadata actions for {@link TreeViewer}s used for data views explore
 * mode
 *
 * @author Sebastian Reinhardt
 */
public class MetadataExploreActionProvider extends MetadataActionProvider {

    /**
     * Standard Constructor
     *
     * @param treeViewer the TreeViewer to which the action will be applied
     */
    public MetadataExploreActionProvider(TreeViewer treeViewer) {
        super(treeViewer);
    }

    /**
     * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)
     */

{
        return (Pair<Object, Object>) cell.getElement();
    }
}


{
        return (Pair<Object, Object>) cell.getElement();
    }

/*
 *
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://example.com>.
 *
 * Contributors:
 *     HUMBOLDT EU Integrated Project #030962
 *     Data Harmonisation Panel <http://www.dhpanel.eu>
 */
package eu.esdihumboldt.hale.ui.views.data.internal.explore;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerCell;
import eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;
import eu.esdihumboldt.util.Pair;

/**
 * Provides metadata actions for {@link TreeViewer}s used for data views explore
 * mode
 *
 * @author Sebastian Reinhardt
 */
public class MetadataExploreActionProvider extends MetadataActionProvider {

    /**
     * Standard Constructor
     *
     * @param treeViewer the TreeViewer to which the action will be applied
     */
    public MetadataExploreActionProvider(TreeViewer treeViewer) {
        super(treeViewer);
    }

    /**
     * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)
     */
    @SuppressWarnings("unchecked")
    @Override
    protected Pair<Object, Object> retrieveMetadata(ViewerCell cell)


/*
 *
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://example.com>.
 *
 * Contributors:
 *     HUMBOLDT EU Integrated Project #030962
 *     Data Harmonisation Panel <http://www.dhpanel.eu>
 */
package eu.esdihumboldt.hale.ui.views.data.internal.explore;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerCell;
import eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;
import eu.esdihumboldt.util.Pair;

/**
 * Provides metadata actions for {@link TreeViewer}s used for data views explore
 * mode
 *
 * @author Sebastian Reinhardt
 */
public class MetadataExploreActionProvider extends MetadataActionProvider {

    /**
     * Standard Constructor
     *
     * @param treeViewer the TreeViewer to which the action will be applied
     */
    public MetadataExploreActionProvider(TreeViewer treeViewer) {
        super(treeViewer);
    }

    /**
     * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)
     */
    @SuppressWarnings("unchecked")
    @Override
    protected Pair<Object, Object> retrieveMetadata(ViewerCell cell) {
        return (


@SuppressWarnings("unchecked")
    @Override
    protected Pair<Object, Object> retrieveMetadata(ViewerCell cell) {
        return (Pair<Object, Object>) cell.getElement();
    }


@Override
    protected AbstractFilePickerFragment<FtpFile> getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick)

package com.nononsenseapps.filepicker.sample.ftp;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.nononsenseapps.filepicker.AbstractFilePickerActivity;
import com.nononsenseapps.filepicker.AbstractFilePickerFragment;
import org.apache.commons.net.ftp.FTPClient;

/**
 * An example implementation of an FTP file-picker
 */
public class FtpPickerActivity extends AbstractFilePickerActivity<FtpFile> {

{
        return FtpPickerFragment.newInstance(startPath, mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, "debian.simnet.is", FTPClient.DEFAULT_PORT, null, null, "/");
    }
}


{
        return FtpPickerFragment.newInstance(startPath, mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, "debian.simnet.is", FTPClient.DEFAULT_PORT, null, null, "/");
    }

package com.nononsenseapps.filepicker.sample.ftp;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.nononsenseapps.filepicker.AbstractFilePickerActivity;
import com.nononsenseapps.filepicker.AbstractFilePickerFragment;
import org.apache.commons.net.ftp.FTPClient;

/**
 * An example implementation of an FTP file-picker
 */
public class FtpPickerActivity extends AbstractFilePickerActivity<FtpFile> {

    @Override
    protected AbstractFilePickerFragment<FtpFile> getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick)


ode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, "debian.simnet.is", FTPClient.DEFAULT_PORT, null, null, "/");

package com.nononsenseapps.filepicker.sample.ftp;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.nononsenseapps.filepicker.AbstractFilePickerActivity;
import com.nononsenseapps.filepicker.AbstractFilePickerFragment;
import org.apache.commons.net.ftp.FTPClient;

/**
 * An example implementation of an FTP file-picker
 */
public class FtpPickerActivity extends AbstractFilePickerActivity<FtpFile> {

    @Override
    protected AbstractFilePickerFragment<FtpFile> getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) {
        return FtpPickerFragment.newInstance(startPath, m


public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object)

package net.sf.robocode.peer;

import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import java.io.Serializable;
import java.nio.ByteBuffer;

/**
 * @author Pavel Savara (original)
 */
public class TeamMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    public TeamMessage(String sender, String recipient, byte[] message) {
        this.sender = sender;
        this.recipient = recipient;
        this.message = message;
    }

    public final String sender;

    public final String recipient;

    public final byte[] message;

    static ISerializableHelper createHiddenSerializer() {
        return new SerializableHelper();
    }

    private static class SerializableHelper implements ISerializableHelper {

        public int sizeOf(RbSerializer serializer, Object object) {
            TeamMessage obj = (TeamMessage) object;
            final int s = serializer.sizeOf(obj.sender);
            final int r = serializer.sizeOf(obj.recipient);
            final int m = serializer.sizeOf(obj.message);
            return RbSerializer.SIZEOF_TYPEINFO + s + r + m;
        }

{
            TeamMessage obj = (TeamMessage) object;
            serializer.serialize(buffer, obj.sender);
            serializer.serialize(buffer, obj.recipient);
            serializer.serialize(buffer, obj.message);
        }

        public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
            String sender = serializer.deserializeString(buffer);
            String recipient = serializer.deserializeString(buffer);
            byte[] message = serializer.deserializeBytes(buffer);
            return new TeamMessage(sender, recipient, message);
        }
    }
}


{
            TeamMessage obj = (TeamMessage) object;
            final int s = serializer.sizeOf(obj.sender);
            final int r = serializer.sizeOf(obj.recipient);
            final int m = serializer.sizeOf(obj.message);
            return RbSerializer.SIZEOF_TYPEINFO + s + r + m;
        }

package net.sf.robocode.peer;

import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import java.io.Serializable;
import java.nio.ByteBuffer;

/**
 * @author Pavel Savara (original)
 */
public class TeamMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    public TeamMessage(String sender, String recipient, byte[] message) {
        this.sender = sender;
        this.recipient = recipient;
        this.message = message;
    }

    public final String sender;

    public final String recipient;

    public final byte[] message;

    static ISerializableHelper createHiddenSerializer() {
        return new SerializableHelper();
    }

    private static class SerializableHelper implements ISerializableHelper {

        public int sizeOf(RbSerializer serializer, Object object)

        public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {
            TeamMessage obj = (TeamMessage) object;
            serializer.serialize(buffer, obj.sender);
            serializer.serialize(buffer, obj.recipient);
            serializer.serialize(buffer, obj.message);
        }

        public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
            String sender = serializer.deserializeString(buffer);
            String recipient = serializer.deserializeString(buffer);
            byte[] message = serializer.deserializeBytes(buffer);
            return new TeamMessage(sender, recipient, message);
        }
    }
}


package net.sf.robocode.peer;

import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import java.io.Serializable;
import java.nio.ByteBuffer;

/**
 * @author Pavel Savara (original)
 */
public class TeamMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    public TeamMessage(String sender, String recipient, byte[] message) {
        this.sender = sender;
        this.recipient = recipient;
        this.message = message;
    }

    public final String sender;

    public final String recipient;

    public final byte[] message;

    static ISerializableHelper createHiddenSerializer() {
        return new SerializableHelper();
    }

    private static class SerializableHelper implements ISerializableHelper {

        public int sizeOf(RbSerializer serializer, Object object) {
            TeamMessage obj = (TeamMessage) object;
            final int s = serializer.sizeOf(obj.sender);
            final int r = serializer.sizeOf(obj.recipient);
            final int m = serializer.sizeOf(obj.message);
            return RbSerializer.SIZEOF_TYPEINFO + s + r + m;
        }

        public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {
            TeamMessage obj = (TeamMessage) object;
            serializer.serialize(buffer, obj.sender);
            serializer.serialize(buffer, obj.recipient);
            serializer.serialize(buffe

        }

        public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
            String sender = serializer.deserializeString(buffer);
            String recipient = serializer.deserializeString(buffer);
            byte[] message = serializer.deserializeBytes(buffer);
            return new TeamMessage(sender, recipient, message);
        }
    }
}


private boolean hasExtension(String name, String ext)

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

{
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}


{
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath)

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}


/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];


if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();

        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}


for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();

            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}


while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
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.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();

        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {
                try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }
            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}