Ejemplo n.º 1
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;
    }
Ejemplo n.º 2
0
  public XmlNSDescriptor getNSDescriptor(final String namespace, boolean strict) {
    final XmlTag parentTag = getParentTag();

    if (parentTag == null && namespace.equals(XmlUtil.XHTML_URI)) {
      final XmlNSDescriptor descriptor = getDtdDescriptor(XmlUtil.getContainingFile(this));
      if (descriptor != null) {
        return descriptor;
      }
    }

    Map<String, CachedValue<XmlNSDescriptor>> map = initNSDescriptorsMap();
    final CachedValue<XmlNSDescriptor> descriptor = map.get(namespace);
    if (descriptor != null) {
      final XmlNSDescriptor value = descriptor.getValue();
      if (value != null) {
        return value;
      }
    }

    if (parentTag == null) {
      final XmlDocument parentOfType = PsiTreeUtil.getParentOfType(this, XmlDocument.class);
      if (parentOfType == null) {
        return null;
      }
      return parentOfType.getDefaultNSDescriptor(namespace, strict);
    }

    return parentTag.getNSDescriptor(namespace, strict);
  }
 @NotNull
 public XPathType getExpectedType(XPathExpression expr) {
   final XmlTag tag = PsiTreeUtil.getContextOfType(expr, XmlTag.class, true);
   if (tag != null && XsltSupport.isXsltTag(tag)) {
     final XsltElement element =
         XsltElementFactory.getInstance().wrapElement(tag, XsltElement.class);
     if (element instanceof XsltVariable) {
       return ((XsltVariable) element).getType();
     } else {
       final XmlAttribute attr = PsiTreeUtil.getContextOfType(expr, XmlAttribute.class, true);
       if (attr != null) {
         if (element instanceof XsltWithParam) {
           final XmlAttribute nameAttr = tag.getAttribute("name", null);
           if (nameAttr != null) {
             final XmlAttributeValue valueElement = nameAttr.getValueElement();
             if (valueElement != null) {
               final PsiReference[] references = valueElement.getReferences();
               for (PsiReference reference : references) {
                 final PsiElement psiElement = reference.resolve();
                 if (psiElement instanceof XsltVariable) {
                   return ((XsltVariable) psiElement).getType();
                 }
               }
             }
           }
         } else {
           final String name = attr.getName();
           return getTypeForTag(tag, name);
         }
       }
     }
   }
   return XPathType.UNKNOWN;
 }
  private void checkDuplicateAttribute(XmlTag tag, final XmlAttribute attribute) {
    if (skipValidation(tag)) {
      return;
    }

    final XmlAttribute[] attributes = tag.getAttributes();
    final PsiFile containingFile = tag.getContainingFile();
    final XmlExtension extension =
        containingFile instanceof XmlFile
            ? XmlExtension.getExtension(containingFile)
            : XmlExtension.DEFAULT_EXTENSION;
    for (XmlAttribute tagAttribute : attributes) {
      ProgressManager.checkCanceled();
      if (attribute != tagAttribute
          && Comparing.strEqual(attribute.getName(), tagAttribute.getName())) {
        final String localName = attribute.getLocalName();

        if (extension.canBeDuplicated(tagAttribute))
          continue; // multiple import attributes are allowed in jsp directive

        HighlightInfo highlightInfo =
            HighlightInfo.createHighlightInfo(
                getTagProblemInfoType(tag),
                XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(
                    SourceTreeToPsiMap.psiElementToTree(attribute)),
                XmlErrorMessages.message("duplicate.attribute", localName));
        addToResults(highlightInfo);

        IntentionAction intentionAction = new RemoveAttributeIntentionFix(localName, attribute);

        QuickFixAction.registerQuickFixAction(highlightInfo, intentionAction);
      }
    }
  }
  @Override
  public void visitXmlAttributeValue(XmlAttributeValue value) {
    final PsiElement parent = value.getParent();
    if (!(parent instanceof XmlAttribute)) {
      checkReferences(value);
      return;
    }

    XmlAttribute attribute = (XmlAttribute) parent;

    XmlTag tag = attribute.getParent();

    XmlElementDescriptor elementDescriptor = tag.getDescriptor();
    XmlAttributeDescriptor attributeDescriptor =
        elementDescriptor != null ? elementDescriptor.getAttributeDescriptor(attribute) : null;

    if (attributeDescriptor != null && !skipValidation(value)) {
      String error = attributeDescriptor.validateValue(value, attribute.getValue());

      if (error != null) {
        addToResults(HighlightInfo.createHighlightInfo(getTagProblemInfoType(tag), value, error));
        return;
      }
    }

    checkReferences(value);
  }
  @NotNull
  public XmlFile getContainingFile(@NotNull DomElement domElement) {
    if (domElement instanceof DomFileElement) {
      return ((DomFileElement) domElement).getFile();
    }
    DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(domElement);
    assert handler != null : domElement;
    while (handler != null
        && !(handler instanceof DomRootInvocationHandler)
        && handler.getXmlTag() == null) {
      handler = handler.getParentHandler();
    }
    if (handler instanceof DomRootInvocationHandler) {
      return ((DomRootInvocationHandler) handler).getParent().getFile();
    }
    assert handler != null;
    XmlTag tag = handler.getXmlTag();
    assert tag != null;
    while (true) {
      final PsiElement parentTag = PhysicalDomParentStrategy.getParentTagCandidate(tag);
      if (!(parentTag instanceof XmlTag)) {
        return (XmlFile) tag.getContainingFile();
      }

      tag = (XmlTag) parentTag;
    }
  }
  public static String findUrl(PsiFile file, int offset, String uri) {
    final PsiElement currentElement = file.findElementAt(offset);
    final XmlAttribute attribute = PsiTreeUtil.getParentOfType(currentElement, XmlAttribute.class);

    if (attribute != null) {
      final XmlTag tag = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class);

      if (tag != null) {
        final String prefix = tag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI);
        if (prefix != null) {
          final String attrValue =
              tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI);
          if (attrValue != null) {
            final StringTokenizer tokenizer = new StringTokenizer(attrValue);

            while (tokenizer.hasMoreElements()) {
              if (uri.equals(tokenizer.nextToken())) {
                if (!tokenizer.hasMoreElements()) return uri;
                final String url = tokenizer.nextToken();

                return url.startsWith(HTTP_PROTOCOL) ? url : uri;
              }

              if (!tokenizer.hasMoreElements()) return uri;
              tokenizer.nextToken(); // skip file location
            }
          }
        }
      }
    }
    return uri;
  }
