Example usage for org.eclipse.jdt.core IJavaProject getProject

List of usage examples for org.eclipse.jdt.core IJavaProject getProject

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getProject.

Prototype

IProject getProject();

Source Link

Document

Returns the IProject on which this IJavaProject was created.

Usage

From source file:com.density.ezsbt.views.SbtViewerDropAdapter.java

License:Apache License

@Override
public boolean performDrop(Object data) {
    if (data.getClass().isAssignableFrom(TreeSelection.class)) {
        TreeSelection treeSelection = (TreeSelection) data;
        Object obj = treeSelection.getFirstElement();
        if (IJavaProject.class.isAssignableFrom(obj.getClass())) {
            IJavaProject javaProject = (IJavaProject) obj;
            return addNewSbtProject(javaProject.getProject());
        } else if (IContainer.class.isAssignableFrom(obj.getClass())) {
            return addNewSbtProject((IContainer) obj);
        }// www .j  ava  2 s .  c om
    }
    return false;
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.utils.JavaUtils.java

License:Open Source License

/**
 * Creates a JAR file containing all the resources contained in the source folders of a Java project.
 * @param jp the Java project/*w w  w.j  a va2s .  c  o m*/
 * @param monitor the progress monitor
 * @return the JAR file, which was saved in the temporary folder (and should be deleted after use)
 * @throws InvocationTargetException if the creation failed
 * @throws InterruptedException if the creation was interrupted
 */
public static File createDefaultJar(IJavaProject jp, IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {

    // Create a default JAR for the implementation
    JarPackageData jarDescription = new JarPackageData();
    jarDescription.setIncludeDirectoryEntries(true);
    jarDescription.setExportClassFiles(true);
    jarDescription.setOverwrite(true);
    jarDescription.setIncludeDirectoryEntries(true);

    jarDescription.setExportJavaFiles(false);
    jarDescription.setCompress(true);
    jarDescription.setExportErrors(true);
    jarDescription.setExportWarnings(true);

    // Add all the files in the source folders
    List<Object> filesToPackage = new ArrayList<Object>();
    for (IClasspathEntry entry : getSourceFolders(jp)) {

        // PETALSSTUD-130: use the project location and not the workspace root as a reference
        File f = jp.getProject().getLocation().append(entry.getPath().removeFirstSegments(1)).toFile();
        // PETALSSTUD-130

        IFolder folder = (IFolder) ResourceUtils.getResource(f);
        if (folder != null) {
            List<IFile> files = ResourceUtils.getFilesByRegexp(folder, ".*");
            filesToPackage.addAll(files);
        }
    }

    Object[] elements = new Object[filesToPackage.size()];
    jarDescription.setElements(filesToPackage.toArray(elements));

    // Create the JAR
    IPath jarLocation = new Path(System.getProperty("java.io.tmpdir"))
            .append(jp.getProject().getName() + ".jar");

    // Bug: Windows => path separator = "\"
    // But IPath#isAbsolute() only checks for "/" path separators
    // => We replace the path separator
    // Otherwise, the JAR is created, but not at the location we would expect
    jarLocation = new Path(jarLocation.toString().replaceAll("\\\\", "/"));
    jarDescription.setJarLocation(jarLocation);

    IJarExportRunnable runnable = jarDescription.createJarExportRunnable(null);
    runnable.run(monitor);
    IStatus status = runnable.getStatus();
    if (!status.isOK())
        PetalsCommonPlugin.getDefault().getLog().log(status);

    return jarLocation.toFile();
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.utils.JavaUtils.java

License:Open Source License

/**
 * Creates a new source folder.//from  www. j a v a  2s. co  m
 * <p>
 * If the folder does not exist, it is created.<br />
 * If the directory is already in the class path, then this method does nothing.
 * </p>
 *
 * @param jp the Java project
 * @param folderName the folder name
 * @param monitor the progress monitor
 * @return the created folder
 * @throws CoreException if something went wrong
 */
public static IFolder createSourceFolder(IJavaProject jp, String folderName, IProgressMonitor monitor)
        throws CoreException {

    IFolder newSourceFolder = jp.getProject().getFolder(folderName);
    if (!newSourceFolder.exists())
        newSourceFolder.create(true, true, monitor);

    IClasspathEntry srcEntry = JavaCore.newSourceEntry(newSourceFolder.getFullPath());
    Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>();
    entries.addAll(Arrays.asList(jp.getRawClasspath()));
    entries.add(srcEntry);
    jp.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), monitor);

    return newSourceFolder;
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.utils.JaxWsUtils.java

License:Open Source License

/**
 * Generates a WSDL from a JAX-WS annotated class.
 * <p>//  w  w  w.j  a  va 2 s  . c  o  m
 * If an error occurs during the execution, it will appear in the returned
 * string builder.
 * </p>
 *
 * @param className the name of the annotated class
 * @param targetDirectory the target directory
 * @param jp the Java project that contains this class
 * @return a string builder containing the execution details
 * @throws IOException if WSgen was not found, or if the process could not be started
 * @throws InterruptedException
 * @throws JaxWsException if the generation seems to have failed
 */
public StringBuilder generateWsdl(String className, File targetDirectory, IJavaProject jp)
        throws IOException, InterruptedException, JaxWsException {

    // Create the temporary file
    synchronized (TEMP_FILE) {
        if (!TEMP_FILE.exists() && !TEMP_FILE.mkdir())
            throw new IOException("The class directories could not be created.");
    }

    final StringBuilder outputBuffer = new StringBuilder();
    int exitValue = 0;
    try {
        File executable = getJavaExecutable(true);

        // Build the class path
        StringBuilder classpath = new StringBuilder();
        String separator = System.getProperty("path.separator");
        for (String entry : JavaUtils.getClasspath(jp, true, true))
            classpath.append(entry + separator);

        IPath binPath = null;
        try {
            binPath = jp.getOutputLocation();
        } catch (JavaModelException e) {
            PetalsCommonPlugin.log(e, IStatus.ERROR);
        }

        if (binPath != null) {
            binPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(binPath);
            File binFile = binPath.toFile();
            if (!binFile.exists() && !binFile.mkdir())
                PetalsCommonPlugin.log("The 'bin' directory could not be created.", IStatus.WARNING);
        }

        // Build the command line
        List<String> cmd = new ArrayList<String>();
        cmd.add(executable.getAbsolutePath());
        cmd.add("-verbose");
        cmd.add("-wsdl");
        cmd.add("-classpath");
        cmd.add(classpath.toString());
        cmd.add("-r");
        cmd.add(targetDirectory.getAbsolutePath());
        cmd.add("-d");
        cmd.add(TEMP_FILE.getAbsolutePath());
        cmd.add("-s");
        cmd.add(TEMP_FILE.getAbsolutePath());
        cmd.add(className);

        // Create the process
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb = pb.redirectErrorStream(true);
        final Process process = pb.start();

        // Monitor the execution
        Thread loggingThread = new Thread() {
            @Override
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line = "";
                    try {
                        while ((line = reader.readLine()) != null)
                            outputBuffer.append(line + "\n");
                    } finally {
                        reader.close();
                    }

                } catch (IOException ioe) {
                    PetalsCommonPlugin.log(ioe, IStatus.ERROR);
                }
            }
        };
        loggingThread.start();
        loggingThread.join();
        exitValue = process.waitFor();

    } finally {

        // Free the temporary directory
        synchronized (TEMP_FILE) {
            IoUtils.deleteFilesRecursively(TEMP_FILE.listFiles());
        }

        // Keep a trace of the generation
        JaxWsException loggingException;
        if (exitValue != 0) {
            loggingException = new JaxWsException(
                    "The JAX-WS process did not return 0. An error may have occurred.") {
                private static final long serialVersionUID = -8585870927871804985L;

                @Override
                public void printStackTrace(PrintStream s) {
                    s.print(outputBuffer.toString());
                }

                @Override
                public void printStackTrace(PrintWriter s) {
                    s.print(outputBuffer.toString());
                }
            };

            throw loggingException;

        } else if (PreferencesManager.logAllJaxWsTraces()) {
            loggingException = new JaxWsException(
                    "Logging the WSDL generation trace (" + jp.getProject().getName() + ").") {
                private static final long serialVersionUID = -5344307338271840633L;

                @Override
                public void printStackTrace(PrintStream s) {
                    s.print(outputBuffer.toString());
                }

                @Override
                public void printStackTrace(PrintWriter s) {
                    s.print(outputBuffer.toString());
                }
            };

            PetalsCommonPlugin.log(loggingException, IStatus.INFO);
        }
    }

    return outputBuffer;
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.utils.JaxWsUtils.java

License:Open Source License

/**
 * Searches all the Java types from a Java project that are annotated with @WebService.
 *
 * @param jp the containing Java project
 * @param monitor the progress monitor/*  w  w  w  .  j  ava  2  s  .  com*/
 * @param includeClasses true to include classes in the search results
 * @param includeInterfaces true to include the interfaces in the search results
 * @return a Map
 * <p>
 * Key = the qualified name of the annotated type<br />
 * Value = the associated service name (in the target WSDL)
 * </p>
 *
 * @throws CoreException if the search could not be launched
 */
public static Map<String, String> getJaxAnnotatedJavaTypes(IJavaProject jp, IProgressMonitor monitor,
        final boolean includeClasses, final boolean includeInterfaces) throws CoreException {

    jp.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
    jp.getProject().build(IncrementalProjectBuilder.FULL_BUILD, monitor);

    final Map<String, String> classNameToServiceName = new HashMap<String, String>();
    SearchPattern pattern = SearchPattern.createPattern(WEB_WS_ANNOTATION, IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

    // This is what we do when we find a match
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {

            // We get the Java type that is annotated with @WebService
            if (match.getElement() instanceof IType) {

                // Find the annotation
                IType type = (IType) match.getElement();
                if (type.isInterface() && includeInterfaces || type.isClass() && includeClasses) {

                    IAnnotation ann = type.getAnnotation(WEB_WS_ANNOTATION);
                    if (!ann.exists())
                        ann = type.getAnnotation(SHORT_WEB_WS_ANNOTATION);

                    // Get the service name and store it
                    if (ann.exists()) {
                        String serviceName = null;
                        for (IMemberValuePair pair : ann.getMemberValuePairs()) {
                            if ("serviceName".equalsIgnoreCase(pair.getMemberName())) {
                                serviceName = (String) pair.getValue();
                                break;
                            }
                        }

                        if (serviceName == null)
                            serviceName = type.getElementName() + "Service";

                        classNameToServiceName.put(type.getFullyQualifiedName(), serviceName);
                    }
                }
            }
        }
    };

    new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
            SearchEngine.createJavaSearchScope(new IJavaElement[] { jp }, false), requestor, monitor);

    return classNameToServiceName;
}

