Search in sources :

Example 6 with JavaSdkType

use of com.intellij.openapi.projectRoots.JavaSdkType in project intellij-community by JetBrains.

the class BuildPropertiesImpl method createJdkGenerators.

protected void createJdkGenerators(final Project project) {
    final Sdk[] jdks = getUsedJdks(project);
    if (jdks.length > 0) {
        add(new Comment(CompilerBundle.message("generated.ant.build.jdk.definitions.comment")), 1);
        for (final Sdk jdk : jdks) {
            if (jdk.getHomeDirectory() == null) {
                continue;
            }
            final SdkTypeId sdkType = jdk.getSdkType();
            if (!(sdkType instanceof JavaSdkType) || ((JavaSdkType) sdkType).getBinPath(jdk) == null) {
                continue;
            }
            final File home = VfsUtil.virtualToIoFile(jdk.getHomeDirectory());
            File homeDir;
            try {
                // use canonical path in order to resolve symlinks
                homeDir = home.getCanonicalFile();
            } catch (IOException e) {
                homeDir = home;
            }
            final String jdkName = jdk.getName();
            final String jdkHomeProperty = getJdkHomeProperty(jdkName);
            final FileSet fileSet = new FileSet(propertyRef(jdkHomeProperty));
            final String[] urls = jdk.getRootProvider().getUrls(OrderRootType.CLASSES);
            for (String url : urls) {
                final String path = GenerationUtils.trimJarSeparator(VirtualFileManager.extractPath(url));
                final File pathElement = new File(path);
                final String relativePath = FileUtil.getRelativePath(homeDir, pathElement);
                if (relativePath != null) {
                    fileSet.add(new Include(relativePath.replace(File.separatorChar, '/')));
                }
            }
            final File binPath = toCanonicalFile(new File(((JavaSdkType) sdkType).getBinPath(jdk)));
            final String relativePath = FileUtil.getRelativePath(homeDir, binPath);
            if (relativePath != null) {
                add(new Property(BuildProperties.getJdkBinProperty(jdkName), propertyRef(jdkHomeProperty) + "/" + FileUtil.toSystemIndependentName(relativePath)), 1);
            } else {
                add(new Property(BuildProperties.getJdkBinProperty(jdkName), FileUtil.toSystemIndependentName(binPath.getPath())), 1);
            }
            final Path jdkPath = new Path(getJdkPathId(jdkName));
            jdkPath.add(fileSet);
            add(jdkPath);
        }
    }
    final Sdk projectJdk = ProjectRootManager.getInstance(project).getProjectSdk();
    add(new Property(PROPERTY_PROJECT_JDK_HOME, projectJdk != null ? propertyRef(getJdkHomeProperty(projectJdk.getName())) : ""), 1);
    add(new Property(PROPERTY_PROJECT_JDK_BIN, projectJdk != null ? propertyRef(getJdkBinProperty(projectJdk.getName())) : ""));
    add(new Property(PROPERTY_PROJECT_JDK_CLASSPATH, projectJdk != null ? getJdkPathId(projectJdk.getName()) : ""));
}
Also used : IOException(java.io.IOException) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) Sdk(com.intellij.openapi.projectRoots.Sdk) SdkTypeId(com.intellij.openapi.projectRoots.SdkTypeId) File(java.io.File)

Example 7 with JavaSdkType

use of com.intellij.openapi.projectRoots.JavaSdkType in project intellij-community by JetBrains.

the class BuildManager method launchBuildProcess.

