⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 codetemplate.java

📁 具有不同语法高亮的编辑器实例
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	 * Used in parsing an XML document containing a template.  This method
	 * initializes this template with the data contained in the passed-in node.
	 *
	 * @param template The template to initialize.
	 * @param node The root node of the parsed XML document.
	 * @return <code>true</code> if the template initialization went okay;
	 *         <code>false</code> if an error occured.
	 */
	private static boolean initializeFromXMLFile(CodeTemplate template,
										Node node) {

		/*
		 * This method expects the XML document to be in the following format:
		 *
		 * <?xml version="1.0" encoding="UTF-8" ?>
		 * <macro>
		 *    <macroName>test</macroName>
		 *    <action id="default-typed">abcdefg</action>
		 *    [<action id=...>...</action>]
		 *    ...
		 * </macro>
		 *
		 */

		if (node==null)
			return false;

		int type = node.getNodeType();
		switch (type) {

			// Handle document nodes.
			case Node.DOCUMENT_NODE:
				boolean rc = initializeFromXMLFile(
					template, ((Document)node).getDocumentElement());
				if (rc==false)
					return false;
				break;

			// Handle element nodes.
			case Node.ELEMENT_NODE:

				String nodeName = node.getNodeName();

				if (nodeName.equals(ROOT_ELEMENT)) {
					NodeList childNodes = node.getChildNodes();
					// Will be > 3 due to whitespace nodes.
					if (childNodes==null || childNodes.getLength()<3) {
						return false;
					}
					int childCount = childNodes.getLength();
					for (int i=0; i<childCount; i++) {
						rc = initializeFromXMLFile(template, childNodes.item(i));
						if (rc==false)
							return false;
					}
				}

				else if (nodeName.equals(ID)) {
					NamedNodeMap attributes = node.getAttributes();
					if (attributes==null || attributes.getLength()!=1)
						return false;
					Node node2 = attributes.item(0);
					if (!node2.getNodeName().equals(VALUE)) {
						System.err.println("'value' expected but not found...");
						return false;
					}
					template.id = node2.getNodeValue().toCharArray();
				}

				else if (nodeName.equals(BEFORE_CARET)) {
					NamedNodeMap attributes = node.getAttributes();
					if (attributes==null || attributes.getLength()!=1)
						return false;
					Node node2 = attributes.item(0);
					if (!node2.getNodeName().equals(VALUE)) {
						System.err.println("'value' expected but not found...");
						return false;
					}
					String temp = convertSpecialChars(node2.getNodeValue());
					template.setBeforeCaretText(temp);
				}

				else if (nodeName.equals(AFTER_CARET)) {
					NamedNodeMap attributes = node.getAttributes();
					if (attributes==null || attributes.getLength()!=1)
						return false;
					Node node2 = attributes.item(0);
					if (!node2.getNodeName().equals(VALUE)) {
						System.err.println("'value' expected but not found...");
						return false;
					}
					String temp = convertSpecialChars(node2.getNodeValue());
					template.setAfterCaretText(temp);
				}

				break;

			// Whitespace nodes.
			case Node.TEXT_NODE:
				break;

			// An error occured?
			default:
				System.err.println("... ERROR!!!");
				return false;

		}

		// Everything went okay.
		return true;

	}


/*****************************************************************************/


	/**
	 * Returns whether the specified character is a valid character for a
	 * <code>CodeTemplate</code> id.
	 *
	 * @param ch The character to check.
	 * @return Whether the character is a valid template character.
	 */
	public static final boolean isValidChar(char ch) {
		return RSyntaxUtilities.isLetterOrDigit(ch) || ch=='_';
	}


/*****************************************************************************/


	/**
	 * Returns the <code>CodeTemplate</code> specified in the given
	 * XML file.
	 *
	 * @param xmlFile The XML file from which to load.
	 * @return The <code>CodeTemplate</code> specified, or
	 *         <code>null</code> if the file does not exist or some other
	 *         error occurs.
	 */
	public static CodeTemplate loadFromFile(File xmlFile) {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		Document doc = null;
		try {
			db = dbf.newDocumentBuilder();
			//InputSource is = new InputSource(new FileReader(file));
			InputSource is = new InputSource(new UnicodeReader(
								new FileInputStream(xmlFile), "UTF-8"));
			is.setEncoding("UTF-8");
			doc = db.parse(is);//db.parse(file);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		CodeTemplate template = new CodeTemplate();

		// Traverse the XML tree.
		boolean parsedOK = initializeFromXMLFile(template, doc);
		if (parsedOK==false) {
			return null;
			//throw new IOException("Error parsing XML!");
		}

		// Parsing went okay!
		return template;

	}


/*****************************************************************************/


	/**
	 * Saves this template to the specified file.
	 *
	 * @param xmlFile The file in which to save the template.  If the file
	 *                already exists, it is overwritten.
	 */
	public boolean saveToFile(File xmlFile) throws IOException {
		PrintWriter w = new PrintWriter(
				new BufferedWriter(new FileWriter(xmlFile)));
		w.println("<?xml version=\"1.0\"?>");
		w.println("<template>");
		w.println("   <id value=\"" + new String(id) + "\"/>");
		String bct = getBeforeCaretText().replaceAll("\\n", "\\\\n").
							replaceAll("\\t", "\\\\t");
		w.println("   <beforeCaret value=\"" + bct + "\"/>");
		String act = getAfterCaretText().replaceAll("\\n", "\\\\n").
							replaceAll("\\t", "\\\\t");
		w.println("   <afterCaret value=\"" + act + "\"/>");
		w.println("</template>");
		w.close();
		return true;
	}


/*****************************************************************************/


	/**
	 * Sets the text to place after the caret.
	 *
	 * @param text The text.
	 * @see #getAfterCaretText
	 */
	public void setAfterCaretText(String afterCaret) {
		this.afterCaret = afterCaret;
		updateContainsNewline();
		updateCachedRegex();
	}


/*****************************************************************************/


	/**
	 * Sets the text to place before the caret.
	 *
	 * @param text The text.
	 * @see #getBeforeCaretText
	 */
	public void setBeforeCaretText(String beforeCaret) {
		this.beforeCaret = beforeCaret;
		updateContainsNewline();
		updateCachedRegex();
	}


/*****************************************************************************/


	/**
	 * Returns a string representation of this template for debugging
	 * purposes.
	 *
	 * @return A string representation of this template.
	 */
	public String toString() {
		return "[CodeTemplate: id=" + new String(id) +
			", text=" + beforeCaret + "|" + afterCaret + "]";
	}


/*****************************************************************************/


	/**
	 * Updates the cached regular expression pattern used to match
	 * newlines in our text to insert.
	 */
	private final void updateCachedRegex() {
		matcher = Pattern.compile("\n").matcher(
			getBeforeCaretText() + getAfterCaretText());
	}


/*****************************************************************************/


	/**
	 * Updates our cached value of whether or not this template contains
	 * a newline.
	 */
	private final void updateContainsNewline() {
		containsNewline = false;
		if (beforeCaret!=null && beforeCaret.indexOf("\n")>-1)
			containsNewline = true;
		if (!containsNewline && afterCaret!=null &&
				afterCaret.indexOf("\n")>-1)
			containsNewline = true;
	}


/*****************************************************************************/

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -