Exemplo n.º 1
0
 public String[] knownNamespaces() {
   final PsiElement parentElement = getParent();
   BidirectionalMap<String, String> map = initNamespaceMaps(parentElement);
   Set<String> known = Collections.emptySet();
   if (map != null) {
     known = new HashSet<String>(map.values());
   }
   if (parentElement instanceof XmlTag) {
     if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces();
     ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces());
   } else {
     XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this);
     if (xmlExtension != null) {
       final XmlFile xmlFile = xmlExtension.getContainingFile(this);
       if (xmlFile != null) {
         final XmlTag rootTag = xmlFile.getRootTag();
         if (rootTag != null && rootTag != this) {
           if (known.isEmpty()) return rootTag.knownNamespaces();
           ContainerUtil.addAll(known, rootTag.knownNamespaces());
         }
       }
     }
   }
   return ArrayUtil.toStringArray(known);
 }
 public AntHectorConfigurable(XmlFile file) {
   myFile = file;
   myProject = file.getProject();
   final VirtualFile selfVFile = myFile.getVirtualFile();
   myLocalPath = PathUtil.getLocalPath(selfVFile);
   myFileFilter = GlobalSearchScope.projectScope(myProject);
 }
Exemplo n.º 3
0
    public Object[] get(final PsiElement context, CompletionContext completionContext) {
      XmlFile containingFile = null;
      XmlFile descriptorFile = null;
      final XmlTag tag = PsiTreeUtil.getParentOfType(context, XmlTag.class);

      if (tag != null) {
        containingFile = (XmlFile) tag.getContainingFile();
        descriptorFile = findDescriptorFile(tag, containingFile);
      } else {
        final XmlDocument document = PsiTreeUtil.getParentOfType(context, XmlDocument.class);

        if (document != null) {
          containingFile = (XmlFile) document.getContainingFile();

          final FileType ft = containingFile.getFileType();

          if (ft != StdFileTypes.XML) {
            final String namespace =
                ft == StdFileTypes.XHTML || ft == StdFileTypes.JSPX
                    ? XmlUtil.XHTML_URI
                    : XmlUtil.HTML_URI;
            final XmlNSDescriptor nsDescriptor = document.getDefaultNSDescriptor(namespace, true);

            if (nsDescriptor != null) {
              descriptorFile = nsDescriptor.getDescriptorFile();
            }
          }
        }
      }

      if (descriptorFile != null) {
        final List<Object> results = new ArrayList<Object>();
        final boolean acceptSystemEntities = containingFile.getFileType() == StdFileTypes.XML;

        final PsiElementProcessor processor =
            new PsiElementProcessor() {
              public boolean execute(@NotNull final PsiElement element) {
                if (element instanceof XmlEntityDecl) {
                  final XmlEntityDecl xmlEntityDecl = (XmlEntityDecl) element;
                  if (xmlEntityDecl.isInternalReference() || acceptSystemEntities) {
                    final String name = xmlEntityDecl.getName();
                    final Object _item = getLookupItem(xmlEntityDecl);
                    results.add(_item == null ? name : _item);
                  }
                }
                return true;
              }
            };

        XmlUtil.processXmlElements(descriptorFile, processor, true);
        if (descriptorFile != containingFile && containingFile.getFileType() == StdFileTypes.XML) {
          final XmlProlog element = containingFile.getDocument().getProlog();
          if (element != null) XmlUtil.processXmlElements(element, processor, true);
        }

        return ArrayUtil.toObjectArray(results);
      }

      return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }
  public static DomFileEditor createDomFileEditor(
      final String name,
      @Nullable final Icon icon,
      final DomElement element,
      final Factory<? extends CommittablePanel> committablePanel) {

    final XmlFile file = DomUtil.getFile(element);
    final Factory<BasicDomElementComponent> factory =
        new Factory<BasicDomElementComponent>() {
          @Override
          public BasicDomElementComponent create() {

            CaptionComponent captionComponent = new CaptionComponent(name, icon);
            captionComponent.initErrorPanel(element);
            BasicDomElementComponent component =
                createComponentWithCaption(committablePanel.create(), captionComponent, element);
            Disposer.register(component, captionComponent);
            return component;
          }
        };
    return new DomFileEditor<BasicDomElementComponent>(
        file.getProject(), file.getVirtualFile(), name, factory) {
      @Override
      public JComponent getPreferredFocusedComponent() {
        return null;
      }
    };
  }
  @NotNull
  private static XmlFileHeader calcXmlFileHeader(final XmlFile file) {

    if (file instanceof PsiFileEx
        && ((PsiFileEx) file).isContentsLoaded()
        && file.getNode().isParsed()) {
      return computeHeaderByPsi(file);
    }

    if (!XmlUtil.isStubBuilding() && file.getFileType() == XmlFileType.INSTANCE) {
      VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile instanceof VirtualFileWithId) {
        ObjectStubTree tree =
            StubTreeLoader.getInstance().readFromVFile(file.getProject(), virtualFile);
        if (tree != null) {
          Stub root = tree.getRoot();
          if (root instanceof FileStub) {
            return ((FileStub) root).getHeader();
          }
        }
      }
    }

    if (!file.isValid()) return XmlFileHeader.EMPTY;

    return NanoXmlUtil.parseHeader(file);
  }