Ejemplo n.º 8
0
  public void setText(String value) {
    try {
      XmlText text = null;
      if (StringUtil.isNotEmpty(value)) {
        final XmlText[] texts = getTextElements();
        if (texts.length == 0) {
          text =
              (XmlText)
                  myTag.add(
                      XmlElementFactory.getInstance(myTag.getProject()).createDisplayText("x"));
        } else {
          text = texts[0];
        }
        text.setValue(value);
      }

      if (myElements.length > 0) {
        for (final XmlTagChild child : myElements) {
          if (child != text) {
            child.delete();
          }
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
0
 @Nullable
 @NonNls
 public String getSubTagText(@NonNls String qname) {
   final XmlTag tag = findFirstSubTag(qname);
   if (tag == null) return null;
   return tag.getValue().getText();
 }
Ejemplo n.º 11
0
  private void reportOneTagProblem(
      final XmlTag tag,
      final String name,
      final String localizedMessage,
      final IntentionAction basicIntention,
      final HighlightDisplayKey key,
      final XmlEntitiesInspection inspection,
      final int type) {
    boolean htmlTag = false;

    if (tag instanceof HtmlTag) {
      htmlTag = true;
      if (isAdditionallyDeclared(inspection.getAdditionalEntries(type), name)) return;
    }

    final InspectionProfile profile =
        InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
    final IntentionAction intentionAction = inspection.getIntentionAction(name, type);
    if (htmlTag && profile.isToolEnabled(key, tag)) {
      addElementsForTagWithManyQuickFixes(
          tag,
          localizedMessage,
          isInjectedHtmlTagForWhichNoProblemsReporting((HtmlTag) tag)
              ? HighlightInfoType.INFORMATION
              : SeverityRegistrar.getInstance(tag.getProject())
                  .getHighlightInfoTypeBySeverity(profile.getErrorLevel(key, tag).getSeverity()),
          intentionAction,
          basicIntention);
    } else if (!htmlTag) {
      addElementsForTag(tag, localizedMessage, HighlightInfoType.ERROR, basicIntention);
    }
  }
 private static XmlTag createTag(
     @NotNull XmlTag contextTag, @NotNull XmlElementDescriptor descriptor) {
   String namespace = getNamespace(descriptor);
   XmlTag tag = contextTag.createChildTag(descriptor.getName(), namespace, null, false);
   PsiElement lastChild = tag.getLastChild();
   assert lastChild != null;
   lastChild.delete(); // remove XML_EMPTY_ELEMENT_END
   return tag;
 }
  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);
    }
  }
Ejemplo n.º 14
0
  public static Pair<TextRange, PsiElement> getProblemRange(final XmlTag tag) {
    final PsiElement startToken = XmlTagUtil.getStartTagNameElement(tag);
    if (startToken == null) {
      return Pair.create(tag.getTextRange(), (PsiElement) tag);
    }

    return Pair.create(
        startToken.getTextRange().shiftRight(-tag.getTextRange().getStartOffset()),
        (PsiElement) tag);
  }
  @Override
  protected boolean isValidForFile(
      @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    if (!(file instanceof XmlFile)) return false;

    XmlTag contextTag = getContextTag(editor, file);
    return contextTag != null
        && isInsideTagBody(contextTag, editor)
        && contextTag.getDescriptor() != null;
  }
  public static void handleError(
      SAXParseException ex, PsiFile file, Document document, ValidationMessageConsumer consumer) {
    final String systemId = ex.getSystemId();
    if (LOG.isDebugEnabled()) {
      LOG.debug("RNG Schema error: " + ex.getMessage() + " [" + systemId + "]");
    }

    if (systemId != null) {
      final VirtualFile virtualFile = findVirtualFile(systemId);
      if (!Comparing.equal(virtualFile, file.getVirtualFile())) {
        return;
      }
    }

    final PsiElement at;
    final int line = ex.getLineNumber();
    if (line > 0) {
      final int column = ex.getColumnNumber();
      final int startOffset = document.getLineStartOffset(line - 1);

      if (column > 0) {
        if (file.getFileType() == RncFileType.getInstance()) {
          final PsiElement e = file.findElementAt(startOffset + column);
          if (e == null) {
            at = e;
          } else {
            at = file.findElementAt(startOffset + column - 1);
          }
        } else {
          at = file.findElementAt(startOffset + column - 2);
        }
      } else {
        final PsiElement e = file.findElementAt(startOffset);
        at = e != null ? PsiTreeUtil.nextLeaf(e) : null;
      }
    } else {
      final XmlDocument d = ((XmlFile) file).getDocument();
      assert d != null;
      final XmlTag rootTag = d.getRootTag();
      assert rootTag != null;
      at = rootTag.getFirstChild();
    }

    final PsiElement host;
    if (file instanceof RncFile) {
      host = at;
    } else {
      host = PsiTreeUtil.getParentOfType(at, XmlAttribute.class, XmlTag.class);
    }
    if (at != null && host != null) {
      consumer.onMessage(host, ex.getMessage());
    } else {
      consumer.onMessage(file, ex.getMessage());
    }
  }
Ejemplo n.º 17
0
 public static void acceptAvailableChildren(
     final DomElement element, final DomElementVisitor visitor) {
   final XmlTag tag = element.getXmlTag();
   if (tag != null) {
     for (XmlTag xmlTag : tag.getSubTags()) {
       final DomElement childElement = element.getManager().getDomElement(xmlTag);
       if (childElement != null) {
         childElement.accept(visitor);
       }
     }
   }
 }
  @NotNull
  private static XmlFileHeader calcXmlFileHeader(final PsiFile file) {

    // if (file.getFileType() == XmlFileType.INSTANCE) {
    //  VirtualFile virtualFile = file.getVirtualFile();
    //  if (virtualFile instanceof VirtualFileWithId) {
    //    ObjectStubTree tree = StubTreeLoader.getInstance().readFromVFile(file.getProject(),
    // virtualFile);
    //    if (tree != null) {
    //      return ((FileStub)tree.getRoot()).getHeader();
    //    }
    //  }
    // }
    if (file instanceof XmlFile && file.getNode().isParsed()) {
      final XmlDocument document = ((XmlFile) file).getDocument();
      if (document != null) {
        String publicId = null;
        String systemId = null;
        final XmlProlog prolog = document.getProlog();
        if (prolog != null) {
          final XmlDoctype doctype = prolog.getDoctype();
          if (doctype != null) {
            publicId = doctype.getPublicId();
            systemId = doctype.getSystemId();
            if (systemId == null) {
              systemId = doctype.getDtdUri();
            }
          }
        }

        final XmlTag tag = document.getRootTag();
        if (tag != null) {
          String localName = tag.getLocalName();
          if (StringUtil.isNotEmpty(localName)) {
            if (tag.getPrevSibling() instanceof PsiErrorElement) {
              return XmlFileHeader.EMPTY;
            }

            String psiNs = tag.getNamespace();
            return new XmlFileHeader(
                localName,
                psiNs == XmlUtil.EMPTY_URI || Comparing.equal(psiNs, systemId) ? null : psiNs,
                publicId,
                systemId);
          }
        }
      }
      return XmlFileHeader.EMPTY;
    }

    if (!file.isValid()) return XmlFileHeader.EMPTY;
    return NanoXmlUtil.parseHeader(file);
  }
Ejemplo n.º 19
0
 @NotNull
 public TextRange getTextRange() {
   if (myElements.length == 0) {
     final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild((ASTNode) myTag);
     if (child != null)
       return new TextRange(child.getStartOffset() + 1, child.getStartOffset() + 1);
     return new TextRange(
         myTag.getTextRange().getEndOffset(), myTag.getTextRange().getEndOffset());
   }
   return new TextRange(
       myElements[0].getTextRange().getStartOffset(),
       myElements[myElements.length - 1].getTextRange().getEndOffset());
 }
Ejemplo n.º 20
0
 @NotNull
 public XmlTag[] findSubTags(final String name, final String namespace) {
   final XmlTag[] subTags = getSubTags();
   final List<XmlTag> result = new ArrayList<XmlTag>();
   for (final XmlTag subTag : subTags) {
     if (namespace == null) {
       if (name.equals(subTag.getName())) result.add(subTag);
     } else if (name.equals(subTag.getLocalName()) && namespace.equals(subTag.getNamespace())) {
       result.add(subTag);
     }
   }
   return ContainerUtil.toArray(result, new XmlTag[result.size()]);
 }
 @Override
 public TextRange getRangeInElement() {
   final TextRange rangeInElement = super.getRangeInElement();
   final XmlTag tagElement = getTagElement();
   if (tagElement != null) {
     final String tagElementName = tagElement.getName();
     final int dotIdx = tagElementName.indexOf(".");
     if (dotIdx > -1 && dotIdx + 2 < rangeInElement.getEndOffset()) {
       return new TextRange(
           rangeInElement.getStartOffset() + dotIdx + 1, rangeInElement.getEndOffset());
     }
   }
   return rangeInElement;
 }
  private static void processElementDescriptors(
      XmlElementDescriptor descriptor,
      XmlTag tag,
      ElementNames names,
      Set<XmlElementDescriptor> history) {
    if (!history.add(descriptor)) {
      return;
    }
    final String namespace =
        descriptor instanceof XmlElementDescriptorImpl
            ? ((XmlElementDescriptorImpl) descriptor).getNamespace()
            : tag.getNamespace();
    names.elementNames.add(new QName(namespace, descriptor.getName()));

    final XmlAttributeDescriptor[] attributesDescriptors =
        descriptor.getAttributesDescriptors(null);
    for (XmlAttributeDescriptor attributesDescriptor : attributesDescriptors) {
      final String localPart = attributesDescriptor.getName();
      if (!"xmlns".equals(localPart)) names.attributeNames.add(new QName(localPart));
    }

    final XmlElementDescriptor[] descriptors = descriptor.getElementsDescriptors(tag);
    for (XmlElementDescriptor elem : descriptors) {
      processElementDescriptors(elem, tag, names, history);
    }
  }
Ejemplo n.º 23
0
 public static boolean shouldBeValidated(@NotNull XmlTag tag) {
   PsiElement parent = tag.getParent();
   if (parent instanceof XmlTag) {
     return !skipValidation(parent) && !XmlUtil.tagFromTemplateFramework(tag);
   }
   return true;
 }
Ejemplo n.º 24
0
 private static HighlightInfoType getTagProblemInfoType(XmlTag tag) {
   if (tag instanceof HtmlTag && XmlUtil.HTML_URI.equals(tag.getNamespace())) {
     if (isInjectedHtmlTagForWhichNoProblemsReporting((HtmlTag) tag))
       return HighlightInfoType.INFORMATION;
     return HighlightInfoType.WARNING;
   }
   return HighlightInfoType.WRONG_REF;
 }
  @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;
  }
