incubator-odf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From liud...@apache.org
Subject svn commit: r1406043 [1/2] - in /incubator/odf/trunk/simple/src: main/java/org/odftoolkit/simple/ main/java/org/odftoolkit/simple/common/navigation/ main/java/org/odftoolkit/simple/draw/ test/java/org/odftoolkit/simple/common/field/ test/java/org/odfto...
Date Tue, 06 Nov 2012 05:31:30 GMT
Author: liudali
Date: Tue Nov  6 05:31:29 2012
New Revision: 1406043

URL: http://svn.apache.org/viewvc?rev=1406043&view=rev
Log:
fix for ODFTOOLKIT-330 "Improve the method TextSelection.replaceWith(String). new param types support"
https://issues.apache.org/jira/browse/ODFTOOLKIT-330

Added:
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ImageSelection.java
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ParagraphSelection.java
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TableSelection.java
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextDocumentSelection.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ImageSelectionTest.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ParagraphSelectionTest.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TableSelectionTest.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TextDocumentSelectionTest.java
Modified:
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/TextDocument.java
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextSelection.java
    incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/draw/Image.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/field/VariableFieldTest.java
    incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TextSelectionTest.java

Modified: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/TextDocument.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/TextDocument.java?rev=1406043&r1=1406042&r2=1406043&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/TextDocument.java (original)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/TextDocument.java Tue Nov  6 05:31:29 2012
@@ -45,6 +45,7 @@ import org.odftoolkit.odfdom.dom.element
 import org.odftoolkit.odfdom.dom.element.style.StyleHeaderElement;
 import org.odftoolkit.odfdom.dom.element.style.StyleMasterPageElement;
 import org.odftoolkit.odfdom.dom.element.style.StylePageLayoutPropertiesElement;
+import org.odftoolkit.odfdom.dom.element.table.TableTableElement;
 import org.odftoolkit.odfdom.dom.element.text.TextIndexBodyElement;
 import org.odftoolkit.odfdom.dom.element.text.TextIndexEntryLinkStartElement;
 import org.odftoolkit.odfdom.dom.element.text.TextIndexEntryTabStopElement;
@@ -81,6 +82,7 @@ import org.odftoolkit.simple.common.fiel
 import org.odftoolkit.simple.common.field.VariableField.VariableType;
 import org.odftoolkit.simple.style.MasterPage;
 import org.odftoolkit.simple.style.TOCStyle;
+import org.odftoolkit.simple.table.Table;
 import org.odftoolkit.simple.text.AbstractParagraphContainer;
 import org.odftoolkit.simple.text.Footer;
 import org.odftoolkit.simple.text.Header;
@@ -1254,4 +1256,112 @@ public class TextDocument extends Docume
 		}
 	}
 	
+	/**
+	 * Copy a Paragraph and insert it before or after the Reference Paragraph in the text document, whether the
+	 * Paragraph is in this document or in a different document.
+	 * 
+	 * @param referenceParagraph
+	 *            - where the Paragraph be inserted 
+	 * @param sourceParagraph
+	 *            - the Paragraph which will be copied
+	 * @param before
+	 *            true:insert Paragraph before the reference paragraph. 
+	 *            false:insert Paragraph after the reference paragraph.       
+	 */
+	public Paragraph insertParagraph(Paragraph referenceParagraph, Paragraph sourceParagraph,boolean before) {
+		boolean isForeignNode = false;
+		try {
+			Node refparagraphNode = referenceParagraph.getOdfElement();
+			if (sourceParagraph.getOdfElement().getOwnerDocument() != getContentDom())
+				isForeignNode = true;
+			 TextParagraphElementBase oldParagraphEle = sourceParagraph.getOdfElement();
+			 TextParagraphElementBase newParagraphEle = (TextParagraphElementBase) oldParagraphEle.cloneNode(true);
+			
+			if (isForeignNode)
+				copyForeignStyleRef(sourceParagraph.getOdfElement(), sourceParagraph.getOwnerDocument());
+			if (isForeignNode) // not in a same document
+				newParagraphEle = (TextParagraphElementBase) cloneForeignElement(newParagraphEle, getContentDom(), true);
+			
+			if (before) {
+				refparagraphNode.getParentNode().insertBefore(newParagraphEle, refparagraphNode);
+			} else {
+				// Insert Paragraph after the refParagraph
+				Node refNextNode = refparagraphNode.getNextSibling();
+				if (refNextNode == null) {
+					refparagraphNode.getParentNode().appendChild(newParagraphEle);
+				} else {
+					refparagraphNode.getParentNode().insertBefore(newParagraphEle, refNextNode);
+				}
+			}
+			
+			return Paragraph.getInstanceof(newParagraphEle);
+		} catch (Exception e) {
+			Logger.getLogger(TextDocument.class.getName()).log(Level.SEVERE, null, e);
+		}
+		return null;
+	}
+	/**
+	 * Copy a Table and insert it before or after the Reference Paragraph in the text document, whether the
+	 * Table is in this TextDocument or in a different Document.
+	 * 
+	 * @param referenceParagraph
+	 *            - where the Paragraph be inserted 
+	 * @param sourceParagraph
+	 *            - the Paragraph which will be copied
+	 * @param before
+	 *            true:insert Paragraph before the reference paragraph. 
+	 *            false:insert Paragraph after the reference paragraph.       
+	 */
+	public Table insertTable(Paragraph referenceParagraph, Table sourceTable,boolean before) {
+		
+		Document ownDocument = sourceTable.getOwnerDocument();
+		TableTableElement newTEle = (TableTableElement)insertOdfElement(referenceParagraph.getOdfElement(),ownDocument,sourceTable.getOdfElement(),before);
+		Table table = Table.getInstance(newTEle);
+		return table;
+	}
+	/**
+	 * Copy a OdfElement and insert it before or after the Reference OdfElement in the TextDocument, whether the
+	 * OdfElement is in this TextDocument or in a different Document.
+	 * 
+	 * @param referenceOdfElement
+	 *            - where the OdfElement be inserted 
+	 * @param sourceDocument
+	 *            - the source Document which contain the sourceOdfElement
+	 * @param sourceOdfElement
+	 *            - the OdfElement which will be copied
+	 * @param before
+	 *            true:insert OdfElement before the reference OdfElement. 
+	 *            false:insert OdfElement after the reference OdfElement.       
+	 */
+	public OdfElement insertOdfElement(OdfElement referenceOdfElement,Document sourceDocument ,OdfElement sourceOdfElement,boolean before) {
+		boolean isForeignNode = false;
+		try {
+			
+			if (sourceOdfElement.getOwnerDocument() != getContentDom())
+				isForeignNode = true;
+			 
+			OdfElement newOdfElement = (OdfElement) sourceOdfElement.cloneNode(true);
+			
+			if (isForeignNode)
+				copyForeignStyleRef(sourceOdfElement,sourceDocument);
+			if (isForeignNode) // not in a same document
+				newOdfElement = (OdfElement)  cloneForeignElement(newOdfElement, getContentDom(), true);
+			
+			if (before) {
+				referenceOdfElement.getParentNode().insertBefore(newOdfElement, referenceOdfElement);
+			} else {
+				// Insert newOdfElement after the referenceOdfElement
+				Node refNextNode = referenceOdfElement.getNextSibling();
+				if (refNextNode == null) {
+					referenceOdfElement.getParentNode().appendChild(newOdfElement);
+				} else {
+					referenceOdfElement.getParentNode().insertBefore(newOdfElement, refNextNode);
+				}
+			}
+			return newOdfElement;
+		} catch (Exception e) {
+			Logger.getLogger(TextDocument.class.getName()).log(Level.SEVERE, null, e);
+		}
+		return null;
+	}
 }