From source file:com.ebmwebsourcing.petals.services.jsr181.handlers.Jsr181GenerationHandler.java

License:Open Source License

/**
 * Generates files for the JSR-181.//from w  w w  .  j a v  a2  s.c  o m
 * <p>
 * 1. All the WSDL and XML schemas are deleted from the "jbi" directory.<br />
 * 2. Are listed all the classes contained in the project and annotated @WebService.<br />
 * 3. For each annotated class, a WSDL is generated in the "jbi" directory.<br />
 * 4. Eventually, if the option is activated, a jbi.xml is generated from all the WSDL.
 * </p>
 *
 * @param javaProject
 * @param generateJbiXml
 * @param monitor
 * @throws CoreException
 */
public static void generateJsr181Files(IJavaProject javaProject, boolean generateJbiXml,
        IProgressMonitor monitor) throws CoreException {

    // Delete all the WSDL and XSD files from the "jbi" directory
    IFolder jbiFolder = javaProject.getProject().getFolder(PetalsConstants.LOC_RES_FOLDER);
    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
    for (IResource res : jbiFolder.members()) {
        if (res instanceof IFile && (res.getName().endsWith(".wsdl") || res.getName().endsWith(".xsd")))
            res.delete(true, monitor);
    }

    // Get the classes that contain a JAX annotated service
    Map<String, String> classNameToServiceName = JaxWsUtils.getJaxAnnotatedJavaTypes(javaProject, monitor, true,
            false);

    // Create the WSDL
    Map<String, String> classNameToWsdlName = new HashMap<String, String>(classNameToServiceName.size());
    File targetDirectory = jbiFolder.getLocation().toFile();
    int generationErrorsCpt = 0;
    for (Map.Entry<String, String> entry : classNameToServiceName.entrySet()) {
        try {
            if (monitor != null && monitor.isCanceled())
                throw new OperationCanceledException();

            JaxWsUtils.INSTANCE.generateWsdl(entry.getKey(), targetDirectory, javaProject);

            // Only store those whose were generated without error
            classNameToWsdlName.put(entry.getKey(), entry.getValue() + ".wsdl");

        } catch (IOException e) {
            PetalsJsr181Plugin.log(e, IStatus.ERROR);

        } catch (InterruptedException e) {
            PetalsJsr181Plugin.log(e, IStatus.ERROR);

        } catch (JaxWsException e) {
            generationErrorsCpt++;
            PetalsJsr181Plugin.log(e, IStatus.ERROR);
        }
    }

    jbiFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

    // Generate the jbi.xml?
    if (generateJbiXml)
        generateJbiXml(javaProject.getProject(), classNameToWsdlName, monitor);

    ResourceUtils.selectResourceInPetalsExplorer(true, jbiFolder);

    // Report errors
    if (generationErrorsCpt != 0) {
        final String msg = generationErrorsCpt + (generationErrorsCpt > 1 ? " errors" : " error")
                + " occurred during the generation process.\nCheck the log for more details.";

        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                MessageDialog.openError(new Shell(), "Generation Error", msg);
            }
        });
    }
}

