Ejemplo n.º 1
0
 @Nullable
 public static Configuration load(final InputStream is) throws IOException, JDOMException {
   try {
     final Document document = JDOMUtil.loadDocument(is);
     final ArrayList<Element> elements = new ArrayList<Element>();
     elements.add(document.getRootElement());
     elements.addAll(document.getRootElement().getChildren("component"));
     final Element element =
         ContainerUtil.find(
             elements,
             new Condition<Element>() {
               public boolean value(final Element element) {
                 return "component".equals(element.getName())
                     && COMPONENT_NAME.equals(element.getAttributeValue("name"));
               }
             });
     if (element != null) {
       final Configuration cfg = new Configuration();
       cfg.loadState(element, false);
       return cfg;
     }
     return null;
   } finally {
     is.close();
   }
 }
  @NotNull
  private GradleProjectConfiguration loadLastConfiguration(@NotNull File gradleConfigFile) {
    final GradleProjectConfiguration projectConfig = new GradleProjectConfiguration();
    if (gradleConfigFile.exists()) {
      try {
        final Document document = JDOMUtil.loadDocument(gradleConfigFile);
        XmlSerializer.deserializeInto(projectConfig, document.getRootElement());

        // filter orphan modules
        final Set<String> actualModules = myModulesConfigurationHash.keySet();
        for (Iterator<Map.Entry<String, GradleModuleResourceConfiguration>> iterator =
                projectConfig.moduleConfigurations.entrySet().iterator();
            iterator.hasNext(); ) {
          Map.Entry<String, GradleModuleResourceConfiguration> configurationEntry = iterator.next();
          if (!actualModules.contains(configurationEntry.getKey())) {
            iterator.remove();
          }
        }
      } catch (Exception e) {
        LOG.info(e);
      }
    }

    return projectConfig;
  }
    public ImportRunProfile(VirtualFile file, Project project) {
      myFile = file;
      myProject = project;
      try {
        final Document document = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(myFile));
        final Element config = document.getRootElement().getChild("config");
        if (config != null) {
          String configTypeId = config.getAttributeValue("configId");
          if (configTypeId != null) {
            final ConfigurationType configurationType =
                ConfigurationTypeUtil.findConfigurationType(configTypeId);
            if (configurationType != null) {
              myConfiguration =
                  configurationType.getConfigurationFactories()[0].createTemplateConfiguration(
                      project);
              myConfiguration.setName(config.getAttributeValue("name"));
              myConfiguration.readExternal(config);

              final Executor executor =
                  ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID);
              if (executor != null) {
                if (myConfiguration instanceof SMRunnerConsolePropertiesProvider) {
                  myProperties =
                      ((SMRunnerConsolePropertiesProvider) myConfiguration)
                          .createTestConsoleProperties(executor);
                }
              }
            }
          }
        }
      } catch (Exception ignore) {
      }
    }
  private void validateModule(@NotNull Module module) throws Exception {
    final String importedModulePath = getProject().getBaseDir().getPath();

    final Element actualImlElement = new Element("root");
    ((ModuleRootManagerImpl) ModuleRootManager.getInstance(module))
        .getState()
        .writeExternal(actualImlElement);
    PathMacros.getInstance().setMacro(MODULE_DIR, importedModulePath);
    PathMacroManager.getInstance(module).collapsePaths(actualImlElement);
    PathMacroManager.getInstance(getProject()).collapsePaths(actualImlElement);
    PathMacros.getInstance().removeMacro(MODULE_DIR);

    final String projectPath = getProject().getBaseDir().getPath();
    final File expectedImlFile = new File(projectPath + "/expected/" + module.getName() + ".iml");
    final Document expectedIml = JDOMUtil.loadDocument(expectedImlFile);
    final Element expectedImlElement = expectedIml.getRootElement();

    final String errorMsg =
        "Configuration of module "
            + module.getName()
            + " does not meet expectations.\nExpected:\n"
            + new String(JDOMUtil.printDocument(expectedIml, "\n"))
            + "\nBut got:\n"
            + new String(JDOMUtil.printDocument(new Document(actualImlElement), "\n"));
    Assert.assertTrue(errorMsg, JDOMUtil.areElementsEqual(expectedImlElement, actualImlElement));
    validateFacet(module);
  }
 ApplicationInfoImpl() {
   String resource = IDEA_PATH + ApplicationNamesInfo.getComponentName() + XML_EXTENSION;
   try {
     Document doc = JDOMUtil.loadDocument(ApplicationInfoImpl.class, resource);
     loadState(doc.getRootElement());
   } catch (Exception e) {
     throw new RuntimeException("Cannot load resource: " + resource, e);
   }
 }
