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

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

Introduction

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

Prototype

Map<String, String> getOptions(boolean inheritJavaCoreOptions);

Source Link

Document

Returns the table of the current custom options for this project.

Usage

From source file:org.cubictest.ui.wizards.NewCubicTestProjectWizard.java

License:Open Source License

private IProject createProject(IProgressMonitor monitor, boolean launchNewTestWizard) {

    try {//w w  w .j  a  va  2s.c om
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IProject project = root.getProject(namePage.getProjectName());

        IProjectDescription description = ResourcesPlugin.getWorkspace()
                .newProjectDescription(project.getName());

        if (!Platform.getLocation().equals(namePage.getLocationPath()))
            description.setLocation(namePage.getLocationPath());

        description.setNatureIds(new String[] { JavaCore.NATURE_ID });
        ICommand buildCommand = description.newCommand();
        buildCommand.setBuilderName(JavaCore.BUILDER_ID);
        description.setBuildSpec(new ICommand[] { buildCommand });
        project.create(description, monitor);
        project.open(monitor);

        IJavaProject javaProject = JavaCore.create(project);
        Map<?, ?> java15options = javaProject.getOptions(true);
        JavaCore.setComplianceOptions("1.5", java15options);
        javaProject.setOptions(java15options);

        IFolder testFolder = project.getFolder(TESTS_FOLDER_NAME);
        testFolder.create(false, true, monitor);

        IFolder suiteFolder = project.getFolder(TEST_SUITES_FOLDER_NAME);
        suiteFolder.create(false, true, monitor);

        project.getFolder("src").create(false, true, monitor);
        project.getFolder("src/main").create(false, true, monitor);
        project.getFolder("src/test").create(false, true, monitor);

        IFolder javaSrcFolder = project.getFolder("src/main/java");
        javaSrcFolder.create(false, true, monitor);

        IFolder javaTestFolder = project.getFolder("src/test/java");
        javaTestFolder.create(false, true, monitor);

        IFolder customTestSuites = project.getFolder("src/test/java/customTestSuites");
        customTestSuites.create(false, true, monitor);

        IFolder binFolder = project.getFolder("bin");
        binFolder.create(false, true, monitor);

        IFolder libFolder = project.getFolder("lib");
        libFolder.create(false, true, monitor);

        WizardUtils.copyPom(project.getLocation().toFile());
        WizardUtils.copySampleCustomTestSuite(customTestSuites.getRawLocation().toFile());
        WizardUtils.copySettings(project.getLocation().toFile());

        //construct build path for the new project
        List<IClasspathEntry> classpathlist = new ArrayList<IClasspathEntry>();
        classpathlist.add(JavaCore.newSourceEntry(javaSrcFolder.getFullPath()));
        classpathlist.add(JavaCore.newSourceEntry(javaTestFolder.getFullPath()));
        classpathlist.add(JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")));

        javaProject.setOutputLocation(binFolder.getFullPath(), monitor);

        javaProject.setRawClasspath(classpathlist.toArray(new IClasspathEntry[classpathlist.size()]),
                binFolder.getFullPath(), monitor);

        ResourceNavigator navigator = null;
        IViewPart viewPart = workbench.getActiveWorkbenchWindow().getActivePage().getViewReferences()[0]
                .getView(false);

        if (viewPart instanceof ResourceNavigator) {
            navigator = (ResourceNavigator) viewPart;
        }

        if (launchNewTestWizard) {
            launchNewTestWizard(testFolder);
            if (navigator != null && testFolder.members().length > 0) {
                navigator.selectReveal(new StructuredSelection(testFolder.members()[0]));
            }
        }

        handlePluginBuildPathSupporters(javaProject, libFolder, classpathlist);

        project.refreshLocal(IResource.DEPTH_INFINITE, null);

        return project;

    } catch (Exception e) {
        ErrorHandler.logAndShowErrorDialogAndRethrow(e);
        return null;
    }
}

From source file:org.ebayopensource.turmeric.repositorysystem.imp.impl.TurmericProjectConfigurer.java

License:Open Source License

private void mavenizeAndCleanUp(final IProject project, final ProjectMavenizationRequest request,
        final IProgressMonitor monitor)
        throws CoreException, MavenEclipseApiException, IOException, InterruptedException, TemplateException {
    if (SOALogger.DEBUG)
        logger.entering(project, request);
    final IMavenEclipseApi api = MavenCoreUtils.mavenEclipseAPI();
    try {/* w ww.  j a v a 2 s  .  c  o  m*/
        //         It seems that the pom.xml is not updated in the Eclipse Workspace by the mavenize project operation
        //         Util.refresh( project.getFile( "pom.xml" ) );
        //         Project Mavenization doesn't seem to care that the output directory is set here and set in the pom.xml
        //         it will use the maven default of target-eclipse no matter what.
        IJavaProject javaProject = null;
        try {
            api.mavenizeProject(request, monitor);
            logger.info("Mavenization finished->" + project);
            ProgressUtil.progressOneStep(monitor);
            javaProject = JavaCore.create(project);
            //javaProject.setOutputLocation( project.getFolder( SOAProjectConstants.FOLDER_OUTPUT_DIR).getFullPath(), null );
            FileUtils.deleteDirectory(project.getFolder("target-eclipse").getLocation().toFile());
            //Util.delete( project.getFolder( "target-eclipse" ), null );
            final Map<?, ?> options = javaProject.getOptions(false);
            options.clear();
            javaProject.setOptions(options);
        } catch (NullPointerException e) {
            throw new CoreException(EclipseMessageUtils.createErrorStatus(
                    "NPE occured during projects mavenization.\n\n"
                            + "The possible cause is that the M2Eclipse Maven indexes in your current workspace might be corrupted. "
                            + "Please remove folder {workspace}/.metadata/.plugins/org.maven.ide.eclipse/, and then restart your IDE.",
                    e));
        }
        //         The Mavenization also seemed to take the META-SRC src directory and add an exclusion pattern along with
        //         setting its output location to itself.  Maybe they wanted to do a class library folder?  Either way its
        //         no good for us.  Secondly, we are setting the Maven classpath container to have its entries exported by default.
        //         Finally, we are adding the classpath entry attribute 'org.eclipse.jst.component.dependency' in case the project
        //         is a WTP web project so that WTP will use the maven classpath container when deploying to its runtime servers.
        boolean changed = false;
        final List<IClasspathEntry> newEntries = ListUtil.list();
        final IPath containerPath = new Path(SOAMavenConstants.MAVEN_CLASSPATH_CONTAINER_ID);
        for (final IClasspathEntry cpEntry : JDTUtil.rawClasspath(javaProject, true)) {
            if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (cpEntry.getPath().equals(containerPath)) {
                    newEntries.add(JavaCore.newContainerEntry(containerPath, true));
                    changed |= true;
                }
            } else if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (!ArrayUtils.isEmpty(cpEntry.getExclusionPatterns())
                        || cpEntry.getOutputLocation() != null) {
                    newEntries.add(JavaCore.newSourceEntry(cpEntry.getPath()));
                    changed |= true;
                } else {
                    newEntries.add(cpEntry);
                }
            } else {
                newEntries.add(cpEntry);
            }
        }
        ProgressUtil.progressOneStep(monitor, 15);
        if (changed) {
            javaProject.setRawClasspath(newEntries.toArray(new IClasspathEntry[0]), null);
            ProgressUtil.progressOneStep(monitor);
            //This is a hot fix for the Maven classpath container issue,
            //should be removed as soon as the M2Eclipse guys fix it
            int count = 0; //we only go to sleep 5 times.
            while (MavenCoreUtils.getMaven2ClasspathContainer(javaProject).getClasspathEntries().length == 0
                    && count < 5) {
                logger.warning("Maven Classpath is empty->", SOAMavenConstants.MAVEN_CLASSPATH_CONTAINER_ID,
                        ", going to sleep...");
                Thread.sleep(1000);
                ProgressUtil.progressOneStep(monitor, 10);
                count++;
            }
        }
    } finally {
        if (SOALogger.DEBUG)
            logger.exiting();
    }
}

