Search in sources :

Example 6 with JDOMException

use of org.jdom.JDOMException in project intellij-community by JetBrains.

the class InspectionProfileSchemesPanel method createSchemeActions.

@Override
protected AbstractSchemeActions<InspectionProfileModifiableModel> createSchemeActions() {
    return new DescriptionAwareSchemeActions<InspectionProfileModifiableModel>(this) {

        @Nullable
        @Override
        public String getDescription(@NotNull InspectionProfileModifiableModel scheme) {
            SingleInspectionProfilePanel inspectionProfile = ((InspectionProfileSchemesModel) getModel()).getProfilePanel(scheme);
            return inspectionProfile.getProfile().getDescription();
        }

        @Override
        protected void setDescription(@NotNull InspectionProfileModifiableModel scheme, @NotNull String newDescription) {
            InspectionProfileModifiableModel inspectionProfile = InspectionProfileSchemesPanel.this.getModel().getProfilePanel(scheme).getProfile();
            if (!Comparing.strEqual(newDescription, inspectionProfile.getDescription())) {
                inspectionProfile.setDescription(newDescription);
                inspectionProfile.setModified(true);
            }
        }

        @Override
        protected void importScheme(@NotNull String importerName) {
            final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false) {

                @Override
                public boolean isFileSelectable(VirtualFile file) {
                    return file.getFileType().equals(StdFileTypes.XML);
                }
            };
            descriptor.setDescription("Choose profile file");
            FileChooser.chooseFile(descriptor, myProject, null, file -> {
                if (file != null) {
                    final InspectionProfileImpl profile;
                    try {
                        profile = InspectionToolsConfigurable.importInspectionProfile(JDOMUtil.load(file.getInputStream()), myAppProfileManager, myProject);
                        final SingleInspectionProfilePanel existed = InspectionProfileSchemesPanel.this.getModel().getProfilePanel(profile);
                        if (existed != null) {
                            if (Messages.showOkCancelDialog(myProject, "Profile with name \'" + profile.getName() + "\' already exists. Do you want to overwrite it?", "Warning", Messages.getInformationIcon()) != Messages.OK) {
                                return;
                            }
                            getModel().removeScheme(existed.getProfile());
                        }
                        InspectionProfileModifiableModel model = new InspectionProfileModifiableModel(profile);
                        model.setModified(true);
                        addProfile(model);
                        selectScheme(model);
                    } catch (JDOMException | InvalidDataException | IOException e) {
                        LOG.error(e);
                    }
                }
            });
        }

        @Override
        protected void resetScheme(@NotNull InspectionProfileModifiableModel scheme) {
            final SingleInspectionProfilePanel panel = InspectionProfileSchemesPanel.this.getModel().getProfilePanel(scheme);
            panel.performProfileReset();
        }

        @Override
        protected void duplicateScheme(@NotNull InspectionProfileModifiableModel scheme, @NotNull String newName) {
            final InspectionProfileModifiableModel newProfile = copyToNewProfile(scheme, myProject, newName, false);
            addProfile(newProfile);
            myConfigurable.selectProfile(newProfile);
            selectScheme(newProfile);
        }

        @Override
        protected void exportScheme(@NotNull InspectionProfileModifiableModel scheme, @NotNull String exporterName) {
            FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
            descriptor.setDescription("Choose directory to store profile file");
            FileChooser.chooseFile(descriptor, myProject, null, dir -> {
                try {
                    LOG.assertTrue(true);
                    Element element = scheme.writeScheme(false);
                    Path file = Paths.get(dir.getPath(), sanitizeFileName(scheme.getName()) + ".xml");
                    if (Files.isRegularFile(file.toAbsolutePath()) && Messages.showOkCancelDialog(myProject, "File \'" + file + "\' already exist. Do you want to overwrite it?", "Warning", Messages.getQuestionIcon()) != Messages.OK) {
                        return;
                    }
                    JdomKt.write(element, file);
                } catch (IOException e1) {
                    LOG.error(e1);
                }
            });
        }

        @Override
        protected void onSchemeChanged(@Nullable InspectionProfileModifiableModel scheme) {
            super.onSchemeChanged(scheme);
            if (scheme != null) {
                myConfigurable.selectProfile(scheme);
            }
        }

        @Override
        protected void renameScheme(@NotNull InspectionProfileModifiableModel scheme, @NotNull String newName) {
            scheme.setName(newName);
        }

        @Override
        protected void copyToProject(@NotNull InspectionProfileModifiableModel scheme) {
            copyToAnotherLevel(scheme, true);
        }

        @Override
        protected void copyToIDE(@NotNull InspectionProfileModifiableModel scheme) {
            copyToAnotherLevel(scheme, false);
        }

        @Override
        protected Class<InspectionProfileModifiableModel> getSchemeType() {
            return InspectionProfileModifiableModel.class;
        }

        private void copyToAnotherLevel(InspectionProfileModifiableModel profile, boolean copyToProject) {
            String name = SchemeNameGenerator.getUniqueName(profile.getName(), schemeName -> ((InspectionProfileSchemesModel) getModel()).hasName(schemeName, copyToProject));
            final InspectionProfileModifiableModel newProfile = copyToNewProfile(profile, myProject, name, true);
            addProfile(newProfile);
            selectScheme(newProfile);
            getSchemesPanel().startEdit();
        }
    };
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Path(java.nio.file.Path) InspectionProfileImpl(com.intellij.codeInspection.ex.InspectionProfileImpl) DescriptionAwareSchemeActions(com.intellij.application.options.schemes.DescriptionAwareSchemeActions) FileChooserDescriptor(com.intellij.openapi.fileChooser.FileChooserDescriptor) Element(org.jdom.Element) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) NotNull(org.jetbrains.annotations.NotNull) SingleInspectionProfilePanel(com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel) InspectionProfileModifiableModel(com.intellij.codeInspection.ex.InspectionProfileModifiableModel) InvalidDataException(com.intellij.openapi.util.InvalidDataException) Nullable(org.jetbrains.annotations.Nullable)