Ejemplo n.º 6
0
 public static Document loadDocument(File file) throws CannotConvertException {
   try {
     return JDOMUtil.loadDocument(file);
   } catch (JDOMException e) {
     throw new CannotConvertException(file.getAbsolutePath() + ": " + e.getMessage(), e);
   } catch (IOException e) {
     throw new CannotConvertException(file.getAbsolutePath() + ": " + e.getMessage(), e);
   }
 }
 private static boolean isValidExternalFile(String version, File toCheck) {
   try {
     Document document = JDOMUtil.loadDocument(toCheck);
     String versionPattern = document.getRootElement().getChildText("version");
     return Pattern.compile(versionPattern).matcher(version).find();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
Ejemplo n.º 8
0
 /** Parse and print pretty-formatted XML to {@code logger}, if its level is DEBUG or below. */
 public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull String xml) {
   if (logger.isDebugEnabled()) {
     try {
       logger.debug(
           "\n" + JDOMUtil.createOutputter("\n").outputString(JDOMUtil.loadDocument(xml)));
     } catch (Exception e) {
       logger.debug(e);
     }
   }
 }
 private Element loadRootElement(final File file) {
   try {
     final Element element = JDOMUtil.loadDocument(file).getRootElement();
     myMacroToPathMap.substitute(element, SystemInfo.isFileSystemCaseSensitive);
     return element;
   } catch (JDOMException e) {
     throw new RuntimeException(e);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 public void readExternal(@NotNull URL url) throws InvalidDataException, FileNotFoundException {
   try {
     Document document = JDOMUtil.loadDocument(url);
     readExternal(document, url);
   } catch (FileNotFoundException e) {
     throw e;
   } catch (IOException e) {
     throw new InvalidDataException(e);
   } catch (JDOMException e) {
     throw new InvalidDataException(e);
   }
 }
Ejemplo n.º 11
0
 @Nullable
 public static Document loadDocument(final byte[] bytes) {
   try {
     return bytes == null || bytes.length == 0
         ? null
         : JDOMUtil.loadDocument(new ByteArrayInputStream(bytes));
   } catch (JDOMException e) {
     return null;
   } catch (IOException e) {
     return null;
   }
 }
  @Nullable
  static IdeaPluginDescriptorImpl loadDescriptorFromJar(File file, @NonNls String fileName) {
    try {
      URI fileURL = file.toURI();
      URL jarURL =
          new URL(
              "jar:"
                  + StringUtil.replace(fileURL.toASCIIString(), "!", "%21")
                  + "!/META-INF/"
                  + fileName);

      IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file);
      FileInputStream in = new FileInputStream(file);
      ZipInputStream zipStream = new ZipInputStream(in);
      try {
        ZipEntry entry = zipStream.getNextEntry();
        if (entry.getName().equals(JarMemoryLoader.SIZE_ENTRY)) {
          entry = zipStream.getNextEntry();
          if (entry.getName().equals("META-INF/" + fileName)) {
            byte[] content = FileUtil.loadBytes(zipStream, (int) entry.getSize());
            Document document = JDOMUtil.loadDocument(new ByteArrayInputStream(content));
            descriptor.readExternal(document, jarURL);
            return descriptor;
          }
        }
      } finally {
        zipStream.close();
        in.close();
      }

      descriptor.readExternal(jarURL);
      return descriptor;
    } catch (XmlSerializationException e) {
      getLogger().info("Cannot load " + file, e);
      prepareLoadingPluginsErrorMessage(
          "Plugin file " + file.getName() + " contains invalid plugin descriptor file.");
    } catch (FileNotFoundException e) {
      return null;
    } catch (Exception e) {
      getLogger().info("Cannot load " + file, e);
    } catch (Throwable e) {
      getLogger().info("Cannot load " + file, e);
    }

    return null;
  }
 private boolean loadContext(String zipPostfix, String entryName) {
   try {
     JBZipFile archive = getTasksArchive(zipPostfix);
     JBZipEntry entry = archive.getEntry(entryName.startsWith("/") ? entryName : "/" + entryName);
     if (entry != null) {
       byte[] bytes = entry.getData();
       Document document = JDOMUtil.loadDocument(new String(bytes));
       Element rootElement = document.getRootElement();
       loadContext(rootElement);
       archive.close();
       return true;
     }
   } catch (Exception e) {
     LOG.error(e);
   }
   return false;
 }
Ejemplo n.º 14
0
  @Nullable
  public static Document loadDocument(@Nullable InputStream stream) {
    if (stream == null) {
      return null;
    }

    try {
      try {
        return JDOMUtil.loadDocument(stream);
      } finally {
        stream.close();
      }
    } catch (JDOMException e) {
      return null;
    } catch (IOException e) {
      return null;
    }
  }
Ejemplo n.º 15
0
 @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
 private static Control[] loadControls() {
   Document document;
   try {
     // use temporary bytes stream because otherwise inputStreamSkippingBOM will fail
     // on ZipFileInputStream used in jar files
     final InputStream stream = HTMLControls.class.getResourceAsStream("HtmlControls.xml");
     final byte[] bytes = FileUtilRt.loadBytes(stream);
     stream.close();
     final UnsyncByteArrayInputStream bytesStream = new UnsyncByteArrayInputStream(bytes);
     document = JDOMUtil.loadDocument(CharsetToolkit.inputStreamSkippingBOM(bytesStream));
     bytesStream.close();
   } catch (Exception e) {
     LOG.error(e);
     return new Control[0];
   }
   if (!document.getRootElement().getName().equals("htmlControls")) {
     LOG.error("HTMLControls storage is broken");
     return new Control[0];
   }
   return XmlSerializer.deserialize(document, Control[].class);
 }
  private static boolean hasJSLibraryMappingToOldDartSdkGlobalLib(final @NotNull Project project) {
    /*
        Mapping to old 'Dart SDK' global lib is removed when ScriptingLibraryManager is loaded if 'Dart SDK' lib does not exist. That's why we use hacky way.
        One more bonus is that it works even if JavaScript plugin is disabled and in IntelliJ IDEA Community Edition

        <?xml version="1.0" encoding="UTF-8"?>
        <project version="4">
          <component name="JavaScriptLibraryMappings">
            <file url="PROJECT" libraries="{Dart SDK}" />
            <excludedPredefinedLibrary name="HTML5 / EcmaScript 5" />
          </component>
        </project>
    */
    final File jsLibraryMappingsFile =
        new File(project.getBasePath() + "/.idea/jsLibraryMappings.xml");
    if (jsLibraryMappingsFile.isFile()) {
      try {
        final Document document = JDOMUtil.loadDocument(jsLibraryMappingsFile);
        final Element rootElement = document.getRootElement();
        for (final Element componentElement : rootElement.getChildren("component")) {
          if ("JavaScriptLibraryMappings".equals(componentElement.getAttributeValue("name"))) {
            for (final Element fileElement : componentElement.getChildren("file")) {
              if ("PROJECT".equals(fileElement.getAttributeValue("url"))
                  && "{Dart SDK}".equals(fileElement.getAttributeValue("libraries"))) {
                return true;
              }
            }
          }
        }
      } catch (Throwable ignore) {
        /* unlucky */
      }
    }

    return false;
  }