2013年5月17日 星期五

List 排序

使用 Collections.sort(list) 方法
本方法只能針對 List<Integer> 及 List<String> 進行『升冪排序』
詳見<範例程式 1>及 <範例程式 2>

若要針對其它自訂 Object 物件進行排序
則必須將自訂 Object 宣告為實作 Comparator 之物件,並於 Class 實作 Compare() 方法
實作時可自定排序方式為『升冪』或『降冪』
詳見<範例程式 3>
本例子為升冪,修改 compare() 方法之第一個 if 判斷為
Long.parseLong(value2) - Long.parseLong(value1) > 0
即可轉為降冪排序

--------------範例程式 1--------------
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(4);
        list.add(1);
        list.add(3);
        list.add(2);
        Collections.sort(list);
        for (int value : list) {
            System.out.println(value);
        }
    }


範例程式 1 執行結果 :
1
2
3
4

--------------範例程式 2--------------
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("d");
        list.add("a");
        list.add("c");
        list.add("b");
        Collections.sort(list);
        for (String value : list) {
            System.out.println(value);
        }
    }


範例程式 2 執行結果 :
a
b
c
d

--------------範例程式 3--------------
<3-1>
import java.util.Comparator;

public class TestBean implements Comparator {
    String modifyDate;
    double value;

    public TestBean() {
    }

    public TestBean(String lastModifyDate, double averageTestValue) {
        this.modifyDate = lastModifyDate;
        this.value = averageTestValue;
    }

    @Override
    public int compare(Object obj1, Object obj2) {
        TestBean bean1 = (TestBean) obj1;
        TestBean bean2 = (TestBean) obj2;
        String value1 = bean1.getModifyDate();
        String value2 = bean2.getModifyDate();

        if (Long.parseLong(value1) - Long.parseLong(value2) > 0) {
            return 1;
        } else if (value1.equals(value2)) {
            return 0;
        } else {
            return -1;
        }
    }

    public String getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(String modifyDate) {
        this.modifyDate = modifyDate;
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }
}

<3-2>
import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        List<TestBean> testList = new ArrayList<TestBean>();
        testList.add(new TestBean("20130314000000", 1));
        testList.add(new TestBean("20130311000000", 2));
        testList.add(new TestBean("20130313000000", 3));
        testList.add(new TestBean("20130312130345", 4));
        testList.add(new TestBean("20130312110435", 5));
        Comparator comp = new TestBean();
        Collections.sort(testList, comp);
        for (TestBean a : testList) {
            System.out.println(a.getModifyDate() + ", " + a.getValue());
        }
    }
}

範例程式 3 執行結果 :
20130311000000, 2.0
20130312110435, 5.0
20130312130345, 4.0
20130313000000, 3.0
20130314000000, 1.0

2013年5月6日 星期一

Oracle, SQL 以多個欄位為 Key, 取出 table 中另一欄位為 max 之資料


table_1 資料表如下圖:

如上資料表中,此資料表中並沒有設定 Primary Key欄位,但可由 column_1, column_2, column_3, column_4, column_5, column_6 的組合當成 Key 值,但仍有可能有重覆之資料,如表中所示,column_4 = 8 , 9 , 10 的資料都有多筆,但取資料時又希望依據相同的數據,將這些重覆的過濾掉只留下 check_column 數字最大的那筆時,可利用下面的SQL完成。

select *
from table_1
where (column_1, column_2, column_3, column_4, column_5, column_6, check_column)
in (
      select
          column_1,
          column_2,
          column_3,
          column_4,
          column_5,
          column_6,
          max(check_column)
       from table_1
       group by
          column_1,
          column_2,
          column_3,
          column_4,
          column_5,
          column_6
   )

結果如下圖:

2013年4月11日 星期四

Java 四捨五入至小數第 n 位

//欲四捨五入的數字
double y = 1.890784;

//設定要到小數第 3 位
int n = 3;

//執行四捨五入
double x = new BigDecimal(y).setScale(n, BigDecimal.ROUND_HALF_UP).doubleValue();

//印出結果
System.out.println(x);

//不要有科學記號出現的方法
double x = new BigDecimal(y).setScale(n, BigDecimal.ROUND_HALF_UP).toPlainString();

2013年4月2日 星期二

