public static IJavaProject findJavaProject(ITextViewer viewer) { if (viewer == null) return null; IStructuredModel existingModelForRead = StructuredModelManager.getModelManager().getExistingModelForRead(viewer.getDocument()); if (existingModelForRead == null) return null; IJavaProject javaProject = null; try { String baseLocation = existingModelForRead.getBaseLocation(); // 20041129 (pa) the base location changed for XML model // because of FileBuffers, so this code had to be updated // https://bugs.eclipse.org/bugs/show_bug.cgi?id=79686 IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath filePath = new Path(baseLocation); IProject project = null; if (filePath.segmentCount() > 0) { project = root.getProject(filePath.segment(0)); } if (project != null) { javaProject = JavaCore.create(project); } } catch (Exception ex) { MapperPlugin.getDefault().logException(ex); } return javaProject; }
public void connect(IDocument document) { fDocument = document; // special checks to see source validation should really execute IFile file = null; IStructuredModel model = null; try { model = StructuredModelManager.getModelManager().getExistingModelForRead(document); if (model != null) { String baseLocation = model.getBaseLocation(); // The baseLocation may be a path on disk or relative to the // workspace root. Don't translate on-disk paths to // in-workspace resources. IPath basePath = new Path(baseLocation); if (basePath.segmentCount() > 1) { file = ResourcesPlugin.getWorkspace().getRoot().getFile(basePath); /* * If the IFile doesn't exist, make sure it's not returned */ if (!file.exists()) file = null; } } } finally { if (model != null) { model.releaseFromRead(); } } fEnableSourceValidation = (file != null && isBatchValidatorPreferenceEnabled(file) && shouldValidate(file) && fragmentCheck(file)); }
@Override protected void setUp() throws Exception { tempModel = (IDOMModel) StructuredModelManager.getModelManager() .createUnManagedStructuredModelFor("org.eclipse.m2e.core.pomFile"); }
public static void performOnRootElement( IFile resource, NodeOperation<Element> operation, boolean autoSave) throws IOException, CoreException { assert resource != null; assert operation != null; IDOMModel domModel = null; try { domModel = (IDOMModel) StructuredModelManager.getModelManager().getModelForRead(resource); if (domModel == null) { throw new IllegalArgumentException("Document is not structured: " + resource); } IStructuredDocument document = domModel.getStructuredDocument(); Element root = domModel.getDocument().getDocumentElement(); operation.process(root, document); if (autoSave && domModel.getReferenceCountForEdit() == 0) { domModel.save(); } } finally { if (domModel != null) { domModel.releaseFromRead(); } } }
void processAction(ITextEditor textEditor, IDocument document, ITextSelection textSelection) { int openCommentOffset = textSelection.getOffset(); int closeCommentOffset = openCommentOffset + textSelection.getLength(); if (textSelection.getLength() == 0) { return; } IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForEdit(document); if (model != null) { try { model.beginRecording(this, PHPUIMessages.AddBlockComment_tooltip); model.aboutToChangeModel(); try { document.replace(closeCommentOffset, 0, CLOSE_COMMENT); document.replace(openCommentOffset, 0, OPEN_COMMENT); } catch (BadLocationException e) { Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); } finally { model.changedModel(); model.endRecording(this); } } finally { model.releaseFromEdit(); } } }
public void testFindChildren() { tempModel .getStructuredDocument() .setText( StructuredModelManager.getModelManager(), // "<dependencies>" + // "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>" + // "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>" + // "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>" + // "<dependency><artifactId>BBB</artifactId><tag4/></dependency>" + "</dependencies>"); Element docElement = tempModel.getDocument().getDocumentElement(); assertTrue("null parent should return empty list", findChilds(null, "dependency").isEmpty()); assertTrue( "missing child should return empty list", findChilds(docElement, "missingElement").isEmpty()); List<Element> dep = findChilds(docElement, "dependency"); assertEquals("Children found", 4, dep.size()); for (Element d : dep) { assertEquals("Node type", "dependency", d.getLocalName()); } // Should return first match assertDependencyChild("Unexpected child", "AAA", "BBB", "tag1", dep.get(0)); assertDependencyChild("Unexpected child", "AAAB", "BBB", "tag2", dep.get(1)); assertDependencyChild("Unexpected child", "AAA", "BBBB", "tag3", dep.get(2)); assertDependencyChild("Unexpected child", null, "BBB", "tag4", dep.get(3)); }
public void testFindChild() { tempModel .getStructuredDocument() .setText( StructuredModelManager.getModelManager(), // "<dependencies>" + // "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>" + // "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>" + // "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>" + // "<dependency><artifactId>BBB</artifactId><tag4/></dependency>" + "</dependencies>"); Element docElement = tempModel.getDocument().getDocumentElement(); assertNull("null parent should return null", findChild(null, "dependency")); assertNull("missing child should return null", findChild(docElement, "missingElement")); Element dep = findChild(docElement, "dependency"); assertNotNull("Expected node found", dep); assertEquals("Node type", "dependency", dep.getLocalName()); // Should return first match assertDependencyChild(null, "AAA", "BBB", "tag1", dep); }
public void testAddExclusion_existingExclusion() throws Exception { document.setText( StructuredModelManager.getModelManager(), // "<project><dependencies>" + // "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>" + // "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>" + // "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><version>1.0</version>" + // "<exclusions><exclusion><groupId>g</groupId><artifactId>b</artifactId><version>1.0</version></exclusion></exclusions></dependency>" + // "</dependencies></project>"); PomEdits.performOnDOMDocument(new OperationTuple(tempModel, new AddExclusionOperation(d, e))); assertEquals( "Expected no dependency: " + d.toString() + "\n" + document.getText(), 1, dependencyCount(tempModel, d)); assertTrue( "Has exclusion " + e.toString() + "\n" + document.getText(), hasExclusion(tempModel, d, e)); ArtifactKey key = new ArtifactKey("g", "b", "1.0", null); assertTrue( "Existing Exclusion Present " + key.toString() + "\n" + document.getText(), hasExclusion(tempModel, d, key)); assertEquals("Exclusions", 2, getExclusionCount(tempModel, d)); assertEquals("Dependency Count: \n" + document.getText(), 3, getDependencyCount(tempModel)); }
private String removeChild(String xml) { tempModel.getStructuredDocument().setText(StructuredModelManager.getModelManager(), xml); Document doc = tempModel.getDocument(); Element parent = doc.getDocumentElement(); Element child = PomEdits.findChild(parent, PomEdits.BUILD); PomEdits.removeChild(parent, child); return tempModel.getStructuredDocument().getText(); }
public void testMissingDependency_noDependenciesElement() throws Exception { document.setText( StructuredModelManager.getModelManager(), // "<project></project>"); PomEdits.performOnDOMDocument(new OperationTuple(tempModel, new AddExclusionOperation(d, e))); assertEquals( "Expected no dependency: " + d.toString() + "\n" + document.getText(), 0, dependencyCount(tempModel, d)); }
public void testRemoveIfNoChildElement() { tempModel .getStructuredDocument() .setText( StructuredModelManager.getModelManager(), "<project>" + "<build>" + "<pluginManagement>" + "<plugins></plugins" + "</pluginManagement>" + "</build>" + "</project>"); Document doc = tempModel.getDocument(); Element plugins = findChild( findChild(findChild(doc.getDocumentElement(), BUILD), PLUGIN_MANAGEMENT), PLUGINS); assertNotNull(plugins); removeIfNoChildElement(plugins); assertNull(findChild(doc.getDocumentElement(), BUILD)); tempModel .getStructuredDocument() .setText( StructuredModelManager.getModelManager(), "<project>" + "<build>" + "<pluginManagement>" + "<plugins></plugins" + "</pluginManagement>" + "<STOP_ELEMENT/>" + "</build>" + "</project>"); doc = tempModel.getDocument(); plugins = findChild( findChild(findChild(doc.getDocumentElement(), BUILD), PLUGIN_MANAGEMENT), PLUGINS); assertNotNull(plugins); removeIfNoChildElement(plugins); Element build = findChild(doc.getDocumentElement(), BUILD); assertNotNull(build); assertNull(findChild(build, PLUGIN_MANAGEMENT)); }
protected IndexedRegion getCorrespondingNode(IStructuredDocumentRegion sdRegion) { IStructuredModel sModel = StructuredModelManager.getModelManager().getExistingModelForRead(fDocument); IndexedRegion indexedRegion = null; try { if (sModel != null) indexedRegion = sModel.getIndexedRegion(sdRegion.getStart()); } finally { if (sModel != null) sModel.releaseFromRead(); } return indexedRegion; }
/** * @param file the file to get the model for * @return the file's XMLModel */ protected IDOMModel getModelForResource(IFile file) { IStructuredModel model = null; IModelManager manager = StructuredModelManager.getModelManager(); try { model = manager.getModelForRead(file); // TODO.. HTML validator tries again to get a model a 2nd way } catch (Exception e) { // e.printStackTrace(); } return model instanceof IDOMModel ? (IDOMModel) model : null; }
public static boolean isValueExists(IStructuredDocument document, IJSONPath path) { IJSONModel model = null; try { model = (IJSONModel) StructuredModelManager.getModelManager().getModelForRead(document); IJSONPair pair = findByPath(model.getDocument(), path.getSegments()); return pair != null; } finally { if (model != null) { model.releaseFromRead(); } } }
@Override public IStructuredModel getModelForRead() { IModelManager mm = StructuredModelManager.getModelManager(); if (mm != null) { try { return mm.getModelForRead(mFile); } catch (Exception e) { fail(e.toString()); } } return null; }
/** Be sure to release any models obtained from this method. */ IStructuredModel getTestModel() throws IOException, CoreException { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(fProjectName); IFile iFile = (IFile) project.findMember("/files/simple.xml"); // fProjectName + "/files/simple.xml" IStructuredModel model = null; IModelManager modelManager = StructuredModelManager.getModelManager(); model = modelManager.getModelForEdit(iFile); return model; }
public static void removePath(IStructuredDocument document, IJSONPath path) { IJSONModel model = null; try { model = (IJSONModel) StructuredModelManager.getModelManager().getModelForRead(document); IJSONPair pair = findByPath(model.getDocument(), path.getSegments()); if (pair != null) { document.replaceText( document, pair.getStartOffset(), pair.getEndOffset() - pair.getStartOffset(), ""); } } finally { if (model != null) { model.releaseFromRead(); } } }
/* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { tempModel = (IDOMModel) StructuredModelManager.getModelManager() .createUnManagedStructuredModelFor("org.eclipse.m2e.core.pomFile"); document = tempModel.getStructuredDocument(); d = new Dependency(); d.setArtifactId("BBBB"); d.setGroupId("AAA"); d.setVersion("1.0"); e = new ArtifactKey("g", "a", "1.0", null); }
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; }
public static Object getValue(IStructuredDocument document, IJSONPath path) { IJSONModel model = null; try { model = (IJSONModel) StructuredModelManager.getModelManager().getModelForRead(document); IJSONPair pair = findByPath(model.getDocument(), path.getSegments()); if (pair != null) { IJSONValue value = pair.getValue(); return getValue(value); } } finally { if (model != null) { model.releaseFromRead(); } } return null; }
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; }
protected void updateDtdVersion(IProject project, String dtdVersion, String archetypeVesion) { final String tmpPublicId = dtdVersion; final String tmpSystemId = dtdVersion.replaceAll("\\.", "_"); IStructuredModel editModel = null; final IFile[] metaFiles = getLiferayMetaFiles(project); for (IFile file : metaFiles) { try { editModel = StructuredModelManager.getModelManager().getModelForEdit(file); if (editModel != null && editModel instanceof IDOMModel) { final IDOMDocument xmlDocument = ((IDOMModel) editModel).getDocument(); final DocumentTypeImpl docType = (DocumentTypeImpl) xmlDocument.getDoctype(); final String publicId = docType.getPublicId(); final String newPublicId = getNewDoctTypeSetting(publicId, tmpPublicId, publicid_pattern); if (newPublicId != null) { docType.setPublicId(newPublicId); } final String systemId = docType.getSystemId(); final String newSystemId = getNewDoctTypeSetting(systemId, tmpSystemId, systemid_pattern); if (newSystemId != null) { docType.setSystemId(newSystemId); } editModel.save(); } } catch (Exception e) { final IStatus error = ProjectCore.createErrorStatus( "Unable to upgrade deployment meta file for " + file.getName(), e); ProjectCore.logError(error); } finally { if (editModel != null) { editModel.releaseFromEdit(); } } } ProjectCore.operate( project, UpdateDescriptorVersionOperation.class, archetypeVesion, dtdVersion); }
/** * Returns the content type of document * * @param document - assumes document is not null * @return String content type of given document */ private String getContentType() { String type = null; IModelManager mgr = StructuredModelManager.getModelManager(); IStructuredModel model = null; try { model = mgr.getExistingModelForRead(document); if (model != null) { type = model.getContentTypeIdentifier(); } } finally { if (model != null) { model.releaseFromRead(); } } return type; }
public void testMissingDependency_withDependencies() throws Exception { document.setText( StructuredModelManager.getModelManager(), // "<project><dependencies>" + // "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>" + // "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>" + // "</dependencies></project>"); PomEdits.performOnDOMDocument(new OperationTuple(tempModel, new AddExclusionOperation(d, e))); assertEquals( "Expected no dependency: " + d.toString() + "\n" + document.getText(), 0, dependencyCount(tempModel, d)); assertEquals("Dependency Count: \n" + document.getText(), 2, getDependencyCount(tempModel)); }
/** * this method grabs the IDOMModel for the IDocument, performs the passed operation on the root * element of the document and then releases the IDOMModel root Element value is also an instance * of IndexedRegion * * @param doc * @param operation */ public static void performOnRootElement(IDocument doc, NodeOperation<Element> operation) { assert doc != null; assert operation != null; IDOMModel domModel = null; try { domModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(doc); if (domModel == null) { throw new IllegalArgumentException("Document is not structured: " + doc); } IStructuredDocument document = domModel.getStructuredDocument(); Element root = domModel.getDocument().getDocumentElement(); operation.process(root, document); } finally { if (domModel != null) { domModel.releaseFromRead(); } } }
/** * Method validateEdit. * * @param file org.eclipse.core.resources.IFile * @param context org.eclipse.swt.widgets.Shell * @return IStatus */ private static IStatus validateEdit(IFile file, Shell context) { if (file == null || !file.exists()) return STATUS_ERROR; if (!(file.isReadOnly())) return STATUS_OK; IPath location = file.getLocation(); final long beforeModifiedFromJavaIO = (location != null) ? location.toFile().lastModified() : IResource.NULL_STAMP; final long beforeModifiedFromIFile = file.getModificationStamp(); IStatus status = ResourcesPlugin.getWorkspace().validateEdit(new IFile[] {file}, context); if (!status.isOK()) return status; final long afterModifiedFromJavaIO = (location != null) ? location.toFile().lastModified() : IResource.NULL_STAMP; final long afterModifiedFromIFile = file.getModificationStamp(); if (beforeModifiedFromJavaIO != afterModifiedFromJavaIO || beforeModifiedFromIFile != afterModifiedFromIFile) { IModelManager manager = StructuredModelManager.getModelManager(); IStructuredModel model = manager.getExistingModelForRead(file); if (model != null) { if (!model.isDirty()) { try { file.refreshLocal(IResource.DEPTH_ONE, null); } catch (CoreException e) { return STATUS_ERROR; } finally { model.releaseFromRead(); } } else { model.releaseFromRead(); } } } if ((beforeModifiedFromJavaIO != afterModifiedFromJavaIO) || (beforeModifiedFromIFile != afterModifiedFromIFile)) { // the file is replaced. Modification cannot be // applied. return STATUS_ERROR; } return STATUS_OK; }
public void testMatchers() { tempModel .getStructuredDocument() .setText( StructuredModelManager.getModelManager(), "<dependencies>" + "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>" + "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>" + "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>" + "<dependency><artifactId>BBB</artifactId><tag4/></dependency>" + "</dependencies>"); Document doc = tempModel.getDocument(); Element el = findChild(doc.getDocumentElement(), DEPENDENCY, childEquals(ARTIFACT_ID, "BBBB")); assertNotNull(findChild(el, "tag3")); el = findChild(doc.getDocumentElement(), DEPENDENCY, childEquals(ARTIFACT_ID, "BBB")); assertNotNull(findChild(el, "tag1")); el = findChild( doc.getDocumentElement(), DEPENDENCY, childEquals(GROUP_ID, "AAAB"), childEquals(ARTIFACT_ID, "BBB")); assertNotNull(findChild(el, "tag2")); el = findChild( doc.getDocumentElement(), DEPENDENCY, childMissingOrEqual(GROUP_ID, "CCC"), childEquals(ARTIFACT_ID, "BBB")); assertNotNull(findChild(el, "tag4")); el = findChild( doc.getDocumentElement(), DEPENDENCY, childEquals(GROUP_ID, "AAA"), childMissingOrEqual(ARTIFACT_ID, "BBBB")); assertNotNull(findChild(el, "tag3")); }
public static IProject getProject(IDocument document) { IStructuredModel model = null; try { model = StructuredModelManager.getModelManager().getExistingModelForRead(document); if (model != null) { String baselocation = model.getBaseLocation(); if (baselocation != null) { // copied from JSPTranslationAdapter#getJavaProject IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath filePath = new Path(baselocation); if (filePath.segmentCount() > 0) { return root.getProject(filePath.segment(0)); } } } return null; } finally { if (model != null) model.releaseFromRead(); } }
/** * Returns the closest IndexedRegion for the offset and viewer allowing for differences between * viewer offsets and model positions. note: this method returns an IndexedRegion for read only * * @param viewer the viewer whose document is used to compute the proposals * @param documentOffset an offset within the document for which completions should be computed * @return an IndexedRegion */ public static IndexedRegion getNodeAt(ITextViewer viewer, int documentOffset) { if (viewer == null) return null; IndexedRegion node = null; IModelManager mm = StructuredModelManager.getModelManager(); IStructuredModel model = null; if (mm != null) model = mm.getExistingModelForRead(viewer.getDocument()); try { if (model != null) { int lastOffset = documentOffset; node = model.getIndexedRegion(documentOffset); while (node == null && lastOffset >= 0) { lastOffset--; node = model.getIndexedRegion(lastOffset); } } } finally { if (model != null) model.releaseFromRead(); } return node; }
/** * Validate one file. It's assumed that the file has JSP content type. * * @param f * @param reporter */ protected void validateFile(IFile f, IReporter reporter) { if (JsValidator.DEBUG) { Logger.log(Logger.INFO, getClass().getName() + " validating: " + f); // $NON-NLS-1$ } IStructuredModel model = null; try { // get jsp model, get tranlsation model = StructuredModelManager.getModelManager().getModelForRead(f); if (!reporter.isCancelled() && model != null) { // get DOM model then translation // WorkbenchReporter.removeAllMessages(f.getProject(), jsdtValidator, f.toString()); // reporter.removeAllMessages(fMessageOriginator, f); performValidation(f, reporter, model, false); } } catch (IOException e) { Logger.logException(e); } catch (CoreException e) { Logger.logException(e); } finally { if (model != null) { model.releaseFromRead(); } } }