﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-Dedian-随笔分类-Java Memo</title><link>http://www.blogjava.net/dedian/category/14228.html</link><description>-- 关注搜索引擎的开发</description><language>zh-cn</language><lastBuildDate>Tue, 27 Feb 2007 08:50:37 GMT</lastBuildDate><pubDate>Tue, 27 Feb 2007 08:50:37 GMT</pubDate><ttl>60</ttl><item><title>Again, Problem or Bug for URLConnection ?</title><link>http://www.blogjava.net/dedian/archive/2006/10/21/76488.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Fri, 20 Oct 2006 23:20:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/10/21/76488.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/76488.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/10/21/76488.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/76488.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/76488.html</trackback:ping><description><![CDATA[Not sure if it is a bug of (Http)URLConnection, but it hang sometimes for some URLs while calling any functions to get information from connection (includes getResponseCode, getInputStream, getContent, getContentLength, getHeaderField blabla..) after connection has been built (even I have set the read timeout and connect time out). <br /><br />the functions openConnection() and connect() are ok, curious about that problem.<br /><br />anybody has the same problem or similar problem with URLConnection?<br /><img src ="http://www.blogjava.net/dedian/aggbug/76488.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-10-21 07:20 <a href="http://www.blogjava.net/dedian/archive/2006/10/21/76488.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Ajax 浅谈</title><link>http://www.blogjava.net/dedian/archive/2006/10/07/73599.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Fri, 06 Oct 2006 23:05:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/10/07/73599.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/73599.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/10/07/73599.html#Feedback</comments><slash:comments>2</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/73599.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/73599.html</trackback:ping><description><![CDATA[
		<br />---祝大家中秋愉快---<br /><br />Ajax (<i><a href="http://en.wikipedia.org/wiki/Asynchronous" title="Asynchronous">Asynchronous</a><a href="http://en.wikipedia.org/wiki/JavaScript" title="JavaScript">JavaScript</a> and <a href="http://en.wikipedia.org/wiki/XML" title="XML">XML</a></i>)是近年来流行的一门web 技术。在Blogjava上看到有人开始在介绍AJAX，但仿佛流于概念或理论的东西，对于想用Ajax的初学者似乎不是很make sense。我想，学习任何一样新的技术，例子和步骤是极为make sense的两样东西。<br /><br />笔者想结合过去的学习经验简单讲讲使用Ajax的基本步骤和举几个实用例子。由于笔者主要在于后台端的开发，所以很多脚本并不是很擅长。Ajax也主要限于以前大学的修课和近期的一些为后台端程序的测试的简单实现。所以只是一个抛砖引玉的使用Ajax版本，欢迎相互学习交流。<br /><br /><b>0. 导读</b><br /><br />    <b>1。使用Ajax的基本流程<br />    </b><b>2。使用Ajax的基本步骤。(简单例子--&gt; <a href="http://dedian.us/ajax-ex.htm">Demo</a>)<br />    3。</b><b>再来一个例子(Google Suggest)。(<a href="http://dedian.us/dogooglesuggest.html">Demo</a>)<br /></b><b>    4。家庭作业 :)</b><br /><b><br /></b><br /><b>1。使用Ajax的基本流程</b><br /><br />在笔者看来，Ajax更像是一个简单的网络框架，它描述着如何高效地使网络前端的数据展现和网络后端的数据之间的交互。基本上，就是浏览器提供一个XMLHttpRequest(当然在IE里是ActiveXObject)的对象向后台端的脚本程序或者Servlet Classes发送http请求，从后台端的回应中获取文本数据(如xml格式和最近有人讨论的Json格式)并嵌入前台段的网页中或脚本中。<br /><br />下图是一个简单的流程图：<br /><br /><div align="center"><img src="http://dedian.us/image/ajax.jpg" /><br /></div><br /><b>2。使用Ajax的基本步骤。</b><br /><br />下面，我们结合上面的流程，以及一个简单的例子(见<a href="http://www.xml.com/pub/a/2005/02/09/xml-http-request.html">这篇文章</a>)过一遍基本的步骤。(蓝色代码为标准写法)<br /><br />第一步：Form 代码：接受前台端的输入，并通过Action方法(方法函数里包含创建XMLHttpRequest对象)把request post到后台端。<br /><br /><font color="#003300">&lt;input id="username" name="username" type="text" <br />  onblur="checkName(this.value,'')" /&gt;<br />&lt;span class="hidden" id="nameCheckFailed"&gt;<br />  This name is in use, please try another. <br />&lt;/span&gt;<br /><br />&lt;script language="javascript"&gt;<br />function checkName(input, response)<br />{<br />  if (response != ''){ <br />    // Response mode<br />    message   = document.getElementById('nameCheckFailed');<br />    if (response == '1'){<br />      message.className = 'error';<br />    }else{<br />      message.className = 'hidden';<br />    } <br />  }else{<br />    // Input mode<br />    url  = 'http://localhost/xml/checkUserName.php?q=' + input;<br />    loadXMLDoc(url);<br />  }<br />}<br /><br />var req;<br /><br />function loadXMLDoc(url) <br />{<br />    // branch for native XMLHttpRequest object<br />    if (window.XMLHttpRequest) {<br />        req = new XMLHttpRequest();<br />        req.onreadystatechange = processReqChange;<br />        req.open("GET", url, true);<br />        req.send(null);<br />    // branch for IE/Windows ActiveX version<br />    } else if (window.ActiveXObject) {<br />        req = new ActiveXObject("Microsoft.XMLHTTP");<br />        if (req) {<br />            req.onreadystatechange = processReqChange;<br />            req.open("GET", url, true);<br />            req.send();<br />        }<br />    }<br />}<br />&lt;/script&gt;<br /></font><br /><br />注：<br />1。 这里的form只是一个input box,action的方法是onblur,就是响应失去焦点的事件，然后调用一个函数checkName, 这个函数里通过XMLHttpRequest向PHP server script 发送Post请求(看得出来，这里的php server script的文件名叫checkUserName.php，唯一参数是q)。<br />2。函数loadXMLDoc里有个通用的创建XMLHttpRequest对象的代码，标准代码整理如下：<br /> <font color="#0000ff">       var req;<br />        function foo()<br />        {<br />            req = false;<br /><br />            // branch for native XMLHttpRequest object<br />            if(window.XMLHttpRequest) <br />            {<br />                try <br />                {<br />                    req = new XMLHttpRequest();<br />                } <br />                catch(e) <br />                {<br />                    req = false;<br />                }<br />            } <br />            else if(window.ActiveXObject) // branch for IE/Windows ActiveX version<br />            {<br />                try <br />                {<br />                    req = new ActiveXObject("Msxml2.XMLHTTP");<br />                } <br />                catch(e) <br />                {<br />                    try <br />                    {<br />                        req = new ActiveXObject("Microsoft.XMLHTTP");<br />                    } <br />                    catch(e) <br />                    {<br />                        req = false;<br />                    }<br />                }<br />            }<br />            if(req) <br />            {<br />                      </font><font color="#0000ff"><font color="#00ff00">//do something here</font><br />             }<br />            <br /><br />        }<br /></font><br />第二步：响应文本处理代码：XMLHttpRequest对象里有个类似消息响应函数的属性，即通过设置 req.onreadystatechange 来告诉XMLHttpRequest在哪个函数里处理服务端返回的文本信息。<br />如在上面的例子中：<br /><pre><code>req.onreadystatechange = processReqChange;</code></pre>
那么我们接着要有一个processReqChange的函数：<br /><pre><code><font color="#0000ff">function processReqChange() <br />{<br />    // only if req shows "complete"<br />    if (req.readyState == 4) {<br />        // only if "OK"<br />        if (req.status == 200) <br />	{<br />            // ...processing statements go here...<br />	    processResponse();<br />        } else {<br />            alert("There was a problem retrieving <br />               the XML data:\n" + req.statusText);<br />        }<br />    }<br />}</font><br /><br />function processResponse()<br />{<br />    response  = req.responseXML.documentElement;<br />    method    = response.getElementsByTagName('method')[0].firstChild.data;<br />    result    = response.getElementsByTagName('result')[0].firstChild.data;<br />    eval(method + '(\'\', result)');<br /><br />}<br /></code></pre>注：<br />1。 基本上<code>processReqChange</code> 函数是标准代码的写法。<br />2。这里要用到前面定义的全局变量(XMLHttpRequest对象)req<br /><br />第三步：后台端代码(这个例子是php server script)：接受前台端的请求，处理其参数，并返回相应的结果。<br /><br />文件名: checkUserName.php<br /><br />&lt;?php<br />header('Content-Type: text/xml');<br /><br />function nameInUse($q)<br />{  <br />  if (isset($q)){<br />    switch(strtolower($q))<br />    {<br />      case  'drew' :<br />          return '1';<br />          break;<br />      case  'fred' :<br />          return '1';<br />          break;<br />      default:<br />          return '0';<br />    }<br />  }else{<br />    return '0';<br />  }<br />  <br />}<br />?&gt;<br />&lt;?php echo '&lt;?xml version="1.0" encoding="UTF-8"  standalone="yes"?&gt;'; ?&gt;<br />&lt;response&gt;<br />  &lt;method&gt;checkName&lt;/method&gt;<br />  &lt;result&gt;&lt;?php <br />    echo nameInUse($_GET['q']) ?&gt;<br />  &lt;/result&gt;<br />&lt;/response&gt;<br />注：代码很简单，就不用解释了。这里返回的是xml格式的字符串。<br /><br />总体效果见<a href="http://dedian.us/ajax-ex.htm">这里</a><br />输入"fred"或者"drew"的名字，失去焦点后会显示名字已存在的信息。<br /><br /><br /> <b>3。再来一个例子。</b><br /><br />这里再讲一个实用的例子，这是以前上课的一个课堂作业，也很有代表性。是关于<a href="http://www.google.com/webhp?complete=1">Google Suggest</a>(好像新的Google Toolbar上就用的这个功能)的应用问题。这里是写好的<a href="http://dedian.us/dogooglesuggest.html">DEMO</a>。现在越来越多的网站提供类似Web Service的API, 我们利用他们提供的API URL可以返回一些我们用的着的数据，放在我们的网页上。这里就用的上Ajax。只不过有些返回来的文本数据是xml格式的，就可以利用上面的简单例子来处理，但很多像Google Suggest那样是返回一段类似代码格式的文本。我们就要利用Javascript的eval函数，把这些文本当作一段代码在嵌入自己的网页中。如果嵌入的代码中含有函数，则需要自己再写一个同名的函数作为实现。(这就是流程图中的optional的func 3)<br /><br />这里完整代码就不贴了，贴一些关键代码(原本后台端是用Java Servlet写的，但做demo的空间没有Tomcat不支持Servlet,所以改用Php实现，大家可以自己用Java再写一边作为家庭作业 :) )：<br /><br />1) form 代码：<br /><br />&lt;form name = "QForm" method="POST" action="google_suggest.php"&gt;<br />    &lt;table bgcolor="8080C0" width="90%" &gt;<br />    &lt;tr&gt;<br />        &lt;td  nowrap&gt;Search Term:&lt;/td&gt;<br />        &lt;td &gt;&lt;input type="text" name="qtext"  onkeyup="return GetSuggestion()" size="60"&gt;&lt;/td&gt;<br />    &lt;/tr&gt;<br />    &lt;tr&gt;<br />        &lt;th colspan="2" align="left" bgcolor="#A8A8FF"&gt;&lt;DIV id=google_suggest_target&gt;results go here . . . &lt;/DIV&gt;&lt;/th&gt;<br />    &lt;/tr&gt;<br />    &lt;/table&gt;<br />    &lt;/form&gt;<br /><br />注：<br />a. 看得出来，要把查询的字符串post到google_suggest.php上<br />b. action的函数是GetSuggestion()，其返回的字符串会显示在预留的网页空间里。<br /><br />2) 后台端代码(PHP)：这里主要接收前台的请求，并不请求转化为向Google Suggest的API URL请求，把接收到的文本信息返回给前端。代码很简单，如下：<br /><br />文件名：google_suggest.php<br /><br />&lt;?php <br />function getGoogleSuggest($q)<br />{<br /><br />    $url = "http://www.google.com/complete/search?hl=en&amp;js=true&amp;qu=" . $q;<br />    return file_get_contents($url);<br />}<br />?&gt;<br /><br />&lt;?php echo getGoogleSuggest($_POST['q']) ?&gt;<br /><br />注：<br />a。 <a href="http://www.google.com/complete/search?hl=en&amp;js=true&amp;qu=">Google Suggest API 返回</a>的是一个代码格式的文本信息，如下：<br />sendRPCDone(frameElement, "", new Array(), new Array(), new Array(""));<br />所以我们再前台接受到这个文本信息之后，应该写一个sendRPCDone的函数来做进一步信息处理(比如说列表出查询结果)。<br /><br />3) 前台文本处理代码：<br /><br />    &lt;script type="text/javascript"&gt;<br />        var req;<br />        function GetSuggestion()<br />        {<br />            req = false;<br />            var f = document.QForm;<br /><br />            // branch for native XMLHttpRequest object<br />            if(window.XMLHttpRequest) <br />            {<br />                try <br />                {<br />                    req = new XMLHttpRequest();<br />                } <br />                catch(e) <br />                {<br />                    req = false;<br />                }<br />            } <br />            else if(window.ActiveXObject) // branch for IE/Windows ActiveX version<br />            {<br />                try <br />                {<br />                    req = new ActiveXObject("Msxml2.XMLHTTP");<br />                } <br />                catch(e) <br />                {<br />                    try <br />                    {<br />                        req = new ActiveXObject("Microsoft.XMLHTTP");<br />                    } <br />                    catch(e) <br />                    {<br />                        req = false;<br />                    }<br />                }<br />            }<br />            if(req) <br />            {<br />                var url = "google_suggest.php";<br />        <br /><font color="#0000ff">                req.onreadystatechange = processReqChange; <br />                req.open("POST", url, true); <br /><br />                req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");<br />                req.setRequestHeader("Method", "POST " + url + " HTTP/1.1");<br />                req.send("q=" + escape(document.QForm.qtext.value));<br /></font>            }<br />            <br /><br />        }<br />        <br />        function processReqChange() <br />        {<br />            if(req.readyState == 4) // only if req shows "loaded"<br />            {<br />                         if (req.status == 200) // only if "OK"<br />                         {<br /> <font color="#0000ff">                                x = req.responseText;<br />                                 eval(x);<br />  </font>                       }<br />                         else<br />                         {<br />                                 alert("There was a problem retrieving the XML data:\n" + req.statusText);<br />                         }<br />            }<br />            else if(req.readyState == 2)<br />            {<br />            }<br />        }<br />        <br />        function sendRPCDone(frameElement, qString, arr1, arr2, arr3)<br />        {<br />        <br />            var suggest_results = eval(arr1);<br />            var counts = eval(arr2);<br />            var htmlstr = "&lt;TABLE cellspacing=4 border=0&gt;";<br />            for (var i=0; i &lt; suggest_results.length; i++)<br />            {<br />                htmlstr += "&lt;tr&gt;&lt;td&gt;&lt;a href=\"javascript:self.location=\'http://www.google.com/search?hl=en&amp;q=" + suggest_results[i] + "&amp;btnG=Google+Search\'\"&gt;" + suggest_results[i] + "&lt;/a&gt;&lt;/td&gt;";<br />                htmlstr += "&lt;TD width=200&gt;&lt;font color= 228b22&gt;" + counts[i] + "&lt;/font&gt;&lt;/TD&gt;&lt;/TR&gt;" <br />                     <br />            }<br />            htmlstr += "&lt;/TABLE&gt;";<br />            document.getElementById("google_suggest_target").innerHTML = htmlstr;<br />        <br />        }<br />        <br />        &lt;/script&gt;<br /><br /><b>4。家庭作业 :)</b><br /><br />一定要自己写一些代码，才能巩固知识:)<br />题目：<br />我们经常用<a href="http://del.icio.us">del.icio.us</a>来收藏我们喜欢的网站或者文章，并加一些类似读书笔记的注释。那么我们怎么利用del.icio.us提供的API来访问我们的读书笔记信息，并显示在自己的Blog里呢？<br />提示：<br />1。你要有一个del.icio.us的账号，并且已经有所网页收藏作为实验数据:)<br />2。API URL 是 "http://del.icio.us/feeds/json/" + "你的账号名"；自己参看一下，看返回什么样的格式文本。另外，如果要限制返回的记录数，可以加"?count=10"这样的参数。<br /><br /><br />最后，祝大家中秋愉快！<br /><br />---------------------------完----------------------------<br /><br /><br /><br /><br /><img src ="http://www.blogjava.net/dedian/aggbug/73599.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-10-07 07:05 <a href="http://www.blogjava.net/dedian/archive/2006/10/07/73599.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>PHP/Java Integration on Windows</title><link>http://www.blogjava.net/dedian/archive/2006/10/06/73506.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Fri, 06 Oct 2006 01:05:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/10/06/73506.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/73506.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/10/06/73506.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/73506.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/73506.html</trackback:ping><description><![CDATA[reference: http://us3.php.net/java<br />help doc: http://php-java-bridge.sourceforge.net/<br /><br /><code><span class="html">
1- Make sure u have <a href="/dedian/archive/2006/09/29/72704.html">Installed Apache 2 &amp; PHP 5</a> and Java J2EE 1.5<br />
2- download <a href="http://museum.php.net/php5/">pecl-5.0.5-Win32.zip</a> and <a href="http://sourceforge.net/projects/php-java-bridge">php-java-bridge_2.0.8.zip</a>, which will include <br />
extra dll(s)<br />
    - unpack pecl pkg to your extensions folder, in PHP5 its ext.<br />
    - unpack java-Bridge to root php folder, in my case its simply C:\PHP<br />
    <br />Note: <br />1. the java-Bridge inculdes new versions of certain files like php_java.dll<br />
    so, it would be wise to rename your old files that came with PECL pkg for example<br />
    file_old, to rollback at anytime.<br />2. Don't run batch file under php-java-bridge after unpacking to php root folder, just add following lines in php.ini configure file (depends on installation fold of j2ee):<br /><br />extension=php_java.dll<br />extension_dir = "C:\php\ext" <br />[java]<br />java.java_home=C:\Program Files\Java\jre1.5.0_06<br />java.java=C:\Program Files\Java\jre1.5.0_06\bin\javaw.exe<br />java.log_level=2<br />;java.log_file=ext/JavaBridge.log<br /><br /></span></code><img src ="http://www.blogjava.net/dedian/aggbug/73506.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-10-06 09:05 <a href="http://www.blogjava.net/dedian/archive/2006/10/06/73506.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpURLConnect Problem</title><link>http://www.blogjava.net/dedian/archive/2006/09/21/70965.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Wed, 20 Sep 2006 22:32:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/09/21/70965.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/70965.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/09/21/70965.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/70965.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/70965.html</trackback:ping><description><![CDATA[When I try to get some information of http connection to some websites (say http://linuxbyte.net) by function <font face="">HttpURLConnection.getResponseCode(), it seems tthat JVM hangs for quite a while. Somebody says that is maybe the problem of http server who must be a Microsoft webserver. <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4352956">Here</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4258697">here</a> are the bug report information for Java 1.3 or before. Though it is said that the problem has been solved after java 1.4, i still get undesirable a long time waiting before a SocketException (Connection reset) is thrown out. Btw, conn.setConnectTimeout or conn.setConnectTimeout is involved for this problem. I am not sure if there is any method that can save time to skip those bad links.<br /></font><img src ="http://www.blogjava.net/dedian/aggbug/70965.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-09-21 06:32 <a href="http://www.blogjava.net/dedian/archive/2006/09/21/70965.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Getting the IP Address and Hostname</title><link>http://www.blogjava.net/dedian/archive/2006/08/18/64237.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Thu, 17 Aug 2006 22:53:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/08/18/64237.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/64237.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/08/18/64237.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/64237.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/64237.html</trackback:ping><description><![CDATA[
		<h3>1. Getting the IP Address of a Hostname</h3>
		<pre>    try <br />    {<br />        InetAddress addr = InetAddress.getByName(<font color="#0066ff"><i>"yahoo.com"</i></font>);<br />        byte[] ipAddr = addr.getAddress();<br /><br />        // Convert to dot representation<br />        String ipAddrStr = "";<br />        for (int i=0; i&lt;ipAddr.length; i++) {<br />            if (i &gt; 0) {<br />                ipAddrStr += ".";<br />            }<br />            ipAddrStr += ipAddr[i]&amp;0xFF;<br />        }<br />    } <br />    catch (UnknownHostException e) {<br />    }<br /><br /><br /></pre>
		<h3>2. Getting the Hostname of an IP Address</h3>

This example attempts to retrieve the hostname for an IP address.
Note that <code>getHostName()</code> may not succeed, in which case it simply
returns the IP address.


    <br /><br /><pre>try {<br />        // Get hostname by textual representation of IP address<br />        InetAddress addr = InetAddress.getByName(<font color="#0066ff"><i>"127.0.0.1"</i></font>);<br /><br />        // Get hostname by a byte array containing the IP address<br />        byte[] ipAddr = new byte[]{<font color="#0066ff"><i>127</i></font>, <font color="#0066ff"><i>0</i></font>, <font color="#0066ff"><i>0</i></font>, <font color="#0066ff"><i>1</i></font>};<br />        addr = InetAddress.getByAddress(ipAddr);<br /><br />        // Get the host name<br />        String hostname = addr.getHostName();<br /><br />        // Get canonical host name<br />        String hostnameCanonical = addr.getCanonicalHostName();<br />    } catch (UnknownHostException e) {<br />    }</pre><br /><h3>3. Getting the IP Address and Hostname of the Local Machine</h3><pre>    try {<br />        InetAddress addr = InetAddress.getLocalHost();<br /><br />        // Get IP Address<br />        byte[] ipAddr = addr.getAddress();<br /><br />        // Get hostname<br />        String hostname = addr.getHostName();<br />    } catch (UnknownHostException e) {<br />    }<br /></pre><br /><img src ="http://www.blogjava.net/dedian/aggbug/64237.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-08-18 06:53 <a href="http://www.blogjava.net/dedian/archive/2006/08/18/64237.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>CVS Tutorial</title><link>http://www.blogjava.net/dedian/archive/2006/07/20/59103.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Wed, 19 Jul 2006 23:06:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/07/20/59103.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/59103.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/07/20/59103.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/59103.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/59103.html</trackback:ping><description><![CDATA[
		<h3>--  Getting Ready to Use CVS</h3>First set the variable CVSROOT to /class/`username`/cvsroot<br />[Or any other directory you wish]<br />[For csh/tcsh: setenv CVSROOT ~/cvsroot]<br />[For bash/ksh: CVSROOT=~/cvsroot;export CVSROOT]<br /><br />Next run <b>cvsinit</b>. It will create this directory along with the subdirectory CVSROOT and put several files into CVSROOT.<br /><br /><h3>-- How to put a project under CVS</h3>A simple program consisting of multiple files is in /workspaces/project.<br /><br />To put this program under cvs first<br /><br /><b>cd to /workspaces/project</b><br /><br />Next<br /><br /><b>cvs import -m "Sample Program" project sample start</b><br /><br />CVS should respond with<br /><i>N project/Makefile<br />N project/main.c<br />N project/bar.c<br />N project/foo.c<br /><br />No conflicts created by this import</i><br /><br />If your were importing your own program, you could now delete the original source.<br />(Of course, keeping a backup is always a good idea)<br /><br /><h3>-- Basic CVS Usage</h3>Now that you have added 'project' to your CVS repository, you will want to be able to modify the code.<br /><br />To do this you want to check out the source. You will want to cd to your home directory before you do this.<br /><br /><b>cd</b><br /><br /><b>cvs checkout project</b><br /><br />CVS should respond with<br /><i>cvs checkout: Updating project<br />U project/Makefile<br />U project/bar.c<br />U project/foo.c<br />U project/main.c</i><br /><br /><br />This creates the project directory in your home directory and puts the files: Makefile, bar.c, foo.c, and main.c into the directory along with a CVS directory which stores some information about the files.<br /><br />You can now make changes to any of the files in the source tree.<br />Lets say you add a <font size="+1">printf("DONE\n");</font> after the function call to bar()<br />[Or just cp /class/bfennema/project_other/main2.c to main.c]<br /><br />Now you have to check in the new copy<br /><br /><b>cvs commit -m "Added a DONE message." main.c</b><br /><br />CVS should respond with<br /><i>Checking in main.c;<br />/class/'username'/cvsroot/project/main.c,v &lt;-- main.c<br />new revision: 1.2; previous revision: 1.1<br />done</i><br /><br />Note, the -m option lets you define the checking message on the command line. If you omit it you will be placed into an editor where you can type in the checking message.<br /><br /><h3>-- Using CVS with Multiple Developers</h3>To simulate multiple developers, first create a directory for your second developer.<br />Call it devel2 (Create it in your home directory).<br />Next check out another copy of project.<br /><ul><li>HINT: <b>cvs checkout project</b></li></ul>Next, in the devel2/project directory, add a <font size="+1">printf("YOU\n");</font> after the <font size="+1">printf("BAR\n");</font><br />[Or copy /class/bfennema/project_other/bar2.c to bar.c]<br /><br />Next, check in bar.c as developer two.<br /><ul><li>HINT: <b>cvs commit -m "Added a YOU" bar.c</b></li></ul>Now, go back to the original developer directory.<br />[Probably /class/'username'/project]<br /><br />Now look at bar.c. As you can see, the change made by developer one has no been integrated into your version. For that to happen you must<br /><br /><b>cvs update bar.c</b><br /><br />CVS should respond with<br /><i>U bar.c</i><br /><br />Now look at bar.c. It should now be the same as developer two's.<br />Next, edit foo.c as the original developer and add <font size="+1">printf("YOU\n");</font> after the <font size="+1">printf("FOO\n");</font><br />[Or copy /class/bfennema/project_other/foo2.c to foo.c]<br /><br />Then check in foo.c<br /><br /><ul><li>HINT: <b>cvs commit -m "Added YOU" foo.c</b></li></ul>Next, cd back to developer two's directory.<br />Add <font size="+1">printf("TOO\n");</font> after the <font size="+1">printf("FOO\n");</font><br />[Or copy /class/bfennema/project_other/foo3.c to foo.c]<br /><br />Now type<br /><br /><b>cvs status foo.c</b><br /><br />CVS should respond with<br /><pre><i>===================================================================
File: foo.c             Status: Needs Merge

   Working revision:    1.1.1.1 'Some Date'
   Repository revision: 1.2     /class/'username'/cvsroot/project/foo.c,v
   Sticky Tag:          (none)
   Sticky Date:         (none)
   Sticky Options:      (none)</i></pre>The various status of a file are:<br />Up-to-date 
<ul>The file is identical with the latest revision in the repository.</ul>Locally Modified 
<ul>You have edited the file, and not yet committed your changes.</ul>Needing Patch 
<ul>Someone else has committed a newer revision to the repository.</ul>Needs Merge 
<ul>Someone else has committed a newer revision to the repository, and you have also made modifications to the file.</ul><br />Therefore, this is telling use we need to merge our changes with the changes made by developer one. To do this<br /><br /><b>cvs update foo.c</b><br /><br />CVS should respond with<br /><i>RCS file: /class/'username'/cvsroot/project/foo.c,v<br />retrieving revision 1.1.1.1<br />retrieving revision 1.2<br />Merging differences between 1.1.1.1 and 1.2 into foo.c<br />rcsmerge: warning: conflicts during merge<br />cvs update: conflicts found in foo.c<br />C foo.c</i><br /><br />Since the changes we made to each version were so close together, we must manually adjust foo.c to look the way we want it to look. Looking at foo.c we see:<br /><pre><i>void foo()
{
  printf("FOO\n");
&lt;&lt;&lt;&lt;&lt;&lt;&lt; foo.c
  printf("TOO\n");
=======
  printf("YOU\n");
&gt;&gt;&gt;&gt;&gt;&gt;&gt; 1.2
}</i></pre><br />We see that the text we added as developer one is between the ======= and the &gt;&gt;&gt;&gt;&gt;&gt;&gt; 1.2.<br />The text we just added is between the ======= and the &lt;&lt;&lt;&lt;&lt;&lt;&lt; foo.c<br /><br />To fix this, move the <font size="+1">printf("TOO\n");</font>to after the <font size="+1">printf("YOU\n");</font>line and delete the additional lines the CVS inserted. [Or copy /class/bfennema/project_other/foo4.c to foo.c] <br />Next, commit foo.c<br /><br /><b>cvs commit -m "Added TOO" foo.c</b><br /><br />Since you issued a cvs update command and integrated the changes made by developer one, the integrated changes are committed to the source tree.<br /><br /><h3>-- Additional CVS Commands</h3>To add a new file to a module: 
<ul><li>Get a working copy of the module. 
</li><li>Create the new file inside your working copy. 
</li><li>use <b>cvs add <i>filename</i></b> to tell CVS to version control the file. 
</li><li>use <b>cvs commit <i>filename</i></b> to check in the file to the repository. </li></ul><br />Removing files from a module: 
<ul><li>Make sure you haven't made any uncommitted modifications to the file. 
</li><li>Remove the file from the working copy of the module. <b>rm <i>filename</i></b>. 
</li><li>use <b>cvs remove <i>filename</i></b> to tell CVS you want to delete the file. 
</li><li>use <b>cvs commit <i>filename</i></b> to actually perform the removal from the repository. </li></ul><br />For more information see the cvs man pages or the cvs.ps file in cvs-1.7/doc.<br /><br />---------------<br />copy from <a href="http://www.csc.calpoly.edu/%7Edbutler/tutorials/winter96/cvs/">http://www.csc.calpoly.edu/~dbutler/tutorials/winter96/cvs/</a><img src ="http://www.blogjava.net/dedian/aggbug/59103.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-07-20 07:06 <a href="http://www.blogjava.net/dedian/archive/2006/07/20/59103.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Retrieve values in HashTable or HashMap</title><link>http://www.blogjava.net/dedian/archive/2006/06/02/49836.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Thu, 01 Jun 2006 23:16:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/06/02/49836.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/49836.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/06/02/49836.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/49836.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/49836.html</trackback:ping><description><![CDATA[Unlike collection types such as Vector or List, Map (HashTable or
HashMap) accesses a value by a key. If we want to retrieve all the
values that have been put in a Map, one of simple ways to do that is
employing a Collection or plus an Iterator, here is the sample code
(just retrieve vaules, skip keys), assuming there is a variable:
HashMap&lt;String, &lt;ComplexDataType&gt;&gt; links<br /><br />
Collection c = links.value();<br />
Vector&lt;ComplexDataType&gt; v = new Vector&lt;ComplexDataType&gt;(c);<br />
for(int i = 0; i&lt; v.size(); i++)<br />
{<br />
    ComplexDataType tempData = (ComplexDataType)v.get(i);<br />
    <font color="#006600"><i>dosomethingwith</i></font>(tempData);<br />
}<br /><br /><br />
P.S. Map provides three views of map: keySet, entrySet and values collection, we can use any of them .<br /><img src ="http://www.blogjava.net/dedian/aggbug/49836.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-06-02 07:16 <a href="http://www.blogjava.net/dedian/archive/2006/06/02/49836.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java Reading &amp; Writing file</title><link>http://www.blogjava.net/dedian/archive/2006/05/31/49154.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Wed, 31 May 2006 00:12:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/05/31/49154.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/49154.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/05/31/49154.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/49154.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/49154.html</trackback:ping><description><![CDATA[
		<b>
				<u>1. Reading text from Standard Input</u>
		</b>
		<br />
		<pre>try <br />{<br />       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));<br />       String str = "";<br />       while (str != null) <br />       {<br />          System.out.print(<font color="#0066ff"><i>"&gt; some prompt "</i></font>);<br />          str = in.readLine();<br /><font color="#0066ff"><i>	  dosomethingwith</i></font>(str);<br />       }<br />} <br />catch (IOException e) <br />{<br />}</pre>
		<br />
		<u>
				<b>
2. Reading text from a file</b>
		</u>
		<br />
		<pre>try <br />{<br />     BufferedReader in = new BufferedReader(new FileReader(<font color="#0066ff"><i>"filename"</i></font>));<br />     String str;<br />     while ((str = in.readLine()) != null) <br />     {<br /><font color="#0066ff"><i>	dosomethingwith</i></font>(str);<br />     }<br />     in.close();<br />} <br />catch (IOException e) <br />{<br />}</pre>
		<br />
		<u>
				<b>
3. Reading a file into a BityArray</b>
		</u>
		<br />
		<br />
		<pre>    // Returns the contents of the file in a byte array.<br />    public static byte[] getBytesFromFile(File file) throws IOException <br />    {<br />        InputStream is = new FileInputStream(file);<br /><br />        // Get the size of the file<br />        long length = file.length();<br /><br />        // You cannot create an array using a long type.<br />        // It needs to be an int type.<br />        // Before converting to an int type, check<br />        // to ensure that file is not larger than Integer.MAX_VALUE.<br />        if (length &gt; Integer.MAX_VALUE) <br />	{<br />            // File is too large<br />        }<br /><br />        // Create the byte array to hold the data<br />        byte[] bytes = new byte[(int)length];<br /><br />        // Read in the bytes<br />        int offset = 0;<br />        int numRead = 0;<br />        while (offset &lt; bytes.length<br />               &amp;&amp; (numRead=is.read(bytes, offset, bytes.length-offset)) &gt;= 0) <br />	{<br />            offset += numRead;<br />        }<br /><br />        // Ensure all the bytes have been read in<br />        if (offset &lt; bytes.length) <br />	{<br />            throw new IOException("Could not completely read file "+file.getName());<br />        }<br /><br />        // Close the input stream and return bytes<br />        is.close();<br />        return bytes;<br /><br />    }</pre>
		<br />
		<u>
				<b>
4. Writing to a file</b>
		</u>
		<br />
		<br />
		<pre>try <br />{<br />    BufferedWriter out = new BufferedWriter(new FileWriter(<font color="#0066ff"><i>"filename"</i></font>));<br />    out.write(<font color="#0066ff"><i>"some string"</i></font>);<br />    out.close();<br />} <br />catch (IOException e) <br />{<br />}</pre>
Note: 

If the file does not already exist, it is automatically created.<br /><u><b><br />

5. Appending to a file</b></u><br /><br /><pre>try <br />{<br />     BufferedWriter out = new BufferedWriter(new FileWriter(<font color="#0066ff"><i>"filename"</i></font>, true));<br />     out.write(<font color="#0066ff"><i>"appending String"</i></font>);<br />     out.close();<br />} <br />catch (IOException e) <br />{<br />}</pre><br /><u><b>
6. Using a Random Access File</b></u><br /><br /><pre>try <br />{<br />     File f = new File(<font color="#0066ff"><i>"filename"</i></font>);<br />     RandomAccessFile raf = new RandomAccessFile(f, "rw");<br /><br />     // Read a character<br />     char ch = raf.readChar();<br /><br />     // Seek to end of file<br />     raf.seek(f.length());<br /><br />     // Append to the end<br />     raf.writeChars(<font color="#0066ff"><i>"aString"</i></font>);<br />     raf.close();<br />} <br />catch (IOException e) <br />{<br />}<br /><br /><br /></pre>
reference:<br />
http://javaalmanac.com/egs/java.io/pkg.html<br /><img src ="http://www.blogjava.net/dedian/aggbug/49154.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-05-31 08:12 <a href="http://www.blogjava.net/dedian/archive/2006/05/31/49154.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>convertion between InputStream &amp; String</title><link>http://www.blogjava.net/dedian/archive/2006/04/29/43911.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Fri, 28 Apr 2006 21:17:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/04/29/43911.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/43911.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/04/29/43911.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/43911.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/43911.html</trackback:ping><description><![CDATA[1. String --&gt; InputStream<br /><br />
InputStream convertToInputStream(String str)<br />
{<br />
        ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());<br />
        return is;<br />
}<br /><br />
2. InputStream --&gt; String<br />
     <br />
String convertToString(InputStream is)<br />
{<br />
        <br />
       BufferedReader in = new BufferedReader(new InputStreamReader(is));<br />
        StringBuffer buffer = new StringBuffer();<br />
        String line = "";<br />
        while ((line = in.readLine()) != null)<br />
        {<br />
             buffer.append(line);<br />
         }<br />
         return buffer.toString();<br />
            <br />
}<br /><br />
When I do the socket programming, I always need to deal with
inputstream and string, above are the basic ways to so that, but I am
not sure if there are any simpler ways to do that...<br /><br /><img src ="http://www.blogjava.net/dedian/aggbug/43911.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-04-29 05:17 <a href="http://www.blogjava.net/dedian/archive/2006/04/29/43911.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Simple way to convert between int &amp; String in Java</title><link>http://www.blogjava.net/dedian/archive/2006/04/25/42930.html</link><dc:creator>Dedian</dc:creator><author>Dedian</author><pubDate>Tue, 25 Apr 2006 01:22:00 GMT</pubDate><guid>http://www.blogjava.net/dedian/archive/2006/04/25/42930.html</guid><wfw:comment>http://www.blogjava.net/dedian/comments/42930.html</wfw:comment><comments>http://www.blogjava.net/dedian/archive/2006/04/25/42930.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/dedian/comments/commentRss/42930.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/dedian/services/trackbacks/42930.html</trackback:ping><description><![CDATA[It is common problem of convertion between int &amp; string for certian
computer language. Well, in Java, following are some easy ways I
usually apply:<br /><br />
1. int --&gt; String<br />
    a. apply "+" operation with an empty string<br />
            ex:<br />
            int index = 20;<br />
            String indexStr = "" + index;<br />
    b. use String function<br />
            ex:<br />
            int index = 20;<br />
            String indexStr = String.valueOf(index);<br />
    c. convert to Integer class firstly<br />
            ex:<br />
            int index = 20;<br />
            Integer Index = new Integer(index);<br />
            String indexStr = Index.toString();<br />
            or<br />
            String indexStr = Integer.toString(index);<br /><br />
2. String --&gt; int<br />
    a. use class Integer parse funtion<br />
        ex: <br />
        String indexStr = "20";<br />
        int index = Integer.parseInt(indexStr);<br />
        or<br />
        int index = (new Integer(indexStr)).intValue();<br /><br />
note: above convertion methods can be applied to other number types, such as float, long, double...<br /><br />
P.S. for 1.a method, should be noticed that following two expression are different:<br />
int i = 7;<br />
int j = 8;<br /><br />
String str1 = i + j + ""; //(str1 == "15")<br />
String str2 = "" + i + j; //(str2 == "78")<br />
 <br /><img src ="http://www.blogjava.net/dedian/aggbug/42930.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/dedian/" target="_blank">Dedian</a> 2006-04-25 09:22 <a href="http://www.blogjava.net/dedian/archive/2006/04/25/42930.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>