Java XPath 使用範例

XML 範例:books.xml
<?xml version="1.0" encoding="UTF-8"?>
<LIBRARY>
    <BOOKS>
        <BOOK isbn="ABCD7327923">
            <NAME>Java Programing</NAME>
            <SUBJECT>Java J2EE</SUBJECT>
            <AUTHORS>
                <AUTHOR>Tuna TORE</AUTHOR>
                <AUTHOR>Linus Torvalds</AUTHOR>
                <AUTHOR>James Gosling</AUTHOR>
            </AUTHORS>
        </BOOK>
        <BOOK isbn="DFGH09093232">
             <NAME>XPATH for Dummies</NAME>
           <SUBJECT> XPATH development</SUBJECT>
            <AUTHORS>
                <AUTHOR>Linus Torvalds</AUTHOR>
                <AUTHOR>John Hawking</AUTHOR>
            </AUTHORS>
        </BOOK>
        <BOOK isbn="DSKL2393A">
            <NAME>J2EE Patterns</NAME>
            <SUBJECT>Design Patterns</SUBJECT>
            <AUTHORS>
                <AUTHOR>Aka Tuna</AUTHOR>
            </AUTHORS>
        </BOOK>
    </BOOKS>
    <DVDS>
        <DVD id="123456">
            <NAME>Music DVD</NAME>
            <CONTENT>Music</CONTENT>
            <AUTHORS>
                <AUTHOR>James Gosling</AUTHOR>
                <AUTHOR>Bill Gates</AUTHOR>
            </AUTHORS>
        </DVD>
        <DVD id="3213324">
            <NAME>Natural Science</NAME>
            <CONTENT>Science</CONTENT>
            <AUTHORS>
                <AUTHOR>John Green</AUTHOR>
                <AUTHOR>Bill Gates</AUTHOR>
            </AUTHORS>
        </DVD>
        <DVD id="4353534">
            <NAME>Rally</NAME>
            <CONTENT>Race</CONTENT>
            <AUTHORS>
                <AUTHOR>Tuna</AUTHOR>
            </AUTHORS>
        </DVD>
    </DVDS>
</LIBRARY>



程式範例: XpathTest.java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XPathTest {

    public static void main(String[] args) throws Exception {

        //loading the XML document from a file
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        Document xmlDocument = builder.parse("src\\books.xml");

        XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        //getting the name of the book having an isbn number == ABCD7327923
        String isbnNum = "ABCD7327923";
        XPathExpression xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" + isbnNum + "']//NAME");
        String nameOfTheBook = xPathExpression.evaluate(xmlDocument, XPathConstants.STRING).toString();

        System.out.println("name of the Book ---> " + nameOfTheBook);

        //getting all authors for the book having an isbn number == ABCD7327923
        xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" + isbnNum + "']//AUTHORS//AUTHOR");

        NodeList nodeListBook = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);
        System.out.println("Total number of authors for the book " + nameOfTheBook + " is --> "
                + nodeListBook.getLength());

        for (int index = 0; index < nodeListBook.getLength(); index++) {
            String author = nodeListBook.item(index).getTextContent();
            System.out.println("Author " + (index + 1) + " ---> " + author);
        }

        //getting all tags for the dvd having id == 3213324
        String dvdID = "3213324";
        xPathExpression = xPath.compile("//LIBRARY//DVDS//DVD[@id='" + dvdID + "']");
        NodeList nodeDVD = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);
        NodeList nodeListForDVD = nodeDVD.item(0).getChildNodes();

        for (int index = 0; index < nodeDVD.item(0).getChildNodes().getLength(); index++) {
            String tagName = nodeListForDVD.item(index).getNodeName();
            String tagValue = nodeListForDVD.item(index).getTextContent();
            if (!tagName.equals("#text")) //handling empty comment (#text)
                System.out.println(tagName + " value ---> " + tagValue);
        }
    }
}

執行結果:
name of the Book: Java Programing
Total number of authors for the book Java Programing is --> 3
Author 1: Tuna TORE
Author 2: Linus Torvalds
Author 3: James Gosling
NAME value: Natural Science
CONTENT value: Science
AUTHORS value:
                John Green
                Bill Gates

