Java 类com.intellij.openapi.util.JDOMUtil 实例源码

项目:educational-plugin    文件:StudyMigrationTest.java   
private void doTest(int version) throws IOException, JDOMException, StudySerializationUtils.StudyUnrecognizedFormatException {
  final String name = PlatformTestUtil.getTestName(this.name.getMethodName(), true);
  final Path before = getTestDataPath().resolve(name + ".xml");
  final Path after = getTestDataPath().resolve(name + ".after.xml");
  Element element = JdomKt.loadElement(before);
  Element converted = element;
  switch (version) {
    case 1:
      converted = StudySerializationUtils.Xml.convertToSecondVersion(element);
      break;
    case 3:
      converted = StudySerializationUtils.Xml.convertToForthVersion(element);
      break;
    case 4:
      converted = StudySerializationUtils.Xml.convertToFifthVersion(element);
      break;
  }
  assertTrue(JDOMUtil.areElementsEqual(converted, JdomKt.loadElement(after)));
}
项目:teamcity-telegram-plugin    文件:TelegramSettingsManager.java   
private synchronized void reloadConfiguration() throws JDOMException, IOException {
  LOG.info("Loading configuration file: " + configFile);
  Document document = JDOMUtil.loadDocument(configFile.toFile());

  Element root = document.getRootElement();

  TelegramSettings newSettings = new TelegramSettings();
  newSettings.setBotToken(unscramble(root.getAttributeValue(BOT_TOKEN_ATTR)));
  newSettings.setPaused(Boolean.parseBoolean(root.getAttributeValue(PAUSE_ATTR)));
  newSettings.setUseProxy(Boolean.parseBoolean(root.getAttributeValue(USE_PROXY_ATTR)));
  newSettings.setProxyServer(root.getAttributeValue(PROXY_SERVER_ATTR));
  newSettings.setProxyPort(restoreInteger(root.getAttributeValue(PROXY_PORT_ATTR)));
  newSettings.setProxyUsername(root.getAttributeValue(PROXY_PASSWORD_ATTR));
  newSettings.setProxyPassword(unscramble(root.getAttributeValue(PROXY_PASSWORD_ATTR)));

  settings = newSettings;
  botManager.reloadIfNeeded(settings);
}
项目:teamcity-s3-artifact-storage-plugin    文件:S3PreSignUrlHelper.java   
@NotNull
public static Map<String, URL> readPreSignUrlMapping(String data) throws IOException {
  Document document;
  try {
    document = JDOMUtil.loadDocument(data);
  } catch (JDOMException e) {
    return Collections.emptyMap();
  }
  Element rootElement = document.getRootElement();
  if(!rootElement.getName().equals(S3_PRESIGN_URL_MAPPING)) return Collections.emptyMap();
  final Map<String, URL> result = new HashMap<String, URL>();
  for(Object mapEntryElement : rootElement.getChildren(S3_PRESIGN_URL_MAP_ENTRY)){
    Element mapEntryElementCasted = (Element) mapEntryElement;
    String s3ObjectKey = mapEntryElementCasted.getChild(S3_OBJECT_KEY).getValue();
    String preSignUrlString = mapEntryElementCasted.getChild(PRE_SIGN_URL).getValue();
    result.put(s3ObjectKey, new URL(preSignUrlString));
  }
  return result;
}
项目:teamcity-s3-artifact-storage-plugin    文件:S3PreSignUrlHelper.java   
@NotNull
public static String writePreSignUrlMapping(@NotNull Map<String, URL> data) throws IOException {
  Element rootElement = new Element(S3_PRESIGN_URL_MAPPING);
  for (String s3ObjectKey : data.keySet()){
    URL preSignUrl = data.get(s3ObjectKey);
    Element mapEntry = new Element(S3_PRESIGN_URL_MAP_ENTRY);
    Element preSignUrlElement = new Element(PRE_SIGN_URL);
    preSignUrlElement.addContent(preSignUrl.toString());
    mapEntry.addContent(preSignUrlElement);
    Element s3ObjectKeyElement = new Element(S3_OBJECT_KEY);
    s3ObjectKeyElement.addContent(s3ObjectKey);
    mapEntry.addContent(s3ObjectKeyElement);
    rootElement.addContent(mapEntry);
  }
  return JDOMUtil.writeDocument(new Document(rootElement), System.getProperty("line.separator"));
}
项目:intellij-ce-playground    文件:MavenIndicesManager.java   
private void saveUserArchetypes() {
  Element root = new Element(ELEMENT_ARCHETYPES);
  for (MavenArchetype each : myUserArchetypes) {
    Element childElement = new Element(ELEMENT_ARCHETYPE);
    childElement.setAttribute(ELEMENT_GROUP_ID, each.groupId);
    childElement.setAttribute(ELEMENT_ARTIFACT_ID, each.artifactId);
    childElement.setAttribute(ELEMENT_VERSION, each.version);
    if (each.repository != null) {
      childElement.setAttribute(ELEMENT_REPOSITORY, each.repository);
    }
    if (each.description != null) {
      childElement.setAttribute(ELEMENT_DESCRIPTION, each.description);
    }
    root.addContent(childElement);
  }
  try {
    File file = getUserArchetypesFile();
    file.getParentFile().mkdirs();
    JDOMUtil.writeDocument(new Document(root), file, "\n");
  }
  catch (IOException e) {
    MavenLog.LOG.warn(e);
  }
}
项目:intellij-ce-playground    文件:EclipseClasspathTest.java   
static void checkModule(String path, Module module) throws IOException, JDOMException, ConversionException {
  final File classpathFile1 = new File(path, EclipseXml.DOT_CLASSPATH_EXT);
  if (!classpathFile1.exists()) return;
  String fileText1 = FileUtil.loadFile(classpathFile1).replaceAll("\\$ROOT\\$", module.getProject().getBaseDir().getPath());
  if (!SystemInfo.isWindows) {
    fileText1 = fileText1.replaceAll(EclipseXml.FILE_PROTOCOL + "/", EclipseXml.FILE_PROTOCOL);
  }

  Element classpathElement1 = JDOMUtil.loadDocument(fileText1).getRootElement();
  ModuleRootModel model = ModuleRootManager.getInstance(module);
  Element resultClasspathElement = new EclipseClasspathWriter().writeClasspath(classpathElement1, model);

  String resulted = new String(JDOMUtil.printDocument(new Document(resultClasspathElement), "\n"));
  assertTrue(resulted.replaceAll(StringUtil.escapeToRegexp(module.getProject().getBaseDir().getPath()), "\\$ROOT\\$"),
             JDOMUtil.areElementsEqual(classpathElement1, resultClasspathElement));
}
项目:intellij-ce-playground    文件:JpsLoaderBase.java   
private static Element tryLoadRootElement(File file) throws IOException, JDOMException {
  for (int i = 0; i < MAX_ATTEMPTS - 1; i++) {
    try {
      return JDOMUtil.loadDocument(file).getRootElement();
    }
    catch (Exception e) {
      LOG.info("Loading attempt #" + i + " failed", e);
    }
    //most likely configuration file is being written by IDE so we'll wait a little
    try {
      //noinspection BusyWait
      Thread.sleep(300);
    }
    catch (InterruptedException ignored) { }
  }
  return JDOMUtil.loadDocument(file).getRootElement();
}
项目:intellij-ce-playground    文件:JpsEncodingModelSerializerExtension.java   
@Override
public void loadExtension(@NotNull JpsProject project, @NotNull Element componentTag) {
  String projectEncoding = null;
  Map<String, String> urlToEncoding = new HashMap<String, String>();
  for (Element fileTag : JDOMUtil.getChildren(componentTag, "file")) {
    String url = fileTag.getAttributeValue("url");
    String encoding = fileTag.getAttributeValue("charset");
    if (url.equals("PROJECT")) {
      projectEncoding = encoding;
    }
    else {
      urlToEncoding.put(url, encoding);
    }
  }
  JpsEncodingConfigurationService.getInstance().setEncodingConfiguration(project, projectEncoding, urlToEncoding);
}
项目:intellij-ce-playground    文件:PsiTestCase.java   
private PsiTestData loadData(String dataName) throws Exception {
  PsiTestData data = createData();
  Element documentElement = JDOMUtil.load(new File(myDataRoot + "/" + "data.xml"));

  final List nodes = documentElement.getChildren("data");

  for (Object node1 : nodes) {
    Element node = (Element)node1;
    String value = node.getAttributeValue("name");

    if (value.equals(dataName)) {
      DefaultJDOMExternalizer.readExternal(data, node);
      data.loadText(myDataRoot);

      return data;
    }
  }

  throw new IllegalArgumentException("Cannot find data chunk '" + dataName + "'");
}
项目:intellij-ce-playground    文件:WorkingContextManager.java   
private synchronized boolean loadContext(String zipPostfix, String entryName) {
  JBZipFile archive = null;
  try {
    archive = getTasksArchive(zipPostfix);
    JBZipEntry entry = archive.getEntry(StringUtil.startsWithChar(entryName, '/') ? entryName : "/" + entryName);
    if (entry != null) {
      byte[] bytes = entry.getData();
      Document document = JDOMUtil.loadDocument(new String(bytes));
      Element rootElement = document.getRootElement();
      loadContext(rootElement);
      return true;
    }
  }
  catch (Exception e) {
    LOG.error(e);
  }
  finally {
    closeArchive(archive);
  }
  return false;
}
项目:intellij-ce-playground    文件:MigrationMapSet.java   
public void saveMaps() throws IOException{
  File dir = getMapDirectory();
  if (dir == null) {
    return;
  }

  File[] files = getMapFiles();

  @NonNls String[] filePaths = new String[myMaps.size()];
  Document[] documents = new Document[myMaps.size()];

  UniqueNameGenerator namesProvider = new UniqueNameGenerator();
  for(int i = 0; i < myMaps.size(); i++){
    MigrationMap map = myMaps.get(i);

    filePaths[i] = dir + File.separator + namesProvider.generateUniqueName(FileUtil.sanitizeFileName(map.getName(), false)) + ".xml";
    documents[i] = saveMap(map);
  }

  JDOMUtil.updateFileSet(files, filePaths, documents, CodeStyleSettingsManager.getSettings(null).getLineSeparator());
}
项目:intellij-ce-playground    文件:InspectionProfilesConverterTest.java   
private static void doTest(final String dirName) throws Exception {
  InspectionProfileImpl.INIT_INSPECTIONS = true;
  try {
    final String relativePath = "/inspection/converter/";
    final File projectFile = new File(JavaTestUtil.getJavaTestDataPath() + relativePath + dirName + "/options.ipr");
    for (Element element : JDOMUtil.loadDocument(projectFile).getRootElement().getChildren("component")) {
      if (Comparing.strEqual(element.getAttributeValue("name"), "InspectionProjectProfileManager")) {
        final InspectionProjectProfileManager profileManager = InspectionProjectProfileManager.getInstance(getProject());
        profileManager.loadState(element);

        Element configElement = profileManager.getState();
        final File file = new File(JavaTestUtil.getJavaTestDataPath() + relativePath + dirName + "/options.after.xml");
        PlatformTestUtil.assertElementsEqual(JDOMUtil.loadDocument(file).getRootElement(), configElement);
        break;
      }
    }
  }
  finally {
    InspectionProfileImpl.INIT_INSPECTIONS = false;
  }
}
项目:intellij-ce-playground    文件:InspectionProfileTest.java   
public void testReloadProfileWithUnknownScopes() throws Exception {
  final Element element = JDOMUtil.loadDocument("<inspections version=\"1.0\">\n" +
                                                "  <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
                                                "  <inspection_tool class=\"ArgNamesErrorsInspection\" enabled=\"true\" level=\"ERROR\" enabled_by_default=\"false\" />\n" +
                                                "  <inspection_tool class=\"ArgNamesWarningsInspection\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\" />\n" +
                                                "  <inspection_tool class=\"AroundAdviceStyleInspection\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\" />\n" +
                                                "  <inspection_tool class=\"DeclareParentsInspection\" enabled=\"true\" level=\"ERROR\" enabled_by_default=\"false\" />\n" +
                                                /*"  <inspection_tool class=\"ManifestDomInspection\" enabled=\"true\" level=\"ERROR\" enabled_by_default=\"false\" />\n" +*/
                                                "  <inspection_tool class=\"MissingAspectjAutoproxyInspection\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\" />\n" +
                                                "  <inspection_tool class=\"UNUSED_IMPORT\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"true\">\n" +
                                                "    <scope name=\"Unknown scope name\" level=\"WARNING\" enabled=\"true\" />\n" +
                                                "  </inspection_tool>\n" +
                                                "</inspections>").getRootElement();
  final InspectionProfileImpl profile = createProfile();
  profile.readExternal(element);
  final ModifiableModel model = profile.getModifiableModel();
  model.commit();
  final Element copy = new Element("inspections");
  profile.writeExternal(copy);
  assertElementsEqual(element, copy);
}
项目:intellij-ce-playground    文件:InspectionProfileTest.java   
public void testPreserveCompatibility() throws Exception {
  InspectionProfileImpl foo = new InspectionProfileImpl("foo", InspectionToolRegistrar.getInstance(), InspectionProjectProfileManager.getInstance(getProject()));
  String test = "<profile version=\"1.0\" is_locked=\"false\">\n" +
               "  <option name=\"myName\" value=\"idea.default\" />\n" +
               "  <option name=\"myLocal\" value=\"false\" />\n" +
               "  <inspection_tool class=\"AbstractMethodCallInConstructor\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"true\" />\n" +
               "  <inspection_tool class=\"AssignmentToForLoopParameter\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"true\">\n" +
               "    <option name=\"m_checkForeachParameters\" value=\"false\" />\n" +
               "  </inspection_tool>\n" +
               "</profile>";
  foo.readExternal(JDOMUtil.loadDocument(test).getRootElement());
  foo.initInspectionTools(getProject());
  Element serialized = new Element("profile");
  foo.writeExternal(serialized);
  assertEquals(test, JDOMUtil.writeElement(serialized));
}
项目:intellij-ce-playground    文件:EntryPointsConverterTest.java   
private static void doTest(String type, String fqName, String expectedFQName) throws Exception {
  final Element entryPoints = setUpEntryPoint(type, fqName);

  final HashMap<String, SmartRefElementPointer> persistentEntryPoints = new HashMap<String, SmartRefElementPointer>();
  EntryPointsManagerBase.convert(entryPoints, persistentEntryPoints);

  final Element testElement = new Element("comp");
  EntryPointsManagerBase.writeExternal(testElement, persistentEntryPoints, new JDOMExternalizableStringList());

  final Element expectedEntryPoints = setUpEntryPoint(type, expectedFQName);
  expectedEntryPoints.setAttribute("version", "2.0");
  final Element expected = new Element("comp");
  expected.addContent(expectedEntryPoints);

  assertTrue(JDOMUtil.areElementsEqual(testElement, expected));
}
项目:intellij-ce-playground    文件:LocalArchivedTemplate.java   
public LocalArchivedTemplate(@NotNull URL archivePath,
                             @NotNull ClassLoader classLoader) {
  super(getTemplateName(archivePath), null);

  myArchivePath = archivePath;
  myModuleType = computeModuleType(this);
  String s = readEntry(TEMPLATE_DESCRIPTOR);
  if (s != null) {
    try {
      Element templateElement = JDOMUtil.loadDocument(s).getRootElement();
      populateFromElement(templateElement);
      String iconPath = templateElement.getChildText("icon-path");
      if (iconPath != null) {
        myIcon = IconLoader.findIcon(iconPath, classLoader);
      }
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}
项目:intellij-ce-playground    文件:ProjectFromSourcesBuilderImpl.java   
@Nullable
private static ModuleType getModuleType(ModuleDescriptor moduleDescriptor) throws InvalidDataException, JDOMException, IOException {
  if (moduleDescriptor.isReuseExistingElement()) {
    final File file = new File(moduleDescriptor.computeModuleFilePath());
    if (file.exists()) {
      final Element rootElement = JDOMUtil.loadDocument(file).getRootElement();
      final String type = rootElement.getAttributeValue("type");
      if (type != null) {
        return ModuleTypeManager.getInstance().findByID(type);
      }
    }
    return null;
  }
  else {
    return moduleDescriptor.getModuleType();
  }
}
项目:intellij-ce-playground    文件:GradleResourceCompilerConfigurationGenerator.java   
@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;
}
项目:intellij-ce-playground    文件:GenericRepositoryType.java   
@Override
public TaskRepository createRepository() {
  Document document;
  try {
    String configFileName = myName.toLowerCase() + ".xml";
    //URL resourceUrl = ResourceUtil.getResource(GenericRepositoryType.class, "connectors", configFileName);
    URL resourceUrl = GenericRepository.class.getResource("connectors/" + configFileName);
    if (resourceUrl == null) {
      throw new AssertionError("Repository configuration file '" + configFileName + "' not found");
    }
    document = JDOMUtil.loadResourceDocument(resourceUrl);
  }
  catch (Exception e) {
    throw new AssertionError(e);
  }
  GenericRepository repository = XmlSerializer.deserialize(document.getRootElement(), GenericRepository.class);
  if (repository != null) {
    repository.setRepositoryType(GenericRepositoryType.this);
    repository.setSubtypeName(getName());
  }
  return repository;
}
项目:intellij-ce-playground    文件:ScopeToolState.java   
public boolean equalTo(@NotNull ScopeToolState state2) {
  if (isEnabled() != state2.isEnabled()) return false;
  if (getLevel() != state2.getLevel()) return false;
  InspectionToolWrapper toolWrapper = getTool();
  InspectionToolWrapper toolWrapper2 = state2.getTool();
  if (!toolWrapper.isInitialized() && !toolWrapper2.isInitialized()) return true;
  try {
    @NonNls String tempRoot = "root";
    Element oldToolSettings = new Element(tempRoot);
    toolWrapper.getTool().writeSettings(oldToolSettings);
    Element newToolSettings = new Element(tempRoot);
    toolWrapper2.getTool().writeSettings(newToolSettings);
    return JDOMUtil.areElementsEqual(oldToolSettings, newToolSettings);
  }
  catch (WriteExternalException e) {
    LOG.error(e);
  }
  return false;
}
项目:intellij-ce-playground    文件:TaskSettingsTest.java   
public void testCarriageReturnInFormat() throws Exception {
  TaskRepository repository = new YouTrackRepository();
  String format = "foo \n bar";
  repository.setCommitMessageFormat(format);
  ((TaskManagerImpl)myTaskManager).setRepositories(Collections.singletonList(repository));
  TaskManagerImpl.Config config = ((TaskManagerImpl)myTaskManager).getState();
  Element element = XmlSerializer.serialize(config);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  JDOMUtil.writeDocument(new Document(element), stream, "\n");

  Element element1 = JDOMUtil.load(new ByteArrayInputStream(stream.toByteArray()));
  TaskManagerImpl.Config deserialize = XmlSerializer.deserialize(element1, TaskManagerImpl.Config.class);
  ((TaskManagerImpl)myTaskManager).loadState(deserialize);

  TaskRepository[] repositories = myTaskManager.getAllRepositories();
  assertEquals(format, repositories[0].getCommitMessageFormat());
}
项目:intellij-ce-playground    文件:FileEditorManagerTestCase.java   
protected void openFiles(@NotNull String femSerialisedText) throws IOException, JDOMException, InterruptedException, ExecutionException {
  Document document = JDOMUtil.loadDocument(femSerialisedText);
  Element rootElement = document.getRootElement();
  ExpandMacroToPathMap map = new ExpandMacroToPathMap();
  map.addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, getTestDataPath());
  map.substitute(rootElement, true, true);

  myManager.readExternal(rootElement);

  Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
    @Override
    public void run() {
      myManager.getMainSplitters().openFiles();
    }
  });
  while (true) {
    try {
      future.get(100, TimeUnit.MILLISECONDS);
      return;
    }
    catch (TimeoutException e) {
      UIUtil.dispatchAllInvocationEvents();
    }
  }
}
项目:intellij-ce-playground    文件:PluginsAdvertiser.java   
public static KnownExtensions loadExtensions() {
  KnownExtensions knownExtensions = ourKnownExtensions.get();
  if (knownExtensions != null) return knownExtensions;
  try {
    File file = getExtensionsFile();
    if (file.isFile()) {
      knownExtensions = XmlSerializer.deserialize(JDOMUtil.load(file), KnownExtensions.class);
      ourKnownExtensions = new SoftReference<KnownExtensions>(knownExtensions);
      return knownExtensions;
    }
  }
  catch (Exception e) {
    LOG.info(e);
  }
  return null;
}
项目:intellij-ce-playground    文件:XMLOutputterTest.java   
private String printElement(Element root) throws IOException {
  XMLOutputter xmlOutputter = JDOMUtil.createOutputter("\n");
  final Format format = xmlOutputter.getFormat().setOmitDeclaration(true).setOmitEncoding(true).setExpandEmptyElements(true);
  xmlOutputter.setFormat(format);

  CharArrayWriter writer = new CharArrayWriter();

  xmlOutputter.output(root, writer);
  String res = new String(writer.toCharArray());
  return res;
}
项目:intellij-ce-playground    文件:JpsAntModelSerializerExtension.java   
@Override
public void loadExtension(@NotNull JpsGlobal global, @NotNull Element componentTag) {
  for (Element antTag : JDOMUtil.getChildren(componentTag.getChild("registeredAnts"), "ant")) {
    String name = getValueAttribute(antTag, "name");
    String homeDir = getValueAttribute(antTag, "homeDir");
    List<String> classpath = new ArrayList<String>();
    List<String> jarDirectories = new ArrayList<String>();
    for (Element classpathItemTag : JDOMUtil.getChildren(antTag.getChild("classpath"), "classpathItem")) {
      String fileUrl = classpathItemTag.getAttributeValue("path");
      String dirUrl = classpathItemTag.getAttributeValue("dir");
      if (fileUrl != null) {
        classpath.add(JpsPathUtil.urlToPath(fileUrl));
      }
      else if (dirUrl != null) {
        jarDirectories.add(JpsPathUtil.urlToPath(dirUrl));
      }
    }

    if (name != null && homeDir != null) {
      JpsAntExtensionService.addAntInstallation(global, new JpsAntInstallationImpl(new File(homeDir), name, classpath, jarDirectories));
    }
  }
}
项目:intellij-ce-playground    文件:XDebuggerSettingsManager.java   
@Override
public SettingsState getState() {
  SettingsState settingsState = new SettingsState();
  settingsState.setDataViewSettings(myDataViewSettings);
  settingsState.setGeneralSettings(myGeneralSettings);

  initSettings();
  if (!mySettingsById.isEmpty()) {
    SkipDefaultValuesSerializationFilters filter = new SkipDefaultValuesSerializationFilters();
    for (XDebuggerSettings<?> settings : mySettingsById.values()) {
      Object subState = settings.getState();
      if (subState != null) {
        Element serializedState = XmlSerializer.serializeIfNotDefault(subState, filter);
        if (!JDOMUtil.isEmpty(serializedState)) {
          SpecificSettingsState state = new SpecificSettingsState();
          state.id = settings.getId();
          state.configuration = serializedState;
          settingsState.specificStates.add(state);
        }
      }
    }
  }
  return settingsState;
}
项目:intellij-ce-playground    文件:XBreakpointManagerTest.java   
public void testConditionConvert() {
  String condition = "old-style condition";
  String logExpression = "old-style expression";
  String oldStyle =
  "<breakpoint-manager>" +
  "<breakpoints>" +
  "<line-breakpoint enabled=\"true\" type=\"" + MY_LINE_BREAKPOINT_TYPE.getId() + "\">" +
  "      <condition>" + condition + "</condition>" +
  "      <url>url</url>" +
  "      <log-expression>" + logExpression + "</log-expression>" +
  "</line-breakpoint>" +
  "</breakpoints>" +
  "<option name=\"time\" value=\"1\" />" +
  "</breakpoint-manager>";
  try {
    Document document = JDOMUtil.loadDocument(oldStyle);
    load(document.getRootElement());
  }
  catch (Exception e) {
    e.printStackTrace();
    fail();
  }
  XLineBreakpoint<MyBreakpointProperties> breakpoint = assertOneElement(myBreakpointManager.getBreakpoints(MY_LINE_BREAKPOINT_TYPE));
  assertEquals(condition, breakpoint.getCondition());
  assertEquals(logExpression, breakpoint.getLogExpression());
}
项目:intellij-ce-playground    文件:ConversionServiceImpl.java   
@NotNull
private static CachedConversionResult loadCachedConversionResult(File projectFile) {
  try {
    final File infoFile = getConversionInfoFile(projectFile);
    if (!infoFile.exists()) {
      return new CachedConversionResult();
    }
    final Document document = JDOMUtil.loadDocument(infoFile);
    final CachedConversionResult result = XmlSerializer.deserialize(document, CachedConversionResult.class);
    return result != null ? result : new CachedConversionResult();
  }
  catch (Exception e) {
    LOG.info(e);
    return new CachedConversionResult();
  }
}
项目:intellij-ce-playground    文件:InspectionDiff.java   
private static void writeInspectionDiff(final String oldPath, final String newPath, final String outPath) {
  try {
    InputStream oldStream = oldPath != null ? new BufferedInputStream(new FileInputStream(oldPath)) : null;
    InputStream newStream = new BufferedInputStream(new FileInputStream(newPath));

    Document oldDoc = oldStream != null ? JDOMUtil.loadDocument(oldStream) : null;
    Document newDoc = JDOMUtil.loadDocument(newStream);

    OutputStream outStream = System.out;
    if (outPath != null) {
      outStream = new BufferedOutputStream(new FileOutputStream(outPath + File.separator + new File(newPath).getName()));
    }

    Document delta = createDelta(oldDoc, newDoc);
    JDOMUtil.writeDocument(delta, outStream, "\n");
    if (outStream != System.out) {
      outStream.close();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
项目:intellij-ce-playground    文件:JpsGradleExtensionServiceImpl.java   
@NotNull
public GradleProjectConfiguration getGradleProjectConfiguration(@NotNull File dataStorageRoot) {
  final File configFile = new File(dataStorageRoot, GradleProjectConfiguration.CONFIGURATION_FILE_RELATIVE_PATH);
  GradleProjectConfiguration config;
  synchronized (myLoadedConfigs) {
    config = myLoadedConfigs.get(configFile);
    if (config == null) {
      config = new GradleProjectConfiguration();
      try {
        final Document document = JDOMUtil.loadDocument(configFile);
        XmlSerializer.deserializeInto(config, document.getRootElement());
      }
      catch (Exception e) {
        LOG.info(e);
      }
      myLoadedConfigs.put(configFile, config);
    }
  }
  return config;
}
项目:intellij-ce-playground    文件:MavenPlugin.java   
@Override
public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  MavenPlugin that = (MavenPlugin)o;

  if (myDefault != that.myDefault) return false;
  if (myGroupId != null ? !myGroupId.equals(that.myGroupId) : that.myGroupId != null) return false;
  if (myArtifactId != null ? !myArtifactId.equals(that.myArtifactId) : that.myArtifactId != null) return false;
  if (myVersion != null ? !myVersion.equals(that.myVersion) : that.myVersion != null) return false;
  if (!JDOMUtil.areElementsEqual(myConfiguration, that.myConfiguration)) return false;
  if (myExecutions != null ? !myExecutions.equals(that.myExecutions) : that.myExecutions != null) return false;
  if (myDependencies != null ? !myDependencies.equals(that.myDependencies) : that.myDependencies != null) return false;

  return true;
}
项目:intellij-ce-playground    文件:ConversionContextImpl.java   
@NotNull
public List<File> getClassRoots(Element libraryElement, @Nullable ModuleSettingsImpl moduleSettings) {
  List<File> files = new ArrayList<File>();
  //todo[nik] support jar directories
  final Element classesChild = libraryElement.getChild("CLASSES");
  if (classesChild != null) {
    final List<Element> roots = JDOMUtil.getChildren(classesChild, "root");
    final ExpandMacroToPathMap pathMap = createExpandMacroMap(moduleSettings);
    for (Element root : roots) {
      final String url = root.getAttributeValue("url");
      final String path = VfsUtilCore.urlToPath(url);
      files.add(new File(PathUtil.getLocalPath(pathMap.substitute(path, true))));
    }
  }
  return files;
}
项目:intellij-ce-playground    文件:JpsMavenExtensionServiceImpl.java   
@NotNull
public MavenProjectConfiguration getMavenProjectConfiguration(@NotNull File dataStorageRoot) {
  final File configFile = new File(dataStorageRoot, MavenProjectConfiguration.CONFIGURATION_FILE_RELATIVE_PATH);
  MavenProjectConfiguration config;
  synchronized (myLoadedConfigs) {
    config = myLoadedConfigs.get(configFile);
    if (config == null) {
      config = new MavenProjectConfiguration();
      try {
        final Document document = JDOMUtil.loadDocument(configFile);
        XmlSerializer.deserializeInto(config, document.getRootElement());
      }
      catch (Exception e) {
        LOG.info(e);
      }
      myLoadedConfigs.put(configFile, config);
    }
  }
  return config;
}
项目:intellij-ce-playground    文件:EclipseImportBuilder.java   
@NotNull
public static Set<String> collectNatures(@NotNull String path) {
  Set<String> naturesNames = new THashSet<String>();
  try {
    Element natures = JDOMUtil.load(new File(path, EclipseXml.DOT_PROJECT_EXT)).getChild("natures");
    if (natures != null) {
      for (Element nature : natures.getChildren("nature")) {
        String natureName = nature.getText();
        if (!StringUtil.isEmptyOrSpaces(natureName)) {
          naturesNames.add(natureName);
        }
      }
    }
  }
  catch (Exception ignore) {
  }
  return naturesNames;
}
项目:intellij-ce-playground    文件:MultilanguageDuplocatorSettings.java   
@Override
public Element getState() {
  synchronized (mySettingsMap) {
    Element state = new Element("state");
    if (mySettingsMap.isEmpty()) {
      return state;
    }

    SkipDefaultValuesSerializationFilters filter = new SkipDefaultValuesSerializationFilters();
    for (String name : mySettingsMap.keySet()) {
      Element child = XmlSerializer.serialize(mySettingsMap.get(name), filter);
      if (!JDOMUtil.isEmpty(child)) {
        child.setName("object");
        child.setAttribute("language", name);
        state.addContent(child);
      }
    }
    return state;
  }
}
项目:intellij-ce-playground    文件:HTMLControls.java   
@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);
}
项目:intellij-ce-playground    文件:TaskUtil.java   
/**
 * Parse and print pretty-formatted XML to {@code logger}, if its level is DEBUG or below.
 */