From source file:org.eclim.plugin.jdt.command.format.FormatCommand.java

License:Open Source License

/**
 * {@inheritDoc}// w  ww .j a v a 2 s  .  c  o m
 * @see org.eclim.command.Command#execute(CommandLine)
 */
public String execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int bByteOffset = commandLine.getIntValue(Options.BOFFSET_OPTION);
    int eByteOffset = commandLine.getIntValue(Options.EOFFSET_OPTION);
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);

    IJavaProject myProject = JavaUtils.getJavaProject(project);
    DefaultCodeFormatter formatter = new DefaultCodeFormatter(myProject.getOptions(false));

    int kind = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS;

    String source = src.getBuffer().getContents();
    String vimEncoding = "UTF-8";
    byte[] byteSource = source.getBytes(vimEncoding);
    ByteArrayOutputStream outStream = null;

    outStream = new ByteArrayOutputStream();
    outStream.write(byteSource, 0, bByteOffset);
    String sourcePrefix = outStream.toString(vimEncoding);

    outStream = new ByteArrayOutputStream();
    outStream.write(byteSource, bByteOffset, eByteOffset - bByteOffset);
    String sourceRoot = outStream.toString(vimEncoding);

    int bCharOffset = sourcePrefix.length();
    int eCharOffset = bCharOffset + sourceRoot.length();
    int charLength = eCharOffset - bCharOffset;

    String lineDelimiter = StubUtility.getLineDelimiterUsed(src);
    TextEdit edits = formatter.format(kind, source, bCharOffset, charLength, 0, lineDelimiter);
    if (edits == null) {
        return "no edits returned on attempt to format the source.";
    }
    Document document = new Document(src.getBuffer().getContents());
    edits.apply(document);
    src.getBuffer().setContents(document.get());
    src.save(null, false);

    return StringUtils.EMPTY;
}