參考文件:http://tunatore.wordpress.com/2011/05/20/how-to-use-xpath-i-java-simple-example/

2013年3月18日 星期一

Ant 部署工具使用範例


分為兩部份:
1. build.sh
2. build.xml


《build.sh》
#!/bin/bash
# ---------------------------------------------------------------
#
#
# ---------------------------------------------------------------

# define variables
export ANT_HOME=/app/build/ant-1.8.1
export BUILD_HOME=/app/build
export BUILD_FILE=$BUILD_HOME/build.xml

#target=$1

$ANT_HOME/bin/ant -buildfile $BUILD_FILE



《build.xml》

<!--basedir 代表執行目錄為當前所在目錄,default 屬性代表預設執行的 target 區塊之 name-->
<project name="nova" basedir="." default="make-dist">
<!--property標籤用來設定變數,目前範例為設定備用的目錄路徑-->
<property name="src.dir" value="/app/build/nova/src" />
<property name="src.resource.dir" value="${src.dir}/src/main/resource/" />
<property name="target.dir" value="/app/build/nova/target" />
<property name="dist.dir" value="/app/build/nova/dist" />
<property name="backup.dir" value="/app/build/nova/bakup" />

<target name="update-src">

<!--log information from svn and stop build if there is any error -->
<exec executable="svn" spawn="false" failonerror="true">
<arg line="update --username svnreader --password svnreader ${src.dir}" />
</exec>
</target>

<target name="prepare">

<delete dir="${backup.dir}" />
<mkdir dir="${target.dir}" />
<mkdir dir="${backup.dir}" />
<copy todir="${backup.dir}">
<fileset dir="${target.dir}" />
</copy>
</target>

<target name="clean" depends="prepare">

<delete includeemptydirs="true">
<fileset dir="${target.dir}" includes="**/*" />
</delete>

</target>


<target name="compile-src" depends="update-src, prepare, clean">

<javac srcdir="${src.dir}" destdir="${target.dir}" debug="on" optimize="off" deprecation="on">
<classpath>
<fileset dir="${src.dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
</javac>
</target>

<target name="make-dist" depends="compile-src">

<copy todir="${dist.dir}">
<fileset dir="${target.dir}" />
</copy>
<copy todir="${dist.dir}">
<fileset dir="${src.resource.dir}">
<include name="**/*.vm/**" />
</fileset>
</copy>
</target>

</project>


參考資料網站:
http://itgroup.blueshop.com.tw/Gpx1981/gpx1981?n=convew&i=8916


2013年3月16日 星期六

安裝 Samba 範例


<準備安裝檔案>
創建 samba 目錄於 /tmp
將 samba-3.5.8.tar.gz (samba的安裝檔) 復製到 /tmp/samba 底下
tar -zxf samba-3.5.8.tar.gz
(/tmp/samba/samba-3.5.8 目錄會出現)

<開始安裝>
cd /tmp/samba/samba-3.5.8
cd source3
./configure --prefix=/usr/local/samba --enable-vfs
make proto
make
make install

<修改設定檔案>
vi /etc/samba/smb.conf 或 vim smb.conf

於檔案最下方加入以下參數
[XXXX] ← 中括號內的文字即代表[分享名稱] :這個分享名稱很重要,它是一個『代號』而已。
        path = /old_file
        writeable = no
        browseable = yes
        valid users = XXXX


[YYYY]
comment = Public Stuff
path = /aaa/bbb/ccc/
public = yes
writable = yes
printable = no
write list = +staf
browseable = yes
guest ok = yes  ←  代表任何人都可以看到



存檔後離開 vi 編輯器,回到命令提示字元

<建立 Samba 帳號>
1.
smbpasswd -a XXXX  ←  即剛才設定的[分享名稱]
New SMB password: xxxx
Retype new SMB password: xxxx


smbpasswd -a YYYY ←  即剛才設定的[分享名稱]
New SMB password: yyyy
Retype new SMB password: yyyy



<啟動/關閉 等 Samba 相關指令>
[root@twplmfs02 samba]# /etc/rc.d/init.d/smb 參數
參數種類 {start|stop|restart|reload|status|condrestart}

<刪除 Samba 帳號>
pdbedit -x -u 帳號名

<參考文件>
http://linux.vbird.org/linux_server/0370samba.php