Antony Lee的技術(shù)之路
步步為營(yíng) |
Table of Contents
本文翻譯自L(fǎng)ars Vogel的DocBook with Eclipse教程, http://www.vogella.de/articles/DocBook/article.html
在翻譯過(guò)程中,本人保留原文的一切鏈接。
原文一切權(quán)利歸原作者所有,譯文一切權(quán)利歸本人所有。如欲轉(zhuǎn)載原文,請(qǐng)征得作者授權(quán)。如欲轉(zhuǎn)載譯文,請(qǐng)注明本文原始鏈接。
本文的翻譯已獲得原作者授權(quán)。
DocBook是一種文檔標(biāo)準(zhǔn),用以創(chuàng)建結(jié)構(gòu)化的純文本文檔。用DocBook創(chuàng)建的文檔能夠方便的在不同的操作系統(tǒng)之間以及不同的文本處理 工具之間進(jìn)行移植,并可以通過(guò)XSLT 轉(zhuǎn)為其他的輸出格式。XSLT是EXtensible Stylesheet Language Transformation的縮寫(xiě)。 由于DocBook是使用純文本編輯的,因此你可以使用任何一個(gè)文本 編輯器來(lái)編寫(xiě)DocBook,并納入版本控制系統(tǒng)的管理。
目前,有多種不同的樣式表,能夠把DocBook文件轉(zhuǎn)換為不同的輸出格式,例如轉(zhuǎn)換為HTML,pdf,java help以及Unix man pages.
DocBook有兩種主要的文檔,一種是book,另一種是article。其中
Article: 用來(lái)寫(xiě)一些技術(shù)文章,下文都以article為例。article通常是由一系列的section組成。
Book: 用來(lái)寫(xiě)一些更長(zhǎng)的描述。book比article多了一種結(jié)構(gòu):chapter。
下面就是一個(gè)DocBook文檔的例子。
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "../docbook-xml-4.5/docbookx.dtd"> <article> <articleinfo> <title>DocBook Intro</title> <author> <firstname>Lars</firstname> <surname>Vogel</surname> </author> </articleinfo> <sect1 label="1.0"> <title>An introduction to DocBook</title> <para> This is text. </para> </sect1> </article>
請(qǐng)注意,在上面的例子中,DTD文件的位置:當(dāng)前目錄的上一級(jí)目錄,其中的docbook-xml-4.5文件夾內(nèi)。
想要?jiǎng)?chuàng)建DocBook文件并轉(zhuǎn)換成其他格式,你需要以下工具:
DocBook的DTD文件。這個(gè)文件定義了DocBook文檔的格式。
XSLT樣式表,用來(lái)把DocBook文檔轉(zhuǎn)換成其他格式。
XSLT解析器
我們使用Eclipse 作為XML編輯器,Xalan作為XSLT解析器,并使用 Apache Ant 來(lái)進(jìn)行XSLT的轉(zhuǎn)換。
你需要安裝Eclipse,可以參看這篇文章 Eclipse IDE 來(lái)學(xué)習(xí)Eclipse的安裝和使用。我們需要用到的Ant已經(jīng)被集成到Eclipse里面了,因此關(guān)于Ant我們不需要安裝任何額外的東西。
你還需要下載Docbook的DTD,以及用來(lái)轉(zhuǎn)換的Docbook文檔的樣式表。Docbook的DTD可以在 http://www.oasis-open.org/docbook/xml/4.5下載, 而XSLT樣式表可以在 http://docbook.sourceforge.net/ 下載。在寫(xiě)這篇文檔時(shí),最新的版本是“1.75.2”(譯者注:在翻譯這篇文檔時(shí),最新的版本是1.76.1)。你需要下載的docbook-xsl的發(fā)布文件, 例如“docbook-xsl-1.75.2.zip”。
要命的是JVM自帶的XSL處理器在處理XSLT樣式表的時(shí)候有問(wèn)題……所以我們需要從 http://xml.apache.org/xalan-j/ 下載Xalan,用來(lái)作為我們的XSL處理器。
可以在Eclipse中,創(chuàng)建一個(gè)"de.vogella.docbook.first"的新工程,方法是File -> New -> Project,并從彈出的 窗口中選擇General -> Projects.
在工程中創(chuàng)建如下的目錄結(jié)構(gòu):
output : Docbook轉(zhuǎn)換成其他格式時(shí)的輸出目錄
docbook-xml-4.5: 用來(lái)放Docbook的DTD定義文件
docbook-xsl: 用來(lái)放進(jìn)行Docbook轉(zhuǎn)換的樣式表文件
lib: 用來(lái)包含你需要的庫(kù)文件(用來(lái)創(chuàng)建pdf)
documents: 用來(lái)放你的DocBook文件
把DocBook的DTD和XSLT的樣式表放入相應(yīng)的文件夾中。
在lib文件夾下創(chuàng)建xalan文件夾,并把xalan相關(guān)的jar包拷入這個(gè)文件夾中。 結(jié)果應(yīng)該看起來(lái)是這樣的:
在“documents”文件夾里面,創(chuàng)建一個(gè)“book.xml”文件,并輸入下面的xml文件
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "../docbook-xml-4.5/docbookx.dtd"> <article> <articleinfo> <title>DocBook Intro</title> <author> <firstname>Lars</firstname> <surname>Vogel</surname> </author> </articleinfo> <sect1 label="1.0"> <title>An introduction to DocBook</title> <para> This is text. </para> </sect1> </article>
在xml文件中,“../docbook-xml-4.5/docbook.dtd”對(duì)應(yīng)于我們剛剛創(chuàng)建的文件夾以及放入的DTD文件。
接下來(lái)我們配置ANT。在工程目錄中,創(chuàng)建build.xml文件如下:
<?xml version="1.0"?> <!-- - Author: Lars Vogel --> <project name="docbook-src" default="build-html"> <description> This Ant buildhtml.xml file is used to transform DocBook XML to html output </description> <!-- - Configure basic properties that will be used in the file. --> <property name="docbook.xsl.dir" value="docbook-xsl" /> <property name="doc.dir" value="output" /> <property name="documents" value="documents" /> <property name="html.stylesheet" value="${docbook.xsl.dir}/html/docbook.xsl" /> <!-- Making xalan available --> <path id="xalan.class.path"> <pathelement location="lib/xalan/serializer.jar" /> <pathelement location="lib/xalan/xalan.jar" /> <pathelement location="lib/xalan/xercesImpl.jar" /> <pathelement location="lib/xalan/xml-apis.jar" /> </path> <!-- - target: usage --> <target name="usage" description="Prints the Ant build.xml usage"> <echo message="Use -projecthelp to get a list of the available targets." /> </target> <!-- - target: clean --> <target name="clean" description="Cleans up generated files."> <delete dir="${doc.dir}" /> </target> <!-- - target: depends --> <target name="depends"> <mkdir dir="${doc.dir}" /> </target> <!-- - target: build-html - description: Iterates through a directory and transforms - .xml files into .html files using the DocBook XSL. --> <target name="build-html" depends="depends" description="Generates HTML files from DocBook XML"> <xslt style="${html.stylesheet}" extension=".html" basedir="${documents}" destdir="${doc.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="html.stylesheet" expression="style.css" /> <classpath refid="xalan.class.path" /> </xslt> <!-- Copy the stylesheet to the same directory as the HTML files --> <copy todir="${doc.dir}"> <fileset dir="lib"> <include name="style.css" /> </fileset> </copy> </target> </project>
運(yùn)行build.xml文件(右鍵 -> Run As -> Ant Build)。運(yùn)行之后,在你的output文件夾里面, 應(yīng)該已經(jīng)有一個(gè)“book.html”了。
恭喜你完成了第一個(gè)Docbook文檔,并順利的轉(zhuǎn)成了HTML格式!
下面是一些使用Docbook標(biāo)簽的概覽。
Table 1. Docbook一些重要的標(biāo)簽
Tag | 說(shuō)明 |
---|---|
<![CDATA[ 此處可輸入特殊字符,e.g. & ]]> | 在標(biāo)簽中可以輸入某些特殊字符,例如某些xml以及Docbook的特殊字符。 |
<programlisting> </programlisting> | 表示該文本是程序代碼 |
<emphasis> </emphasis> | 表示用強(qiáng)調(diào)(Highlight)該文本 |
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="example1.txt" /> | 包含example1.xml的內(nèi)容。該文件可以是一個(gè)獨(dú)立的xml文件 |
<ulink url="http://www.heise.de/newsticker">German IT News</ulink> [a] | 在文檔中創(chuàng)建一個(gè)超鏈接 |
& | 在文檔中插入“&”符號(hào) |
[a] 譯者注:Docbook5改變了超鏈接的格式。關(guān)于Docbook5以及更詳細(xì)的Eclipse配置Docbook教程,會(huì)很快放出。 不過(guò),即使是在Docbook5的環(huán)境下,使用ulink一樣可以順利的用XSLT轉(zhuǎn)換,只不過(guò)Eclipse的xml編輯器會(huì)提示有錯(cuò)誤。 |
下面是一個(gè)創(chuàng)建表格的例子
<table frame='all'> <title>Sample Table</title> <tgroup cols='2' align='left' colsep='1' rowsep='1'> <colspec colname='c1' /> <colspec colname='c2' /> <thead> <row> <entry>a4</entry> <entry>a5</entry> </row> </thead> <tfoot> <row> <entry>f4</entry> <entry>f5</entry> </row> </tfoot> <tbody> <row> <entry>b1</entry> <entry>b2</entry> </row> <row> <entry>d1</entry> <entry>d5</entry> </row> </tbody> </tgroup> </table>
生成的表格看起來(lái)是這樣的
沒(méi)有序號(hào)的列表可以這樣創(chuàng)建:
<itemizedlist> <listitem> <para>Item1</para> </listitem> <listitem> <para>Item2</para> </listitem> <listitem> <para>Item3</para> </listitem> <listitem> <para>Item4</para> </listitem> </itemizedlist>
輸出結(jié)果如下:
Item1
Item2
Item3
Item4
而帶編號(hào)的列表可以這樣寫(xiě):
<orderedlist> <listitem> <para>This is a list entry</para> </listitem> <listitem> <para>This is another list entry</para> </listitem> </orderedlist>
輸出結(jié)果如下:
This is a list entry
This is another list entry
鏈接可以用下面的方法來(lái)創(chuàng)建:[a]
<para> We use the Ant integrated into Eclipse. See <ulink url="http://www.vogella.de/articles/ApacheAnt/article.html"> Apache Ant Tutorial</ulink> for an introduction into Apache Ant. </para>
Docbook轉(zhuǎn)成pdf的過(guò)程是:先由docbook轉(zhuǎn)成XSL-FO格式,再利用Apache FOP把FO轉(zhuǎn)成 pdf。因此,我們首先需要Apache FOP相關(guān)的庫(kù)。
XML FO,是XML Formating Object的意思,F(xiàn)O格式是一種處理打印、印刷介質(zhì)的XML標(biāo)準(zhǔn)。
可以從http://xmlgraphics.apache.org/fop/下載FOP的最新版本。
從下載的FOP發(fā)行版中,把所有的jar文件都拷貝到你的lib文件夾中,并把這些庫(kù)都加入到ant 的build path中。可以參考 Apach Ant Tutorial來(lái)修改ant的build path。
要在ant中使用fop,我們首先應(yīng)當(dāng)定義一個(gè)fop相關(guān)的ant task,然后在后面的腳本中使用這個(gè)任務(wù)。 下面的這個(gè)例子演示了怎樣定義一個(gè)ant task并怎樣調(diào)用。第二個(gè)例子是一個(gè)完整的build.xml文件的例子。
<!-- - Defines the ant task for fop --> <taskdef name="fop" classname="org.apache.fop.tools.anttasks.Fop" /> <!-- Transformation into pdf - Two steps - 1.) First create the FO files - 2.) Then transform the FO files into pdf files --> <!-- - target: build-pdf - description: Iterates through a directory and transforms - .xml files into .fo files using the DocBook XSL. --> <target name="build-pdf" depends="depends, xinclude" description="Generates HTML files from DocBook XML"> <!-- Convert DocBook Files into FO --> <xslt style="${fo.stylesheet}" extension=".fo" basedir="${src.tmp}" destdir="${src.tmp}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="section.autolabel" expression="1" /> </xslt> <!-- Convert FO Files into pdf --> <fop format="application/pdf" outdir="${doc.dir}"> <fileset dir="${src.tmp}"> <include name="**/*.fo" /> </fileset> </fop> </target>
<?xml version="1.0"?> <!-- - Author: Lars Vogel --> <project name="docbook-src" default="all"> <description> This Ant build.xml file is used to transform DocBook XML to various output formats </description> <!-- - Defines the ant task for xinclude --> <taskdef name="xinclude" classname="de.vogella.xinclude.XIncludeTask" /> <!-- - Defines the ant task for xinclude --> <taskdef name="fop" classname="org.apache.fop.tools.anttasks.Fop" /> <!-- - Configure basic properties that will be used in the file. --> <property name="javahelp.dir" value="${basedir}/../Documentation/output/vogella/javahelp" /> <property name="src" value="${basedir}/documentation" /> <property name="output.dir" value="${basedir}/../Documentation/output/vogella/articles" /> <property name="output.tmp" value="${basedir}/output.tmp" /> <property name="lib" value="${basedir}/lib/" /> <property name="docbook.xsl.dir" value="${basedir}/docbook-xsl-1.72.0" /> <property name="xinclude.lib.dir" value="${basedir}/lib/" /> <!-- - Usage of the differect style sheets which will be used for the transformation --> <property name="eclipse.stylesheet" value="${docbook.xsl.dir}/eclipse/eclipse.xsl" /> <property name="html.stylesheet" value="${docbook.xsl.dir}/html/docbook.xsl" /> <property name="fo.stylesheet" value="${docbook.xsl.dir}/fo/docbook.xsl" /> <property name="javahelp.stylesheet" value="${docbook.xsl.dir}/javahelp/javahelp.xsl" /> <property name="chunk-html.stylesheet" value="${docbook.xsl.dir}/html/chunk.xsl" /> <!-- - target: usage --> <target name="usage" description="Prints the Ant build.xml usage"> <echo message="Use -projecthelp to get a list of the available targets." /> </target> <!-- - target: clean --> <target name="clean" description="Cleans up generated files."> <delete dir="${output.dir}" /> </target> <!-- - target: depends --> <target name="depends"> <mkdir dir="${output.dir}" /> </target> <!-- - target: copy - Copies the images from the subdirectories to the target folder --> <target name="copy"> <echo message="Copy the images" /> <copy todir="${output.dir}"> <fileset dir="${src}"> <include name="**/images/*.*" /> </fileset> </copy> </target> <!-- - target: xinclude - description: Creates one combined temporary files for the different inputs files. - The combined file will then be processed via different ant tasks --> <target name="xinclude"> <xinclude in="${src}/DocBook/article.xml" out="${output.tmp}/DocBook/article.xml" /> <xinclude in="${src}/JavaConventions/article.xml" out="${output.tmp}/JavaConventions/article.xml" /> <xinclude in="${src}/JUnit/article.xml" out="${output.tmp}/JUnit/article.xml" /> <xinclude in="${src}/EclipseReview/article.xml" out="${output.tmp}/EclipseReview/article.xml" /> <xinclude in="${src}/HTML/article.xml" out="${output.tmp}/HTML/article.xml" /> <xinclude in="${src}/Eclipse/article.xml" out="${output.tmp}/Eclipse/article.xml" /> <xinclude in="${src}/Logging/article.xml" out="${output.tmp}/Logging/article.xml" /> <!-- <xinclude in="${src}/ant/article.xml" out="${src.tmp}/ant/article.xml" /> --> </target> <!-- - target: build-html - description: Iterates through a directory and transforms - .xml files into .html files using the DocBook XSL. --> <target name="build-html" depends="depends, xinclude" description="Generates HTML files from DocBook XML"> <xslt style="${html.stylesheet}" extension=".html" basedir="${output.tmp}" destdir="${output.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="html.stylesheet" expression="styles.css" /> <param name="section.autolabel" expression="1" /> <param name="html.cleanup" expression="1" /> <outputproperty name="indent" value="yes" /> </xslt> <!-- Copy the stylesheet to the same directory as the HTML files --> <copy todir="${output.dir}"> <fileset dir="lib"> <include name="styles.css" /> </fileset> </copy> </target> <!-- - target: build-javahelp - description: Iterates through a directory and transforms - .xml files into .html files using the DocBook XSL. --> <target name="build-javahelp" depends="depends, xinclude" description="Generates HTML files from DocBook XML"> <xslt style="${javahelp.stylesheet}" extension=".html" basedir="${output.tmp}" destdir="${javahelp.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <outputproperty name="indent" value="yes" /> </xslt> </target> <!-- - target: chunks-html - description: Iterates through a directory and transforms - .xml files into seperate .html files using the DocBook XSL. --> <target name="build-chunks" depends="depends, xinclude" description="Generates chunk HTML files from DocBook XML"> <xslt style="${html.stylesheet}" extension=".html" basedir="${output.tmp}" destdir="${output.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="html.stylesheet" expression="styles.css" /> <param name="section.autolabel" expression="1" /> <param name="html.cleanup" expression="1" /> <param name="chunk.first.selection" expression="1" /> </xslt> <!-- Copy the stylesheet to the same directory as the HTML files --> <copy todir="${output.dir}"> <fileset dir="lib"> <include name="styles.css" /> </fileset> </copy> </target> <!-- Transformation into pdf - Two steps - 1.) First create the FO files - 2.) Then transform the FO files into pdf files --> <!-- - target: build-pdf - description: Iterates through a directory and transforms - .xml files into .fo files using the DocBook XSL. - Relativebase is set to true to enable FOP to find the graphics which are included - in the images directory --> <target name="build-pdf" depends="depends, xinclude" description="Generates HTML files from DocBook XML"> <!-- Convert DocBook Files into FO --> <xslt style="${fo.stylesheet}" extension=".fo" basedir="${output.tmp}" destdir="${output.tmp}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="section.autolabel" expression="1" /> </xslt> <!-- Convert FO Files into pdf --> <fop format="application/pdf" outdir="${output.dir}" relativebase="true"> <fileset dir="${output.tmp}"> <include name="**/*.fo" /> </fileset> </fop> </target> <!-- - target: chunks-html - description: Iterates through a directory and transforms - .xml files into seperate .html files using the DocBook XSL. --> <target name="build-eclipse" depends="depends, xinclude" description="Generates Eclipse help files from DocBook XML"> <xslt style="${eclipse.stylesheet}" basedir="${output.tmp}" destdir="${output.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> </xslt> </target> <target name="all" depends="copy, build-html, build-pdf, build-chunks, build-eclipse"> </target> </project>
我們可以通過(guò)修改XSLT樣式表的參數(shù)來(lái)影響輸出的結(jié)果。下面其中一些參數(shù)的介紹。
Table 3. HTML參數(shù)
參數(shù) | 說(shuō)明 |
---|---|
name="section.autolabel" expression="1" | 為section自動(dòng)編號(hào)(例如,第一個(gè)section是1,其下一集的section是1.1,以此類(lèi)推) |
name="chapter.autolabel" expression="1" | 為chapter自動(dòng)編號(hào) |
name="html.stylesheet" expression="styles.css" | 定義html使用的樣式表 |
name="html.cleanup" expression="1" | 清理html使之更具可讀性 |
Docbook允許在轉(zhuǎn)換成html的時(shí)候,導(dǎo)入并包含一個(gè)外部的html文件。你可以使用這種技術(shù),在生成 html的時(shí)候向其中插入javascript代碼。
下面是一個(gè)包含html文件的例子。
<?dbhtml-include href="../../myadditonalcontent.html"?>
Inserting external HTML code 有更多的描述。
XInclude技術(shù)能幫你重新組織你的docbook文件。你可以在書(shū)寫(xiě)每一個(gè)章節(jié)的時(shí)候,都使用 一個(gè)單獨(dú)的xml文件,然后用一個(gè)總的xml文件把這些章節(jié)都組合起來(lái)。簡(jiǎn)單的說(shuō),XInclude 能把不同的xml文件組合成為一個(gè)大的xml文件。
例如,假設(shè)你要引入一個(gè)“foo.xml”文件,則可以寫(xiě)成:
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="foo.xml" />
下面這個(gè)例子是要把導(dǎo)入的文件當(dāng)做文本: [1]
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="bar.xml" />Eclipse XSL project提供一個(gè)XInclude的ant task。在此,我很自豪的告訴各位:這個(gè)ant task是我提供給XSL project 的:)
Eclipse XSL工具提供了對(duì)XSLT的支持,包括XSL的編輯以及debug的支持。雖然我們這里僅僅使用其中的ant task, 但還是得完整的安裝整個(gè)包。
安裝XSL工具可以通過(guò)Eclipse的update manager完成。 [2] 你可以通過(guò) Using the Eclipse update manager 來(lái)獲得更多信息。
在你的Eclipse安裝路徑中找到“org.eclipse.wst.xsl.core.jar”并把這個(gè)jar包加入到ANT的classpath中。 這樣,你應(yīng)該就可以創(chuàng)建和運(yùn)行xinclude tast了。下面是一個(gè)build.xml文件的例子:
<?xml version="1.0"?> <!-- - Author: Lars Vogel --> <project name="docbook-src" default="usage"> <description> This Ant build.xml file is used to transform DocBook XML to various output formats </description> <!-- - Configure basic properties that will be used in the file. --> <property name="doc.dir" value="${basedir}/output" /> <property name="src" value="${basedir}/src" /> <property name="src.tmp" value="${basedir}/src.tmp" /> <property name="lib" value="${basedir}/lib/" /> <property name="docbook.xsl.dir" value="${basedir}/docbook-xsl-1.72.0" /> <property name="html.stylesheet" value="${docbook.xsl.dir}/html/docbook.xsl" /> <property name="xinclude.lib.dir" value="${basedir}/lib/" /> <!-- - target: usage --> <target name="usage" description="Prints the Ant build.xml usage"> <echo message="Use -projecthelp to get a list of the available targets." /> </target> <!-- - target: clean --> <target name="clean" description="Cleans up generated files."> <delete dir="${doc.dir}" /> </target> <!-- - target: depends --> <target name="depends"> <mkdir dir="${doc.dir}" /> </target> <!-- - target: xinclude - description: Creates one combined temporary files for the different inputs files. - The combined file will then be processed via different ant tasks --> <target name="xinclude"> <xsl.xinclude in="${src}/DocBook/article.xml" out="${src.tmp}/DocBook/article.xml" /> </target> <!-- - target: build-html - description: Iterates through a directory and transforms - .xml files into .html files using the DocBook XSL. --> <target name="build-html" depends="depends, xinclude" description="Generates HTML files from DocBook XML"> <xslt style="${html.stylesheet}" extension=".html" basedir="${src.tmp}" destdir="${doc.dir}"> <include name="**/*book.xml" /> <include name="**/*article.xml" /> <param name="html.stylesheet" expression="styles.css" /> </xslt> <!-- Copy the stylesheet to the same directory as the HTML files --> <copy todir="${doc.dir}"> <fileset dir="lib"> <include name="styles.css" /> </fileset> </copy> </target> </project>
http://www.sagehill.net/docbookxsl/index.html Docbook XSL Online Book
http://sourceforge.net/projects/docbook/ Docbook XSLT樣式表項(xiàng)目
http://docbook.sourceforge.net/release/xsl/current/doc/ XSLT樣式表的參數(shù)手冊(cè)
http://sourceforge.net/apps/mediawiki/xslthl/index.php?title=Main_Page 如何使用XSLT實(shí)現(xiàn)語(yǔ)法高亮
http://www.docbook.org/tdg/en/html/docbook.html Docbook參數(shù)手冊(cè)
http://xmlgraphics.apache.org/fop/ Apache FOP項(xiàng)目
我會(huì)爭(zhēng)取在近期用Python寫(xiě)個(gè)圖形界面。之所以現(xiàn)在不寫(xiě),是因?yàn)楝F(xiàn)在我還不會(huì)……
原理很簡(jiǎn)單,就是用程序去獲得騰訊星座網(wǎng)站的源碼,然后簡(jiǎn)單解析一下就可以了。原來(lái)試圖用dom解析,結(jié)果發(fā)現(xiàn)騰訊和新浪的網(wǎng)站都會(huì)解析出錯(cuò),一狠心干脆直接用字符串的替換。
Java那個(gè)程序的功能多一些,寫(xiě)了讀取“明天”、“本周”、“下周”、“本月”、“下月”的功能,主函數(shù)中提供了讀取“明天”的功能,默認(rèn)會(huì)在當(dāng)前工作目錄下生成“yuncheng_XXX.txt”文件。實(shí)在懶得寫(xiě)客戶(hù)端了,甚至于命令行客戶(hù)端都不想寫(xiě)了,因?yàn)樽蛱鞂?xiě)這個(gè)破東西寫(xiě)到了11點(diǎn)半,原以為很簡(jiǎn)單的呢,結(jié)果郁悶壞了。真是水平大幅度下滑啊。
今天晚上用python寫(xiě)了一個(gè)程序,這是我用Python寫(xiě)的第一個(gè)程序喲~~(如果不算helloworld的話(huà)。。。)這個(gè)程序功能比較簡(jiǎn)單,只能獲得明日運(yùn)程。
剛剛寫(xiě)出來(lái)而已,注釋很亂,代碼很亂。寫(xiě)這篇博客只是因?yàn)槟鸽u心態(tài):好歹有了個(gè)新東西了,怎么也得讓我叫喚兩聲吧。
下載地址:
http://www.rayfile.com/files/bc9485dc-88e8-11de-b777-0014221f469f/一、基本概念
所謂動(dòng)態(tài)代理,基本上是如下場(chǎng)景:假設(shè)我有個(gè)接口IHelloWorld
問(wèn)題是,現(xiàn)在,我打算為HelloWorldImpl增強(qiáng)功能,需要在調(diào)用sayHello方法前后各執(zhí)行一些操作。在有些情況下,你無(wú)法修改HelloWorldImpl的源代碼,那怎么辦呢?
從道理上來(lái)說(shuō),我們可以攔截對(duì)HelloWorldImpl對(duì)象里sayHello()函數(shù)的調(diào)用。也就是說(shuō),每當(dāng)有代碼調(diào)用sayHello函數(shù)時(shí),我們都把這種調(diào)用請(qǐng)求攔截下來(lái)之后,做自己想做的事情。
那怎么攔截呢?
首先,需要開(kāi)發(fā)一個(gè)InvocationHandler。這個(gè)東東表示的是,你攔截下函數(shù)調(diào)用之后,究竟想干什么。InvocationHandler是一個(gè)接口,里面的聲明的函數(shù)只有一個(gè):
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
這個(gè)函數(shù)表示一次被攔截的函數(shù)調(diào)用。因此,proxy表示這個(gè)被攔截的調(diào)用,原本是對(duì)哪個(gè)對(duì)象調(diào)用的;method表示這個(gè)被攔截的調(diào)用,究竟是調(diào)用什么方法;args表示這個(gè)被攔截的調(diào)用里,參數(shù)分別是什么。
我們下面寫(xiě)一個(gè)攔截器,讓他在函數(shù)調(diào)用之前和之后分別輸出一句話(huà)。
有了這個(gè)Handler之后,下面要做的,就是把這個(gè)Handler和一個(gè)IHelloWorld類(lèi)型的對(duì)象裝配起來(lái)。重點(diǎn)的函數(shù)只有一個(gè),那就是java.lang.reflect.Proxy類(lèi)中的一個(gè)靜態(tài)工廠(chǎng)方法:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
這個(gè)方法返回一個(gè)對(duì)象,我們稱(chēng)返回的對(duì)象為代理對(duì)象(proxy)。
而后,我們就不把真正的原對(duì)象暴露給外接,而使用這個(gè)代理對(duì)象。這個(gè)代理對(duì)象接受對(duì)源對(duì)象的一切函數(shù)調(diào)用(也就是把所有調(diào)用都攔截了),然后根據(jù)我們寫(xiě)的InvocationHandler,來(lái)對(duì)函數(shù)進(jìn)行處理。
產(chǎn)生代理對(duì)象的過(guò)程,我把它理解成一個(gè)裝配的過(guò)程:由源對(duì)象、源對(duì)象實(shí)現(xiàn)的接口、InvocationHandler裝配產(chǎn)生一個(gè)代理對(duì)象。
相應(yīng)的測(cè)試代碼如下:
利用ant編譯運(yùn)行的結(jié)果:
[java] ################################
[java] method name : sayHello
[java] Do Before
[java] Hello, World
[java] Do After
[java] ################################
二、更多理解
我們看產(chǎn)生代理對(duì)象的newProxyInstance函數(shù)的聲明:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
這個(gè)函數(shù)的第一個(gè)參數(shù)是ClassLoader,第三個(gè)參數(shù)是InvocationHandler,基本都沒(méi)什么問(wèn)題。
第二個(gè)參數(shù)是一個(gè)Class類(lèi)型的數(shù)組,名字叫interfaces,表示的是產(chǎn)生的動(dòng)態(tài)代理對(duì)象實(shí)現(xiàn)的接口。
仔細(xì)想想,有兩個(gè)問(wèn)題。第一,產(chǎn)生一個(gè)代理對(duì)象,需要源對(duì)象么?第二,我能不能產(chǎn)生一個(gè)動(dòng)態(tài)代理對(duì)象,來(lái)實(shí)現(xiàn)源對(duì)象沒(méi)有實(shí)現(xiàn)的接口?
第一個(gè)問(wèn)題和第二個(gè)問(wèn)題其實(shí)是一致的。我們完全可以脫離源對(duì)象,而直接產(chǎn)生一個(gè)代理對(duì)象,也可以利用動(dòng)態(tài)代理,讓源對(duì)象實(shí)現(xiàn)更多的接口,為源對(duì)象增強(qiáng)功能。
例如,假設(shè)我們希望讓源對(duì)象實(shí)現(xiàn)java.io.Closeable接口,則首先修改一下我們的Handler的invoke方法,讓他在獲取colse方法時(shí),不要傳遞給源對(duì)象(因?yàn)樵磳?duì)象沒(méi)有實(shí)現(xiàn)該方法):
然后,我們?cè)谘b配的過(guò)程中,改變一下參數(shù),并強(qiáng)轉(zhuǎn)之后調(diào)用一下close方法:
ant運(yùn)行結(jié)果:
[java] ################################
[java] method name : close
[java] Do Before
[java] I got the close() method!
[java] Do After
[java] ################################
三、更多的代理~
我們現(xiàn)在能夠讓sayHello()函數(shù)執(zhí)行之前和之后,輸出一些內(nèi)容了。那如果我還想在裝配一個(gè)Handler呢?
最簡(jiǎn)單的方法:
| |||||||||
日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
---|---|---|---|---|---|---|---|---|---|
22 | 23 | 24 | 25 | 26 | 27 | 28 | |||
1 | 2 | 3 | 4 | 5 | 6 | 7 | |||
8 | 9 | 10 | 11 | 12 | 13 | 14 | |||
15 | 16 | 17 | 18 | 19 | 20 | 21 | |||
22 | 23 | 24 | 25 | 26 | 27 | 28 | |||
29 | 30 | 31 | 1 | 2 | 3 | 4 |