Example 7 with JDOMException

use of org.jdom.JDOMException in project intellij-community by JetBrains.

the class ExistingModuleLoader method validate.

@Override
public boolean validate(final Project current, final Project dest) {
    if (getName() == null)
        return false;
    String moduleFilePath = getModuleFilePath();
    if (moduleFilePath == null)
        return false;
    final File file = new File(moduleFilePath);
    if (file.exists()) {
        try {
            final ConversionResult result = ConversionService.getInstance().convertModule(dest, file);
            if (result.openingIsCanceled()) {
                return false;
            }
            final Element root = JDOMUtil.load(file);
            final Set<String> usedMacros = PathMacrosCollector.getMacroNames(root);
            usedMacros.remove("$" + PathMacroUtil.MODULE_DIR_MACRO_NAME + "$");
            usedMacros.removeAll(PathMacros.getInstance().getAllMacroNames());
            if (usedMacros.size() > 0) {
                final boolean ok = ProjectMacrosUtil.showMacrosConfigurationDialog(current, usedMacros);
                if (!ok) {
                    return false;
                }
            }
        } catch (JDOMException | IOException e) {
            Messages.showMessageDialog(e.getMessage(), IdeBundle.message("title.error.reading.file"), Messages.getErrorIcon());
            return false;
        }
    } else {
        Messages.showErrorDialog(current, IdeBundle.message("title.module.file.does.not.exist", moduleFilePath), CommonBundle.message("title.error"));
        return false;
    }
    return true;
}
Also used : ConversionResult(com.intellij.conversion.ConversionResult) Element(org.jdom.Element) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) File(java.io.File)

Example 8 with JDOMException

use of org.jdom.JDOMException in project intellij-community by JetBrains.

the class PlainTextFormatter method convert.