Added: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ImageSelection.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ImageSelection.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ImageSelection.java (added)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ImageSelection.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,362 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
+import org.odftoolkit.odfdom.dom.OdfSchemaDocument;
+import org.odftoolkit.odfdom.dom.element.draw.DrawFrameElement;
+import org.odftoolkit.odfdom.dom.element.draw.DrawImageElement;
+import org.odftoolkit.odfdom.dom.element.text.TextSElement;
+import org.odftoolkit.odfdom.pkg.OdfElement;
+import org.odftoolkit.odfdom.pkg.OdfFileDom;
+import org.odftoolkit.odfdom.pkg.manifest.OdfFileEntry;
+import org.odftoolkit.simple.common.TextExtractor;
+import org.odftoolkit.simple.draw.Image;
+import org.odftoolkit.simple.style.StyleTypeDefinitions.AnchorType;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * This is a decorator class of TextSelection, which help user replace a text content with a Image from Document or from URI.
+ * 
+ */
+public class ImageSelection extends Selection {
+
+	private TextSelection textSelection;
+	private DrawFrameElement imageContainer;
+
+	private boolean mIsInserted;
+	
+	/**
+	 * Replace the content with a Image
+	 * 
+	 * @param image the reference Image to replace.
+	 *   
+	 * @return the new Image in the TextDocument,the image name is set to "replace" + System.currentTimeMillis(), please update the name to others by yourself.
+	 *
+	 */
+	public Image replaceWithImage(Image image) {
+		Image mImage =null;
+		int leftLength = textSelection.getText().length();
+		int index = textSelection.getIndex();
+		mIsInserted = false;
+		OdfElement parentElement = textSelection.getContainerElement();
+		OdfFileDom ownerDom = (OdfFileDom) parentElement.getOwnerDocument();
+		
+		try {
+			if (imageContainer == null) {
+				delete(index, leftLength, parentElement);
+				// PrepareContainer
+				imageContainer = ownerDom.newOdfElement(DrawFrameElement.class);
+				insertOdfElement(imageContainer, index, parentElement);
+			} else {
+				NodeList nodeImages = imageContainer.getElementsByTagName("draw:image");
+				Node nodeImage = nodeImages.item(0);
+				DrawImageElement im = (DrawImageElement) nodeImage;
+				Image oldimage = Image.getInstanceof(im);
+				oldimage.remove();
+				// PrepareContainer
+				imageContainer = ownerDom.newOdfElement(DrawFrameElement.class);
+				insertOdfElement(imageContainer, index, parentElement);
+			}
+			// Insert Image resource to package
+			DrawImageElement imageElement = imageContainer.newDrawImageElement();
+			InputStream is = image.getImageInputStream();
+			String internalPath = image.getInternalPath();
+			String mediaType = OdfFileEntry.getMediaTypeString(internalPath);
+			OdfSchemaDocument mOdfSchemaDoc = (OdfSchemaDocument) ownerDom.getDocument();
+			String packagePath = Image.getPackagePath(mOdfSchemaDoc,internalPath);
+			mOdfSchemaDoc.getPackage().insert(is, packagePath, mediaType);
+			packagePath = packagePath.replaceFirst(ownerDom.getDocument().getDocumentPath(), "");
+			Image.configureInsertedImage((OdfSchemaDocument) ownerDom.getDocument(), imageElement,packagePath, false);
+			// get image object
+			mImage = Image.getInstanceof(imageElement);
+			mImage.getStyleHandler().setAchorType(AnchorType.AS_CHARACTER);
+			mImage.setName("replace" + System.currentTimeMillis());
+
+		} catch (Exception e) {
+			Logger.getLogger(ImageSelection.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+		}
+		return mImage;
+	}	
+	/**
+	 * Replace the content with a Image
+	 * 
+	 * @param imageUri the URI of the reference Image to replace
+	 *   
+	 * @return the new Image in the TextDocument,the image name is set to "replace" + System.currentTimeMillis(), please update the name to others by yourself
+	 *
+	 */
+	public Image replaceWithImage(URI imageUri) {
+		Image mImage =null;
+		int leftLength = textSelection.getText().length();
+		int index = textSelection.getIndex();
+		mIsInserted = false;
+		OdfElement parentElement = textSelection.getContainerElement();
+		OdfFileDom ownerDom = (OdfFileDom) parentElement.getOwnerDocument();
+		try{
+			if (imageContainer == null) {
+				delete(index, leftLength, parentElement);
+				// PrepareContainer
+				imageContainer = ownerDom.newOdfElement(DrawFrameElement.class);
+				insertOdfElement(imageContainer, index, parentElement);
+			} else {
+				NodeList nodeImages = imageContainer.getElementsByTagName("draw:image");
+				Node nodeImage = nodeImages.item(0);
+				DrawImageElement im = (DrawImageElement) nodeImage;
+				Image oldimage = Image.getInstanceof(im);
+				oldimage.remove();
+				// PrepareContainer
+				imageContainer = ownerDom.newOdfElement(DrawFrameElement.class);
+				insertOdfElement(imageContainer, index, parentElement);
+			}
+			// Insert Image resource to package
+			DrawImageElement imageElement = imageContainer.newDrawImageElement();
+			String imageRef = imageUri.toString();
+			String mediaType = OdfFileEntry.getMediaTypeString(imageRef);
+			OdfSchemaDocument mOdfSchemaDoc = (OdfSchemaDocument) ownerDom.getDocument();
+			String packagePath = Image.getPackagePath(mOdfSchemaDoc, imageRef);
+			mOdfSchemaDoc.getPackage().insert(imageUri, packagePath, mediaType);
+			packagePath = packagePath.replaceFirst(ownerDom.getDocument().getDocumentPath(), "");
+			Image.configureInsertedImage((OdfSchemaDocument) ownerDom.getDocument(), imageElement,packagePath, false);
+			// get image object
+			mImage = Image.getInstanceof(imageElement);
+			mImage.getStyleHandler().setAchorType(AnchorType.AS_CHARACTER);
+			mImage.setName("replace" + System.currentTimeMillis());
+			
+		} catch (Exception e) {
+			Logger.getLogger(ImageSelection.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+		}
+		return mImage;
+	}	
+	/*
+	 * Delete the <code>pNode<code> from the <code>fromIndex</code> text, and
+	 * delete <code>leftLength</code> text.
+	 */
+	private void delete(int fromIndex, int leftLength, Node pNode) {
+		if ((fromIndex == 0) && (leftLength == 0)) {
+			return;
+		}
+		int nodeLength = 0;
+		Node node = pNode.getFirstChild();
+		while (node != null) {
+			if ((fromIndex == 0) && (leftLength == 0)) {
+				return;
+			}
+			if (node.getNodeType() == Node.TEXT_NODE) {
+				nodeLength = node.getNodeValue().length();
+			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+				// text:s
+				if (node.getLocalName().equals("s")) {
+					try {
+						nodeLength = Integer.parseInt(((Element) node).getAttributeNS(OdfDocumentNamespace.TEXT
+								.getUri(), "c"));
+					} catch (Exception e) {
+						nodeLength = 1;
+					}
+				} else if (node.getLocalName().equals("line-break")) {
+					nodeLength = 1;
+				} else if (node.getLocalName().equals("tab")) {
+					nodeLength = 1;
+				} else {
+					nodeLength = TextExtractor.getText((OdfElement) node).length();
+				}
+			}
+			if (nodeLength <= fromIndex) {
+				fromIndex -= nodeLength;
+			} else {
+				// the start index is in this node
+				if (node.getNodeType() == Node.TEXT_NODE) {
+					String value = node.getNodeValue();
+					StringBuffer buffer = new StringBuffer();
+					buffer.append(value.substring(0, fromIndex));
+					int endLength = fromIndex + leftLength;
+					int nextLength = value.length() - endLength;
+					fromIndex = 0;
+					if (nextLength >= 0) {
+						// delete the result
+						buffer.append(value.substring(endLength, value.length()));
+						leftLength = 0;
+					} else {
+						leftLength = endLength - value.length();
+					}
+					node.setNodeValue(buffer.toString());
+
+				} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+					// if text:s?????????
+					// text:s
+					if (node.getLocalName().equals("s")) {
+						// delete space
+						((TextSElement) node).setTextCAttribute(new Integer(nodeLength - fromIndex));
+						leftLength = leftLength - (nodeLength - fromIndex);
+						fromIndex = 0;
+					} else if (node.getLocalName().equals("line-break") || node.getLocalName().equals("tab")) {
+						fromIndex = 0;
+						leftLength--;
+					} else {
+						delete(fromIndex, leftLength, node);
+						int length = (fromIndex + leftLength) - nodeLength;
+						leftLength = length > 0 ? length : 0;
+						fromIndex = 0;
+					}
+				}
+			}
+			node = node.getNextSibling();
+		}
+	}
+
+	/**
+	 * Construct a ImageSelection with TextSelection. Then user can replace text
+	 * content with Image from Document or Image form System
+	 * 
+	 * @param selection
+	 *            the TextSelection to be decorated.
+	 */
+	public ImageSelection(TextSelection selection) {
+		textSelection = selection;
+		
+		imageContainer = null;
+	}
+
+	/**
+	 * Delete the selection from the document the other matched selection in the
+	 * same container element will be updated automatically because the start
+	 * index of the following selections will be changed when the previous
+	 * selection has been deleted.
+	 * 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void cut() throws InvalidNavigationException {
+		textSelection.cut();
+	}
+
+	/**
+	 * Paste this selection just after a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtEndOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtEndOf(positionItem);
+	}
+	
+
+	/**
+	 * Paste this selection just before a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtFrontOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtFrontOf(positionItem);
+	}
+
+	protected void refresh(int offset) {
+		textSelection.refresh(offset);
+	}
+
+	protected void refreshAfterFrontalDelete(Selection deletedItem) {
+		textSelection.refreshAfterFrontalDelete(deletedItem);
+	}
+
+	protected void refreshAfterFrontalInsert(Selection insertedItem) {
+		textSelection.refreshAfterFrontalInsert(insertedItem);
+	}
+	
+	private void insertOdfElement(OdfElement odfElement, int fromIndex, Node pNode) {
+		if (fromIndex < 0) {
+			fromIndex = 0;
+		}
+		if (fromIndex == 0 && mIsInserted) {
+			return;
+		}
+		int nodeLength = 0;
+		Node node = pNode.getFirstChild();
+		while (node != null) {
+			if (fromIndex <= 0 && mIsInserted) {
+				return;
+			}
+			if (node.getNodeType() == Node.TEXT_NODE) {
+				nodeLength = node.getNodeValue().length();
+				if ((fromIndex != 0) && (nodeLength < fromIndex)) {
+					fromIndex -= nodeLength;
+				} else {
+					// insert result after node, and insert an new text node
+					// after the result node
+					String value = node.getNodeValue();
+					StringBuffer buffer = new StringBuffer();
+					buffer.append(value.substring(0, fromIndex));
+					// insert the text span in appropriate position
+					node.setNodeValue(buffer.toString());
+					Node nextNode = node.getNextSibling();
+					Node parNode = node.getParentNode();
+					Node newNode = node.cloneNode(true);
+					newNode.setNodeValue(value.substring(fromIndex, value.length()));
+					if (nextNode != null) {
+						parNode.insertBefore(odfElement, nextNode);
+						parNode.insertBefore(newNode, nextNode);
+					} else {
+						parNode.appendChild(odfElement);
+						parNode.appendChild(newNode);
+					}
+					mIsInserted = true;
+					return;
+				}
+			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+				// text:s
+				if (node.getLocalName().equals("s")) {
+					try {
+						nodeLength = Integer.parseInt(((Element) node).getAttributeNS(OdfDocumentNamespace.TEXT
+								.getUri(), "c"));
+					} catch (Exception e) {
+						nodeLength = 1;
+					}
+					fromIndex -= nodeLength;
+				} else if (node.getLocalName().equals("line-break")) {
+					nodeLength = 1;
+					fromIndex--;
+				} else if (node.getLocalName().equals("tab")) {
+					nodeLength = 1;
+					fromIndex--;
+				} else {
+					nodeLength = TextExtractor.getText((OdfElement) node).length();
+					insertOdfElement(odfElement, fromIndex, node);
+					fromIndex -= nodeLength;
+				}
+			}
+			node = node.getNextSibling();
+		}
+	}
+
+}

Added: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ParagraphSelection.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ParagraphSelection.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ParagraphSelection.java (added)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/ParagraphSelection.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,240 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
+import org.odftoolkit.odfdom.dom.element.text.TextParagraphElementBase;
+import org.odftoolkit.odfdom.dom.element.text.TextSElement;
+import org.odftoolkit.odfdom.pkg.OdfElement;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.common.TextExtractor;
+import org.odftoolkit.simple.text.Paragraph;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * This is a decorator class of TextSelection, which help user replace a text content with a Paragraph.
+ * 
+ */
+public class ParagraphSelection extends Selection {
+
+	private TextSelection textSelection;
+	private Paragraph paragraphContainer;
+	private Paragraph sourceParagraph;
+	
+	/**
+	 * Replace the content with a paragraph, the paragraph can be in the same TextDocument or in a different Document.
+	 * 
+	 * @param paragraph
+	 *            the reference paragraph to replace.
+	 */
+	public Paragraph replaceWithParagraph(Paragraph paragraph) {
+		this.sourceParagraph=paragraph;
+		int leftLength = textSelection.getText().length();
+		int index = textSelection.getIndex();
+		prepareParagraphContainer(leftLength, index);
+		return paragraphContainer;
+	}
+
+	/**
+	 * Construct a ParagraphSelection with TextSelection. Then user can replace text
+	 * content with paragraph.
+	 * 
+	 * @param selection
+	 *            the TextSelection to be decorated.
+	 */
+	public ParagraphSelection(TextSelection selection) {
+		textSelection = selection;
+		paragraphContainer = null;
+	}
+
+	/**
+	 * Delete the selection from the document the other matched selection in the
+	 * same container element will be updated automatically because the start
+	 * index of the following selections will be changed when the previous
+	 * selection has been deleted.
+	 * 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void cut() throws InvalidNavigationException {
+		textSelection.cut();
+	}
+
+	/**
+	 * Paste this selection just after a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtEndOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtEndOf(positionItem);
+	}
+	private void delete(int fromIndex, int leftLength, Node pNode) {
+		if ((fromIndex == 0) && (leftLength == 0)) {
+			return;
+		}
+		int nodeLength = 0;
+		Node node = pNode.getFirstChild();
+		while (node != null) {
+			if ((fromIndex == 0) && (leftLength == 0)) {
+				return;
+			}
+			if (node.getNodeType() == Node.TEXT_NODE) {
+				nodeLength = node.getNodeValue().length();
+			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+				// text:s
+				if (node.getLocalName().equals("s")) {
+					try {
+						nodeLength = Integer.parseInt(((Element) node).getAttributeNS(OdfDocumentNamespace.TEXT
+								.getUri(), "c"));
+					} catch (Exception e) {
+						nodeLength = 1;
+					}
+				} else if (node.getLocalName().equals("line-break")) {
+					nodeLength = 1;
+				} else if (node.getLocalName().equals("tab")) {
+					nodeLength = 1;
+				} else {
+					nodeLength = TextExtractor.getText((OdfElement) node).length();
+				}
+			}
+			if (nodeLength <= fromIndex) {
+				fromIndex -= nodeLength;
+			} else {
+				// the start index is in this node
+				if (node.getNodeType() == Node.TEXT_NODE) {
+					String value = node.getNodeValue();
+					StringBuffer buffer = new StringBuffer();
+					buffer.append(value.substring(0, fromIndex));
+					int endLength = fromIndex + leftLength;
+					int nextLength = value.length() - endLength;
+					fromIndex = 0;
+					if (nextLength >= 0) {
+						// delete the result
+						buffer.append(value.substring(endLength, value.length()));
+						leftLength = 0;
+					} else {
+						leftLength = endLength - value.length();
+					}
+					node.setNodeValue(buffer.toString());
+
+				} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+					// if text:s?????????
+					// text:s
+					if (node.getLocalName().equals("s")) {
+						// delete space
+						((TextSElement) node).setTextCAttribute(new Integer(nodeLength - fromIndex));
+						leftLength = leftLength - (nodeLength - fromIndex);
+						fromIndex = 0;
+					} else if (node.getLocalName().equals("line-break") || node.getLocalName().equals("tab")) {
+						fromIndex = 0;
+						leftLength--;
+					} else {
+						delete(fromIndex, leftLength, node);
+						int length = (fromIndex + leftLength) - nodeLength;
+						leftLength = length > 0 ? length : 0;
+						fromIndex = 0;
+					}
+				}
+			}
+			node = node.getNextSibling();
+		}
+	}
+
+	/**
+	 * Paste this selection just before a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtFrontOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtFrontOf(positionItem);
+	}
+
+	protected void refresh(int offset) {
+		textSelection.refresh(offset);
+	}
+
+	protected void refreshAfterFrontalDelete(Selection deletedItem) {
+		textSelection.refreshAfterFrontalDelete(deletedItem);
+	}
+
+	protected void refreshAfterFrontalInsert(Selection insertedItem) {
+		textSelection.refreshAfterFrontalInsert(insertedItem);
+	}
+
+	private void prepareParagraphContainer(int leftLength, int index) {
+		if (paragraphContainer == null) {
+			OdfElement rightparentElement = textSelection.getContainerElement();
+			int nodeLength = TextExtractor.getText(rightparentElement).length();
+			if(index==0){
+				if(leftLength==nodeLength){
+					//Replace whole Paragraph
+					Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+					TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+					paragraphContainer = document.insertParagraph(orgparagraph, sourceParagraph, false);
+					NodeList cnl = rightparentElement.getChildNodes();
+					for(int i=0;i<cnl.getLength();i++){
+						rightparentElement.removeChild(cnl.item(i));
+					}
+				}else{
+					//at the start of original Paragraph, insert before original Paragraph
+					delete(index, leftLength, rightparentElement);
+					Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+					TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+					paragraphContainer = document.insertParagraph(orgparagraph, sourceParagraph, true);					
+				}
+			}
+			else if(nodeLength==(index+leftLength)){
+				//at the end of original Paragraph, insert after original Paragraph
+				delete(index, leftLength, rightparentElement);
+				Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+				TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+				paragraphContainer = document.insertParagraph(orgparagraph, sourceParagraph, false);
+			}else{
+				//at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+				delete(index, leftLength, rightparentElement);
+				Node leftparentElement = rightparentElement.cloneNode(true);
+				rightparentElement.getParentNode().insertBefore(leftparentElement,rightparentElement);
+				nodeLength = TextExtractor.getText((OdfElement) leftparentElement).length();
+				delete(index, nodeLength-index, leftparentElement);
+				delete(0, index, rightparentElement);
+				Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+				TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+				paragraphContainer = document.insertParagraph(orgparagraph, sourceParagraph, true);
+				
+			}
+		} else{
+			TextDocument document = (TextDocument)paragraphContainer.getOwnerDocument();
+			Paragraph tmp = document.insertParagraph(paragraphContainer, sourceParagraph, true);
+			paragraphContainer.remove();
+			paragraphContainer=tmp;
+		}
+	}
+}

Added: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TableSelection.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TableSelection.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TableSelection.java (added)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TableSelection.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,245 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
+import org.odftoolkit.odfdom.dom.element.table.TableTableElement;
+import org.odftoolkit.odfdom.dom.element.text.TextParagraphElementBase;
+import org.odftoolkit.odfdom.dom.element.text.TextSElement;
+import org.odftoolkit.odfdom.pkg.OdfElement;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.common.TextExtractor;
+import org.odftoolkit.simple.table.Table;
+import org.odftoolkit.simple.text.Paragraph;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * This is a decorator class of TextSelection, which help user replace a text content with a Table.
+ * 
+ */
+public class TableSelection extends Selection {
+
+	private TextSelection textSelection;
+	private Table tableContainer;
+	private Table sourceTable;
+	
+	/**
+	 * Replace the content with a Table , the table can be in the same TextDocument or in a different Document.
+	 * 
+	 * @param paragraph the reference table to replace.
+	 * 
+	 * @return the new Table in the TextDocument
+	 */
+	public Table replaceWithTable(Table table) {
+		this.sourceTable=table;
+		int leftLength = textSelection.getText().length();
+		int index = textSelection.getIndex();
+		preparetableContainer(leftLength, index);
+		return tableContainer;
+	}
+
+	/**
+	 * Construct a TableSelection with TextSelection. Then user can replace text
+	 * content with {@link org.odftoolkit.simple.table.Table table}.
+	 * 
+	 * @param selection
+	 *            the TextSelection to be decorated.
+	 */
+	public TableSelection(TextSelection selection) {
+		textSelection = selection;
+		tableContainer = null;
+	}
+
+	/**
+	 * Delete the selection from the document the other matched selection in the
+	 * same container element will be updated automatically because the start
+	 * index of the following selections will be changed when the previous
+	 * selection has been deleted.
+	 * 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void cut() throws InvalidNavigationException {
+		textSelection.cut();
+	}
+
+	/**
+	 * Paste this selection just after a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtEndOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtEndOf(positionItem);
+	}
+	private void delete(int fromIndex, int leftLength, Node pNode) {
+		if ((fromIndex == 0) && (leftLength == 0)) {
+			return;
+		}
+		int nodeLength = 0;
+		Node node = pNode.getFirstChild();
+		while (node != null) {
+			if ((fromIndex == 0) && (leftLength == 0)) {
+				return;
+			}
+			if (node.getNodeType() == Node.TEXT_NODE) {
+				nodeLength = node.getNodeValue().length();
+			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+				// text:s
+				if (node.getLocalName().equals("s")) {
+					try {
+						nodeLength = Integer.parseInt(((Element) node).getAttributeNS(OdfDocumentNamespace.TEXT
+								.getUri(), "c"));
+					} catch (Exception e) {
+						nodeLength = 1;
+					}
+				} else if (node.getLocalName().equals("line-break")) {
+					nodeLength = 1;
+				} else if (node.getLocalName().equals("tab")) {
+					nodeLength = 1;
+				} else {
+					nodeLength = TextExtractor.getText((OdfElement) node).length();
+				}
+			}
+			if (nodeLength <= fromIndex) {
+				fromIndex -= nodeLength;
+			} else {
+				// the start index is in this node
+				if (node.getNodeType() == Node.TEXT_NODE) {
+					String value = node.getNodeValue();
+					StringBuffer buffer = new StringBuffer();
+					buffer.append(value.substring(0, fromIndex));
+					int endLength = fromIndex + leftLength;
+					int nextLength = value.length() - endLength;
+					fromIndex = 0;
+					if (nextLength >= 0) {
+						// delete the result
+						buffer.append(value.substring(endLength, value.length()));
+						leftLength = 0;
+					} else {
+						leftLength = endLength - value.length();
+					}
+					node.setNodeValue(buffer.toString());
+
+				} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+					// if text:s?????????
+					// text:s
+					if (node.getLocalName().equals("s")) {
+						// delete space
+						((TextSElement) node).setTextCAttribute(new Integer(nodeLength - fromIndex));
+						leftLength = leftLength - (nodeLength - fromIndex);
+						fromIndex = 0;
+					} else if (node.getLocalName().equals("line-break") || node.getLocalName().equals("tab")) {
+						fromIndex = 0;
+						leftLength--;
+					} else {
+						delete(fromIndex, leftLength, node);
+						int length = (fromIndex + leftLength) - nodeLength;
+						leftLength = length > 0 ? length : 0;
+						fromIndex = 0;
+					}
+				}
+			}
+			node = node.getNextSibling();
+		}
+	}
+
+	/**
+	 * Paste this selection just before a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtFrontOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtFrontOf(positionItem);
+	}
+
+	protected void refresh(int offset) {
+		textSelection.refresh(offset);
+	}
+
+	protected void refreshAfterFrontalDelete(Selection deletedItem) {
+		textSelection.refreshAfterFrontalDelete(deletedItem);
+	}
+
+	protected void refreshAfterFrontalInsert(Selection insertedItem) {
+		textSelection.refreshAfterFrontalInsert(insertedItem);
+	}
+
+	private void preparetableContainer(int leftLength, int index) {
+		if (tableContainer == null) {
+			OdfElement rightparentElement = textSelection.getContainerElement();
+			int nodeLength = TextExtractor.getText(rightparentElement).length();
+			if(index==0){
+				
+				if(leftLength==nodeLength){
+					//Replace whole Paragraph
+					Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+					TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+					tableContainer = document.insertTable(orgparagraph, sourceTable, false);
+					NodeList cnl = rightparentElement.getChildNodes();
+					for(int i=0;i<cnl.getLength();i++){
+						rightparentElement.removeChild(cnl.item(i));
+					}
+					
+				}else{
+					//at the start of original Paragraph, insert before original Paragraph
+					delete(index, leftLength, rightparentElement);
+					Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+					TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+					tableContainer = document.insertTable(orgparagraph, sourceTable, true);					
+				}
+			}
+			else if(nodeLength==(index+leftLength)){
+				//at the end of original Paragraph, insert after original Paragraph
+				delete(index, leftLength, rightparentElement);
+				Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+				TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+				tableContainer =document.insertTable(orgparagraph, sourceTable,false);
+			}else{
+				//at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+				delete(index, leftLength, rightparentElement);
+				Node leftparentElement = rightparentElement.cloneNode(true);
+				rightparentElement.getParentNode().insertBefore(leftparentElement,rightparentElement);
+				nodeLength = TextExtractor.getText((OdfElement) leftparentElement).length();
+				delete(index, nodeLength-index, leftparentElement);
+				delete(0, index, rightparentElement);
+				Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase)rightparentElement);
+				TextDocument document = (TextDocument)orgparagraph.getOwnerDocument();
+				tableContainer =  document.insertTable(orgparagraph, sourceTable, true);
+			}
+		} else{
+			TextDocument document = (TextDocument)tableContainer.getOwnerDocument();
+			TableTableElement newTEle =(TableTableElement) document.insertOdfElement(tableContainer.getOdfElement(),tableContainer.getOwnerDocument(), sourceTable.getOdfElement(), true);
+			tableContainer.getOdfElement().getParentNode().removeChild(tableContainer.getOdfElement());
+			Table table = Table.getInstance(newTEle);
+			tableContainer=table;
+		}
+	}
+}

Added: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextDocumentSelection.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextDocumentSelection.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextDocumentSelection.java (added)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextDocumentSelection.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,296 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+ */
+
+package org.odftoolkit.simple.common.navigation;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
+import org.odftoolkit.odfdom.dom.element.office.OfficeTextElement;
+import org.odftoolkit.odfdom.dom.element.text.TextParagraphElementBase;
+import org.odftoolkit.odfdom.dom.element.text.TextSElement;
+import org.odftoolkit.odfdom.pkg.OdfElement;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.common.TextExtractor;
+import org.odftoolkit.simple.text.Paragraph;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * This is a decorator class of TextSelection, which help user replace a text
+ * content with a TextDocument, all Styles be included.
+ */
+public class TextDocumentSelection extends Selection {
+	
+	private TextSelection textSelection;
+	private TextDocument sourceDocument;
+	
+	/**
+	 * Replace the Searched Content with a TextDocument with Styles.
+	 * <p>
+	 * Note: You need cache the TextNavigation.nextSelection item because after
+	 * you replace currtenTextSelection with TextDocument,
+	 * TextNavigation.nextSelection will search from the inserted Content, it
+	 * will make you into a loop if the Search keyword also can be found in the
+	 * new inserted Content.
+	 * </p>
+	 * The right way to use this replaceWithTextDocument(TextDocument
+	 * textDocument) method should like this: <Code>
+	 * <p>	search = new TextNavigation("SIMPLE", doc);    </p>
+	 * <p>	TextSelection currtenTextSelection,nextTextSelection=null;</p>
+	 * <p>		while (search.hasNext()) {</p>
+	 * <p>			if(nextTextSelection!=null){</p>
+	 * <p>				currtenTextSelection=nextTextSelection;</p>
+	 * <p>			}else {</p>
+	 * <p>			 	currtenTextSelection = (TextSelection) search.nextSelection();</p>
+	 * <p>			}</p>
+	 * <p>			nextTextSelection = (TextSelection) search.nextSelection();</p>
+	 * <p>			if(currtenTextSelection!=null){</p>
+	 * <p>				TextDocumentSelection nextParagraphSelection = new TextDocumentSelection(currtenTextSelection);</p>
+	 * <p>				try {</p>
+	 * <p>					nextParagraphSelection.replaceWithTextDocument(sourcedoc);</p>
+	 * <p>				} catch (Exception e) {</p>
+	 * <p>					e.printStackTrace();</p>
+	 * <p>				}</p>
+	 * <p>			}</p>
+	 * <p>		}</p>
+	 * <p>		if(nextTextSelection!=null){</p>
+	 * <p>			TextDocumentSelection nextParagraphSelection = new TextDocumentSelection(nextTextSelection);</p>
+	 * <p>			try {</p>
+	 * <p>				nextParagraphSelection.replaceWithTextDocument(sourcedoc);</p>
+	 * <p>			} catch (Exception e) {</p>
+	 * <p>				e.printStackTrace();</p>
+	 * <p>			}</p>
+	 * <p>		}</p>
+	 * </Code>
+	 * 
+	 * @param textDocument
+	 *            the reference TextDocument to replace.
+	 * @throws Exception
+	 */
+	public void replaceWithTextDocument(TextDocument textDocument) throws Exception {
+		this.sourceDocument = textDocument;
+		int leftLength = textSelection.getText().length();
+		int index = textSelection.getIndex();
+		prepareParagraphContainer(leftLength, index);
+	}
+	
+	/**
+	 * Construct a TextDocumentSelection with TextSelection. Then user can
+	 * replace text content with a TextDocument.
+	 * 
+	 * @param selection
+	 *            the TextSelection to be decorated.
+	 */
+	public TextDocumentSelection(TextSelection selection) {
+		textSelection = selection;
+	}
+	
+	/**
+	 * Delete the selection from the document the other matched selection in the
+	 * same container element will be updated automatically because the start
+	 * index of the following selections will be changed when the previous
+	 * selection has been deleted.
+	 * 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void cut() throws InvalidNavigationException {
+		textSelection.cut();
+	}
+	
+	/**
+	 * Paste this selection just after a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtEndOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtEndOf(positionItem);
+	}
+	
+	private void delete(int fromIndex, int leftLength, Node pNode) {
+		if ((fromIndex == 0) && (leftLength == 0)) {
+			return;
+		}
+		int nodeLength = 0;
+		Node node = pNode.getFirstChild();
+		while (node != null) {
+			if ((fromIndex == 0) && (leftLength == 0)) {
+				return;
+			}
+			if (node.getNodeType() == Node.TEXT_NODE) {
+				nodeLength = node.getNodeValue().length();
+			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+				// text:s
+				if (node.getLocalName().equals("s")) {
+					try {
+						nodeLength = Integer.parseInt(((Element) node).getAttributeNS(OdfDocumentNamespace.TEXT.getUri(), "c"));
+					} catch (Exception e) {
+						nodeLength = 1;
+					}
+				} else if (node.getLocalName().equals("line-break")) {
+					nodeLength = 1;
+				} else if (node.getLocalName().equals("tab")) {
+					nodeLength = 1;
+				} else {
+					nodeLength = TextExtractor.getText((OdfElement) node).length();
+				}
+			}
+			if (nodeLength <= fromIndex) {
+				fromIndex -= nodeLength;
+			} else {
+				// the start index is in this node
+				if (node.getNodeType() == Node.TEXT_NODE) {
+					String value = node.getNodeValue();
+					StringBuffer buffer = new StringBuffer();
+					buffer.append(value.substring(0, fromIndex));
+					int endLength = fromIndex + leftLength;
+					int nextLength = value.length() - endLength;
+					fromIndex = 0;
+					if (nextLength >= 0) {
+						// delete the result
+						buffer.append(value.substring(endLength, value.length()));
+						leftLength = 0;
+					} else {
+						leftLength = endLength - value.length();
+					}
+					node.setNodeValue(buffer.toString());
+					
+				} else if (node.getNodeType() == Node.ELEMENT_NODE) {
+					// if text:s?????????
+					// text:s
+					if (node.getLocalName().equals("s")) {
+						// delete space
+						((TextSElement) node).setTextCAttribute(new Integer(nodeLength - fromIndex));
+						leftLength = leftLength - (nodeLength - fromIndex);
+						fromIndex = 0;
+					} else if (node.getLocalName().equals("line-break") || node.getLocalName().equals("tab")) {
+						fromIndex = 0;
+						leftLength--;
+					} else {
+						delete(fromIndex, leftLength, node);
+						int length = (fromIndex + leftLength) - nodeLength;
+						leftLength = length > 0 ? length : 0;
+						fromIndex = 0;
+					}
+				}
+			}
+			node = node.getNextSibling();
+		}
+	}
+	
+	/**
+	 * Paste this selection just before a specific selection.
+	 * 
+	 * @param positionItem
+	 *            a selection that is used to point out the position
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 */
+	@Override
+	public void pasteAtFrontOf(Selection positionItem) throws InvalidNavigationException {
+		textSelection.pasteAtFrontOf(positionItem);
+	}
+	
+	protected void refresh(int offset) {
+		textSelection.refresh(offset);
+	}
+	
+	protected void refreshAfterFrontalDelete(Selection deletedItem) {
+		textSelection.refreshAfterFrontalDelete(deletedItem);
+	}
+	
+	protected void refreshAfterFrontalInsert(Selection insertedItem) {
+		textSelection.refreshAfterFrontalInsert(insertedItem);
+	}
+	
+	private void prepareParagraphContainer(int leftLength, int index) throws Exception {
+		OdfElement rightparentElement = textSelection.getContainerElement();
+		int nodeLength = TextExtractor.getText(rightparentElement).length();
+		Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase) rightparentElement);
+		
+		TextDocument document = (TextDocument) orgparagraph.getOwnerDocument();
+		OfficeTextElement sroot = sourceDocument.getContentRoot();
+		NodeList clist = sroot.getChildNodes();
+		
+		try {
+			OfficeTextElement documentRoot = document.getContentRoot();
+			Node rootNode = rightparentElement.getParentNode();
+			if (!rootNode.equals(documentRoot)) {
+				throw new RuntimeException(
+						"The ParentNode of text content's ContainerElement which will be replaced is not Document ContentRoot, TextDocument only can be insert to the Docuemnt ContentRoot");
+			}
+		} catch (Exception e) {
+			Logger.getLogger(TextDocumentSelection.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+		}
+		
+		if (index == 0) {
+			if (leftLength == nodeLength) {
+				// Replace whole Paragraph
+				
+				for (int i = 0; i < clist.getLength(); i++) {
+					OdfElement node = (OdfElement) clist.item(i);
+					document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, false);
+				}
+				
+				NodeList cnl = rightparentElement.getChildNodes();
+				for (int i = 0; i < cnl.getLength(); i++) {
+					rightparentElement.removeChild(cnl.item(i));
+				}
+			} else {
+				// at the start of original Paragraph, insert before original
+				// Paragraph
+				delete(index, leftLength, rightparentElement);
+				for (int i = 0; i < clist.getLength(); i++) {
+					OdfElement node = (OdfElement) clist.item(i);
+					document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, true);
+				}
+			}
+		} else if (nodeLength == (index + leftLength)) {
+			// at the end of original Paragraph, insert after original Paragraph
+			delete(index, leftLength, rightparentElement);
+			for (int i = 0; i < clist.getLength(); i++) {
+				OdfElement node = (OdfElement) clist.item(i);
+				document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, false);
+			}
+		} else {
+			// at the middle of original Paragraph, split original Paragraph,
+			// insert before the second Paragraph.
+			delete(index, leftLength, rightparentElement);
+			Node leftparentElement = rightparentElement.cloneNode(true);
+			rightparentElement.getParentNode().insertBefore(leftparentElement, rightparentElement);
+			nodeLength = TextExtractor.getText((OdfElement) leftparentElement).length();
+			delete(index, nodeLength - index, leftparentElement);
+			delete(0, index, rightparentElement);
+			for (int i = 0; i < clist.getLength(); i++) {
+				OdfElement node = (OdfElement) clist.item(i);
+				document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, true);
+			}
+			int offset = 0 - leftLength - index;
+			SelectionManager.refresh(rightparentElement, offset, offset);
+		}
+	}
+}