From source file:com.ebmwebsourcing.petals.services.jsr181.v11.Jsr181ProvidesWizard11.java

License:Open Source License

@Override
public IStatus performLastActions(IFolder resourceFolder, AbstractEndpoint ae, IProgressMonitor monitor) {

    // Generate the JAX-WS part
    IStatus result = Status.OK_STATUS;//from w w  w .j  a  v  a2  s  .  c  o  m
    try {
        // Java project
        IJavaProject jp = JavaUtils.createJavaProject(resourceFolder.getProject());

        // Start working on the JAX-WS part
        if (this.page.isWsdlFirst()) {
            wsdlFirstApproach(jp, ae, monitor);
        } else {
            implementationFirstApproach(jp.getProject(), ae, monitor);
        }

        // Find the libraries to add in the project class path
        JavaUtils.updateClasspathWithProjectLibraries(jp, monitor, "libs-cdk-p4", "libs-jsr181");

    } catch (CoreException e) {
        result = new Status(Status.ERROR, PetalsJsr181Plugin.PLUGIN_ID, "Jsr181 Error", e);

    } catch (IOException e) {
        result = new Status(Status.ERROR, PetalsJsr181Plugin.PLUGIN_ID, "Jsr181 Error", e);
    }

    return result;
}

From source file:com.ebmwebsourcing.petals.services.jsr181.v11.Jsr181ProvidesWizard11.java