From source file:org.eclim.plugin.jdt.preference.OptionHandler.java

License:Open Source License

@Override
public Map<String, String> getValues(IProject project) throws Exception {
    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        throw new IllegalArgumentException(Services.getMessage("project.not.found", project.getName()));
    }//w  ww  . j a v a2  s . co  m

    @SuppressWarnings("unchecked")
    Map<String, String> coreOptions = javaProject.getOptions(true);
    Map<String, String> options = new Hashtable<String, String>();
    options.putAll(coreOptions);
    options.putAll(getUIValues(project));

    URL javadoc = JavaUI.getProjectJavadocLocation(javaProject);
    options.put(PROJECT_JAVADOC, javadoc != null ? javadoc.toString() : "");

    return options;
}

From source file:org.eclim.plugin.jdt.preference.OptionHandler.java

License:Open Source License

@Override
public void setOption(IProject project, String name, String value) throws Exception {
    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        throw new IllegalArgumentException(Services.getMessage("project.not.found", project.getName()));
    }/*from   w w  w.j a  v  a 2  s  .c  om*/

    @SuppressWarnings("unchecked")
    Map<String, String> global = javaProject.getOptions(true);
    @SuppressWarnings("unchecked")
    Map<String, String> options = javaProject.getOptions(false);

    Object current = global.get(name);
    if (current == null || !current.equals(value)) {
        if (name.equals(JavaCore.COMPILER_SOURCE)) {
            JavaUtils.setCompilerSourceCompliance(javaProject, value);
        } else if (name.equals(PROJECT_JAVADOC)) {
            if (value != null && value.trim().length() == 0) {
                value = null;
            }
            try {
                JavaUI.setProjectJavadocLocation(javaProject, value != null ? new URL(value) : null);
            } catch (MalformedURLException mue) {
                throw new IllegalArgumentException(
                        PROJECT_JAVADOC + ": Invalid javadoc url: " + mue.getMessage());
            }
        } else if (name.startsWith(JavaUI.ID_PLUGIN)) {
            Preferences.getInstance().setPreference(JavaUI.ID_PLUGIN, project, name, value);
        } else {
            options.put(name, value);
            javaProject.setOptions(options);
        }
    }
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Gets the java version for which all source is to be compatable with.
 *
 * @param project The java project.//  ww w  .  ja  va  2s  . c  o m
 * @return The source compliance version.
 */