@Override
public void convert(@NotNull final String rawDataDirectoryPath, @Nullable final String outputPath, @NotNull final Map<String, Tools> tools, @NotNull final List<File> inspectionsResults) throws ConversionException {
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    final URL descrExtractorXsltUrl = getClass().getResource("description-text.xsl");
    final Source xslSource;
    final Transformer transformer;
    try {
        xslSource = new StreamSource(URLUtil.openStream(descrExtractorXsltUrl));
        transformer = transformerFactory.newTransformer(xslSource);
    } catch (IOException e) {
        throw new ConversionException("Cannot find inspection descriptions converter.");
    } catch (TransformerConfigurationException e) {
        throw new ConversionException("Fail to load inspection descriptions converter.");
    }
    // write to file/stdout:
    final Writer w;
    if (outputPath != null) {
        final File outputFile = new File(outputPath);
        try {
            w = new FileWriter(outputFile);
        } catch (IOException e) {
            throw new ConversionException("Cannot edit file: " + outputFile.getPath());
        }
    } else {
        w = new PrintWriter(System.out);
    }
    try {
        for (File inspectionData : inspectionsResults) {
            if (inspectionData.isDirectory()) {
                warn("Folder isn't expected here: " + inspectionData.getName());
                continue;
            }
            final String fileNameWithoutExt = FileUtil.getNameWithoutExtension(inspectionData);
            if (InspectionApplication.DESCRIPTIONS.equals(fileNameWithoutExt)) {
                continue;
            }
            InspectionToolWrapper toolWrapper = tools.get(fileNameWithoutExt).getTool();
            // Tool name and group
            w.append(getToolPresentableName(toolWrapper)).append("\n");
            // Description is HTML based, need to be converted in plain text
            writeInspectionDescription(w, toolWrapper, transformer);
            // separator before file list
            w.append("\n");
            // parse xml and output results
            final SAXBuilder builder = new SAXBuilder();
            try {
                final Document doc = builder.build(inspectionData);
                final Element root = doc.getRootElement();
                final List problems = root.getChildren(PROBLEM_ELEMENT);
                // let's count max file path & line_number length to align problem descriptions
                final int maxFileColonLineLength = getMaxFileColonLineNumLength(inspectionData, toolWrapper, problems);
                for (Object problem : problems) {
                    // Format:
                    //   file_path:line_num   [severity] problem description
                    final Element fileElement = ((Element) problem).getChild(FILE_ELEMENT);
                    final String filePath = getPath(fileElement);
                    // skip suppressed results
                    if (resultsIgnored(inspectionData, toolWrapper)) {
                        continue;
                    }
                    final Element lineElement = ((Element) problem).getChild(LINE_ELEMENT);
                    final Element problemDescrElement = ((Element) problem).getChild(DESCRIPTION_ELEMENT);
                    final String severity = ((Element) problem).getChild(PROBLEM_CLASS_ELEMENT).getAttributeValue(SEVERITY_ATTRIBUTE);
                    final String fileLineNum = lineElement.getText();
                    w.append("  ").append(filePath).append(':').append(fileLineNum);
                    // align descriptions
                    for (int i = maxFileColonLineLength - 1 - filePath.length() - fileLineNum.length() + 4; i >= 0; i--) {
                        w.append(' ');
                    }
                    w.append("[").append(severity).append("] ");
                    w.append(problemDescrElement.getText()).append('\n');
                }
            } catch (JDOMException e) {
                throw new ConversionException("Unknown results format, file = " + inspectionData.getPath() + ". Error: " + e.getMessage());
            }
            // separator between neighbour inspections
            w.append("\n");
        }
    } catch (IOException e) {
        throw new ConversionException("Cannot write inspection results: " + e.getMessage());
    } finally {
        if (w != null) {
            try {
                w.close();
            } catch (IOException e) {
                warn("Cannot save inspection results: " + e.getMessage());
            }
        }
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) StreamSource(javax.xml.transform.stream.StreamSource) Element(org.jdom.Element) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Document(org.jdom.Document) JDOMException(org.jdom.JDOMException) URL(java.net.URL) StreamSource(javax.xml.transform.stream.StreamSource) List(java.util.List)

Example 9 with JDOMException

use of org.jdom.JDOMException in project intellij-community by JetBrains.

the class SonatypeSourceSearcher method findSourceJar.

@Nullable
@Override
public String findSourceJar(@NotNull final ProgressIndicator indicator, @NotNull String artifactId, @NotNull String version, @NotNull VirtualFile classesJar) throws SourceSearchException {
    try {
        indicator.setIndeterminate(true);
        indicator.setText("Connecting to https://oss.sonatype.org");
        indicator.checkCanceled();
        String url = "https://oss.sonatype.org/service/local/lucene/search?collapseresults=true&c=sources&a=" + artifactId + "&v=" + version;
        String groupId = findMavenGroupId(classesJar, artifactId);
        if (groupId != null) {
            url += ("&g=" + groupId);
        }
        List<Element> artifactList = (List<Element>) XPath.newInstance("/searchNGResponse/data/artifact").selectNodes(readDocumentCancelable(indicator, url));
        if (artifactList.isEmpty()) {
            return null;
        }
        Element element;
        if (artifactList.size() == 1) {
            element = artifactList.get(0);
        } else {
            // TODO handle
            return null;
        }
        List<Element> artifactHintList = (List<Element>) XPath.newInstance("artifactHits/artifactHit/artifactLinks/artifactLink/classifier[text()='sources']/../../..").selectNodes(element);
        if (artifactHintList.isEmpty()) {
            return null;
        }
        groupId = element.getChildTextTrim("groupId");
        String repositoryId = artifactHintList.get(0).getChildTextTrim("repositoryId");
        return "https://oss.sonatype.org/service/local/artifact/maven/redirect?r=" + repositoryId + "&g=" + groupId + "&a=" + artifactId + "&v=" + version + "&e=jar&c=sources";
    } catch (JDOMException e) {
        LOG.warn(e);
        throw new SourceSearchException("Failed to parse response from server. See log for more details.");
    } catch (IOException e) {
        // Cause of IOException may be canceling of operation.
        indicator.checkCanceled();
        LOG.warn(e);
        throw new SourceSearchException("Connection problem. See log for more details.");
    }
}
Also used : Element(org.jdom.Element) List(java.util.List) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) Nullable(org.jetbrains.annotations.Nullable)