Modified: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextSelection.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextSelection.java?rev=1406043&r1=1406042&r2=1406043&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextSelection.java (original)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/common/navigation/TextSelection.java Tue Nov  6 05:31:29 2012
@@ -19,6 +19,7 @@ under the License.
 
 package org.odftoolkit.simple.common.navigation;
 
+import java.net.URI;
 import java.net.URL;
 import java.text.SimpleDateFormat;
 import java.util.Date;
@@ -35,9 +36,13 @@ import org.odftoolkit.odfdom.dom.element
 import org.odftoolkit.odfdom.dom.element.office.OfficeAnnotationElement;
 import org.odftoolkit.odfdom.dom.element.style.StyleTextPropertiesElement;
 import org.odftoolkit.odfdom.dom.element.text.TextAElement;
+import org.odftoolkit.odfdom.dom.element.text.TextConditionalTextElement;
 import org.odftoolkit.odfdom.dom.element.text.TextPElement;
+import org.odftoolkit.odfdom.dom.element.text.TextParagraphElementBase;
 import org.odftoolkit.odfdom.dom.element.text.TextSElement;
 import org.odftoolkit.odfdom.dom.element.text.TextSpanElement;
+import org.odftoolkit.odfdom.dom.element.text.TextUserFieldDeclElement;
+import org.odftoolkit.odfdom.dom.element.text.TextVariableDeclElement;
 import org.odftoolkit.odfdom.dom.style.OdfStyleFamily;
 import org.odftoolkit.odfdom.dom.style.props.OdfStylePropertiesSet;
 import org.odftoolkit.odfdom.dom.style.props.OdfStyleProperty;