public static String getCompilerSourceCompliance(IJavaProject project) {
    return (String) project.getOptions(true).get(JavaCore.COMPILER_SOURCE);
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Sets the java version for which all source is to be compatable with.
 *
 * @param project The java project.//  ww w .j  av a  2  s .c  o m
 * @param version The java version.
 */
@SuppressWarnings("unchecked")
public static void setCompilerSourceCompliance(IJavaProject project, String version) throws Exception {
    // using project.setOption(String,String) doesn't save the setting.
    Map<String, String> options = project.getOptions(false);
    options.put(JavaCore.COMPILER_SOURCE, version);
    options.put(JavaCore.COMPILER_COMPLIANCE, version);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, version);

    project.setOptions(options);
}

From source file:org.eclipse.ajdt.core.javaelements.AJCompilationUnit.java

License:Open Source License

/**
 * builds the structure of this Compilation unit.  We need to use an aspect-aware parser for this (in the org.aspectj.org.eclipse... world, which
 * makes things a little messy//w  w w  .j  ava 2s  .  co  m
 */
protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    AJCompilationUnitInfo unitInfo = (AJCompilationUnitInfo) info;

    if (ajFile == null) {
        return false;
    }

    // ensure buffer is opened
    IBuffer buffer = getBufferManager().getBuffer(this);
    if (buffer == null) {
        openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
    }

    // generate structure and compute syntax problems if needed
    AJCompilationUnitStructureRequestor requestor = new AJCompilationUnitStructureRequestor(this, unitInfo,
            newElements);
    JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
    IJavaProject project = getJavaProject();

    boolean createAST;
    boolean resolveBindings;
    int reconcileFlags;
    //        HashMap problems;
    AJCompilationUnitInfo astHolder = (AJCompilationUnitInfo) info;
    createAST = astHolder.getASTLevel() != NO_AST;
    resolveBindings = astHolder.doResolveBindings();
    reconcileFlags = astHolder.getReconcileFlags();
    //        problems = astHolder.getProblems();

    boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
            && AspectJPlugin.isAJProject(project.getProject());
    org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory problemFactory = new org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory();
    Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
    if (!computeProblems) {
        // disable task tags checking to speed up parsing
        options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    }

    // ensure parser sees the real contents (not the fake java buffer)
    this.requestOriginalContentMode();

    // use an aspectj aware source parser
    AJSourceElementParser ajdtParser = new AJSourceElementParser(requestor, problemFactory,
            new org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions(options),
            true/*report local declarations*/,
            !createAST /*optimize string literals only if not creating a DOM AST*/);

    ajdtParser.reportOnlyOneSyntaxError = !computeProblems;
    ajdtParser.setMethodsFullRecovery(true);
    ajdtParser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

    if (!computeProblems && !resolveBindings && !createAST) {
        // disable javadoc parsing if not computing problems, not resolving and not creating ast
        ajdtParser.javadocParser.checkDocComment = false;
    }
    requestor.setParser(ajdtParser);

    // update timestamp (might be IResource.NULL_STAMP if original does not exist)
    if (underlyingResource == null) {
        underlyingResource = getResource();
    }
    // underlying resource is null in the case of a working copy on a class file in a jar
    if (underlyingResource != null)
        unitInfo.setTimestamp(((IFile) underlyingResource).getModificationStamp());

    // compute other problems if needed
    CompilationUnitDeclaration compilationUnitDeclaration = null;
    final AJCompilationUnit source = ajCloneCachingContents();
    requestor.setSource(source.getContents());
    try {
        if (false) {
            // for now, don't go here
            // the problem is that we can't find problems and build structure at the same time
            // they require difference kinds of parsers.
            //            if (computeProblems) {
            //                if (problems == null) {
            //                    // report problems to the problem requestor
            //                    problems = new HashMap();
            //                    compilationUnitDeclaration = AJCompilationUnitProblemFinder.processAJ(
            //                            source, ajdtParser, this.owner, problems, createAST, reconcileFlags, pm);
            //                    try {
            //                        perWorkingCopyInfo.beginReporting();
            //                        for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
            //                            CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
            //                            if (categorizedProblems == null) continue;
            //                            for (int i = 0, length = categorizedProblems.length; i < length; i++) {
            //                                perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
            //                            }
            //                        }
            //                    } finally {
            //                        perWorkingCopyInfo.endReporting();
            //                    }
            //                } else {
            //                    // collect problems
            //                    compilationUnitDeclaration = AJCompilationUnitProblemFinder.processAJ(source, ajdtParser, this.owner, problems, createAST, reconcileFlags, pm);
            //                }
        } else {
            // since we are doing n aspectj aware parse with the AJ parser
            // need to wrap the results in a JDT CompilationUnitDeclaration
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration ajDeclaration = ajdtParser
                    .parseCompilationUnit(
                            new org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
                                public char[] getContents() {
                                    return source.getContents();
                                }

                                public char[] getMainTypeName() {
                                    return source.getMainTypeName();
                                }

                                public char[][] getPackageName() {
                                    return source.getPackageName();
                                }

                                public char[] getFileName() {
                                    return source.getFileName();
                                }

                                public boolean ignoreOptionalProblems() {
                                    return false;
                                }
                            }, true /*full parse to find local elements*/);
            compilationUnitDeclaration = new AJCompilationUnitDeclarationWrapper(ajDeclaration, source);
        }

        if (createAST) {
            // XXX hmmmm...may not work
            int astLevel = unitInfo.getASTLevel();
            org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel,
                    compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
            unitInfo.setAST(cu);
        }
    } finally {
        discardOriginalContentMode();
        if (compilationUnitDeclaration != null) {
            compilationUnitDeclaration.cleanUp();
        }
    }

    return unitInfo.isStructureKnown();
}