private OSProcessHandler launchBuildProcess(Project project, final int port, final UUID sessionId, boolean requestProjectPreload) throws ExecutionException {
    final String compilerPath;
    final String vmExecutablePath;
    JavaSdkVersion sdkVersion = null;
    final String forcedCompiledJdkHome = Registry.stringValue(COMPILER_PROCESS_JDK_PROPERTY);
    if (StringUtil.isEmptyOrSpaces(forcedCompiledJdkHome)) {
        // choosing sdk with which the build process should be run
        final Pair<Sdk, JavaSdkVersion> pair = getBuildProcessRuntimeSdk(project);
        final Sdk projectJdk = pair.first;
        sdkVersion = pair.second;
        final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
        // validate tools.jar presence
        final JavaSdkType projectJdkType = (JavaSdkType) projectJdk.getSdkType();
        if (FileUtil.pathsEqual(projectJdk.getHomePath(), internalJdk.getHomePath())) {
            // important: because internal JDK can be either JDK or JRE,
            // this is the most universal way to obtain tools.jar path in this particular case
            final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
            if (systemCompiler == null) {
                throw new ExecutionException("No system java compiler is provided by the JRE. Make sure tools.jar is present in IntelliJ IDEA classpath.");
            }
            compilerPath = ClasspathBootstrap.getResourcePath(systemCompiler.getClass());
        } else {
            compilerPath = projectJdkType.getToolsPath(projectJdk);
            if (compilerPath == null) {
                throw new ExecutionException("Cannot determine path to 'tools.jar' library for " + projectJdk.getName() + " (" + projectJdk.getHomePath() + ")");
            }
        }
        vmExecutablePath = projectJdkType.getVMExecutablePath(projectJdk);
    } else {
        compilerPath = new File(forcedCompiledJdkHome, "lib/tools.jar").getAbsolutePath();
        vmExecutablePath = new File(forcedCompiledJdkHome, "bin/java").getAbsolutePath();
    }
    final CompilerConfiguration projectConfig = CompilerConfiguration.getInstance(project);
    final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project);
    final GeneralCommandLine cmdLine = new GeneralCommandLine();
    cmdLine.setExePath(vmExecutablePath);
    //cmdLine.addParameter("-XX:MaxPermSize=150m");
    //cmdLine.addParameter("-XX:ReservedCodeCacheSize=64m");
    boolean isProfilingMode = false;
    String userDefinedHeapSize = null;
    final List<String> userAdditionalOptionsList = new SmartList<>();
    final String userAdditionalVMOptions = config.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
    final boolean userLocalOptionsActive = !StringUtil.isEmptyOrSpaces(userAdditionalVMOptions);
    final String additionalOptions = userLocalOptionsActive ? userAdditionalVMOptions : projectConfig.getBuildProcessVMOptions();
    if (!StringUtil.isEmptyOrSpaces(additionalOptions)) {
        final StringTokenizer tokenizer = new StringTokenizer(additionalOptions, " ", false);
        while (tokenizer.hasMoreTokens()) {
            final String option = tokenizer.nextToken();
            if (StringUtil.startsWithIgnoreCase(option, "-Xmx")) {
                if (userLocalOptionsActive) {
                    userDefinedHeapSize = option;
                }
            } else {
                if ("-Dprofiling.mode=true".equals(option)) {
                    isProfilingMode = true;
                }
                userAdditionalOptionsList.add(option);
            }
        }
    }
    if (userDefinedHeapSize != null) {
        cmdLine.addParameter(userDefinedHeapSize);
    } else {
        final int heapSize = projectConfig.getBuildProcessHeapSize(JavacConfiguration.getOptions(project, JavacConfiguration.class).MAXIMUM_HEAP_SIZE);
        cmdLine.addParameter("-Xmx" + heapSize + "m");
    }
    if (SystemInfo.isMac && sdkVersion != null && JavaSdkVersion.JDK_1_6.equals(sdkVersion) && Registry.is("compiler.process.32bit.vm.on.mac")) {
        // unfortunately -d32 is supported on jdk 1.6 only
        cmdLine.addParameter("-d32");
    }
    cmdLine.addParameter("-Djava.awt.headless=true");
    if (sdkVersion != null && sdkVersion.ordinal() < JavaSdkVersion.JDK_1_9.ordinal()) {
        //-Djava.endorsed.dirs is not supported in JDK 9+, may result in abnormal process termination
        // turn off all jre customizations for predictable behaviour
        cmdLine.addParameter("-Djava.endorsed.dirs=\"\"");
    }
    if (IS_UNIT_TEST_MODE) {
        cmdLine.addParameter("-Dtest.mode=true");
    }
    // always run eclipse compiler in single-threaded mode
    cmdLine.addParameter("-Djdt.compiler.useSingleThread=true");
    if (requestProjectPreload) {
        cmdLine.addParameter("-Dpreload.project.path=" + FileUtil.toCanonicalPath(getProjectPath(project)));
        cmdLine.addParameter("-Dpreload.config.path=" + FileUtil.toCanonicalPath(PathManager.getOptionsPath()));
    }
    final String shouldGenerateIndex = System.getProperty(GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION);
    if (shouldGenerateIndex != null) {
        cmdLine.addParameter("-D" + GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION + "=" + shouldGenerateIndex);
    }
    cmdLine.addParameter("-D" + GlobalOptions.COMPILE_PARALLEL_OPTION + "=" + Boolean.toString(config.PARALLEL_COMPILATION));
    cmdLine.addParameter("-D" + GlobalOptions.REBUILD_ON_DEPENDENCY_CHANGE_OPTION + "=" + Boolean.toString(config.REBUILD_ON_DEPENDENCY_CHANGE));
    if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack", "false")))) {
        cmdLine.addParameter("-Djava.net.preferIPv4Stack=true");
    }
    // this will make netty initialization faster on some systems
    cmdLine.addParameter("-Dio.netty.initialSeedUniquifier=" + ThreadLocalRandom.getInitialSeedUniquifier());
    for (String option : userAdditionalOptionsList) {
        cmdLine.addParameter(option);
    }
    if (isProfilingMode) {
        cmdLine.addParameter("-agentlib:yjpagent=disablealloc,delay=10000,sessionname=ExternalBuild");
    }
    // debugging
    int debugPort = -1;
    if (myBuildProcessDebuggingEnabled) {
        debugPort = Registry.intValue("compiler.process.debug.port");
        if (debugPort <= 0) {
            try {
                debugPort = NetUtils.findAvailableSocketPort();
            } catch (IOException e) {
                throw new ExecutionException("Cannot find free port to debug build process", e);
            }
        }
        if (debugPort > 0) {
            cmdLine.addParameter("-XX:+HeapDumpOnOutOfMemoryError");
            cmdLine.addParameter("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + debugPort);
        }
    }
    if (!Registry.is("compiler.process.use.memory.temp.cache")) {
        cmdLine.addParameter("-D" + GlobalOptions.USE_MEMORY_TEMP_CACHE_OPTION + "=false");
    }
    // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language
    cmdLine.setCharset(mySystemCharset);
    cmdLine.addParameter("-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + mySystemCharset.name());
    cmdLine.addParameter("-D" + JpsGlobalLoader.FILE_TYPES_COMPONENT_NAME_KEY + "=" + FileTypeManagerImpl.getFileTypeComponentName());
    String[] propertiesToPass = { "user.language", "user.country", "user.region", PathManager.PROPERTY_PATHS_SELECTOR, "idea.case.sensitive.fs" };
    for (String name : propertiesToPass) {
        final String value = System.getProperty(name);
        if (value != null) {
            cmdLine.addParameter("-D" + name + "=" + value);
        }
    }
    cmdLine.addParameter("-D" + PathManager.PROPERTY_HOME_PATH + "=" + PathManager.getHomePath());
    cmdLine.addParameter("-D" + PathManager.PROPERTY_CONFIG_PATH + "=" + PathManager.getConfigPath());
    cmdLine.addParameter("-D" + PathManager.PROPERTY_PLUGINS_PATH + "=" + PathManager.getPluginsPath());
    cmdLine.addParameter("-D" + GlobalOptions.LOG_DIR_OPTION + "=" + FileUtil.toSystemIndependentName(getBuildLogDirectory().getAbsolutePath()));
    cmdLine.addParameters(myFallbackJdkParams);
    cmdLine.addParameter("-Dio.netty.noUnsafe=true");
    final File workDirectory = getBuildSystemDirectory();
    //noinspection ResultOfMethodCallIgnored
    workDirectory.mkdirs();
    final File projectSystemRoot = getProjectSystemDirectory(project);
    if (projectSystemRoot != null) {
        cmdLine.addParameter("-Djava.io.tmpdir=" + FileUtil.toSystemIndependentName(projectSystemRoot.getPath()) + "/" + TEMP_DIR_NAME);
    }
    for (BuildProcessParametersProvider provider : project.getExtensions(BuildProcessParametersProvider.EP_NAME)) {
        final List<String> args = provider.getVMArguments();
        cmdLine.addParameters(args);
    }
    @SuppressWarnings("UnnecessaryFullyQualifiedName") final Class<?> launcherClass = org.jetbrains.jps.cmdline.Launcher.class;
    final List<String> launcherCp = new ArrayList<>();
    launcherCp.add(ClasspathBootstrap.getResourcePath(launcherClass));
    launcherCp.addAll(BuildProcessClasspathManager.getLauncherClasspath(project));
    launcherCp.add(compilerPath);
    ClasspathBootstrap.appendJavaCompilerClasspath(launcherCp, shouldIncludeEclipseCompiler(projectConfig));
    cmdLine.addParameter("-classpath");
    cmdLine.addParameter(classpathToString(launcherCp));
    cmdLine.addParameter(launcherClass.getName());
    final List<String> cp = ClasspathBootstrap.getBuildProcessApplicationClasspath();
    cp.addAll(myClasspathManager.getBuildProcessPluginsClasspath(project));
    if (isProfilingMode) {
        cp.add(new File(workDirectory, "yjp-controller-api-redist.jar").getPath());
    }
    cmdLine.addParameter(classpathToString(cp));
    cmdLine.addParameter(BuildMain.class.getName());
    cmdLine.addParameter(Boolean.valueOf(System.getProperty("java.net.preferIPv6Addresses", "false")) ? "::1" : "127.0.0.1");
    cmdLine.addParameter(Integer.toString(port));
    cmdLine.addParameter(sessionId.toString());
    cmdLine.addParameter(FileUtil.toSystemIndependentName(workDirectory.getPath()));
    cmdLine.setWorkDirectory(workDirectory);
    try {
        ApplicationManager.getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).beforeBuildProcessStarted(project, sessionId);
    } catch (Throwable e) {
        LOG.error(e);
    }
    final OSProcessHandler processHandler = new OSProcessHandler(cmdLine) {

        @Override
        protected boolean shouldDestroyProcessRecursively() {
            return true;
        }

        @NotNull
        @Override
        protected BaseOutputReader.Options readerOptions() {
            return BaseOutputReader.Options.BLOCKING;
        }
    };
    processHandler.addProcessListener(new ProcessAdapter() {

        @Override
        public void onTextAvailable(ProcessEvent event, Key outputType) {
            // re-translate builder's output to idea.log
            final String text = event.getText();
            if (!StringUtil.isEmptyOrSpaces(text)) {
                if (ProcessOutputTypes.SYSTEM.equals(outputType)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("BUILDER_PROCESS [" + outputType.toString() + "]: " + text.trim());
                    }
                } else {
                    LOG.info("BUILDER_PROCESS [" + outputType.toString() + "]: " + text.trim());
                }
            }
        }
    });
    if (debugPort > 0) {
        processHandler.putUserData(COMPILER_PROCESS_DEBUG_PORT, debugPort);
    }
    return processHandler;
}
Also used : JavaSdkVersion(com.intellij.openapi.projectRoots.JavaSdkVersion) IntArrayList(com.intellij.util.containers.IntArrayList) BuildMain(org.jetbrains.jps.cmdline.BuildMain) JpsJavaSdkType(org.jetbrains.jps.model.java.JpsJavaSdkType) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) CompilerConfiguration(com.intellij.compiler.CompilerConfiguration) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) Sdk(com.intellij.openapi.projectRoots.Sdk) ExecutionException(com.intellij.execution.ExecutionException) CompilerWorkspaceConfiguration(com.intellij.compiler.CompilerWorkspaceConfiguration) IOException(java.io.IOException) BaseOutputReader(com.intellij.util.io.BaseOutputReader) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 8 with JavaSdkType

