private void formatAndAssertEquals(
      String beforePath, String afterPath, XMLFormattingPreferences prefs)
      throws UnsupportedEncodingException, IOException, CoreException {
    IStructuredModel beforeModel = null, afterModel = null;
    try {
      beforeModel = getModelForEdit(beforePath);
      assertNotNull("could not retrieve structured model for : " + beforePath, beforeModel);

      afterModel = getModelForEdit(afterPath);
      assertNotNull("could not retrieve structured model for : " + afterPath, afterModel);

      IStructuredDocument document = beforeModel.getStructuredDocument();

      String normalizedContents = document.get();
      normalizedContents = StringUtils.replace(normalizedContents, "\r\n", "\n");
      normalizedContents = StringUtils.replace(normalizedContents, "\r", "\n");
      document.set(normalizedContents);

      if (prefs == null) prefs = new XMLFormattingPreferences();
      TextEdit edit = partitionFormatter.format(beforeModel, 0, document.getLength(), prefs);
      try {
        edit.apply(document);
      } catch (MalformedTreeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      ByteArrayOutputStream formattedBytes = new ByteArrayOutputStream();
      beforeModel.save(formattedBytes); // "beforeModel" should now be
      // after the formatter

      ByteArrayOutputStream afterBytes = new ByteArrayOutputStream();
      afterModel.save(afterBytes);

      String expectedContents = new String(afterBytes.toByteArray(), UTF_8);
      String actualContents = new String(formattedBytes.toByteArray(), UTF_8);

      /* Make some adjustments to ignore cross platform line delimiter issues */
      expectedContents = StringUtils.replace(expectedContents, "\r\n", "\n");
      expectedContents = StringUtils.replace(expectedContents, "\r", "\n");
      actualContents = StringUtils.replace(actualContents, "\r\n", "\n");
      actualContents = StringUtils.replace(actualContents, "\r", "\n");

      assertTrue(
          "Formatted document differs from the expected.\nExpected Contents:\n"
              + expectedContents
              + "\nActual Contents:\n"
              + actualContents,
          fStringCompareUtil.equalsIgnoreLineSeperator(expectedContents, actualContents));
    } finally {
      if (beforeModel != null) beforeModel.releaseFromEdit();
      if (afterModel != null) afterModel.releaseFromEdit();
    }
  }
 public void testGetStructuredDocument() throws IOException, CoreException {
   IStructuredModel model = getTestModel();
   try {
     IStructuredDocument doc = model.getStructuredDocument();
     assertNotNull("document is null", doc);
   } finally {
     if (model != null) {
       model.releaseFromEdit();
     }
   }
 }
  @Test
  public void test(String fileName) {
    PdttFileExt testFile = filesMap.get(fileName);
    IFile file = project.findFile(testFile.getTestFiles().get(0).getName());

    IStructuredModel model = null;
    try {
      model = createUnManagedStructuredModelFor(file);
    } catch (IOException e) {
      fail(e.getMessage());
    } catch (CoreException e) {
      fail(e.getMessage());
    }
    assertNotNull(model);

    IStructuredDocument structuredDocument = model.getStructuredDocument();
    assertNotNull(structuredDocument);

    int start = Integer.valueOf(testFile.getConfig().get("start"));

    int length = Integer.valueOf(testFile.getConfig().get("length"));

    String visibility = testFile.getConfig().get("visibility");

    ExtractFunctionRefactoring processor =
        new ExtractFunctionRefactoring(
            DLTKCore.createSourceModuleFrom(file), structuredDocument, start, length);

    if ("default".equals(visibility)) {
      processor.setVisibility(Modifiers.AccDefault);
    }

    if ("public".equals(visibility)) {
      processor.setVisibility(Modifiers.AccPublic);
    }

    if ("prvate".equals(visibility)) {
      processor.setVisibility(Modifiers.AccPrivate);
    }

    if ("protected".equals(visibility)) {
      processor.setVisibility(Modifiers.AccProtected);
    }

    processor.setNewFunctionName(testFile.getConfig().get("newName"));

    checkInitCondition(processor);
    performChange(processor);
    checkTestResult(testFile, structuredDocument);
  }
 SourceViewer doCreateViewer(Composite parent, SourceViewerConfiguration viewerConfiguration) {
   SourceViewer viewer = null;
   String contentTypeID = ContentTypeIdForHTML.ContentTypeID_HTML;
   viewer =
       new StructuredTextViewer(
           parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
   viewer
       .getTextWidget()
       .setFont(JFaceResources.getFont("org.eclipse.wst.sse.ui.textfont")); // $NON-NLS-1$
   IStructuredModel scratchModel =
       StructuredModelManager.getModelManager().createUnManagedStructuredModelFor(contentTypeID);
   IDocument document = scratchModel.getStructuredDocument();
   viewer.configure(viewerConfiguration);
   viewer.setDocument(document);
   return viewer;
 }
  private boolean addXmlFileChanges(IFile file, CompositeChange changes, boolean isManifest) {
    IModelManager modelManager = StructuredModelManager.getModelManager();
    IStructuredModel model = null;
    try {
      model = modelManager.getExistingModelForRead(file);
      if (model == null) {
        model = modelManager.getModelForRead(file);
      }
      if (model != null) {
        IStructuredDocument document = model.getStructuredDocument();
        if (model instanceof IDOMModel) {
          IDOMModel domModel = (IDOMModel) model;
          Element root = domModel.getDocument().getDocumentElement();
          if (root != null) {
            List<TextEdit> edits = new ArrayList<TextEdit>();
            if (isManifest) {
              addManifestReplacements(edits, root, document);
            } else {
              addLayoutReplacements(edits, root, document);
            }
            if (!edits.isEmpty()) {
              MultiTextEdit rootEdit = new MultiTextEdit();
              rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
              TextFileChange change = new TextFileChange(file.getName(), file);
              change.setTextType(EXT_XML);
              change.setEdit(rootEdit);
              changes.add(change);
            }
          }
        } else {
          return false;
        }
      }

      return true;
    } catch (IOException e) {
      AdtPlugin.log(e, null);
    } catch (CoreException e) {
      AdtPlugin.log(e, null);
    } finally {
      if (model != null) {
        model.releaseFromRead();
      }
    }

    return false;
  }
 public void replaceSource(IStructuredModel model, int offset, int length, String source) {
   if (model == null) return;
   IStructuredDocument structuredDocument = model.getStructuredDocument();
   if (structuredDocument == null) return;
   if (offset >= 0 && length >= 0 && offset + length <= structuredDocument.getLength()) {
     if (structuredDocument.containsReadOnly(offset, length)) return;
     if (source == null) source = new String();
     // We use 'structuredDocument' as the requester object just so
     // this and the other
     // format-related 'repalceText' (in replaceSource) can use the
     // same requester.
     // Otherwise, if requester is not identical,
     // the undo group gets "broken" into multiple pieces based
     // on the requesters being different. Technically, any unique,
     // common
     // requester object would work.
     structuredDocument.replaceText(structuredDocument, offset, length, source);
   }
 }
예제 #7
0
 /**
  * originally copied from org.eclipse.wst.xml.ui.internal.hyperlink.XMLHyperlinkDetector this
  * method grabs the IDOMModel for the IDocument, performs the passed operation on the node at the
  * offset and then releases the IDOMModel operation's Node value is also an instance of
  * IndexedRegion
  *
  * @param offset
  */
 public static void performOnCurrentElement(
     IDocument document, int offset, NodeOperation<Node> operation) {
   assert document != null;
   assert operation != null;
   // get the current node at the offset (returns either: element,
   // doctype, text)
   IStructuredModel sModel = null;
   try {
     sModel = StructuredModelManager.getModelManager().getExistingModelForRead(document);
     if (sModel != null) {
       IndexedRegion inode = sModel.getIndexedRegion(offset);
       if (inode == null) {
         inode = sModel.getIndexedRegion(offset - 1);
       }
       if (inode instanceof Node) {
         operation.process((Node) inode, sModel.getStructuredDocument());
       }
     }
   } finally {
     if (sModel != null) {
       sModel.releaseFromRead();
     }
   }
 }
예제 #8
0
  @Override
  protected List<Change> computeChanges(IProgressMonitor monitor) {
    String name = getViewClass(mTypeFqcn);

    IFile file = mDelegate.getEditor().getInputFile();
    List<Change> changes = new ArrayList<Change>();
    if (file == null) {
      return changes;
    }
    TextFileChange change = new TextFileChange(file.getName(), file);
    MultiTextEdit rootEdit = new MultiTextEdit();
    change.setEdit(rootEdit);
    change.setTextType(EXT_XML);
    changes.add(change);

    for (Element element : getElements()) {
      IndexedRegion region = getRegion(element);
      String text = getText(region.getStartOffset(), region.getEndOffset());
      String oldName = element.getNodeName();
      int open = text.indexOf(oldName);
      int close = text.lastIndexOf(oldName);
      if (element instanceof ElementImpl && ((ElementImpl) element).isEmptyTag()) {
        close = -1;
      }

      if (open != -1) {
        int oldLength = oldName.length();
        rootEdit.addChild(new ReplaceEdit(region.getStartOffset() + open, oldLength, name));
      }
      if (close != -1 && close != open) {
        int oldLength = oldName.length();
        rootEdit.addChild(new ReplaceEdit(region.getStartOffset() + close, oldLength, name));
      }

      // Change tag type
      String oldId = getId(element);
      String newId = ensureIdMatchesType(element, mTypeFqcn, rootEdit);
      // Update any layout references to the old id with the new id
      if (oldId != null && newId != null) {
        IStructuredModel model = mDelegate.getEditor().getModelForRead();
        try {
          IStructuredDocument doc = model.getStructuredDocument();
          if (doc != null) {
            IndexedRegion range = getRegion(element);
            int skipStart = range.getStartOffset();
            int skipEnd = range.getEndOffset();
            List<TextEdit> replaceIds =
                replaceIds(getAndroidNamespacePrefix(), doc, skipStart, skipEnd, oldId, newId);
            for (TextEdit edit : replaceIds) {
              rootEdit.addChild(edit);
            }
          }
        } finally {
          model.releaseFromRead();
        }
      }

      // Strip out attributes that no longer make sense
      removeUndefinedAttrs(rootEdit, element);
    }

    return changes;
  }