Exemplo n.º 6
0
  /**
   * TODO: this method should be removed when find by xpath is ready, and currently works fine only
   * with one attribute
   *
   * @return
   */
  @NotNull
  public static List<XmlTag> findTagInFile(
      @NotNull XmlFile xmlFile, @NotNull String nodeName, Map<String, String> attributes) {
    List<XmlTag> xmlTags = new ArrayList<XmlTag>();
    // XmlTag rootTag = xmlFile.getRootTag();
    // xmlFile.getDocument().getManager();
    String xmlText = xmlFile.getText();

    // final XPathSupport support = XPathSupport.getInstance();

    String regex = "<" + nodeName + "[\\s>]+.*?";
    if (attributes != null) {
      for (Map.Entry<String, String> entry : attributes.entrySet()) {
        String attrName = entry.getKey();
        String attrValue = entry.getValue();
        regex += attrName + "\\s*" + "=\\s*\"" + attrValue + "\"\\s*";
      }
    }
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(xmlText);
    List<Integer> positions = new ArrayList<Integer>();
    while (m.find()) {
      positions.add(m.start());
    }
    for (Integer position : positions) {
      PsiElement psiElement = xmlFile.findElementAt(position);
      XmlTag xmlTag = XmlHelper.getParentOfType(psiElement, XmlTag.class, false);
      if (xmlTag != null) {
        xmlTags.add(xmlTag);
      }
    }

    return xmlTags;
  }
 @Nullable
 public final <T extends DomElement> DomFileElementImpl<T> getFileElement(XmlFile file) {
   if (file == null) return null;
   if (!(file.getFileType() instanceof DomSupportEnabled)) return null;
   final VirtualFile virtualFile = file.getVirtualFile();
   if (virtualFile != null && virtualFile.isDirectory()) return null;
   return this.<T>getOrCreateCachedValueProvider(file).getFileElement();
 }
  private static void fillFromSchema(PsiFile file, ElementNames names) {
    if (!(file instanceof XmlFile)) return;
    final XmlFile f = (XmlFile) file;
    final XmlDocument d = f.getDocument();
    if (d == null) return;
    final XmlTag rootTag = d.getRootTag();
    if (rootTag == null) return;

    //noinspection unchecked
    names.dependencies.add(new NSDeclTracker(rootTag));

    try {
      final Map<String, String> namespaceDeclarations = rootTag.getLocalNamespaceDeclarations();
      final Collection<String> prefixes = namespaceDeclarations.keySet();

      //noinspection unchecked
      final Set<XmlElementDescriptor> history = new THashSet<XmlElementDescriptor>();

      final XmlElementFactory ef = XmlElementFactory.getInstance(file.getProject());
      int noSchemaNamespaces = 0;
      for (String prefix : prefixes) {
        final String namespace = namespaceDeclarations.get(prefix);
        if (isIgnoredNamespace(prefix, namespace)) continue;

        final XmlTag tag =
            ef.createTagFromText("<dummy-tag xmlns='" + namespace + "' />", XMLLanguage.INSTANCE);
        final XmlDocument document = PsiTreeUtil.getParentOfType(tag, XmlDocument.class);
        final XmlNSDescriptor rootDescriptor = tag.getNSDescriptor(tag.getNamespace(), true);
        if (rootDescriptor == null
            || (rootDescriptor instanceof XmlNSDescriptorImpl
                && ((XmlNSDescriptorImpl) rootDescriptor).getTag() == null)
            || !rootDescriptor.getDeclaration().isPhysical()) {
          final QName any = QNameUtil.createAnyLocalName(namespace);
          names.elementNames.add(any);
          names.attributeNames.add(any);
          noSchemaNamespaces++;
          continue;
        }

        //noinspection unchecked
        names.dependencies.add(rootDescriptor.getDescriptorFile());

        final XmlElementDescriptor[] e = rootDescriptor.getRootElementsDescriptors(document);
        for (XmlElementDescriptor descriptor : e) {
          processElementDescriptors(descriptor, tag, names, history);
        }
      }

      names.validateNames = names.elementNames.size() > noSchemaNamespaces;

      //            final QName any = QNameUtil.createAnyLocalName("");
      //            names.elementNames.add(any);
      //            names.attributeNames.add(any);
    } catch (IncorrectOperationException e) {
      Logger.getInstance(XsltContextProvider.class.getName()).error(e);
    }
  }
 public static XmlNSDescriptorImpl getRedefinedElementDescriptor(final XmlTag parentTag) {
   XmlFile file = getRedefinedElementDescriptorFile(parentTag);
   if (file != null) {
     final XmlDocument document = file.getDocument();
     final PsiMetaData metaData = document != null ? document.getMetaData() : null;
     if (metaData instanceof XmlNSDescriptorImpl) return (XmlNSDescriptorImpl) metaData;
   }
   return null;
 }
 @Override
 public boolean deannotate(
     @NotNull final PsiModifierListOwner listOwner, @NotNull final String annotationFQN) {
   try {
     final List<XmlFile> files = findExternalAnnotationsXmlFiles(listOwner);
     if (files == null) {
       return false;
     }
     for (XmlFile file : files) {
       if (!file.isValid()) {
         continue;
       }
       final XmlDocument document = file.getDocument();
       if (document == null) {
         continue;
       }
       final XmlTag rootTag = document.getRootTag();
       if (rootTag == null) {
         continue;
       }
       final String externalName = getExternalName(listOwner, false);
       final String oldExternalName = getNormalizedExternalName(listOwner);
       for (final XmlTag tag : rootTag.getSubTags()) {
         final String className = tag.getAttributeValue("name");
         if (!Comparing.strEqual(className, externalName)
             && !Comparing.strEqual(className, oldExternalName)) {
           continue;
         }
         for (XmlTag annotationTag : tag.getSubTags()) {
           if (!Comparing.strEqual(annotationTag.getAttributeValue("name"), annotationFQN)) {
             continue;
           }
           if (ReadonlyStatusHandler.getInstance(myPsiManager.getProject())
               .ensureFilesWritable(file.getVirtualFile())
               .hasReadonlyFiles()) {
             return false;
           }
           try {
             annotationTag.delete();
             if (tag.getSubTags().length == 0) {
               tag.delete();
             }
           } catch (IncorrectOperationException e) {
             LOG.error(e);
           }
           return true;
         }
         return false;
       }
     }
     return false;
   } finally {
     dropCache();
   }
 }