public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull InputStream xml) {
  if (logger.isDebugEnabled()) {
    try {
      logger.debug("\n" + JDOMUtil.createOutputter("\n").outputString(JDOMUtil.loadDocument(xml)));
    }
    catch (Exception e) {
      logger.debug(e);
    }
  }
}
项目:intellij-ce-playground    文件:JpsGlobalElementSaver.java   
private void saveGlobalComponents(JpsGlobalExtensionSerializer serializer, File optionsDir) throws IOException {
  String fileName = serializer.getConfigFileName();
  File configFile = new File(optionsDir, fileName != null ? fileName : "other.xml");
  Element rootElement = loadOrCreateRootElement(configFile);
  serializer.saveExtension(myGlobal, JDomSerializationUtil.findOrCreateComponentElement(rootElement, serializer.getComponentName()));
  JDOMUtil.writeDocument(new Document(rootElement), configFile, SystemProperties.getLineSeparator());
}
项目:intellij-ce-playground    文件:JDomSerializationUtil.java   
@Nullable
public static Element findComponent(@Nullable Element root, @NonNls String componentName) {
  for (Element element : JDOMUtil.getChildren(root, COMPONENT_ELEMENT)) {
    if (componentName.equals(element.getAttributeValue(NAME_ATTRIBUTE))) {
      return element;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:EclipseProjectFinder.java   
@Nullable
public static LinkedResource findLinkedResource(@NotNull String projectPath, @NotNull String relativePath) {
  String independentPath = FileUtil.toSystemIndependentName(relativePath);
  @NotNull String resourceName = independentPath;
  final int idx = independentPath.indexOf('/');
  if (idx != -1) {
    resourceName = independentPath.substring(0, idx);
  }
  final File file = new File(projectPath, DOT_PROJECT_EXT);
  if (file.isFile()) {
    try {
      for (Object o : JDOMUtil.loadDocument(file).getRootElement().getChildren(LINKED_RESOURCES)) {
        for (Object l : ((Element)o).getChildren(LINK)) {
          if (Comparing.strEqual(((Element)l).getChildText(NAME_TAG), resourceName)) {
            LinkedResource linkedResource = new LinkedResource();
            final String relativeToLinkedResourcePath =
              independentPath.length() > resourceName.length() ? independentPath.substring(resourceName.length()) : "";

            final Element locationURI = ((Element)l).getChild("locationURI");
            if (locationURI != null) {
              linkedResource.setURI(FileUtil.toSystemIndependentName(locationURI.getText()) + relativeToLinkedResourcePath);
            }

            final Element location = ((Element)l).getChild("location");
            if (location != null) {
              linkedResource.setLocation(FileUtil.toSystemIndependentName(location.getText()) + relativeToLinkedResourcePath);
            }
            return linkedResource;
          }
        }
      }
    }
    catch (Exception ignore) {
    }
  }
  return null;
}