use of com.intellij.openapi.util.ThrowableComputable in project intellij-community by JetBrains.
the class JarFromModulesTemplate method doCreateArtifact.
@Nullable
public NewArtifactConfiguration doCreateArtifact(final Module[] modules, final String mainClassName, final String directoryForManifest, final boolean extractLibrariesToJar, final boolean includeTests) {
VirtualFile manifestFile = null;
final Project project = myContext.getProject();
if (mainClassName != null && !mainClassName.isEmpty() || !extractLibrariesToJar) {
final VirtualFile directory;
try {
directory = ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<VirtualFile, IOException>() {
@Override
public VirtualFile compute() throws IOException {
return VfsUtil.createDirectoryIfMissing(directoryForManifest);
}
});
} catch (IOException e) {
LOG.info(e);
Messages.showErrorDialog(project, "Cannot create directory '" + directoryForManifest + "': " + e.getMessage(), CommonBundle.getErrorTitle());
return null;
}
if (directory == null)
return null;
manifestFile = ManifestFileUtil.createManifestFile(directory, project);
if (manifestFile == null) {
return null;
}
ManifestFileUtil.updateManifest(manifestFile, mainClassName, null, true);
}
String name = modules.length == 1 ? modules[0].getName() : project.getName();
final PackagingElementFactory factory = PackagingElementFactory.getInstance();
final CompositePackagingElement<?> archive = factory.createArchive(ArtifactUtil.suggestArtifactFileName(name) + ".jar");
OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(project).orderEntries(Arrays.asList(modules));
final Set<Library> libraries = new THashSet<>();
if (!includeTests) {
orderEnumerator = orderEnumerator.productionOnly();
}
final ModulesProvider modulesProvider = myContext.getModulesProvider();
final OrderEnumerator enumerator = orderEnumerator.using(modulesProvider).withoutSdk().runtimeOnly().recursively();
enumerator.forEachLibrary(new CommonProcessors.CollectProcessor<>(libraries));
enumerator.forEachModule(module -> {
if (ProductionModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) {
archive.addOrFindChild(factory.createModuleOutput(module));
}
if (includeTests && TestModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) {
archive.addOrFindChild(factory.createTestModuleOutput(module));
}
return true;
});
final JarArtifactType jarArtifactType = JarArtifactType.getInstance();
if (manifestFile != null && !manifestFile.equals(ManifestFileUtil.findManifestFile(archive, myContext, jarArtifactType))) {
archive.addFirstChild(factory.createFileCopyWithParentDirectories(manifestFile.getPath(), ManifestFileUtil.MANIFEST_DIR_NAME));
}
final String artifactName = name + ":jar";
if (extractLibrariesToJar) {
addExtractedLibrariesToJar(archive, factory, libraries);
return new NewArtifactConfiguration(archive, artifactName, jarArtifactType);
} else {
final ArtifactRootElement<?> root = factory.createArtifactRootElement();
List<String> classpath = new ArrayList<>();
root.addOrFindChild(archive);
addLibraries(libraries, root, archive, classpath);
ManifestFileUtil.updateManifest(manifestFile, mainClassName, classpath, true);
return new NewArtifactConfiguration(root, artifactName, PlainArtifactType.getInstance());
}
}
use of com.intellij.openapi.util.ThrowableComputable in project intellij-community by JetBrains.
the class ModuleTestCase method loadModule.
protected Module loadModule(@NotNull String modulePath) {
final ModuleManager moduleManager = ModuleManager.getInstance(myProject);
Module module;
try {
module = ApplicationManager.getApplication().runWriteAction((ThrowableComputable<Module, Exception>) () -> moduleManager.loadModule(FileUtil.toSystemIndependentName(modulePath)));
} catch (Exception e) {
LOG.error(e);
return null;
}
myModulesToDispose.add(module);
return module;
}
use of com.intellij.openapi.util.ThrowableComputable in project intellij-plugins by JetBrains.
the class FlexMainStep method commit.
@Override
public void commit(final CommitType commitType) throws CommitStepException {
super.commit(commitType);
// let's replace parent component only if template contains 'Superclass' macro
final FileTemplate template;
try {
template = ClassLoaderUtil.runWithClassLoader(ActionScriptCreateClassOrInterfaceFix.class.getClassLoader(), new ThrowableComputable<FileTemplate, IOException>() {
@Override
public FileTemplate compute() throws IOException {
return FileTemplateManager.getDefaultInstance().getInternalTemplate(myModel.getTemplateName());
}
});
String[] attributes = FileTemplateUtil.calculateAttributes(template.getText(), new Properties(), true, myProject);
if (ArrayUtil.contains(ActionScriptCreateClassOrInterfaceFix.SUPERCLASS, attributes)) {
myModel.setSuperclassFqn(getSuperclassFqn());
}
} catch (IOException e) {
// ignore as the action will not succeed
} catch (ParseException e) {
// ignore as the action will not succeed
}
}
use of com.intellij.openapi.util.ThrowableComputable in project android by JetBrains.
the class CaptureService method finalizeCaptureFileAsynchronous.
/**
* Closes the file and asynchronously returns the generated {@code Capture} on the EDT within the given {@code onCompletion} callback.
*
* @param captureHandle is the handle returned by {@link #startCaptureFile(Class)}
* @param onCompletion will be called when the asynchronous closing of the file and generating the {@code Capture} is completed or error'ed
* @param executor is the executor to run the onCompletion callbacks
*/
public void finalizeCaptureFileAsynchronous(@NotNull final CaptureHandle captureHandle, @Nullable FutureCallback<Capture> onCompletion, @Nullable Executor executor) {
final ListenableFutureTask<Capture> postCloseTask = ListenableFutureTask.create(new Callable<Capture>() {
@Override
public Capture call() throws Exception {
ApplicationManager.getApplication().assertIsDispatchThread();
if (captureHandle.getWriteToTempFile()) {
ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<Object, IOException>() {
@Override
public Object compute() throws IOException {
String tempFilePath = captureHandle.getFile().getCanonicalPath();
assert tempFilePath.endsWith(TEMP_FILE_EXTENSION);
String originalFilePath = tempFilePath.substring(0, tempFilePath.length() - TEMP_FILE_EXTENSION.length());
captureHandle.move(new File(originalFilePath));
return null;
}
});
}
return createCapture(captureHandle);
}
});
if (onCompletion != null) {
assert executor != null;
Futures.addCallback(postCloseTask, onCompletion, executor);
}
closeCaptureFileInternal(captureHandle, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().invokeLater(postCloseTask);
}
});
}
use of com.intellij.openapi.util.ThrowableComputable in project intellij-community by JetBrains.
the class EclipseImportBuilder method commit.
@Override
public List<Module> commit(final Project project, ModifiableModuleModel model, ModulesProvider modulesProvider, ModifiableArtifactModel artifactModel) {
final Collection<String> unknownLibraries = new TreeSet<>();
final Collection<String> unknownJdks = new TreeSet<>();
final Set<String> refsToModules = new HashSet<>();
final List<Module> result = new ArrayList<>();
final Map<Module, Set<String>> module2NatureNames = new HashMap<>();
try {
final ModifiableModuleModel moduleModel = model != null ? model : ModuleManager.getInstance(project).getModifiableModel();
final ModifiableRootModel[] rootModels = new ModifiableRootModel[getParameters().projectsToConvert.size()];
final Set<File> files = new HashSet<>();
final Set<String> moduleNames = new THashSet<>(getParameters().projectsToConvert.size());
for (String path : getParameters().projectsToConvert) {
String modulesDirectory = getParameters().converterOptions.commonModulesDirectory;
if (modulesDirectory == null) {
modulesDirectory = path;
}
final String moduleName = EclipseProjectFinder.findProjectName(path);
moduleNames.add(moduleName);
final File imlFile = new File(modulesDirectory + File.separator + moduleName + ModuleManagerImpl.IML_EXTENSION);
if (imlFile.isFile()) {
files.add(imlFile);
}
final File emlFile = new File(modulesDirectory + File.separator + moduleName + EclipseXml.IDEA_SETTINGS_POSTFIX);
if (emlFile.isFile()) {
files.add(emlFile);
}
}
if (!files.isEmpty()) {
final int resultCode = Messages.showYesNoCancelDialog(ApplicationNamesInfo.getInstance().getFullProductName() + " module files found:\n" + StringUtil.join(files, file -> file.getPath(), "\n") + ".\n Would you like to reuse them?", "Module Files Found", Messages.getQuestionIcon());
if (resultCode != Messages.YES) {
if (resultCode == Messages.NO) {
final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
for (File file : files) {
final VirtualFile virtualFile = localFileSystem.findFileByIoFile(file);
if (virtualFile != null) {
ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<Void, IOException>() {
@Override
public Void compute() throws IOException {
virtualFile.delete(this);
return null;
}
});
} else {
FileUtil.delete(file);
}
}
} else {
return result;
}
}
}
int idx = 0;
for (String path : getParameters().projectsToConvert) {
String modulesDirectory = getParameters().converterOptions.commonModulesDirectory;
if (modulesDirectory == null) {
modulesDirectory = path;
}
final Module module = moduleModel.newModule(modulesDirectory + "/" + EclipseProjectFinder.findProjectName(path) + ModuleManagerImpl.IML_EXTENSION, StdModuleTypes.JAVA.getId());
result.add(module);
final Set<String> natures = collectNatures(path);
if (natures.size() > 0) {
module2NatureNames.put(module, natures);
}
final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel();
rootModels[idx++] = rootModel;
final File classpathFile = new File(path, EclipseXml.DOT_CLASSPATH_EXT);
final EclipseClasspathReader classpathReader = new EclipseClasspathReader(path, project, getParameters().projectsToConvert, moduleNames);
classpathReader.init(rootModel);
if (classpathFile.exists()) {
Element classpathElement = JDOMUtil.load(classpathFile);
classpathReader.readClasspath(rootModel, unknownLibraries, unknownJdks, refsToModules, getParameters().converterOptions.testPattern, classpathElement);
} else {
EclipseClasspathReader.setOutputUrl(rootModel, path + "/bin");
}
ClasspathStorage.setStorageType(rootModel, getParameters().linkConverted ? JpsEclipseClasspathSerializer.CLASSPATH_STORAGE_ID : ClassPathStorageUtil.DEFAULT_STORAGE);
if (model != null) {
ApplicationManager.getApplication().runWriteAction(() -> rootModel.commit());
}
}
if (model == null) {
ApplicationManager.getApplication().runWriteAction(() -> ModifiableModelCommitter.multiCommit(rootModels, moduleModel));
}
} catch (Exception e) {
LOG.error(e);
}
scheduleNaturesImporting(project, module2NatureNames);
createEclipseLibrary(project, unknownLibraries, IdeaXml.ECLIPSE_LIBRARY);
StringBuilder message = new StringBuilder();
refsToModules.removeAll(getParameters().existingModuleNames);
for (String path : getParameters().projectsToConvert) {
final String projectName = EclipseProjectFinder.findProjectName(path);
if (projectName != null) {
refsToModules.remove(projectName);
getParameters().existingModuleNames.add(projectName);
}
}
if (!refsToModules.isEmpty()) {
message.append("Unknown modules detected");
for (String module : refsToModules) {
message.append("\n").append(module);
}
}
if (!unknownJdks.isEmpty()) {
if (message.length() > 0) {
message.append("\nand jdks");
} else {
message.append("Imported project refers to unknown jdks");
}
for (String unknownJdk : unknownJdks) {
message.append("\n").append(unknownJdk);
}
}
if (!unknownLibraries.isEmpty()) {
final StringBuilder buf = new StringBuilder();
buf.append("<html><body>");
buf.append(EclipseBundle.message("eclipse.import.warning.undefinded.libraries"));
for (String name : unknownLibraries) {
buf.append("<br>").append(name);
}
if (model == null) {
buf.append("<br><b>Please export Eclipse user libraries and import them now from resulted .userlibraries file</b>");
buf.append("</body></html>");
final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false) {
@Override
public boolean isFileSelectable(VirtualFile file) {
return super.isFileSelectable(file) && Comparing.strEqual(file.getExtension(), "userlibraries");
}
};
descriptor.setDescription(buf.toString());
descriptor.setTitle(getTitle());
final VirtualFile selectedFile = FileChooser.chooseFile(descriptor, project, project.getBaseDir());
if (selectedFile != null) {
try {
EclipseUserLibrariesHelper.readProjectLibrariesContent(selectedFile, project, unknownLibraries);
} catch (Exception e) {
LOG.error(e);
}
}
}
}
if (message.length() > 0) {
Messages.showErrorDialog(project, message.toString(), getTitle());
}
return result;
}
Aggregations