Exemplo n.º 11
0
 private boolean isGeneratedFromDtd(XmlNSDescriptor defaultNSDescriptorInner) {
   if (defaultNSDescriptorInner == null) {
     return false;
   }
   XmlFile descriptorFile = defaultNSDescriptorInner.getDescriptorFile();
   if (descriptorFile == null) {
     return false;
   }
   @NonNls String otherName = XmlUtil.getContainingFile(this).getName() + ".dtd";
   return descriptorFile.getName().equals(otherName);
 }
Exemplo n.º 12
0
 public final <T extends DomElement> T createMockElement(
     final Class<T> aClass, final Module module, final boolean physical) {
   final XmlFile file =
       (XmlFile)
           PsiFileFactory.getInstance(myProject)
               .createFileFromText("a.xml", StdFileTypes.XML, "", (long) 0, physical);
   file.putUserData(MOCK_ELEMENT_MODULE, module);
   file.putUserData(MOCK, new Object());
   return getFileElement(
           file, aClass, "I_sincerely_hope_that_nobody_will_have_such_a_root_tag_name")
       .getRootElement();
 }
Exemplo n.º 13
0
 @NotNull
 public final <T extends DomElement> DomFileElementImpl<T> getFileElement(
     final XmlFile file, final Class<T> aClass, String rootTagName) {
   //noinspection unchecked
   if (file.getUserData(MOCK_DESCRIPTION) == null) {
     file.putUserData(MOCK_DESCRIPTION, new MockDomFileDescription<T>(aClass, rootTagName, file));
     mySemService.clearCache();
   }
   final DomFileElementImpl<T> fileElement = getFileElement(file);
   assert fileElement != null;
   return fileElement;
 }
  @Nullable
  private <T> T processSchema(String schema, SchemaProcessor<T> processor) {
    VirtualFile file = MavenSchemaProvider.getSchemaFile(schema);
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
    if (!(psiFile instanceof XmlFile)) return null;

    XmlFile xmlFile = (XmlFile) psiFile;
    XmlDocument document = xmlFile.getDocument();
    XmlNSDescriptor desc = (XmlNSDescriptor) document.getMetaData();
    XmlElementDescriptor[] descriptors = desc.getRootElementsDescriptors(document);
    return doProcessSchema(descriptors, null, processor, new THashSet<XmlElementDescriptor>());
  }
  private void annotateExternally(
      @NotNull final VirtualFile file,
      @NotNull final PsiModifierListOwner listOwner,
      @NotNull Project project,
      @NotNull final String packageName,
      final VirtualFile virtualFile,
      @NotNull final String annotationFQName,
      @NotNull final PsiFile fromFile,
      final PsiNameValuePair[] value) {
    final XmlFile[] annotationsXml = new XmlFile[1];
    List<XmlFile> xmlFiles = findExternalAnnotationsXmlFiles(listOwner);
    if (xmlFiles != null) {
      for (XmlFile xmlFile : xmlFiles) {
        final VirtualFile vXmlFile = xmlFile.getVirtualFile();
        assert vXmlFile != null;
        if (VfsUtilCore.isAncestor(file, vXmlFile, false)) {
          annotationsXml[0] = xmlFile;
          if (!CodeInsightUtilBase.preparePsiElementForWrite(xmlFile)) return;
        }
      }
    } else {
      xmlFiles = new ArrayList<XmlFile>();
    }

    final List<PsiFile> annotationFiles = new ArrayList<PsiFile>(xmlFiles);
    new WriteCommandAction(project) {
      @Override
      protected void run(final Result result) throws Throwable {
        if (annotationsXml[0] == null) {
          annotationsXml[0] = createAnnotationsXml(file, packageName);
        }
        if (annotationsXml[0] != null) {
          annotationFiles.add(annotationsXml[0]);
          myExternalAnnotations.put(getFQN(packageName, virtualFile), annotationFiles);
          annotateExternally(listOwner, annotationFQName, annotationsXml[0], fromFile, value);
        }
      }
    }.execute();

    UndoManager.getInstance(project)
        .undoableActionPerformed(
            new BasicUndoableAction() {
              @Override
              public void undo() throws UnexpectedUndoException {
                dropCache();
              }

              @Override
              public void redo() throws UnexpectedUndoException {
                dropCache();
              }
            });
  }
