private void onDescriptorsChanged() { IStructuredModel model = getModelForRead(); if (model != null) { try { Node node = getManifestXmlNode(getXmlDocument(model)); mUiManifestNode.reloadFromXmlNode(node); } finally { model.releaseFromRead(); } } if (mOverviewPage != null) { mOverviewPage.refreshUiApplicationNode(); } if (mAppPage != null) { mAppPage.refreshUiApplicationNode(); } if (mPermissionPage != null) { mPermissionPage.refreshUiNode(); } if (mInstrumentationPage != null) { mInstrumentationPage.refreshUiNode(); } }
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)); }
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 List collectJSONNodes(IStructuredModel model, int start, int length) { List nodes = new ArrayList(); IndexedRegion startNode = model.getIndexedRegion(start); IndexedRegion endNode = model.getIndexedRegion(start + length - 1); if (startNode == null || endNode == null) { return nodes; } if (model instanceof IJSONModel && startNode instanceof IJSONNode && endNode instanceof IJSONNode) { // JSON model IJSONNode ca = getCommonAncestor((IJSONNode) startNode, (IJSONNode) endNode); if (ca != null) { for (IJSONNode node = ca.getFirstChild(); node != null && start + length < ((IndexedRegion) node).getStartOffset(); node = node.getNextSibling()) { if (start < ((IndexedRegion) node).getEndOffset()) { nodes.add(node); } } } } return nodes; }
/** * To see whether the textSelection start and end are on the same. * * @param model * @param textSelection * @return the node */ static boolean isSame(IStructuredModel model, TextSelection textSelection) { if (model != null && textSelection != null) { int t1 = textSelection.getOffset(); int t2 = textSelection.getLength() + t1; return model.getIndexedRegion(t1) == model.getIndexedRegion(t2); } return false; }
public void testIsSaveNeeded() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { assertFalse("save should not be needed", model.isSaveNeeded()); } finally { if (model != null) { model.releaseFromEdit(); } } }
public void testIsModelStateChanging() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { assertFalse("model should not be changing", model.isModelStateChanging()); } finally { if (model != null) { model.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(); } } }
public void testAboutToChangeModel() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { model.aboutToChangeModel(); assertTrue(true); } finally { if (model != null) { model.releaseFromEdit(); } } }
public void testIsNew() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { // this API seems strange // assertFalse("new model check failed", model.isNew()); } finally { if (model != null) { model.releaseFromEdit(); } } }
public void testGetIndexedRegions() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { // not implemented yet... // model.getIndexedRegions(); } finally { if (model != null) { model.releaseFromEdit(); } } }
public void testGetIndexedRegion() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { model.getIndexedRegion(0); assertTrue(true); } finally { if (model != null) { model.releaseFromEdit(); } } }
public void testGetBaseLocation() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { String location = model.getBaseLocation(); assertTrue("wrong base location", location.equals("/" + fProjectName + "/files/simple.xml")); } finally { if (model != null) { model.releaseFromEdit(); } } }
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; }
public void testGetContentType() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { String ct = model.getContentTypeIdentifier(); assertTrue( "model has wrong content type:" + ct + " != " + ContentTypeIdForXML.ContentTypeID_XML, ct.equals(ContentTypeIdForXML.ContentTypeID_XML)); } 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); }
/** * Test expectes an exception since only a changedModel sent, without beginning * 'aboutToChangeModel' * * @throws CoreException * @throws IOException */ public void testChangedModel() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { try { model.changedModel(); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } } finally { if (model != null) { model.releaseFromEdit(); } } }
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; }
public void testNewInstance() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { IStructuredModel newInstance = null; try { newInstance = model.newInstance(); } catch (IOException e) { assertTrue("IOException during model new instance", false); } assertNotNull("new instance is null", newInstance); } finally { if (model != null) { model.releaseFromEdit(); } } }
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; }
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; }
private void tryConnectTo(IWorkbenchPart part) { if (part instanceof IEditorPart) { IStructuredModel model = (IStructuredModel) part.getAdapter(IStructuredModel.class); if (part != swtXmlEditorPart && model != null && SwtXmlModelHandler.associatedContentTypeID.equals(model.getContentTypeIdentifier())) { connectTo(part); } else if (((IEditorPart) part).getEditorInput() instanceof FileEditorInput) { if (((FileEditorInput) (((IEditorPart) part).getEditorInput())) .getFile() .toString() .endsWith(".properties")) { propertiesFileEditorPart = (IEditorPart) part; propertiesFileEditorPart.addPropertyListener(updatePreviewOnSavePropertiesFile); } } } }
/** * 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 testAddRemoveModelStateListener() throws IOException, CoreException { IStructuredModel model = getTestModel(); try { IModelStateListener listener = new IModelStateListener() { public void modelAboutToBeChanged(IStructuredModel model) { // } public void modelChanged(IStructuredModel model) { // } public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) { // } public void modelResourceDeleted(IStructuredModel model) { // } public void modelResourceMoved(IStructuredModel oldModel, IStructuredModel newModel) { // } public void modelAboutToBeReinitialized(IStructuredModel structuredModel) { // } public void modelReinitialized(IStructuredModel structuredModel) { // } }; model.aboutToChangeModel(); model.removeModelStateListener(listener); } finally { if (model != null) { model.releaseFromEdit(); } } }
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 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(); } }
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(); } } }
/** * Get node at indexed position. * * @param model * @param position * @return the node at position */ static Node getNodeAt(IStructuredModel model, int position) { try { IndexedRegion region = model.getIndexedRegion(position); if (region instanceof Node) { return (Node) region; } return null; } catch (Exception e) { // "Error in region node creation" _log.error("Error.EditModelQuery.1", e); // $NON-NLS-1$ return null; } }