@@ -49,7 +54,16 @@ import org.odftoolkit.odfdom.incubator.d
 import org.odftoolkit.odfdom.pkg.OdfElement;
 import org.odftoolkit.odfdom.pkg.OdfFileDom;
 import org.odftoolkit.simple.Document;
+import org.odftoolkit.simple.TextDocument;
 import org.odftoolkit.simple.common.TextExtractor;
+import org.odftoolkit.simple.common.field.ConditionField;
+import org.odftoolkit.simple.common.field.Field;
+import org.odftoolkit.simple.common.field.Field.FieldType;
+import org.odftoolkit.simple.common.field.Fields;
+import org.odftoolkit.simple.common.field.VariableField;
+import org.odftoolkit.simple.draw.Image;
+import org.odftoolkit.simple.table.Table;
+import org.odftoolkit.simple.text.Paragraph;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
@@ -224,7 +238,228 @@ public class TextSelection extends Selec
 		SelectionManager.refresh(getContainerElement(), offset, index + getText().length());
 		mMatchedText = newText;
 	}
-
+	
+	/**
+	 * Replace the text content of selection with a new Table.
+	 * 
+	 * @param newTable
+	 *            the replace Table
+	 * @return 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 * @return the new Table in the TextDocument
+	 */
+	public Table replaceWith(Table newTable) throws InvalidNavigationException {
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		TableSelection nextTableSelection=new TableSelection(this);
+		return nextTableSelection.replaceWithTable(newTable);
+	}
+	/**
+	 * Replace the text content of selection with a new Image.
+	 * 
+	 * @param newImage
+	 *            the replace Image
+	 * @return 
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 * @return the new Image in the TextDocument,the image name is set to "replace" + System.currentTimeMillis(), please update the name to others by yourself.
+	 */
+	public Image replaceWith(Image newImage) throws InvalidNavigationException {
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		ImageSelection nextImageSelection=new ImageSelection(this);
+		return nextImageSelection.replaceWithImage(newImage);
+	}
+	/**
+	 * Replace the text content of selection with a new Image.
+	 * 
+	 * @param imageUri
+	 *            the replace Image URI
+	 * @throws InvalidNavigationException
+	 *             if the selection is unavailable.
+	 * @return the new Image in the TextDocument,the image name is set to "replace" + System.currentTimeMillis(), please update the name to others by yourself.
+	 */
+	public Image replaceWith(URI imageUri) throws InvalidNavigationException {
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		ImageSelection nextImageSelection=new ImageSelection(this);
+		return nextImageSelection.replaceWithImage(imageUri);
+	}
+	/**
+	 * Replace the content with a Field
+	 * 
+	 * @param orgField
+	 *            the reference Field to replace.
+     * @throws InvalidNavigationException
+	 *             if the selection is unavailable.   
+	 * @return the created field.         
+	 */
+	public Field replaceWith(Field orgField) throws InvalidNavigationException {
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		Field newfield=null;
+		OdfElement parentElement = getContainerElement();
+		Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase) parentElement);
+		TextDocument document = (TextDocument) orgparagraph.getOwnerDocument();
+		
+		FieldSelection nextFieldSelection=new FieldSelection(this);
+		FieldType fieldType = orgField.getFieldType();
+	
+		switch (fieldType) {
+		case DATE_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case FIXED_DATE_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case TIME_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case FIXED_TIME_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case PREVIOUS_PAGE_NUMBER_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case CURRENT_PAGE_NUMBER_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case NEXT_PAGE_NUMBER_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case PAGE_COUNT_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case TITLE_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case SUBJECT_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case AUTHOR_NAME_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case AUTHOR_INITIALS_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case CHAPTER_FIELD:
+			newfield=nextFieldSelection.replaceWithSimpleField(fieldType);
+			break;
+		case SIMPLE_VARIABLE_FIELD:
+			VariableField SimpleVariableField = (VariableField)orgField;
+			String simplefieldname = SimpleVariableField.getVariableName();
+			VariableField simplefield=Fields.createSimpleVariableField(document, simplefieldname);
+			nextFieldSelection.replaceWithVariableField(simplefield);
+			newfield=simplefield;
+			break;
+		case USER_VARIABLE_FIELD:
+			VariableField userVariableField = (VariableField)orgField;
+			TextUserFieldDeclElement textUserFieldDeclElement =(TextUserFieldDeclElement) userVariableField.getOdfElement();
+			String fieldname = userVariableField.getVariableName();
+			String value=textUserFieldDeclElement.getOfficeStringValueAttribute();
+			VariableField variableField=Fields.createUserVariableField(document, fieldname,value);
+			nextFieldSelection.replaceWithVariableField(variableField);
+			newfield=variableField;
+			break;
+		case CONDITION_FIELD:
+			ConditionField conditionField = (ConditionField)orgField;
+			TextConditionalTextElement textConditionalTextElement =(TextConditionalTextElement) conditionField.getOdfElement();
+			String StringValueIfFalse=textConditionalTextElement.getTextStringValueIfFalseAttribute();
+			String StringValueIfTrue=textConditionalTextElement.getTextStringValueIfTrueAttribute();
+			String StringCondition=textConditionalTextElement.getTextConditionAttribute();
+			boolean CurrentValue=textConditionalTextElement.getTextCurrentValueAttribute();
+			ConditionField newdConditionField = nextFieldSelection.replaceWithConditionField(StringCondition, StringValueIfTrue, StringValueIfFalse);
+			TextConditionalTextElement newTextConditionalTextElement=(TextConditionalTextElement)newdConditionField.getOdfElement();
+			newTextConditionalTextElement.setTextCurrentValueAttribute(CurrentValue);
+			newfield=newdConditionField;
+			break;
+		case HIDDEN_TEXT_FIELD:
+			ConditionField conditionFieldHIDDEN = (ConditionField)orgField;
+			TextConditionalTextElement textConditionalTextElementHIDDEN =(TextConditionalTextElement) conditionFieldHIDDEN.getOdfElement();
+			String StringValueIfFalseHIDDEN=textConditionalTextElementHIDDEN.getTextStringValueIfFalseAttribute();
+			String StringConditionHIDDEN=textConditionalTextElementHIDDEN.getTextConditionAttribute();
+			boolean CurrentValueHIDDEN=textConditionalTextElementHIDDEN.getTextCurrentValueAttribute();
+			ConditionField newdConditionFieldHIDDEN = nextFieldSelection.replaceWithHiddenTextField(StringConditionHIDDEN, StringValueIfFalseHIDDEN);
+			TextConditionalTextElement newTextConditionalTextElementHIDDEN=(TextConditionalTextElement)newdConditionFieldHIDDEN.getOdfElement();
+			newTextConditionalTextElementHIDDEN.setTextCurrentValueAttribute(CurrentValueHIDDEN);
+			newfield=newdConditionFieldHIDDEN;
+			break;
+		case REFERENCE_FIELD:
+		default: throw new IllegalArgumentException("Simple Java API for ODF doesn't support this type now.");
+		}
+		return newfield;
+	}
+	
+	/**
+	 * Replace the content with a paragraph, the paragraph can be in the same TextDocument or in a different Document.
+	 * 
+	 * @param newParagraph
+	 *            the reference paragraph to replace.
+     * @throws InvalidNavigationException
+	 *             if the selection is unavailable.   
+	 * @return the replaced Paragraph.             
+	 */
+	public Paragraph replaceWith(Paragraph newParagraph) throws InvalidNavigationException {
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		ParagraphSelection nextParagraphSelection=new ParagraphSelection(this);
+		return nextParagraphSelection.replaceWithParagraph(newParagraph);
+	}
+	/**
+	 * Replace the content with a TextDocument with Styles.
+	 * Note: You need cache the TextNavigation.nextSelection item because after
+	 * you replace currtenTextSelection with TextDocument, TextNavigation.nextSelection will search from the inserted Content, 
+	 * it will make you into a loop if the Search keyword also can be found in the new inserted Content.
+	 * </p>
+	 * The right way to use this replaceWithTextDocument(TextDocument textDocument) method should like this: 
+	 * <Code>
+	 * <p>	search = new TextNavigation("SIMPLE", doc);    </p>
+	 * <p>	TextSelection currtenTextSelection,nextTextSelection=null;</p>
+	 * <p>		while (search.hasNext()) {</p>
+	 * <p>			if(nextTextSelection!=null){</p>
+	 * <p>				currtenTextSelection=nextTextSelection;</p>
+	 * <p>			}else {</p>
+	 * <p>			 	currtenTextSelection = (TextSelection) search.nextSelection();</p>
+	 * <p>			}</p>
+	 * <p>			nextTextSelection = (TextSelection) search.nextSelection();</p>
+	 * <p>			if(currtenTextSelection!=null){</p>
+	 * <p>				try {</p>
+	 * <p>					nextTextSelection.replaceWithTextDocument(sourcedoc);</p>
+	 * <p>				} catch (Exception e) {</p>
+	 * <p>					e.printStackTrace();</p>
+	 * <p>				}</p>
+	 * <p>			}</p>
+	 * <p>		}</p>
+	 * <p>		if(nextTextSelection!=null){</p>
+	 * <p>			try {</p>
+	 * <p>				nextTextSelection.replaceWithTextDocument(sourcedoc);</p>
+	 * <p>			} catch (Exception e) {</p>
+	 * <p>				e.printStackTrace();</p>
+	 * <p>			}</p>
+	 * <p>		}</p>
+	 * </Code>
+	 * 
+	 * @param newTextDocument
+	 *            the reference TextDocument to replace.
+	 * @throws InvalidNavigationException 
+	 */
+	public void replaceWith(TextDocument newTextDocument) throws InvalidNavigationException{
+		if (validate() == false) {
+			throw new InvalidNavigationException("No matched string at this position");
+		}
+		TextDocumentSelection nextTextDocumentSelection=new TextDocumentSelection(this);
+		try {
+			nextTextDocumentSelection.replaceWithTextDocument(newTextDocument);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
 	/**
 	 * Create a span element for this text selection.
 	 * 

Modified: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/draw/Image.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/draw/Image.java?rev=1406043&r1=1406042&r2=1406043&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/draw/Image.java (original)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/draw/Image.java Tue Nov  6 05:31:29 2012
@@ -254,7 +254,7 @@ public class Image extends Component {
 	}
 
 	/* Helper method */
-	private static String getPackagePath(OdfSchemaDocument mOdfSchemaDoc, String imageRef) {
+	public static String getPackagePath(OdfSchemaDocument mOdfSchemaDoc, String imageRef) {
 		if (imageRef.contains(SLASH)) {
 			imageRef = imageRef.substring(imageRef.lastIndexOf(SLASH) + 1, imageRef.length());
 		}
@@ -263,7 +263,7 @@ public class Image extends Component {
 	}
 
 	/* Helper method */
-	private static URI configureInsertedImage(OdfSchemaDocument mOdfSchemaDoc, DrawImageElement imageElement,
+	public static URI configureInsertedImage(OdfSchemaDocument mOdfSchemaDoc, DrawImageElement imageElement,
 			String packagePath, boolean isResetSize) throws Exception {
 		// Set path to image attribute
 		URI uri = new URI(AnyURI.encodePath(packagePath).toString());

Modified: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/field/VariableFieldTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/field/VariableFieldTest.java?rev=1406043&r1=1406042&r2=1406043&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/field/VariableFieldTest.java (original)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/field/VariableFieldTest.java Tue Nov  6 05:31:29 2012
@@ -28,6 +28,7 @@ import org.junit.Test;
 import org.odftoolkit.odfdom.dom.element.text.TextSpanElement;
 import org.odftoolkit.simple.TextDocument;
 import org.odftoolkit.simple.common.field.Field.FieldType;
+import org.odftoolkit.simple.common.navigation.FieldSelectionTest;
 import org.odftoolkit.simple.utils.ResourceUtilities;
 
 public class VariableFieldTest {
@@ -60,6 +61,15 @@ public class VariableFieldTest {
 			FieldType fieldType = simpleVariableField.getFieldType();
 			Assert.assertNotNull(fieldType);
 			Assert.assertEquals(FieldType.SIMPLE_VARIABLE_FIELD, fieldType);
+			newTextSpanElement = doc.newParagraph("Show Simple Variable Field:").newTextSpanElement();
+			simpleVariableField.displayField(newTextSpanElement);
+			simpleVariableField.updateField("aaaa", newTextSpanElement);
+			try {
+				doc.save(ResourceUtilities.newTestOutputFile("TextFieldSampleDocumentVariableField.odt"));
+			} catch (Exception e) {
+				Logger.getLogger(FieldSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+				Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+			}
 		} catch (Exception e) {
 			LOG.log(Level.SEVERE, e.getMessage(), e);
 			Assert.fail(e.getMessage());

Added: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ImageSelectionTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ImageSelectionTest.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ImageSelectionTest.java (added)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ImageSelectionTest.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,164 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import java.net.URI;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.odftoolkit.odfdom.dom.element.draw.DrawImageElement;
+import org.odftoolkit.odfdom.dom.element.text.TextParagraphElementBase;
+import org.odftoolkit.simple.Document;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.draw.Image;
+import org.odftoolkit.simple.text.Paragraph;
+import org.odftoolkit.simple.utils.ResourceUtilities;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Test the method of class
+ * org.odftoolkit.simple.common.navigation.ImageSelection
+ */
+public class ImageSelectionTest {
+
+	private static final String TEXT_FILE = "TestTextSelection.odt";
+	TextDocument doc,sourcedoc;
+	TextNavigation search;
+	private Image image2;
+
+	@BeforeClass
+	public static void setUpClass() throws Exception {
+	}
+
+	@AfterClass
+	public static void tearDownClass() throws Exception {
+	}
+
+	@Before
+	public void setUp() {
+		try {
+			doc = (TextDocument) Document.loadDocument(ResourceUtilities.getAbsolutePath(TEXT_FILE));
+			sourcedoc=TextDocument.newTextDocument();
+			Paragraph para = sourcedoc.addParagraph("helloImage");
+			Image image = Image.newImage(para, ResourceUtilities.getURI("image_list_item.png"));
+			image.setName("this image 1");
+			image.setHyperlink(new URI("http://odftoolkit.org"));
+			
+			Paragraph para2 = sourcedoc.addParagraph("helloImage2");
+			image2 = Image.newImage(para2, ResourceUtilities.getURI("testA.jpg"));
+			image2.setName("this image 2");
+			image2.setHyperlink(new URI("http://odftoolkit.org"));
+			
+			
+		} catch (Exception e) {
+			Logger.getLogger(ImageSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+
+	@After
+	public void tearDown() {
+	}
+	/**
+	 * Test ReplaceWithImage method of
+	 * org.odftoolkit.simple.common.navigation.ImageSelection replace "SIMPLE" to a Image from Document
+	 */
+	@Test
+	public void testReplaceWithImage() {
+		search = null;
+		//6 Simple, at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+		search = new TextNavigation("SIMPLE", doc);
+		int i=0;
+		try {
+			ImageSelection nextImageSelection=null;
+			while (search.hasNext()) {
+				TextSelection item= (TextSelection) search.nextSelection();
+				nextImageSelection=new ImageSelection(item);
+				Paragraph paragraph=sourcedoc.getParagraphByIndex(0, true);
+				TextParagraphElementBase textParaEleBase = paragraph.getOdfElement();
+				NodeList nodeImages = textParaEleBase.getElementsByTagName("draw:image");
+				Node nodeImage = nodeImages.item(0);
+				DrawImageElement im = (DrawImageElement)nodeImage;
+				Image ima = Image.getInstanceof(im);
+				Image image = nextImageSelection.replaceWithImage(ima);
+				Assert.assertNotNull(image);
+				if(image.getName().startsWith("replace")){
+					Assert.assertTrue(true);
+				}else{
+					Assert.fail();
+				}
+				String name="simple"+(i++);
+				image.setName(name);
+				Assert.assertEquals(name,image.getName());
+		}
+			Image image =nextImageSelection.replaceWithImage(image2);
+			image.setName("simpletwice");
+			Assert.assertEquals("simpletwice",image.getName());
+		doc.save(ResourceUtilities.newTestOutputFile("TestImageSelectionImageResult.odt"));
+		} catch (Exception e) {
+			Logger.getLogger(ImageSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+	/**
+	 * Test ReplaceWithImage method of
+	 * org.odftoolkit.simple.common.navigation.ImageSelection replace "SIMPLE" to a Image from Image URI
+	 */
+	@Test
+	public void testReplaceWithImageURI() {
+		search = null;
+		//6 Simple, at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+		search = new TextNavigation("SIMPLE", doc);
+		int i=0;
+		try {
+			ImageSelection nextImageSelection=null;
+			while (search.hasNext()) {
+				TextSelection item= (TextSelection) search.nextSelection();
+				nextImageSelection=new ImageSelection(item);
+				URI imageuri = ResourceUtilities.getURI("image_list_item.png");
+				Image image = nextImageSelection.replaceWithImage(imageuri);
+				Assert.assertNotNull(image);
+				if(image.getName().startsWith("replace")){
+					Assert.assertTrue(true);
+				}else{
+					Assert.fail();
+				}
+				String name="simple"+(i++);
+				image.setName(name);
+				Assert.assertEquals(name,image.getName());
+		}
+			URI imageuri =  ResourceUtilities.getURI("testA.jpg");
+			Image image =nextImageSelection.replaceWithImage(imageuri);
+			image.setName("simpletwice");
+			Assert.assertEquals("simpletwice",image.getName());
+		doc.save(ResourceUtilities.newTestOutputFile("TestImageSelectionURIResult.odt"));
+		} catch (Exception e) {
+			Logger.getLogger(ImageSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+}

Added: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ParagraphSelectionTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ParagraphSelectionTest.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ParagraphSelectionTest.java (added)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/ParagraphSelectionTest.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,140 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.odftoolkit.simple.Document;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.text.Paragraph;
+import org.odftoolkit.simple.utils.ResourceUtilities;
+
+/**
+ * Test the method of class
+ * org.odftoolkit.simple.common.navigation.ParagraphSelection
+ */
+public class ParagraphSelectionTest {
+
+	private static final String TEXT_FILE = "TestTextSelection.odt";
+	TextDocument doc,sourcedoc;
+	TextNavigation search;
+
+	@BeforeClass
+	public static void setUpClass() throws Exception {
+	}
+
+	@AfterClass
+	public static void tearDownClass() throws Exception {
+	}
+
+	@Before
+	public void setUp() {
+		try {
+			doc = (TextDocument) Document.loadDocument(ResourceUtilities.getAbsolutePath(TEXT_FILE));
+			sourcedoc=TextDocument.newTextDocument();
+			sourcedoc.addParagraph("Hello1 from SIMPLE source document!");
+			sourcedoc.addParagraph("Hello2 from source document!");
+			sourcedoc.addParagraph("Hello3 from source document!");
+		} catch (Exception e) {
+			Logger.getLogger(ParagraphSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+
+	@After
+	public void tearDown() {
+	}
+	/**
+	 * Test ReplaceWithParagraph method of
+	 * org.odftoolkit.simple.common.navigation.ParagraphSelection replace "SIMPLE","Task1","Container" to different Paragraph
+	 */
+	@Test
+	public void testReplaceWithParagraph() {
+		search = null;
+		//6 Simple, at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+		search = new TextNavigation("SIMPLE", doc);
+		int i = 0;
+		while (search.hasNext()) {
+				TextSelection item = (TextSelection) search.nextSelection();
+				ParagraphSelection nextParagraphSelection=new ParagraphSelection(item);
+				Paragraph paragraph=sourcedoc.getParagraphByIndex(0, true);
+				nextParagraphSelection.replaceWithParagraph(paragraph);
+			i++;
+		}
+		search = new TextNavigation("Hello1 from SIMPLE source document!", doc);
+		int j = 0;
+		while (search.hasNext()) {
+			search.nextSelection();
+			j++;
+		}
+		Assert.assertTrue(i == j);
+		
+		//2 Task1, #1 at the start of original Paragraph, #2 replace original Paragraph  
+				search = new TextNavigation("Task1", doc);
+				 i = 0;
+				while (search.hasNext()) {
+						TextSelection item = (TextSelection) search.nextSelection();
+						ParagraphSelection nextParagraphSelection=new ParagraphSelection(item);
+						Paragraph paragraph=sourcedoc.getParagraphByIndex(1, true);
+						nextParagraphSelection.replaceWithParagraph(paragraph);
+					i++;
+				}
+				search = new TextNavigation("Hello2 from source document!", doc);
+				 j = 0;
+				while (search.hasNext()) {
+					search.nextSelection();
+					j++;
+				}
+				Assert.assertTrue(i == j);
+		
+				//1 Container, #1 at the end of original Paragraph, 
+				search = new TextNavigation("Container", doc);
+				 i = 0;
+				while (search.hasNext()) {
+						TextSelection item = (TextSelection) search.nextSelection();
+						ParagraphSelection nextParagraphSelection=new ParagraphSelection(item);
+						Paragraph paragraph=sourcedoc.getParagraphByIndex(2, true);
+						nextParagraphSelection.replaceWithParagraph(paragraph);
+					i++;
+				}
+				search = new TextNavigation("Hello3 from source document!", doc);
+				 j = 0;
+				while (search.hasNext()) {
+					search.nextSelection();
+					j++;
+				}
+				Assert.assertTrue(i == j);
+				
+				
+		try {
+			doc.save(ResourceUtilities.newTestOutputFile("TestParagraphSelectionResult.odt"));
+		} catch (Exception e) {
+			Logger.getLogger(ParagraphSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+}

Added: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TableSelectionTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TableSelectionTest.java?rev=1406043&view=auto
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TableSelectionTest.java (added)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/common/navigation/TableSelectionTest.java Tue Nov  6 05:31:29 2012
@@ -0,0 +1,190 @@
+/* 
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+package org.odftoolkit.simple.common.navigation;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.odftoolkit.simple.Document;
+import org.odftoolkit.simple.TextDocument;
+import org.odftoolkit.simple.table.Cell;
+import org.odftoolkit.simple.table.Table;
+import org.odftoolkit.simple.utils.ResourceUtilities;
+
+/**
+ * Test the method of class
+ * org.odftoolkit.simple.common.navigation.TableSelection
+ */
+public class TableSelectionTest {
+
+	private static final String TEXT_FILE = "TestTextSelection.odt";
+	TextDocument doc,sourcedoc;
+	TextNavigation search;
+
+	@BeforeClass
+	public static void setUpClass() throws Exception {
+	}
+
+	@AfterClass
+	public static void tearDownClass() throws Exception {
+	}
+
+	@Before
+	public void setUp() {
+		try {
+			doc = (TextDocument) Document.loadDocument(ResourceUtilities.getAbsolutePath(TEXT_FILE));
+			sourcedoc=TextDocument.newTextDocument();
+			
+			String tablename = "Table1";
+			int rowcount = 7, columncount = 5;
+			String[][] data = new String[rowcount][columncount];
+			for (int i = 0; i < rowcount; i++) {
+				for (int j = 0; j < columncount; j++) {
+					data[i][j] = "string" + (i * columncount + j);
+				}
+			}
+
+			String[] rowlabels = new String[rowcount];
+			for (int i = 0; i < rowcount; i++) {
+				rowlabels[i] = "RowHeader" + i;
+			}
+
+			String[] columnlabels = new String[columncount];
+			for (int i = 0; i < columncount; i++) {
+				columnlabels[i] = "ColumnHeader" + i;
+			}
+			Table table = Table.newTable(sourcedoc, rowlabels, columnlabels, data);
+			table.setTableName(tablename);
+			
+			
+			String tablename2 = "Table2";
+			int rowcount2 = 10, columncount2 = 4;
+			double[][] data2 = new double[rowcount2][columncount2];
+			for (int i = 0; i < rowcount2; i++) {
+				for (int j = 0; j < columncount2; j++) {
+					data2[i][j] = Math.random();
+				}
+			}
+
+			String[] rowlabels2 = new String[rowcount2];
+			for (int i = 0; i < rowcount2; i++) {
+				rowlabels2[i] = "RowHeader" + i;
+			}
+
+			String[] columnlabels2 = new String[columncount2];
+			for (int i = 0; i < columncount2; i++) {
+				columnlabels2[i] = "ColumnHeader" + i;
+			}
+
+			Table table2 = Table.newTable(sourcedoc, rowlabels2, columnlabels2, data2);
+			table2.setTableName(tablename2);
+			
+			String tablename3 = "Table3";
+			int rownumber3 = 5;
+			int clmnumber3 = 3;
+
+			Table table1 = Table.newTable(sourcedoc, rownumber3, clmnumber3);
+			table1.setTableName(tablename3);
+			sourcedoc.save(ResourceUtilities.newTestOutputFile("TestTableSelectionSource.odt"));
+		} catch (Exception e) {
+			Logger.getLogger(TableSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+
+	@After
+	public void tearDown() {
+	}
+	/**
+	 * Test replaceWithTable method of
+	 * org.odftoolkit.simple.common.navigation.TableSelection replace replace SIMPLE,Task1,Container to different Table
+	 */
+	@Test
+	public void testReplaceWithTable() {
+		search = null;
+		//6 Simple, at the middle of original Paragraph, split original Paragraph, insert before the second Paragraph.
+		search = new TextNavigation("SIMPLE", doc);
+		
+		while (search.hasNext()) {
+				TextSelection item = (TextSelection) search.nextSelection();
+				TableSelection nextTableSelection=new TableSelection(item);
+				Table table=sourcedoc.getTableByName("Table1");
+				Cell cell = table.getCellByPosition(0, 0);
+				cell.setStringValue("SIMPLE");
+				Table newtable = nextTableSelection.replaceWithTable(table);
+				Assert.assertNotNull(newtable);
+				Assert.assertEquals(1, newtable.getHeaderColumnCount());
+				Assert.assertEquals(1, newtable.getHeaderRowCount());
+				Assert.assertEquals(7 + 1, newtable.getRowCount());
+				Assert.assertEquals(5 + 1, newtable.getColumnCount());
+				cell = newtable.getCellByPosition(1, 1);
+				Assert.assertEquals("string", cell.getValueType());
+		}
+	
+		
+		//2 Task1, #1 at the start of original Paragraph, #2 replace original Paragraph  
+				search = new TextNavigation("Task1", doc);
+				 
+				while (search.hasNext()) {
+						TextSelection item = (TextSelection) search.nextSelection();
+						TableSelection nextTableSelection=new TableSelection(item);
+						Table table=sourcedoc.getTableByName("Table2");
+						Table newtable = nextTableSelection.replaceWithTable(table);
+						Cell cell = newtable.getCellByPosition(0, 0);
+						cell.setStringValue("From Source Table2");
+						Assert.assertNotNull(newtable);
+						Assert.assertEquals(1, newtable.getHeaderColumnCount());
+						Assert.assertEquals(1, newtable.getHeaderRowCount());
+						Assert.assertEquals(10 + 1, newtable.getRowCount());
+						Assert.assertEquals(4 + 1, newtable.getColumnCount());
+						
+						cell = newtable.getCellByPosition(1, 1);
+						Assert.assertEquals("float", cell.getValueType());
+				}		
+				//1 RESS%>, #1 at the end of original Paragraph, 
+				search = new TextNavigation("RESS%>", doc);
+
+				while (search.hasNext()) {
+						TextSelection item = (TextSelection) search.nextSelection();
+						TableSelection nextTableSelection=new TableSelection(item);
+						Table table=sourcedoc.getTableByName("Table3");
+						Table newtable = nextTableSelection.replaceWithTable(table);
+						Cell cell = newtable.getCellByPosition(0, 0);
+						cell.setStringValue("From Source Table3");
+						Assert.assertNotNull(newtable);
+						Assert.assertEquals(5, newtable.getRowCount());
+						Assert.assertEquals(3, newtable.getColumnCount());
+
+				}				
+				
+		try {
+			doc.save(ResourceUtilities.newTestOutputFile("TestTableSelectionResult.odt"));
+		} catch (Exception e) {
+			Logger.getLogger(TableSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e);
+			Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'");
+		}
+	}
+}



Mime
View raw message