Ejemplo n.º 26
0
  private void checkRequiredAttributes(
      XmlTag tag, String name, XmlElementDescriptor elementDescriptor) {
    XmlAttributeDescriptor[] attributeDescriptors = elementDescriptor.getAttributesDescriptors(tag);
    Set<String> requiredAttributes = null;

    for (XmlAttributeDescriptor attribute : attributeDescriptors) {
      if (attribute != null && attribute.isRequired()) {
        if (requiredAttributes == null) {
          requiredAttributes = new HashSet<String>();
        }
        requiredAttributes.add(attribute.getName(tag));
      }
    }

    if (requiredAttributes != null) {
      for (final String attrName : requiredAttributes) {
        if (tag.getAttribute(attrName, "") == null
            && !XmlExtension.getExtension(tag.getContainingFile())
                .isRequiredAttributeImplicitlyPresent(tag, attrName)) {

          final InsertRequiredAttributeFix insertRequiredAttributeIntention =
              new InsertRequiredAttributeFix(tag, attrName, null);
          final String localizedMessage =
              XmlErrorMessages.message("element.doesnt.have.required.attribute", name, attrName);
          final InspectionProfile profile =
              InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
          final LocalInspectionToolWrapper toolWrapper =
              (LocalInspectionToolWrapper)
                  profile.getInspectionTool(RequiredAttributesInspection.SHORT_NAME, tag);
          if (toolWrapper != null) {
            RequiredAttributesInspection inspection =
                (RequiredAttributesInspection) toolWrapper.getTool();
            reportOneTagProblem(
                tag,
                attrName,
                localizedMessage,
                insertRequiredAttributeIntention,
                HighlightDisplayKey.find(RequiredAttributesInspection.SHORT_NAME),
                inspection,
                XmlEntitiesInspection.NOT_REQUIRED_ATTRIBUTE);
          }
        }
      }
    }
  }