Exemplo n.º 16
0
 public static XmlFile findDescriptorFile(final XmlTag tag, final XmlFile containingFile) {
   final XmlElementDescriptor descriptor = tag.getDescriptor();
   final XmlNSDescriptor nsDescriptor = descriptor != null ? descriptor.getNSDescriptor() : null;
   XmlFile descriptorFile =
       nsDescriptor != null
           ? nsDescriptor.getDescriptorFile()
           : containingFile.getDocument().getProlog().getDoctype() != null ? containingFile : null;
   if (nsDescriptor != null
       && (descriptorFile == null
           || descriptorFile.getName().equals(containingFile.getName() + ".dtd"))) {
     descriptorFile = containingFile;
   }
   return descriptorFile;
 }
 @Nullable
 private static XmlFile findXmlFileInRoot(
     @Nullable List<XmlFile> xmlFiles, @NotNull VirtualFile root) {
   if (xmlFiles != null) {
     for (XmlFile xmlFile : xmlFiles) {
       VirtualFile vf = xmlFile.getVirtualFile();
       if (vf != null) {
         if (VfsUtilCore.isAncestor(root, vf, false)) {
           return xmlFile;
         }
       }
     }
   }
   return null;
 }
Exemplo n.º 18
0
  private static boolean processTagsInNamespaceInner(
      @NotNull final XmlTag rootTag,
      final String[] tagNames,
      final PsiElementProcessor<XmlTag> processor,
      Set<XmlTag> visitedTags) {
    if (visitedTags == null) visitedTags = new HashSet<XmlTag>(3);
    else if (visitedTags.contains(rootTag)) return true;

    visitedTags.add(rootTag);
    XmlTag[] tags = rootTag.getSubTags();

    NextTag:
    for (XmlTag tag : tags) {
      for (String tagName : tagNames) {
        if (equalsToSchemaName(tag, tagName)) {
          final String name = tag.getAttributeValue("name");

          if (name != null) {
            if (!processor.execute(tag)) {
              return false;
            }
          }

          continue NextTag;
        }
      }

      if (equalsToSchemaName(tag, INCLUDE_TAG_NAME)) {
        final String schemaLocation = tag.getAttributeValue("schemaLocation");

        if (schemaLocation != null) {
          final XmlFile xmlFile =
              XmlUtil.findNamespaceByLocation(rootTag.getContainingFile(), schemaLocation);

          if (xmlFile != null) {
            final XmlDocument includedDocument = xmlFile.getDocument();

            if (includedDocument != null) {
              if (!processTagsInNamespaceInner(
                  includedDocument.getRootTag(), tagNames, processor, visitedTags)) return false;
            }
          }
        }
      }
    }

    return true;
  }