From source file:org.eclipse.ajdt.core.parserbridge.AJCompilationUnitProblemFinder.java

License:Open Source License

private CompilerOptions getCompilerOptions(IJavaElement elt) {
    IJavaProject project = elt.getJavaProject();
    Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
    return new CompilerOptions(options);
}

From source file:org.eclipse.ajdt.internal.ui.editor.CompilationUnitAnnotationModelWrapper.java

License:Open Source License

public void beginReporting() {
    if (delegate != null) {
        ((IProblemRequestor) delegate).beginReporting();

        IJavaProject project = unit.getJavaProject();

        AJCompilationUnitStructureRequestor requestor = new AJCompilationUnitStructureRequestor(unit,
                new AJCompilationUnitInfo(), new HashMap());
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = ((CompilationUnit) unit)
                .getPerWorkingCopyInfo();
        boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null
                && perWorkingCopyInfo.isActive();
        IProblemFactory problemFactory = new DefaultProblemFactory();
        Map options = project.getOptions(true);
        IBuffer buffer;//  ww  w  . j av  a 2 s  .  c o m
        try {
            buffer = unit.getBuffer();

            final char[] contents = buffer == null ? null : buffer.getCharacters();

            AJSourceElementParser parser = new AJSourceElementParser(requestor, problemFactory,
                    new CompilerOptions(options), true/*report local declarations*/, false);
            parser.reportOnlyOneSyntaxError = !computeProblems;

            parser.scanner.source = contents;
            requestor.setParser(parser);

            CompilationUnitDeclaration unitDec = parser.parseCompilationUnit(
                    new org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
                        public char[] getContents() {
                            return contents;
                        }

                        public char[] getMainTypeName() {
                            return ((CompilationUnit) unit).getMainTypeName();
                        }

                        public char[][] getPackageName() {
                            return ((CompilationUnit) unit).getPackageName();
                        }

                        public char[] getFileName() {
                            return ((CompilationUnit) unit).getFileName();
                        }

                        public boolean ignoreOptionalProblems() {
                            return false;
                        }
                    }, true /*full parse to find local elements*/);
            org.aspectj.org.eclipse.jdt.core.compiler.IProblem[] problems = unitDec.compilationResult.problems;
            if (problems != null) {
                for (int i = 0; i < problems.length; i++) {
                    org.aspectj.org.eclipse.jdt.core.compiler.IProblem problem = problems[i];
                    if (problem == null)
                        continue;
                    ((IProblemRequestor) delegate)
                            .acceptProblem(
                                    new DefaultProblem(problem.getOriginatingFileName(), problem.getMessage(),
                                            problem.getID(), problem.getArguments(),
                                            problem.isError() ? ProblemSeverities.Error
                                                    : ProblemSeverities.Warning,
                                            problem.getSourceStart(), problem.getSourceEnd(),
                                            problem.getSourceLineNumber(), 0)); // unknown column
                }
            }
        } catch (JavaModelException e) {
        }
    }
}