use of com.intellij.openapi.projectRoots.JavaSdkType in project intellij-community by JetBrains.

the class BuildManager method getRuntimeSdk.

private static Pair<Sdk, JavaSdkVersion> getRuntimeSdk(@NotNull Project project, final JavaSdkVersion oldestPossibleVersion) {
    final Set<Sdk> candidates = new LinkedHashSet<>();
    final Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk();
    if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) {
        candidates.add(defaultSdk);
    }
    for (Module module : ModuleManager.getInstance(project).getModules()) {
        final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
        if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
            candidates.add(sdk);
        }
    }
    // now select the latest version from the sdks that are used in the project, but not older than the internal sdk version
    final JavaSdk javaSdkType = JavaSdk.getInstance();
    Sdk projectJdk = null;
    int sdkMinorVersion = 0;
    JavaSdkVersion sdkVersion = null;
    for (Sdk candidate : candidates) {
        final String vs = candidate.getVersionString();
        if (vs != null) {
            final JavaSdkVersion candidateVersion = getSdkVersion(javaSdkType, vs);
            if (candidateVersion != null) {
                final int candidateMinorVersion = getMinorVersion(vs);
                if (projectJdk == null) {
                    sdkVersion = candidateVersion;
                    sdkMinorVersion = candidateMinorVersion;
                    projectJdk = candidate;
                } else {
                    final int result = candidateVersion.compareTo(sdkVersion);
                    if (result > 0 || result == 0 && candidateMinorVersion > sdkMinorVersion) {
                        sdkVersion = candidateVersion;
                        sdkMinorVersion = candidateMinorVersion;
                        projectJdk = candidate;
                    }
                }
            }
        }
    }
    if (projectJdk == null || sdkVersion == null || !sdkVersion.isAtLeast(oldestPossibleVersion)) {
        final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
        projectJdk = internalJdk;
        sdkVersion = javaSdkType.getVersion(internalJdk);
    }
    return Pair.create(projectJdk, sdkVersion);
}
Also used : JpsJavaSdkType(org.jetbrains.jps.model.java.JpsJavaSdkType) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) JavaSdkVersion(com.intellij.openapi.projectRoots.JavaSdkVersion) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) Sdk(com.intellij.openapi.projectRoots.Sdk) Module(com.intellij.openapi.module.Module)