Exemplo n.º 19
0
  public void init(PsiElement element) {
    myFile = (XmlFile) element.getContainingFile();

    if (element instanceof XmlTag) {
      myTag = (XmlTag) element;
    } else {
      final XmlDocument document = myFile.getDocument();

      if (document != null) {
        myTag = document.getRootTag();
      }
    }

    if (myTag != null) {
      myTargetNamespace = myTag.getAttributeValue("targetNamespace");
    }

    final THashSet<PsiFile> dependenciesSet = new THashSet<PsiFile>();
    final Set<PsiFile> redefineProcessingSet = myRedefinedDescriptorsInProcessing.get();
    if (redefineProcessingSet != null) {
      dependenciesSet.addAll(redefineProcessingSet);
    }
    collectDependencies(myTag, myFile, dependenciesSet);
    dependencies = ArrayUtil.toObjectArray(dependenciesSet);
  }
 @Override
 @NotNull
 public XmlFileHeader getXmlFileHeader(XmlFile file) {
   return file.isValid()
       ? ourRootTagCache.get(ROOT_TAG_NS_KEY, file, null).getValue()
       : XmlFileHeader.EMPTY;
 }
  private void createNewResourceFile(ResourceType resourceType) {
    AndroidFacet facet = AndroidFacet.getInstance(myModule);
    XmlFile newFile =
        CreateResourceFileAction.createFileResource(
            facet, resourceType, null, null, null, true, null);

    if (newFile != null) {
      String name = newFile.getName();
      int index = name.lastIndexOf('.');
      if (index != -1) {
        name = name.substring(0, index);
      }
      myResultResourceName = "@" + resourceType.getName() + "/" + name;
      close(OK_EXIT_CODE);
    }
  }