Ejemplo n.º 27
0
  @Nullable
  protected XmlElementDescriptor computeElementDescriptor() {
    for (XmlElementDescriptorProvider provider :
        Extensions.getExtensions(XmlElementDescriptorProvider.EP_NAME)) {
      XmlElementDescriptor elementDescriptor = provider.getDescriptor(this);
      if (elementDescriptor != null) {
        return elementDescriptor;
      }
    }

    final String namespace = getNamespace();
    if (XmlUtil.EMPTY_URI.equals(namespace)) { // nonqualified items
      final XmlTag parent = getParentTag();
      if (parent != null) {
        final XmlElementDescriptor descriptor = parent.getDescriptor();
        if (descriptor != null) {
          XmlElementDescriptor fromParent = descriptor.getElementDescriptor(this, parent);
          if (fromParent != null && !(fromParent instanceof AnyXmlElementDescriptor)) {
            return fromParent;
          }
        }
      }
    }

    XmlElementDescriptor elementDescriptor = null;
    final XmlNSDescriptor nsDescriptor = getNSDescriptor(namespace, false);

    LOG.debug(
        "Descriptor for namespace "
            + namespace
            + " is "
            + (nsDescriptor != null ? nsDescriptor.getClass().getCanonicalName() : "NULL"));

    if (nsDescriptor != null) {
      if (!DumbService.getInstance(getProject()).isDumb()
          || DumbService.isDumbAware(nsDescriptor)) {
        elementDescriptor = nsDescriptor.getElementDescriptor(this);
      }
    }
    if (elementDescriptor == null) {
      return XmlUtil.findXmlDescriptorByType(this);
    }

    return elementDescriptor;
  }