Example 9 with JavaSdkType

use of com.intellij.openapi.projectRoots.JavaSdkType in project intellij-community by JetBrains.

the class JavaScratchCompilationSupport method execute.

@Override
public boolean execute(CompileContext context) {
    final Project project = context.getProject();
    final RunConfiguration configuration = CompileStepBeforeRun.getRunConfiguration(context);
    if (!(configuration instanceof JavaScratchConfiguration)) {
        return true;
    }
    final JavaScratchConfiguration scratchConfig = (JavaScratchConfiguration) configuration;
    final String scratchUrl = scratchConfig.getScratchFileUrl();
    if (scratchUrl == null) {
        context.addMessage(CompilerMessageCategory.ERROR, "Associated scratch file not found", null, -1, -1);
        return false;
    }
    @Nullable final Module module = scratchConfig.getConfigurationModule().getModule();
    final Sdk targetSdk = module != null ? ModuleRootManager.getInstance(module).getSdk() : ProjectRootManager.getInstance(project).getProjectSdk();
    if (targetSdk == null) {
        final String message = module != null ? "Cannot find associated SDK for run configuration module \"" + module.getName() + "\".\nPlease check project settings." : "Cannot find associated project SDK for the run configuration.\nPlease check project settings.";
        context.addMessage(CompilerMessageCategory.ERROR, message, scratchUrl, -1, -1);
        return true;
    }
    if (!(targetSdk.getSdkType() instanceof JavaSdkType)) {
        final String message = module != null ? "Expected Java SDK for run configuration module \"" + module.getName() + "\".\nPlease check project settings." : "Expected Java SDK for project \"" + project.getName() + "\".\nPlease check project settings.";
        context.addMessage(CompilerMessageCategory.ERROR, message, scratchUrl, -1, -1);
        return true;
    }
    final File outputDir = getScratchOutputDirectory(project);
    if (outputDir == null) {
        // should not happen for normal projects
        return true;
    }
    // perform cleanup
    FileUtil.delete(outputDir);
    try {
        final File scratchFile = new File(VirtualFileManager.extractPath(scratchUrl));
        File srcFile = scratchFile;
        if (!StringUtil.endsWith(srcFile.getName(), ".java")) {
            final File srcDir = getScratchTempDirectory(project);
            if (srcDir == null) {
                // should not happen for normal projects
                return true;
            }
            // perform cleanup
            FileUtil.delete(srcDir);
            final String srcFileName = ApplicationManager.getApplication().runReadAction(new Computable<String>() {

                @Override
                public String compute() {
                    final VirtualFile vFile = VirtualFileManager.getInstance().findFileByUrl(scratchUrl);
                    if (vFile != null) {
                        final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
                        if (psiFile instanceof PsiJavaFile) {
                            String name = null;
                            // take the name of the first found public top-level class, otherwise the name of any available top-level class
                            for (PsiClass aClass : ((PsiJavaFile) psiFile).getClasses()) {
                                if (name == null) {
                                    name = aClass.getName();
                                    if (isPublic(aClass)) {
                                        break;
                                    }
                                } else if (isPublic(aClass)) {
                                    name = aClass.getName();
                                    break;
                                }
                            }
                            if (name != null) {
                                return name;
                            }
                        }
                    }
                    return FileUtil.getNameWithoutExtension(scratchFile);
                }
            });
            srcFile = new File(srcDir, srcFileName + ".java");
            FileUtil.copy(scratchFile, srcFile);
        }
        final Collection<File> files = Collections.singleton(srcFile);
        final Set<File> cp = new LinkedHashSet<>();
        final List<File> platformCp = new ArrayList<>();
        final Computable<OrderEnumerator> orderEnumerator = module != null ? (Computable<OrderEnumerator>) () -> ModuleRootManager.getInstance(module).orderEntries() : (Computable<OrderEnumerator>) () -> ProjectRootManager.getInstance(project).orderEntries();
        ApplicationManager.getApplication().runReadAction(() -> {
            for (String s : orderEnumerator.compute().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList().getPathList()) {
                cp.add(new File(s));
            }
            for (String s : orderEnumerator.compute().compileOnly().sdkOnly().getPathsList().getPathList()) {
                platformCp.add(new File(s));
            }
        });
        final List<String> options = new ArrayList<>();
        // always compile with debug info
        options.add("-g");
        final JavaSdkVersion sdkVersion = JavaSdk.getInstance().getVersion(targetSdk);
        if (sdkVersion != null) {
            final String langLevel = "1." + Integer.valueOf(3 + sdkVersion.getMaxLanguageLevel().ordinal());
            options.add("-source");
            options.add(langLevel);
            options.add("-target");
            options.add(langLevel);
        }
        // disable annotation processing
        options.add("-proc:none");
        final Collection<ClassObject> result = CompilerManager.getInstance(project).compileJavaCode(options, platformCp, cp, Collections.emptyList(), Collections.emptyList(), files, outputDir);
        for (ClassObject classObject : result) {
            final byte[] bytes = classObject.getContent();
            if (bytes != null) {
                FileUtil.writeToFile(new File(classObject.getPath()), bytes);
            }
        }
    } catch (CompilationException e) {
        for (CompilationException.Message m : e.getMessages()) {
            context.addMessage(m.getCategory(), m.getText(), scratchUrl, m.getLine(), m.getColumn());
        }
    } catch (IOException e) {
        context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), scratchUrl, -1, -1);
    }
    return true;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) JavaSdkVersion(com.intellij.openapi.projectRoots.JavaSdkVersion) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) OrderEnumerator(com.intellij.openapi.roots.OrderEnumerator) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) Sdk(com.intellij.openapi.projectRoots.Sdk) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Example 10 with JavaSdkType