Example 10 with JDOMException

use of org.jdom.JDOMException in project intellij-community by JetBrains.

the class MigrationMapSet method loadMaps.

private void loadMaps() {
    myMaps = new ArrayList<>();
    File dir = getMapDirectory();
    copyPredefinedMaps(dir);
    File[] files = getMapFiles(dir);
    for (int i = 0; i < files.length; i++) {
        try {
            MigrationMap map = readMap(files[i]);
            if (map != null) {
                map.setFileName(FileUtil.getNameWithoutExtension(files[i]));
                myMaps.add(map);
            }
        } catch (InvalidDataException | JDOMException e) {
            LOG.error("Invalid data in file: " + files[i].getAbsolutePath());
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}
Also used : InvalidDataException(com.intellij.openapi.util.InvalidDataException) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) File(java.io.File)

Aggregations

JDOMException (org.jdom.JDOMException)67 IOException (java.io.IOException)55 Element (org.jdom.Element)44 Document (org.jdom.Document)22 File (java.io.File)17 SAXBuilder (org.jdom.input.SAXBuilder)15 VirtualFile (com.intellij.openapi.vfs.VirtualFile)11 Nullable (org.jetbrains.annotations.Nullable)11 NotNull (org.jetbrains.annotations.NotNull)10 StringReader (java.io.StringReader)8 THashMap (gnu.trove.THashMap)6 ArrayList (java.util.ArrayList)6 List (java.util.List)6 InvalidDataException (com.intellij.openapi.util.InvalidDataException)5 Path (java.nio.file.Path)4 Logger (com.intellij.openapi.diagnostic.Logger)3 Project (com.intellij.openapi.project.Project)3 StringWriter (java.io.StringWriter)3 Format (org.jdom.output.Format)3 XMLOutputter (org.jdom.output.XMLOutputter)3