public ReplaceEdit createReplaceFolderEdit(IFolder originalFolder, String newName) {
    IDOMNode domNode = getTextNode();
    String originalName = originalFolder.getName();
    int nameIndex = this.fileName.indexOf(originalName);

    int offset = domNode.getStartOffset();
    return new ReplaceEdit(offset + nameIndex, originalName.length(), newName);
  }
 public boolean isShownInEditor(Match match, IEditorPart editor) {
   Object element = match.getElement();
   if (element instanceof IDOMNode) {
     // DOMNode matched
     IDOMNode node = (IDOMNode) element;
     IStructuredModel editorModel = (IStructuredModel) editor.getAdapter(IStructuredModel.class);
     if (editorModel != null) {
       // Returns true if found node belong to the current XML editor
       // which
       // has launched the search and false otherwise.
       return editorModel.equals(node.getModel());
     }
   }
   return false;
 }
  @Override
  protected ContentAssistRequest computeCompletionProposals(
      String matchString,
      ITextRegion completionRegion,
      IDOMNode treeNode,
      IDOMNode xmlnode,
      CompletionProposalInvocationContext context) {
    ContentAssistRequest contentAssistRequest =
        super.computeCompletionProposals(matchString, completionRegion, treeNode, xmlnode, context);
    if (contentAssistRequest != null) return contentAssistRequest;

    String regionType = completionRegion.getType();
    if (DOMRegionContext.XML_CDATA_TEXT.equals(regionType)) {
      Node parentNode = xmlnode.getParentNode();
      Node statementNode = MybatipseXmlUtil.findEnclosingStatementNode(parentNode);
      if (statementNode == null) return null;

      int offset = context.getInvocationOffset();
      ITextViewer viewer = context.getViewer();
      contentAssistRequest =
          new ContentAssistRequest(
              xmlnode,
              parentNode,
              ContentAssistUtils.getStructuredDocumentRegion(viewer, offset),
              completionRegion,
              offset,
              0,
              matchString);
      proposeStatementText(contentAssistRequest, statementNode);
    }
    return contentAssistRequest;
  }
 private void proposeStatementId(
     ContentAssistRequest contentAssistRequest,
     IJavaProject project,
     String matchString,
     int start,
     int length,
     IDOMNode node)
     throws JavaModelException, XPathExpressionException {
   final List<ICompletionProposal> results = new ArrayList<ICompletionProposal>();
   final List<MapperMethodInfo> methodInfos = new ArrayList<MapperMethodInfo>();
   String qualifiedName = MybatipseXmlUtil.getNamespace(node.getOwnerDocument());
   JavaMapperUtil.findMapperMethod(
       methodInfos, project, qualifiedName, matchString, false, new RejectStatementAnnotation());
   for (MapperMethodInfo methodInfo : methodInfos) {
     String methodName = methodInfo.getMethodName();
     results.add(
         new CompletionProposal(
             methodName,
             start,
             length,
             methodName.length(),
             Activator.getIcon(),
             methodName,
             null,
             null));
   }
   addProposals(contentAssistRequest, results);
 }
  /**
   * Returns the CMDocument that corresponds to the DOM Node. or null if no CMDocument is
   * appropriate for the DOM Node.
   */
  public CMDocument getCorrespondingCMDocument(Node node) {
    CMDocument jcmdoc = null;
    if (node instanceof IDOMNode) {
      IDOMModel model = ((IDOMNode) node).getModel();
      String modelPath = model.getBaseLocation();
      if (modelPath != null && !IModelManager.UNMANAGED_MODEL.equals(modelPath)) {
        float version =
            DeploymentDescriptorPropertyCache.getInstance().getJSPVersion(new Path(modelPath));
        jcmdoc = JSPCMDocumentFactory.getCMDocument(version);
      }
    }
    if (jcmdoc == null) {
      jcmdoc = JSPCMDocumentFactory.getCMDocument();
    }

    CMDocument result = null;
    try {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        String elementName = node.getNodeName();

        // test to see if this node belongs to JSP's CMDocument (case
        // sensitive)
        CMElementDeclaration dec =
            (CMElementDeclaration) jcmdoc.getElements().getNamedItem(elementName);
        if (dec != null) {
          result = jcmdoc;
        }
      }

      String prefix = node.getPrefix();

      if (result == null && prefix != null && prefix.length() > 0 && node instanceof IDOMNode) {
        // check position dependent
        IDOMNode xmlNode = (IDOMNode) node;
        TLDCMDocumentManager tldmgr =
            TaglibController.getTLDCMDocumentManager(xmlNode.getStructuredDocument());
        if (tldmgr != null) {
          List documents = tldmgr.getCMDocumentTrackers(node.getPrefix(), xmlNode.getStartOffset());
          // there shouldn't be more than one cmdocument returned
          if (documents != null && documents.size() > 0) result = (CMDocument) documents.get(0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  public void testCompletion() throws Exception {
    // Get the location of the place where we want to start the completion
    String docString = sourceViewer.getDocument().get();
    IMavenProjectFacade facade =
        MavenPlugin.getDefault().getMavenProjectRegistry().getProject(projects[1]);
    assertNotNull(facade);
    assertNotNull(facade.getMavenProject());
    sourceViewer.setMavenProject(facade.getMavenProject());

    int offset = docString.indexOf("${") + "${".length();

    IDOMNode node = (IDOMNode) ContentAssistUtils.getNodeAt(sourceViewer, offset);
    assertEquals("anotherProperty", node.getLocalName());

    ICompletionProposal[] proposals = getProposals(offset);
    assertTrue("Length less than 1", proposals.length > 1);
    assertEquals(InsertExpressionProposal.class, proposals[0].getClass());
    assertEquals("${aProperty}", ((InsertExpressionProposal) proposals[0]).getDisplayString());
  }
 /*
  * (non-Javadoc)
  *
  * @see org.eclipse.jst.pagedesigner.properties.attrgroup.IElementContextable#setElementContext(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode,
  *      org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement)
  */
 public void setElementContext(IDOMNode ancester, IDOMElement element) {
   if (ancester == null) {
     setProject(null);
     setReferredFile(null);
   } else {
     IDOMModel model = ancester.getModel();
     IFile file = StructuredModelUtil.getFileFor(model);
     IProject prj = (file == null ? null : file.getProject());
     setProject(prj);
     setReferredFile(file);
   }
 }
  public void testModel() {
    IDOMModel model = createXMLModel();
    try {
      Document document = model.getDocument();

      Element a = document.createElement("a");
      document.appendChild(a);
      IDOMNode text = (IDOMNode) document.createTextNode("text");
      a.appendChild(text);

      try {
        text.setSource("hello <");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &lt;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &unk;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &#65;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello & good-bye");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      saveAndCompareTestResults();
    } finally {
      model.releaseFromEdit();
    }
  }
 public BeanReferenceXmlValidationContextHelper(
     BeansEditorValidator validator,
     AttrImpl attribute,
     IDOMNode node,
     IFile file,
     IBeansConfig config,
     IResourceModelElement contextElement,
     IReporter reporter,
     boolean reportError) {
   super(validator, attribute, node, file, config, contextElement, reporter, reportError);
   this.file = (IFile) config.getElementResource();
   this.document = node.getOwnerDocument();
 }
  protected void addAttributeValueProposals(
      ContentAssistRequest contentAssistRequest, CompletionProposalInvocationContext context) {
    IDOMNode node = (IDOMNode) contentAssistRequest.getNode();
    String tagName = node.getNodeName();
    IStructuredDocumentRegion open = node.getFirstStructuredDocumentRegion();
    ITextRegionList openRegions = open.getRegions();
    int i = openRegions.indexOf(contentAssistRequest.getRegion());
    if (i < 0) return;
    ITextRegion nameRegion = null;
    while (i >= 0) {
      nameRegion = openRegions.get(i--);
      if (nameRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) break;
    }

    // get the attribute in question (first attr name to the left of the cursor)
    String attributeName = null;
    if (nameRegion != null) attributeName = open.getText(nameRegion);

    ProposalType proposalType = resolveProposalType(tagName, attributeName);
    if (ProposalType.None.equals(proposalType)) {
      return;
    }

    String currentValue = null;
    if (contentAssistRequest.getRegion().getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)
      currentValue = contentAssistRequest.getText();
    else currentValue = "";

    String matchString = null;
    int matchStrLen = contentAssistRequest.getMatchString().length();
    int start = contentAssistRequest.getReplacementBeginPosition();
    int length = contentAssistRequest.getReplacementLength();
    if (currentValue.length() > StringUtils.strip(currentValue).length()
        && (currentValue.startsWith("\"") || currentValue.startsWith("'"))
        && matchStrLen > 0) {
      // Value is surrounded by (double) quotes.
      matchString = currentValue.substring(1, matchStrLen);
      start++;
      length = currentValue.length() - 2;
      currentValue = currentValue.substring(1, length + 1);
    } else {
      matchString = currentValue.substring(0, matchStrLen);
    }

    IJavaProject project = getJavaProject(contentAssistRequest);
    try {
      switch (proposalType) {
        case Package:
          proposePackage(contentAssistRequest, project, matchString, start, length);
          break;
        case TypeAlias:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeJavaType(project, start, length, false, matchString));
          break;
        case ResultType:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeJavaType(project, start, length, true, matchString));
          break;
        case ResultProperty:
          proposeProperty(contentAssistRequest, matchString, start, length, node);
          break;
        case TypeHandlerType:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeTypeHandler(project, start, length, matchString));
          break;
        case CacheType:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeCacheType(project, start, length, matchString));
          break;
        case SettingName:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeSettingName(start, length, matchString));
          break;
        case ObjectFactory:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeObjectFactory(project, start, length, matchString));
          break;
        case ObjectWrapperFactory:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeObjectWrapperFactory(
                  project, start, length, matchString));
          break;
        case StatementId:
          proposeStatementId(contentAssistRequest, project, matchString, start, length, node);
          break;
        case MapperNamespace:
          proposeMapperNamespace(contentAssistRequest, project, start, length);
          break;
        case ResultMap:
          String ownId =
              "resultMap".equals(tagName) && "extends".equals(attributeName)
                  ? XpathUtil.xpathString(node, "@id")
                  : null;
          addProposals(
              contentAssistRequest,
              proposeResultMapReference(
                  project,
                  node.getOwnerDocument(),
                  start,
                  currentValue,
                  matchString.length(),
                  ownId));
          break;
        case Include:
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeReference(
                  project, node.getOwnerDocument(), matchString, start, length, "sql", null));
          break;
        case SelectId:
          // TODO: include mapper methods with @Select.
          addProposals(
              contentAssistRequest,
              ProposalComputorHelper.proposeReference(
                  project, node.getOwnerDocument(), matchString, start, length, "select", null));
          break;
        case KeyProperty:
          String nodeName = node.getNodeName();
          Node statementNode =
              "update".equals(nodeName) || "insert".equals(nodeName)
                  ? node
                  : MybatipseXmlUtil.findEnclosingStatementNode(node.getParentNode());
          addProposals(
              contentAssistRequest,
              proposeParameter(project, start, length, statementNode, false, matchString));
          break;
        case ParamProperty:
          addProposals(
              contentAssistRequest,
              proposeParameter(
                  project,
                  start,
                  length,
                  MybatipseXmlUtil.findEnclosingStatementNode(node),
                  true,
                  matchString));
          break;
        case ParamPropertyPartial:
          AttrTextParser parser = new AttrTextParser(currentValue, matchString.length());
          addProposals(
              contentAssistRequest,
              proposeParameter(
                  project,
                  start + parser.getMatchStringStart(),
                  parser.getReplacementLength(),
                  MybatipseXmlUtil.findEnclosingStatementNode(node.getParentNode()),
                  true,
                  parser.getMatchString()));
          break;
        default:
          break;
      }
    } catch (Exception e) {
      Activator.log(Status.ERROR, e.getMessage(), e);
    }
  }
 public int getStartTagStartOffset() {
   if (node.getStartStructuredDocumentRegion() != null) {
     return node.getStartStructuredDocumentRegion().getStartOffset();
   }
   return -1;
 }
 public int getEndTagEndOffset() {
   if (node.getEndStructuredDocumentRegion() != null) {
     return node.getEndStructuredDocumentRegion().getEndOffset();
   }
   return -1;
 }
 protected int getOffset(ITextRegion valueRegion, IDOMNode beanNode) {
   return valueRegion.getStart() + beanNode.getStartOffset() + 1;
 }