Ejemplo n.º 28
0
  @Nullable
  public static <T extends DomElement> T findDomElement(
      @Nullable final PsiElement element, final Class<T> beanClass, boolean strict) {
    if (element == null) return null;

    XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class, strict);
    DomElement domElement;

    while (tag != null) {
      domElement = DomManager.getDomManager(tag.getProject()).getDomElement(tag);

      if (domElement != null) {
        return domElement.getParentOfType(beanClass, false);
      }
      tag = tag.getParentTag();
    }
    return null;
  }
 @Override
 public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
   if (element instanceof PsiClass) {
     final String qualifiedName = ((PsiClass) element).getQualifiedName();
     if (qualifiedName != null) {
       final String shortName = StringUtil.getShortName(qualifiedName);
       final XmlTag tagElement = getTagElement();
       if (tagElement != null) {
         final String oldTagName = tagElement.getName();
         if (oldTagName.contains(".")) {
           return tagElement.setName(qualifiedName);
         }
         return tagElement.setName(shortName);
       }
       return getElement();
     }
   }
   return super.bindToElement(element);
 }
 public static void generateTag(@NotNull XmlTag newTag, Editor editor) {
   generateRaw(newTag);
   final XmlTag restored = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(newTag);
   if (restored == null) {
     LOG.error("Could not restore tag: " + newTag.getText());
   }
   TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(restored);
   replaceElements(restored, builder);
   builder.run(editor, false);
 }