Exemplo n.º 22
0
 @Nullable
 private PsiMetaOwner retrieveOwner(final XmlFile file, final String namespace) {
   if (file == null) {
     return namespace.equals(XmlUtil.getTargetSchemaNsFromTag(this)) ? this : null;
   }
   return file.getDocument();
 }
  /**
   * Create a variation (copy) of a given resource file (of a given type).
   *
   * @param xmlFile the XML resource file to fork
   * @param myNewFolder the resource folder to create, or null to ask the user
   * @param open if true, open the file after creating it
   */
  public static void forkResourceFile(
      @NotNull final XmlFile xmlFile, @Nullable String myNewFolder, boolean open) {
    VirtualFile file = xmlFile.getVirtualFile();
    if (file == null) {
      return;
    }
    Module module = AndroidPsiUtils.getModuleSafely(xmlFile);
    if (module == null) {
      return;
    }
    ResourceFolderType folderType = ResourceHelper.getFolderType(xmlFile);
    if (folderType == null || folderType == ResourceFolderType.VALUES) {
      return;
    }
    Configuration configuration = null;
    if (folderType == ResourceFolderType.LAYOUT) {
      AndroidFacet facet = AndroidFacet.getInstance(module);
      if (facet != null) {
        configuration = facet.getConfigurationManager().getConfiguration(file);
      }
    }

    // Suppress: IntelliJ claims folderType can be null here, but it can't (and inserting assert
    // folderType != null is correctly
    // identified as redundant)
    //noinspection ConstantConditions
    forkResourceFile(module, folderType, file, xmlFile, myNewFolder, configuration, open);
  }
Exemplo n.º 24
0
  /**
   * @param xmlFile
   * @param tagName
   * @param tagValue
   * @param path hierarchy path, this will be the parent of the new tag, ex: root/node1/node2
   * @return
   */
  public static XmlTag createTagInFile(
      final XmlFile xmlFile,
      String tagName,
      String tagValue,
      String path,
      Map<String, String> attributes) {
    XmlTag root = xmlFile.getRootTag();

    String[] pathElements = path.split("/");

    if (pathElements.length > 0 && pathElements[0].equals(root.getName())) {
      XmlTag lastExistentParent = root;
      String curPath = pathElements[0];
      pathElements =
          (String[])
              ArrayUtils.remove(
                  pathElements, 0); // ArrayUtils.removeElement(pathElements, pathElements[0]);
      for (String curTagName : pathElements) {
        lastExistentParent = lastExistentParent.findFirstSubTag(curTagName);
        if (lastExistentParent == null) {
          lastExistentParent = createTagInFile(xmlFile, curTagName, "", curPath);
          if (lastExistentParent == null) {
            return null;
          }
        }
        curPath += "/" + curTagName;
      }
      final XmlTag newTag = lastExistentParent.createChildTag(tagName, "", tagValue, false);

      if (attributes != null) {
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
          newTag.setAttribute(entry.getKey(), entry.getValue());
        }
      }

      final XmlTag parent = lastExistentParent;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              new WriteCommandAction.Simple(
                  xmlFile.getProject(), "Create Xml Tag in File", xmlFile) {
                @Override
                protected void run() {

                  //                           newTag = (XmlTag)parent.add(newTag);
                  parent.addAfter(newTag, null);
                }
              }.execute();
            }
          };
      runnable.run();
      // PsiDocumentManager.getInstance(xmlFile.getProject()).commitDocument(document);
      return findSubTag(xmlFile, path + "/" + newTag.getName());

    } else {
      return null;
    }
  }
  public void testCopyFileDescriptionFromOriginalFile() throws Throwable {
    final XmlFile file = (XmlFile) createFile("a.xml", "<b>42</b>");

    getDomManager()
        .registerFileDescription(
            new MockDomFileDescription<>(MyElement.class, "b", file), myDisposable);
    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              file.setName("b.xml");
            });

    assertTrue(getDomManager().isDomFile(file));
    final XmlFile copy = (XmlFile) file.copy();
    assertTrue(getDomManager().isDomFile(copy));
    assertFalse(getDomManager().getFileElement(file).equals(getDomManager().getFileElement(copy)));
  }
  @Nullable
  @Override
  public MyValidationMessageConsumer collectInformation(@NotNull final PsiFile file) {
    final FileType type = file.getFileType();
    if (type != StdFileTypes.XML && type != RncFileType.getInstance()) {
      return null;
    }
    final XmlFile xmlfile = (XmlFile) file;
    final XmlDocument document = xmlfile.getDocument();
    if (document == null) {
      return null;
    }
    if (type == StdFileTypes.XML) {
      final XmlTag rootTag = document.getRootTag();
      if (rootTag == null) {
        return null;
      }
      if (!ApplicationLoader.RNG_NAMESPACE.equals(rootTag.getNamespace())) {
        return null;
      }
    } else {
      if (!ApplicationManager.getApplication().isUnitTestMode()
          && MyErrorFinder.hasError(xmlfile)) {
        return null;
      }
    }
    final Document doc = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);

    final MyValidationMessageConsumer consumer = new MyValidationMessageConsumer();
    ErrorHandler eh =
        new DefaultHandler() {
          @Override
          public void warning(SAXParseException e) {
            handleError(e, file, doc, consumer.warning());
          }

          @Override
          public void error(SAXParseException e) {
            handleError(e, file, doc, consumer.error());
          }
        };

    RngParser.parsePattern(file, eh, true);
    return consumer;
  }