use of com.intellij.openapi.projectRoots.JavaSdkType in project intellij-community by JetBrains.

the class EclipseClasspathWriter method createClasspathEntry.

private void createClasspathEntry(@NotNull OrderEntry entry, @NotNull Element classpathRoot, @NotNull final ModuleRootModel model) throws ConversionException {
    EclipseModuleManager eclipseModuleManager = EclipseModuleManagerImpl.getInstance(entry.getOwnerModule());
    if (entry instanceof ModuleSourceOrderEntry) {
        boolean shouldPlaceSeparately = eclipseModuleManager.isExpectedModuleSourcePlace(ArrayUtil.find(model.getOrderEntries(), entry));
        for (ContentEntry contentEntry : model.getContentEntries()) {
            VirtualFile contentRoot = contentEntry.getFile();
            for (SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
                String srcUrl = sourceFolder.getUrl();
                String relativePath = EPathUtil.collapse2EclipsePath(srcUrl, model);
                if (!Comparing.equal(contentRoot, EPathUtil.getContentRoot(model))) {
                    String linkedPath = EclipseModuleManagerImpl.getInstance(entry.getOwnerModule()).getEclipseLinkedSrcVariablePath(srcUrl);
                    if (linkedPath != null) {
                        relativePath = linkedPath;
                    }
                }
                int index = eclipseModuleManager.getSrcPlace(srcUrl);
                addOrderEntry(EclipseXml.SRC_KIND, relativePath, classpathRoot, shouldPlaceSeparately && index != -1 ? index : -1);
            }
        }
    } else if (entry instanceof ModuleOrderEntry) {
        final String path = '/' + ((ModuleOrderEntry) entry).getModuleName();
        final Element oldElement = getOldElement(EclipseXml.SRC_KIND, path);
        Element orderEntry = addOrderEntry(EclipseXml.SRC_KIND, path, classpathRoot);
        if (oldElement == null) {
            setAttributeIfAbsent(orderEntry, EclipseXml.COMBINEACCESSRULES_ATTR, EclipseXml.FALSE_VALUE);
        }
        setExported(orderEntry, ((ExportableOrderEntry) entry));
    } else if (entry instanceof LibraryOrderEntry) {
        final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) entry;
        final String libraryName = libraryOrderEntry.getLibraryName();
        if (libraryOrderEntry.isModuleLevel()) {
            final String[] files = libraryOrderEntry.getRootUrls(OrderRootType.CLASSES);
            if (files.length > 0) {
                if (libraryName != null && libraryName.contains(IdeaXml.JUNIT) && Comparing.strEqual(files[0], EclipseClasspathReader.getJunitClsUrl(libraryName.contains("4")))) {
                    final Element orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JUNIT_CONTAINER + "/" + libraryName.substring(IdeaXml.JUNIT.length()), classpathRoot);
                    setExported(orderEntry, libraryOrderEntry);
                } else {
                    boolean newVarLibrary = false;
                    boolean link = false;
                    String eclipseVariablePath = eclipseModuleManager.getEclipseVariablePath(files[0]);
                    if (eclipseVariablePath == null) {
                        eclipseVariablePath = eclipseModuleManager.getEclipseLinkedVarPath(files[0]);
                        link = eclipseVariablePath != null;
                    }
                    if (eclipseVariablePath == null && !eclipseModuleManager.isEclipseLibUrl(files[0])) {
                        //new library was added
                        newVarLibrary = true;
                        eclipseVariablePath = EPathUtil.collapse2EclipseVariabledPath(libraryOrderEntry, OrderRootType.CLASSES);
                    }
                    Element orderEntry;
                    if (eclipseVariablePath != null) {
                        orderEntry = addOrderEntry(link ? EclipseXml.LIB_KIND : EclipseXml.VAR_KIND, eclipseVariablePath, classpathRoot);
                    } else {
                        LOG.assertTrue(!StringUtil.isEmptyOrSpaces(files[0]), "Library: " + libraryName);
                        orderEntry = addOrderEntry(EclipseXml.LIB_KIND, EPathUtil.collapse2EclipsePath(files[0], model), classpathRoot);
                    }
                    final String srcRelativePath;
                    String eclipseSrcVariablePath = null;
                    boolean addSrcRoots = true;
                    String[] srcFiles = libraryOrderEntry.getRootUrls(OrderRootType.SOURCES);
                    if (srcFiles.length == 0) {
                        srcRelativePath = null;
                    } else {
                        final String srcFile = srcFiles[0];
                        srcRelativePath = EPathUtil.collapse2EclipsePath(srcFile, model);
                        if (eclipseVariablePath != null) {
                            eclipseSrcVariablePath = eclipseModuleManager.getEclipseSrcVariablePath(srcFile);
                            if (eclipseSrcVariablePath == null) {
                                eclipseSrcVariablePath = eclipseModuleManager.getEclipseLinkedSrcVariablePath(srcFile);
                            }
                            if (eclipseSrcVariablePath == null) {
                                eclipseSrcVariablePath = EPathUtil.collapse2EclipseVariabledPath(libraryOrderEntry, OrderRootType.SOURCES);
                                if (eclipseSrcVariablePath != null) {
                                    eclipseSrcVariablePath = "/" + eclipseSrcVariablePath;
                                } else {
                                    if (newVarLibrary) {
                                        //new library which cannot be replaced with vars
                                        orderEntry.detach();
                                        orderEntry = addOrderEntry(EclipseXml.LIB_KIND, EPathUtil.collapse2EclipsePath(files[0], model), classpathRoot);
                                    } else {
                                        LOG.info("Added root " + srcRelativePath + " (in existing var library) can't be replaced with any variable; src roots placed in .eml only");
                                        addSrcRoots = false;
                                    }
                                }
                            }
                        }
                    }
                    setOrRemoveAttribute(orderEntry, EclipseXml.SOURCEPATH_ATTR, addSrcRoots ? (eclipseSrcVariablePath != null ? eclipseSrcVariablePath : srcRelativePath) : null);
                    EJavadocUtil.setupJavadocAttributes(orderEntry, libraryOrderEntry, model);
                    final String[] nativeRoots = libraryOrderEntry.getUrls(NativeLibraryOrderRootType.getInstance());
                    if (nativeRoots.length > 0) {
                        EJavadocUtil.setupAttributes(orderEntry, nativeRoot -> EPathUtil.collapse2EclipsePath(nativeRoot, model), EclipseXml.DLL_LINK, nativeRoots);
                    }
                    setExported(orderEntry, libraryOrderEntry);
                }
            }
        } else {
            Element orderEntry;
            if (eclipseModuleManager.getUnknownCons().contains(libraryName)) {
                orderEntry = addOrderEntry(EclipseXml.CON_KIND, libraryName, classpathRoot);
            } else if (Comparing.strEqual(libraryName, IdeaXml.ECLIPSE_LIBRARY)) {
                orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.ECLIPSE_PLATFORM, classpathRoot);
            } else {
                orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.USER_LIBRARY + '/' + libraryName, classpathRoot);
            }
            setExported(orderEntry, libraryOrderEntry);
        }
    } else if (entry instanceof JdkOrderEntry) {
        if (entry instanceof InheritedJdkOrderEntry) {
            if (!EclipseModuleManagerImpl.getInstance(entry.getOwnerModule()).isForceConfigureJDK()) {
                addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JRE_CONTAINER, classpathRoot);
            }
        } else {
            final Sdk jdk = ((JdkOrderEntry) entry).getJdk();
            String jdkLink;
            if (jdk == null) {
                jdkLink = EclipseXml.JRE_CONTAINER;
            } else {
                jdkLink = EclipseXml.JRE_CONTAINER;
                if (jdk.getSdkType() instanceof JavaSdkType) {
                    jdkLink += EclipseXml.JAVA_SDK_TYPE;
                }
                jdkLink += '/' + jdk.getName();
            }
            addOrderEntry(EclipseXml.CON_KIND, jdkLink, classpathRoot);
        }
    } else {
        throw new ConversionException("Unknown EclipseProjectModel.ClasspathEntry: " + entry.getClass());
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ConversionException(org.jetbrains.idea.eclipse.ConversionException) Element(org.jdom.Element) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) EclipseModuleManager(org.jetbrains.idea.eclipse.EclipseModuleManager) Sdk(com.intellij.openapi.projectRoots.Sdk)