License:Open Source License

/**
 * Completes the wizard for a WSDL-first approach.
 *
 * @param jp the Java project/*from  w w w  . ja  v a  2s . c om*/
 * @param ae
 * @param resourcesToSelect
 * @param monitor
 */
private void wsdlFirstApproach(IJavaProject jp, AbstractEndpoint ae, IProgressMonitor monitor) {

    try {
        // Create the WS implementation
        IProject project = jp.getProject();
        URI wsdlUri = UriAndUrlHelper.urlToUri(this.page.getWsdlUriAsString());

        IFolder srcFolder = project.getFolder(PetalsConstants.LOC_SRC_FOLDER);
        File srcDirectory = srcFolder.getLocation().toFile();

        Map<String, String> buildOptions = new HashMap<String, String>();
        JaxWsUtils.INSTANCE.generateWsClient(wsdlUri, srcDirectory);
        srcFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        project.build(IncrementalProjectBuilder.FULL_BUILD, JavaCore.BUILDER_ID, buildOptions, monitor);

        srcFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        JaxWsUtils.removeWebServiceClient(jp, monitor);
        Map<String, String> serviceNameToClassName = JaxWsUtils.createJaxWsImplementation(jp, monitor);
        srcFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        project.build(IncrementalProjectBuilder.FULL_BUILD, JavaCore.BUILDER_ID, buildOptions, monitor);

        // Update JBI
        JbiBasicBean bean = WsdlUtils.INSTANCE.parse(this.page.getWsdlUriAsString()).get(0);
        ae.eSet(JbiPackage.Literals.ABSTRACT_ENDPOINT__INTERFACE_NAME, bean.getInterfaceName());
        ae.eSet(JbiPackage.Literals.ABSTRACT_ENDPOINT__SERVICE_NAME, bean.getServiceName());
        ae.eSet(JbiPackage.Literals.ABSTRACT_ENDPOINT__ENDPOINT_NAME, bean.getEndpointName());
        ae.eSet(Jsr181Package.Literals.JSR181_PROVIDES__CLAZZ,
                serviceNameToClassName.values().iterator().next());

        // Import the WSDL in the project
        IFolder resFolder = project.getFolder(PetalsConstants.LOC_RES_FOLDER);
        File resFile = resFolder.getLocation().toFile();
        Map<String, File> uriToFile = new WsdlImportHelper().importWsdlOrXsdAndDependencies(resFile,
                this.page.getWsdlUriAsString());
        File f = uriToFile.get(this.page.getWsdlUriAsString());
        String wsdlName = f == null ? wsdlUri.toURL().getFile() : f.getName();
        ae.eSet(Cdk5Package.Literals.CDK5_PROVIDES__WSDL, wsdlName);

        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Open the implementation file
        final List<IFile> javaFiles = new ArrayList<IFile>();
        for (String className : serviceNameToClassName.values()) {
            IFile javaFile = srcFolder.getFile(className.replaceAll("\\.", "/") + ".java");
            javaFiles.add(javaFile);
        }

        this.resourcesToSelect.addAll(javaFiles);
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {

                try {
                    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                    for (IFile file : javaFiles)
                        IDE.openEditor(page, file);

                } catch (PartInitException e) {
                    PetalsJsr181Plugin.log(e, IStatus.ERROR);

                }
            }
        });

    } catch (Exception e) {
        PetalsJsr181Plugin.log(e, IStatus.ERROR);
    }
}