Exemplo n.º 27
0
 /**
  * @param xmlFile
  * @param path absolute Path
  * @return
  */
 public static XmlTag findSubTag(XmlFile xmlFile, String path) {
   XmlTag root = xmlFile.getRootTag();
   if (root != null) {
     String rootName = root.getName();
     String relativePath = path.substring(rootName.length() + 1);
     return findSubTag(root, relativePath);
   }
   return null;
 }
Exemplo n.º 28
0
 @NotNull
 private static XmlFile parseXmlFileInTemplate(
     String templateString, CustomTemplateCallback callback, boolean createPhysicalFile) {
   XmlFile xmlFile =
       (XmlFile)
           PsiFileFactory.getInstance(callback.getProject())
               .createFileFromText(
                   "dummy.xml",
                   StdFileTypes.XML,
                   templateString,
                   LocalTimeCounter.currentTime(),
                   createPhysicalFile);
   VirtualFile vFile = xmlFile.getVirtualFile();
   if (vFile != null) {
     vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
   }
   return xmlFile;
 }
  public Collection<Html5SectionTreeElement> provideNodes(final TreeElement node) {
    if (!(node instanceof HtmlFileTreeElement)) return Collections.emptyList();

    final XmlFile xmlFile = ((HtmlFileTreeElement) node).getElement();
    final XmlDocument document = xmlFile == null ? null : xmlFile.getDocument();
    if (document == null) return Collections.emptyList();

    final List<XmlTag> rootTags = new ArrayList<XmlTag>();
    document.processElements(new FilterElementProcessor(XmlTagFilter.INSTANCE, rootTags), document);

    final Collection<Html5SectionTreeElement> result = new ArrayList<Html5SectionTreeElement>();

    for (XmlTag tag : rootTags) {
      result.addAll(Html5SectionsProcessor.processAndGetRootSections(tag));
    }

    return result;
  }
  private Collection<SchemaTypeInfo> gatherInheritors(XmlTagImpl xml) {
    XmlAttribute name = getNameAttr(xml);
    if (name == null || StringUtil.isEmptyOrSpaces(name.getValue())) return null;
    String localName = name.getValue();
    final boolean hasPrefix = localName.contains(":");
    localName = hasPrefix ? localName.substring(localName.indexOf(':') + 1) : localName;
    final String nsPrefix =
        hasPrefix ? name.getValue().substring(0, name.getValue().indexOf(':')) : null;

    final XmlFile file = XmlUtil.getContainingFile(xml);
    if (file == null) return null;
    final Project project = file.getProject();
    if (project == null) return null;

    final Set<SchemaTypeInfo> result = new HashSet<SchemaTypeInfo>();
    final ArrayDeque<SchemaTypeInfo> queue = new ArrayDeque<SchemaTypeInfo>();

    String nsUri;
    if (!hasPrefix) {
      nsUri = getDefaultNs(file);
    } else {
      nsUri = XmlUtil.findNamespaceByPrefix(nsPrefix, file.getRootTag());
    }
    if (nsUri == null) return null;

    queue.add(new SchemaTypeInfo(localName, true, nsUri));

    final PairConvertor<String, String, List<Set<SchemaTypeInfo>>> worker =
        SchemaTypeInheritanceIndex.getWorker(project, file.getContainingFile().getVirtualFile());
    while (!queue.isEmpty()) {
      final SchemaTypeInfo info = queue.removeFirst();
      final List<Set<SchemaTypeInfo>> childrenOfType =
          worker.convert(info.getNamespaceUri(), info.getTagName());
      for (Set<SchemaTypeInfo> infos : childrenOfType) {
        for (SchemaTypeInfo typeInfo : infos) {
          if (typeInfo.isIsTypeName()) {
            queue.add(typeInfo);
          }
          result.add(typeInfo);
        }
      }
    }
    return result;
  }