Aggregations

JavaSdkType (com.intellij.openapi.projectRoots.JavaSdkType)14 Sdk (com.intellij.openapi.projectRoots.Sdk)14 Module (com.intellij.openapi.module.Module)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 JavaSdk (com.intellij.openapi.projectRoots.JavaSdk)4 ExecutionException (com.intellij.execution.ExecutionException)3 JavaSdkVersion (com.intellij.openapi.projectRoots.JavaSdkVersion)3 SdkTypeId (com.intellij.openapi.projectRoots.SdkTypeId)3 File (java.io.File)3 IOException (java.io.IOException)3 CantRunException (com.intellij.execution.CantRunException)2 JavaParameters (com.intellij.execution.configurations.JavaParameters)2 ParametersList (com.intellij.execution.configurations.ParametersList)2 Nullable (org.jetbrains.annotations.Nullable)2 JpsJavaSdkType (org.jetbrains.jps.model.java.JpsJavaSdkType)2 CompilerConfiguration (com.intellij.compiler.CompilerConfiguration)1 CompilerWorkspaceConfiguration (com.intellij.compiler.CompilerWorkspaceConfiguration)1 RunnerAndConfigurationSettings (com.intellij.execution.RunnerAndConfigurationSettings)1 ApplicationConfiguration (com.intellij.execution.application.ApplicationConfiguration)1 GeneralCommandLine (com.intellij.execution.configurations.GeneralCommandLine)1