From source file:com.feup.contribution.druid.DruidPlugin.java

License:Open Source License

public void addDruidNature(IProject project) throws CoreException {
    if (project.hasNature(DRUID_NATURE))
        return;//w  w w.j av a2  s. com

    IProjectDescription description = project.getDescription();
    String[] ids = description.getNatureIds();
    String[] newIds = new String[ids.length + 1];
    System.arraycopy(ids, 0, newIds, 0, ids.length);
    newIds[ids.length] = DRUID_NATURE;
    description.setNatureIds(newIds);
    project.setDescription(description, null);

    IJavaProject javaProject = (IJavaProject) JavaCore.create((IProject) project);

    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();

    List<IClasspathEntry> newEntries = new ArrayList<IClasspathEntry>(rawClasspath.length + 1);
    for (IClasspathEntry e : rawClasspath) {
        newEntries.add(e);
    }
    newEntries.add(JavaCore.newContainerEntry(DruidClasspathContainer.CONTAINER_ID));

    IClasspathEntry[] newEntriesArray = new IClasspathEntry[newEntries.size()];
    newEntriesArray = (IClasspathEntry[]) newEntries.toArray(newEntriesArray);
    javaProject.setRawClasspath(newEntriesArray, null);

    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
}

From source file:com.github.caofangkun.bazelipse.classpath.BazelClasspathContainer.java

License:Open Source License

public BazelClasspathContainer(IPath path, IJavaProject project)
        throws IOException, InterruptedException, BackingStoreException, JavaModelException {
    this.path = path;
    this.project = project;
    this.instance = Activator.getBazelCommandInstance(project.getProject());
}