<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Rising Sun

      BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
      148 隨筆 :: 0 文章 :: 22 評論 :: 0 Trackbacks

    2013年5月29日 #

         摘要: 看了網上的許多對于lucene 分詞解析的文章一知半解且代碼比較老舊,為透徹、系統、全面、深刻的了解分詞是怎么一個過程,通過自定義一個分詞器來分析理解。 其中分詞部分利用ICTCLAS4j接口實現。結構如下所示:            要實現自定義的ICTCLAS4jAnalyzer必須繼承Analy...  閱讀全文
    posted @ 2015-01-07 10:11 brock 閱讀(1098) | 評論 (0)編輯 收藏

    Lucene Directory類就像它的意思一樣“目錄”,如“目錄”不存在,第一次啟動被創建,一旦文件被創建,它只能打開閱讀,或刪除。允許讀取和寫入隨機訪問。Java I/O api 不能直接使用,只能通過這個API 。Directory的實現類可以分為文件目錄,內存目錄和目錄的代理類及工具類。具體如下圖所示:


    一:文件目錄

    SimpleFSDirectory:FSDirectory的簡單實現,并發能力有限,遇到多線程讀同一個文件時會遇到瓶頸,通常用NIOFSDirectoryMMapDirectory代替。

    NIOFSDirectory:通過java.nio's FileChannel實行定位讀取,支持多線程讀(默認情況下是線程安全的)。該類僅使用FileChannel進行讀操作,寫操作則是通過FSIndexOutput實現。

    注意:NIOFSDirectory 不適用于Windows系統,另外如果一個訪問該類的線程,在IO阻塞時被interruptcancel,將會導致底層的文件描述符被關閉,后續的線程再次訪問NIOFSDirectory時將會出現ClosedChannelException異常,此種情況應用SimpleFSDirectory代替。

    MMapDirectory:通過內存映射進行讀,通過FSIndexOutput進行寫的FSDirectory實現類。使用該類時要保證用足夠的虛擬地址空間。另外當通過IndexInputclose方法進行關閉時并不會立即關閉底層的文件句柄,只有GC進行資源回收時才會關閉。

     

    為了能適應各個操作系統選擇最佳Directory方案,lucene 提供FSDirectory類的靜態方法open()實現自適應。

     public static FSDirectory open(File path, LockFactory lockFactory) throws IOException {

        if ((Constants.WINDOWS || Constants.SUN_OS || Constants.LINUX)

              && Constants.JRE_IS_64BIT && MMapDirectory.UNMAP_SUPPORTED) {

          return new MMapDirectory(path, lockFactory);

        } else if (Constants.WINDOWS) {

          return new SimpleFSDirectory(path, lockFactory);

        } else {

          return new NIOFSDirectory(path, lockFactory);

        }

      }

    二:內存目錄

    RAMDirectory:常駐內存的Directory實現方式。默認通過SingleInstanceLockFactory(單實例鎖工廠)進行鎖的實現。該類不適合大量索引的情況另外也不適用于多線程的情況 在索引數據量大的情況下建議使用MMapDirectory代替。RAMDirectoryDirectory抽象類在使用內存最為文件存儲的實現類,其主要是將所有的索引文件保存到內存中。這樣可以提高效率。但是如果索引文件過大的話,則會導致內存不足,因此,小型的系統推薦使用,如果大型的,索引文件達到G級別上,推薦使用FSDirectory

    NRTCachingDirectory:是對RAMDirectory的封裝,適用于近乎時時(near-real-time)操作的環境。

    三:Direcotry的代理類及工具類

    FileSwitchDirectory:文件切換的Directory實現.針對lucene的不同的索引文件使用不同的Directory .借助FileSwitchDirectory整合不同的Directory實現類的優點于一身
    比如MMapDirectory,借助內存映射文件方式提高性能,但又要減少內存切換的可能 ,當索引太大的時候,內存映射也需要不斷地切換,這樣優點也可能變缺點,而之前的NIOFSDirectory實現java NIO的方式提高高并發性能,但又因高并發也會導致IO過多的影響,所以這次可以借助FileSwitchDirectory發揮他們兩的優點。

    RateLimitedDirectoryWrapper:通過IOContext來限制讀寫速率的Directory封裝類。

    CompoundFileDirectory:用于訪問一個組合的數據流。僅適用于讀操作。對于同一段內擴展名不同但文件名相同的所有文件合并到一個統一的.cfs文件和一個對應的.cfe文件內。
    .cfs文件由Header,FileDataFileCount組成。.cfe文件由Header,FileCount,FileName,DataOffset,DataLength組成。.cfs文件中存儲著索引的概要信息及組合文件
    的數目(FileCount)。.cfe文件存儲文件目錄的條目內容,內容中包括文件數據扇區的起始位置,文件的長度及文件的名稱。

    TrackingDirectoryWrapperDirectory的代理類。用于記錄哪些文件被寫入和刪除。

    四:Direcotry讀寫對象的類圖




     文章轉載過來的!

    posted @ 2015-01-07 10:09 brock 閱讀(273) | 評論 (0)編輯 收藏

        本機已經安裝了jdk1.6,而比較早期的項目需要依賴jdk1.5,于是同時在本機安裝了jdk1.5和jdk1.6. 

     安裝jdk1.5前,執行java -version得到

    java version "1.6.0_38"
    Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
    Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)


    安裝完jdk1.5,并修改環境變量JAVA_HOME為D:\devSoftware\jdk1.5.再執行 java -version時,依然顯示:

    java version "1.6.0_38"
    Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
    Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)


    看上去,新的環境變量JAVA_HOME=D:\devSoftware\jdk1.5并沒有生效。 在網上找了很多資料才發現:

          在安裝JDK1.6時(本機先安裝jdk1.6再安裝的jdk1.5),自動將java.exe、javaw.exe、javaws.exe三個可執行文件復制到了C:\Windows\System32目錄,由于這個目錄在WINDOWS環境變量中的優先級高于JAVA_HOME設置的環境變量優先級


    解決方案:將java.exe,javaw.exe,javaws.exe刪除即可。開啟新的命令行窗口,再執行java -version時,就得到了期望中的結果

    java version "1.5.0_17"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_17-b04)
    Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_17-b04, mixed mode)


    posted @ 2015-01-06 11:45 brock 閱讀(7029) | 評論 (0)編輯 收藏

    在學lucene 之初看了許多書,都是走馬觀花,沒有項目的驅動下,來一個用例demo感覺也不是很難,“我會了”這是我的第一感覺。

             2013年底公司接到一個項目用到lucene,這是我第一次正真接觸Lucene,代碼比較老3.6版本,不適合新項目的需求(空間查詢)。于是下載了最新版本 4.51,有帶“空間查詢”模塊。各大搜索引擎都沒有找到像樣例子,于是想到了lucene svn trunk目錄測試用例中找到了測試例子,開始了一段lucene之旅。

     

    寫數據,創建IndexWriter,通過它的構造函數需要一個索引目錄(Diectory)和索引寫入配置項(InderWriterConfig,直接上代碼:

    //設置寫入目錄(好幾種呵呵)

    Directory d=FSDirectory.open(new File("D:/luceneTest"));

    //設置分詞 StandardAnalyzer(會把句子中的字單個分詞)

    Analyzer analyzer= new StandardAnalyzer(Version.LUCENE_45);

    //設置索引寫入配置

    IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_45,analyzer);

    //設置創建模式

    //config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

    IndexWriter indexwriter= new IndexWriter(d,config);

     

        上面四行代碼就創建好了indexwriter,下面把數據填入就好了,寫入有多種方式如下圖:


             addDocment 舉例代碼如下:

    Document doc=new Document(); 

            doc.add(new StringField("id", "1", Store.YES));

            doc.add(new StringField("name", "brockhong", Store.YES));

            doc.add(new TextField("content", "lucene 文檔第一次寫看著給分吧", Store.YES)); 

    //寫入數據

    indexwriter.addDocument(doc);

    //提交

    indexwriter.commit();

    Luke 工具查看Text列,這是標準分詞惹的禍哦!寫入成功。


             讀數據查詢,創建 IndexSearcher 構造函數設置indexReader ,輸入查詢條件,上面content字段數據設置了分詞,所以必須通過查詢解析類QueryParser設定分詞字段、版本、分詞模式,并通過parse方法得到查詢條件。代碼如下:       

     //讀數據

     //創建 indexReader 這個已過時 IndexReader.open(d),里面的代碼一樣可能為了兼容老版本

     IndexReader indexReader = DirectoryReader.open(d);

     IndexSearcher indexSearcher = new IndexSearcher(indexReader);

    //查詢 設置分詞字段

    QueryParser queryParser = new QueryParser(Version.LUCENE_45, "content",

                       new StandardAnalyzer(Version.LUCENE_45));

     //or 關系 “給”、“分”

             queryParser.setDefaultOperator(QueryParser.OR_OPERATOR);

    Query query = queryParser.parse("給分");

     

    TopDocs results = indexSearcher.search(query, 100);

    int numTotalHits = results.totalHits;

    System.out.println(" " + numTotalHits + " 完全匹配的文檔");

    ScoreDoc[] hits = results.scoreDocs;

    for (int i = 0; i < hits.length; i++) {

                  Document document = indexSearcher.doc(hits[i].doc);

                  System.out.println("content:" + document.get("content"));

    }


    pasting
    posted @ 2014-12-31 17:07 brock 閱讀(332) | 評論 (0)編輯 收藏

    http://blog.csdn.net/ablipan/article/details/8198692

    使用SAXReader的read(File file)方法時,如果xml文件異常會導致文件被服務器占用不能移動文件,建議不使用read(File file)方法而使用read(FileInputStream fis)等流的方式讀取文件,異常時關閉流,這樣就不會造成流未關閉,文件被鎖的現象了。(在服務器中運行時會鎖住文件,main方法卻不會)。


    1、以下方式xml文件異常時會導致文件被鎖

    1.                    Document document = null;  
    2. File file = new File(xmlFilePath);  
    3. SAXReader saxReader = new SAXReader();  
    4. try  
    5. {  
    6.     document = saxReader.read(file);  
    7. } catch (DocumentException e)  
    8. {  
    9.     logger.error("將文件[" + xmlFilePath + "]轉換成Document異常", e);  
    10. }  


    2、以下方式xml文件異常時不會鎖文件(也可以使用其他的流來讀文件)

    1.                 Document document = null;  
    2. FileInputStream fis = null;  
    3. try  
    4. {  
    5.     fis = new FileInputStream(xmlFilePath);  
    6.     SAXReader reader = new SAXReader();  
    7.     document = reader.read(fis);  
    8. }   
    9. catch (Exception e)  
    10. {  
    11.     logger.error("將文件[" + xmlFilePath + "]轉換成Document異常", e);  
    12. }   
    13. finally  
    14. {  
    15.     if(fis != null)  
    16.     {  
    17.         try  
    18.         {  
    19.             fis.close();  
    20.         } catch (IOException e)  
    21.         {  
    22.             logger.error("將文件[" + xmlFilePath + "]轉換成Document,輸入流關閉異常", e);  
    23.         }  
    24.     }  
    25. }  
    posted @ 2014-09-02 14:00 brock 閱讀(485) | 評論 (0)編輯 收藏

    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>二次開發示例</title>
    <link rel="stylesheet" href="../OpenLayers2.11/theme/default/style.css" type="text/css" />
        <script type="text/javascript" src="../OpenLayers2.11/OpenLayers.js"></script>
        <script type="text/javascript" src="../OpenLayers2.11/OpenLayersEx.js?random=8852c822-1ab8-4c0a-9717-b6f4c2b98115"></script>
     
        <!-- Import OpenLayers, reduced, wms read only version -->
        <!--<script src="../OpenLayers.js" type="text/javascript"></script>-->
    <script type="text/javascript">
       var map;
    var bounds = new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
    function init() {
        var options = {
                           controls:[new OpenLayers.Control.XPanZoomBar(),new OpenLayers.Control.Navigation(),new OpenLayers.Control.MousePosition({numDigits:2})] ,
                            projection: 'EPSG:900913',
                            maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                            maxResolution: 156543.0339,
                            units: 'm',
                            zoomLevel: 8
                        };
        map = new OpenLayers.Map('map',options);    
        
    /*{
            div: "map",
            projection: "EPSG:900913",
            units: "m",
            maxExtent: new OpenLayers.Bounds(
                -20037508.34, -20037508.34, 20037508.34, 20037508.34
            ),
            maxResolution: 156543.0339,
    zoomLevel: 8
        }*/
       // var osm = new OpenLayers.Layer.OSM();
        // If tile matrix identifiers differ from zoom levels (0, 1, 2, ...)
        // then they must be explicitly provided.
        var matrixIds = new Array(19);
        for (var i=0; i<16; ++i) {
            matrixIds[i] = i+"";
        }
    var wmts2 = new OpenLayers.Layer.WMTS({
            name: "Medford Buildings",
            url: "http://t0.tianditu.com/cia_w/wmts",
            layer: "cia",
            matrixSet: "w",
            matrixIds: matrixIds,
            format: "tiles",
            style: "default",
            opacity: 0.7,
            isBaseLayer: false
        });       
        var wmts = new OpenLayers.Layer.WMTS({
            name: "vec",
            url: "http://t0.tianditu.com/vec_w/wmts",
            layer: "vec",
            matrixSet: "w",
            matrixIds: matrixIds,
            format: "tiles",
            style: "default",
            opacity:1,
            isBaseLayer: true
        });                
        map.addLayers( [wmts,wmts2]);
      //  map.addControl(new OpenLayers.Control.LayerSwitcher());
      //  map.setCenter(new OpenLayers.LonLat(13391734.740566667,3535411.228859166),7);
    map.moveTo(new OpenLayers.LonLat(13391734.740566667,3535411.228859166),7);
    }
    </script>
    </head>
     <body onload="init();">
            <h1 id="title">Web Map Tile Service (WMTS) Layer</h1>
            
        
            
            <div id="map" class="smallmap"></div>
            
           
        </body>
    </html>
    posted @ 2014-06-24 17:00 brock 閱讀(833) | 評論 (0)編輯 收藏

    arcgis

    CGCS2000_3_Degree_GK_Zone_40

    WKID: 4528 Authority: EPSG

     

    Projection: Gauss_Kruger

    False_Easting: 40500000.0

    False_Northing: 0.0

    Central_Meridian: 120.0

    Scale_Factor: 1.0

    Latitude_Of_Origin: 0.0

    Linear Unit: Meter (1.0)

     

    Geographic Coordinate System: GCS_China_Geodetic_Coordinate_System_2000

    Angular Unit: Degree (0.0174532925199433)

    Prime Meridian: Greenwich (0.0)

    Datum: D_China_2000

      Spheroid: CGCS2000

        Semimajor Axis: 6378137.0

        Semiminor Axis: 6356752.314140356

    Inverse Flattening: 298.257222101

     

    Java 自定義

     

    String [] proj4_w = new String [] { 

    "+proj=tmerc", 
    "+lat_0=0", 
    "+lon_0=120", 
    "+ellps=GRS80", 
    "+units=m", 
    "+x_0=40500000",
    "+y_0=0",
    "+k=1.0"
    };

    經緯度轉換

           ///+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=40500000 +y_0=0 +ellps=GRS80 +units=m +no_defs

                    Point2D.Double srcProjec = null;

                    Point2D.Double dstProjec = null;

                    Projection proj = ProjectionFactory.fromPROJ4Specification (proj4_w);

    //  "epsg:4528" 數據從proj4 拷貝 nad

    //      Point2D.Double srcProjec = null;

    //      Point2D.Double dstProjec = null;

    //      Projection proj = ProjectionFactory.getNamedPROJ4CoordinateSystem ("epsg:4528");

     

            srcProjec = new Point2D.Double (120.159,30.267);

            //40515348.2903 3349745.5395

           

            dstProjec = proj.transform (srcProjec, new Point2D.Double ());

            System.out.println ("TM:" + dstProjec);

        // TM: Point2D.Double [644904.399587292, 400717.8948938238]

     

            srcProjec = new Point2D.Double (40515348.2903 ,3349745.5395);

            dstProjec = proj.inverseTransform (srcProjec, new Point2D.Double ());

           

            System.out.println ("TM:" + dstProjec);

    posted @ 2014-06-20 11:41 brock 閱讀(3725) | 評論 (0)編輯 收藏

    今天研究Oracle遇到了這個問題ora-01033:oracle initializationor shutdown in progress

    ORA-01033:ORACLEinitialization or shutdown in progress

    解決方法

    1)開始-運行-cmd

    2)命令行中輸入SQLPLUS SYS/SYS AS SYSDBA

    3)輸入SHUTDOWN

    4)輸入STARTUP.注意這里是最重要的地方,在顯示相關數據后,它還會顯示為什么不能啟動的錯誤所在.

     

    C:\Users\lenovo>SQLPLUSSYS/SYS AS SYSDBA

    SQL*Plus: Release 10.2.0.3.0 - Production on星期三 7月 3 11:43:32 2013

    Copyright (c) 1982, 2006, Oracle.  All Rights Reserved.

    連接到:

    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 -Production

    With the Partitioning, OLAPand Data Mining options

    SQL> SHUTDOWN

    ORA-01109:數據庫未打開

    已經卸載數據庫。

    ORACLE例程已經關閉。

    SQL> STARTUP

    ORACLE例程已經啟動。

    Total System Global Area 293601280 bytes

    Fixed Size                 1290208 bytes

    Variable Size            234881056 bytes

    Database Buffers           50331648 bytes

    Redo Buffers               7098368 bytes

    數據庫裝載完畢。

    ORA-01157:無法標識/鎖定數據文件 6 - 請參閱 DBWR 跟蹤文件

    ORA-01110:數據文件 6: 'F:\DC\DB\SDRS\TS_SDRS.DBF'

    SQL> alter databasedatafile'F:\DC\DB\SDRS\TS_SDRS.DBF'offline drop;

     

    數據庫已更改。

     

    SQL> alter database open;

     

    數據庫已更改。

     

    SQL> drop tablespaceTS_SDRS including contents;

     

    表空間已刪除。

    SQL> create undo tablespace TS_SDRS

      2  datafile'CracleoradatasmsdbUNDOTBS01.DBF'size 2048M extent management local;

     

    表空間已創建。

     

    SQL> alter system setundo_tablespace=TS_SDRS;

     

    系統已更改。

     

    SQL> shutdown

    數據庫已經關閉。

    已經卸載數據庫。

    ORACLE例程已經關閉。

    SQL> startup

    ORACLE例程已經啟動。

     

    Total System Global Area  293601280 bytes

    Fixed Size                 1290208 bytes

    Variable Size            243269664 bytes

    Database Buffers          41943040 bytes

    Redo Buffers               7098368 bytes

    數據庫裝載完畢。

    數據庫已經打開。

    SQL>


    ------------------
    ORA-01245、ORA-01547錯誤的解決            

    數據庫rman restore database 之后,執行recover database的時候,報告ORA-01245錯誤,詳細的錯誤信息如下:


    SQL> recover database until cancel;
    ORA-00279: change 575876 generated at 12/01/2009 08:19:49 needed for thread 1
    ORA-00289: suggestion :
    /oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc
    ORA-00280: change 575876 for thread 1 is in sequence #2


    Specify log: {=suggested | filename | AUTO | CANCEL}
    auto
    ORA-00308: cannot open archived log
    '/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc'
    ORA-27037: unable to obtain file status
    Linux Error: 2: No such file or directory
    Additional information: 3


    ORA-00308: cannot open archived log
    '/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc'
    ORA-27037: unable to obtain file status
    Linux Error: 2: No such file or directory
    Additional information: 3


    ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGS would get error below
    ORA-01245: offline file 2 will be lost if RESETLOGS is done
    ORA-01110: data file 2: '/oracle/oradata/orcl/undotbs01.dbf'


    SQL>

     

    [@more@]

    檢查ORA-01245那一行,發現是datafile 2狀態為offline,解決的方法就是首先將datafile 2 online,然后再recover database。

    SQL> alter database datafile 2 online;

    Database altered.

    SQL> recover database until cancel;
    ORA-00279: change 575876 generated at 12/01/2009 08:19:49 needed for thread 1
    ORA-00289: suggestion :
    /oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc
    ORA-00280: change 575876 for thread 1 is in sequence #2


    Specify log: {=suggested | filename | AUTO | CANCEL}
    cancel
    Media recovery cancelled.
    SQL> alter database open resetlogs;

    Database altered.

    SQL>

    --------------------

    ORA-01589: 要打開數據庫則必須使用 RESETLOGS 或 NOR


    ORA-01589: 要打開數據庫則必須使用 RESETLOGS 或 NORESETLOGS
    選項


    SQL> alter database open 
    ORA-01589: 要打開數據庫則必須使用 RESETLOGS 或
    NORESETLOGS 選項

    SQL> alter database open resetlogs;
    alter database
    open resetlogs
    *
    ERROR 位于第 1 行:
    ORA-01113: 文件 1 需要介質恢復
    ORA-01110:
    數據文件 1: 'E:\ORACLE\ORADATA\EYGLE\SYSTEM01.DBF'

    SQL> recover database
    using backup controlfile;
    ORA-00279: 更改 1670743 (在 04/17/2008 14:13:16 生成)
    對于線程 1 是必需的
    ORA-00289: 建議: E:\ORACLE\ORA92\RDBMS\ARC00030.001
    ORA-00280:
    更改 1670743 對于線程 1 是按序列 # 30 進行的

    指定日志: {<RET>=suggested | filename |
    AUTO | CANCEL}
    E:\oracle\oradata\EYGLE\REDO01.LOG
    ORA-00310: 存檔日志包含序列
    29;要求序列 30
    ORA-00334: 歸檔日志:
    'E:\ORACLE\ORADATA\EYGLE\REDO01.LOG'

    SQL> recover database using
    backup controlfile;
    ORA-00279: 更改 1670743 (在 04/17/2008 14:13:16 生成) 對于線程 1
    是必需的
    ORA-00289: 建議: E:\ORACLE\ORA92\RDBMS\ARC00030.001
    ORA-00280: 更改
    1670743 對于線程 1 是按序列 # 30 進行的

    指定日志: {<RET>=suggested | filename |
    AUTO |
    CANCEL}
    E:\oracle\oradata\EYGLE\REDO02.LOG
    已應用的日志。
    完成介質恢復。
    SQL>
    alter database open resetlogs;
    數據庫已更改。


    OK,搞定了!

    posted @ 2014-04-30 14:38 brock 閱讀(9087) | 評論 (0)編輯 收藏

    首先來看問題,然后來看函數的定義,其實什么都在函數定義里面說明白了

    1.正則表達式字符串問題

    首先輸入的regex是一個正則表達式,而不是一個普通的字符串,所以導致很多在正則表達式里面有特殊意義的比如 "." "|" "\" ,如果直接使用是不行的,另外一個方面我們輸入的regex是以字符串形式傳遞的,對有些字符必須要轉義,尤其是"\",下面請看例子

    String[] aa = "aaa|bbb|ccc".split("|");//wrong
    String[] aa = "aaa|bbb|ccc".split("\\|"); //

     

     String[] aa = "aaa*bbb*ccc".split("*");//wrong
     String[] aa = "aaa|bbb|ccc".split("\\*");

     

     String[] aa = "aaa*bbb*ccc".split(".");//wrong
     String[] aa = "aaa|bbb|ccc".split("\\.");

     

    String[] aa = "aaa\\bbb\\bccc".split("\\");//wrong

    String[] aa = "aaa\\bbb\\bccc".split("\\\\");

     

    2.數組長度的問題

    String a = "";
    String[] b = a.split(",");
    b.length為 1;
    *
    String a = "c";
    String[] b = a.split(",");
    b.length為 1;
    **
    String a = "c,,,";
    String[] b = a.split(",");
    b.length為 1;
    ***
    String a = "c,,c";
    String[] b = a.split(",");
    b.length為 3;
    ****
    String a = ",";
    String[] b = a.split(",");
    b.length為 0;

     

    其實只要添加一個參數即可,例如

    String str = "abcdef,ghijk,lmno,pqrst,,,";       

    String[] array = str.split(",");
    輸出:abcdef,ghijk,lmno,pqrst,

     

    String str = "abcdef,ghijk,lmno,pqrst,,,";
    String[] array 
    = str.split(",",-1);

    輸出:abcdef,ghijk,lmno,pqrst,,,,

     

    public String [] split (String  regex, int limit) 

    最后一個參數limit是影響返回數組的長度的

    =========================請關注紅色字體(括號內為注釋)==========================================

    public String[] split(String regex)

    根據給定的正則表達式的匹配來拆分此字符串。

    該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數 split 方法。因此,結果數組中不包括結尾空字符串(直接使用會造成數組大小問題)

    例如,字符串 "boo:and:foo" 產生帶有下面這些表達式的結果:

    Regex結果
    :{ "boo", "and", "foo" }
    o{ "b", "", ":and:f" }

     

    參數:
    regex - 定界正則表達式
    返回:
    字符串數組,根據給定正則表達式的匹配來拆分此字符串,從而生成此數組。

    public String[] split(String regex,
                          int limit)

    根據匹配給定的正則表達式來拆分此字符串。

    此方法返回的數組包含此字符串的每個子字符串,這些子字符串由另一個匹配給定的表達式的子字符串終止或由字符串結束來終止。數組中的子字符串按它們在此字符串中的順序排列。如果表達式不匹配輸入的任何部分,則結果數組只具有一個元素,即此字符串。

    limit 參數控制模式應用的次數,因此影響結果數組的長度。如果該限制 n 大于 0,則模式將被最多應用 n - 1 次,數組的長度將不會大于 n,而且數組的最后項將包含超出最后匹配的定界符的所有輸入。如果 n 為非正,則模式將被應用盡可能多的次數,而且數組可以是任意長度。如果 n 為零,則模式將被應用盡可能多的次數,數組可有任何長度,并且結尾空字符串將被丟棄。

    例如,字符串 "boo:and:foo" 使用這些參數可生成下列結果:

    RegexLimit結果
    :2{ "boo", "and:foo" }
    :5{ "boo", "and", "foo" }
    :-2{ "boo", "and", "foo" }
    o5{ "b", "", ":and:f", "", "" }
    o-2{ "b", "", ":and:f", "", "" }
    o0{ "b", "", ":and:f" }

    這種形式的方法調用 str.split(regex, n) 產生與以下表達式完全相同的結果:

    Pattern.compile(regex).split(str, n)

     

    參數:
    regex - 定界正則表達式
    limit - 結果閾值,如上所述
    返回:
    字符串數組,根據給定正則表達式的匹配來拆分此字符串,從而生成此數組

     

    posted @ 2014-04-28 10:15 brock 閱讀(247) | 評論 (0)編輯 收藏

      List<Calendar> l = new ArrayList<Calendar>(); 
    while (true) {
    l.add(Calendar.getInstance());
    System.out.println(l.size());
    }
    605473
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Calendar.<init>(Unknown Source)
    at java.util.GregorianCalendar.<init>(Unknown Source)
    at java.util.Calendar.createCalendar(Unknown Source)
    at java.util.Calendar.getInstance(Unknown Source)
    at jodatestmemory.Main.main(Main.java:25)
    posted @ 2014-01-08 11:26 brock 閱讀(367) | 評論 (0)編輯 收藏

    頭文件
    #ifndef CLASS_GEOMETRYTOSTRING
    #define CLASS_GEOMETRYTOSTRING
     
    #include <iostream>
    #include <FileGDBAPI.h>
    using namespace std;
    class GeometryToString
    {
    public:
    static  bool getGeometryStr( FileGDBAPI::ShapeBuffer &geometry,string srid,string &geometrystr); 
    private:
    static void getPointGML(FileGDBAPI::PointShapeBuffer *&pbuffer,string srid,string dimension, string &xml);
    static void getLineGML(FileGDBAPI::MultiPartShapeBuffer *&lineGeometry,string srid,string dimension, string &xml);
    static void getMultipointGML(FileGDBAPI::MultiPointShapeBuffer *&multipointGeometry,string srid,string dimension, string &xml);
    static void getPolygonGML(FileGDBAPI::MultiPartShapeBuffer *&polygonGeometry,string srid,string dimension, string &xml);
    };
    #endif
    --------------------------------
    #include <jni.h>
    #include <stdio.h>
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <time.h>
    #include <sstream> 
    #include <FileGDBAPI.h>
    #include "GeometryToString.h"
    using namespace FileGDBAPI;
    using namespace std;
    /**
    ShapeBuffer geometry format to gml
    */
    bool GeometryToString::getGeometryStr( ShapeBuffer &geometry,string srid,string &geometrystr)     
    {
    ShapeType pType;
    string dimension("2");
    try{
    geometry.GetShapeType(pType);
    if(pType==shapeNull){
    return false;
    }
    if(geometry.HasMs(pType) || geometry.HasZs(pType)){
    dimension.assign("3");
    }
    //點
    if(pType==shapePoint){
    PointShapeBuffer *pPoint = static_cast<PointShapeBuffer*>(&geometry);
    getPointGML(pPoint, srid, dimension, geometrystr);
    }
    //復雜點 shapeMultipoint         =  8, shapeMultipointM        = 28,  shapeMultipointZM       = 18, shapeMultipointZ        = 20,
    else if(pType==shapeMultipoint||pType==shapeMultipointZ){
    MultiPointShapeBuffer *pPoint = static_cast<MultiPointShapeBuffer*>(&geometry);
    getMultipointGML(pPoint, srid, dimension, geometrystr);
    }
    //線
    else if(pType==shapePolyline||pType==shapePolylineZ){
    MultiPartShapeBuffer *pPoint = static_cast<MultiPartShapeBuffer*>(&geometry);
    getLineGML(pPoint, srid, dimension, geometrystr);
    }
    //面 shapePolygon            =  5, shapePolygonM           = 25,  shapePolygonZM          = 15,  shapePolygonZ           = 19,
    else if(pType==shapePolygon||pType==shapePolygonZ){
    MultiPartShapeBuffer *pPoint = static_cast<MultiPartShapeBuffer*>(&geometry);
    getPolygonGML(pPoint, srid, dimension, geometrystr);
    }
    //geometrystr = xml;
    }catch(exception& e){
    cout <<"格式化gml出錯"<< e.what() << '\n';
    return false;
    }
    return true;
    }
    /**
    <gml:Polygon srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
    <gml:exterior>
    <gml:LinearRing>
    <gml:posList srsDimension="2">-73.2580598287651 42.7460586400617 -73.0196951738303 42.740396678634 -72.9229974292253 42.7373644761786 -72.4557700038866 42.7258525290856 -72.4621713056891 42.7468405310805 -72.4793225257782 42.7615879021406 -72.507269529053 42.768732690401 -72.513068008801 42.7892594013537 -72.5389169708409 42.8077338159122 -72.5534284639708 42.8606431711071 -72.5248100213574 42.912614176111 -72.5202170578447 42.951672527189 -72.5042636319544 42.9655846501007 -72.4733411974969 42.9761435837694 -72.4571590376321 42.9996036974295 -72.461752087004 43.0465044640799 -72.4434642578885 43.0790393128302 -72.4376049020671 43.1162700005077 -72.4523985528512 43.1560221784821 -72.4355986440692 43.2322535514026 -72.4024188454006 43.3073827061476 -72.4102315830492 43.3234041461304 -72.3976280543775 43.3510068532968 -72.4121395531362 43.3771255999364 -72.3962478080998 43.4101565518933 -72.3825156946812 43.4846296935806 -72.3949977682121 43.5175538931663 -72.3734983899535 43.5723746289273 -72.3330851941569 43.597364792188 -72.3040399378543 43.6985301192074 -72.2600555952028 43.7353001230665 -72.219122921336 43.7506925284353 -72.2060918209679 43.7646350589214 -72.1848363730122 43.80169046066 -72.1700895247441 43.8789176964692 -72.1216496397887 43.9092173247051 -72.1132040793556 43.9391659598858 -72.0917117306645 43.9579911279466 -72.1128078470402 43.9765149671878 -72.109908766997 43.9892291134735 -72.0852043813773 44.0089239861752 -72.0769190441221 44.0320405986229 -72.0347283650035 44.0833740182692 -72.0324473746587 44.0960996192242 -72.0495148341973 44.1004520944913 -72.034919852375 44.1207459288225 -72.0447245537617 44.1564355666161 -72.0592822460624 44.1821766291117 -72.0443903804218 44.2343798441307 -72.0595660047421 44.2614940911533 -72.0354953753776 44.2994343131499 -71.9944335108703 44.327548202346 -71.9389056579791 44.3257860034125 -71.9283617527138 44.3361121851129 -71.8348159803514 44.3441994129005 -71.821197308355 44.3503600453548 -71.7977291908463 44.3841728130012 -71.7665702593917 44.3982488046659 -71.6768843632127 44.4213427403399 -71.6563990024127 44.4401373612433 -71.6477091613881 44.4691741459765 -71.6365547217831 44.4767309013869 -71.6142227691161 44.4745070427354 -71.5866189807601 44.4945375694191 -71.5752435447921 44.5258056891543 -71.5914413886211 44.5388744007984 -71.5922884113102 44.5512031068491 -71.5367908177936 44.578931263059 -71.554102635183 44.5965889130363 -71.5680271516494 44.6374468081651 -71.588749347522 44.6505994869911 -71.6076787297883 44.6778622938611 -71.6311328527304 44.741710760694 -71.583501209059 44.779196995866 -71.5751009123659 44.8160197976273 -71.5063649605901 44.8996711859762 -71.5169776077168 44.9436961331566 -71.5409270967342 44.9765632062274 -71.5053723006288 45.0133517163227 -71.9018687560566 45.0073398737601 -72.547231170846 45.0053701041526 -73.1885457846918 45.0084861445147 -73.3447234868808 45.0061387945908 -73.3507583871194 44.9819729513452 -73.336414678892 44.9326039308501 -73.3823067594393 44.847933618761 -73.3690541280725 44.8191179021752 -73.3267863194035 44.7992935709543 -73.3731585750219 44.7242364367472 -73.3581509561493 44.6803685644813 -73.3730971364166 44.661276356252 -73.3701366913554 44.6343490646186 -73.3818251037205 44.619807725515 -73.3712960298211 44.5791669569445 -73.3478119840265 44.5539715457203 -73.3344524939974 44.5443282463014 -73.2933197444992 44.4328535783628 -73.2999951630005 44.4055331645411 -73.329788093029 44.3673904680867 -73.3053256664728 44.2601422576288 -73.3773326255291 44.2012475171298 -73.3820623364064 44.1721076120789 -73.4078648304615 44.1362270392698 -73.408756830709 44.1066103535608 -73.4352152780239 44.0638978024284 -73.4360007112789 44.0456791904392 -73.4082513023357 44.0182219013789 -73.4174061301201 43.9881969457531 -73.4053345287368 43.9148075869024 -73.3751207851313 43.8859769501208 -73.3847399017653 43.8045079717314 -73.35899716813 43.7784275686935 -73.3566696765928 43.7565583405993 -73.3709893845573 43.7142811167279 -73.4229598542952 43.6321147289768 -73.4183198417113 43.5824793859982 -73.38811421923 43.569143658301 -73.3636855615672 43.6149988679746 -73.303534516911 43.6247148128503 -73.2941043006646 43.6196528756939 -73.2817362682322 43.593187249577 -73.2914024969012 43.5750335705379 -73.2599837938072 43.5593823395161 -73.2383913589494 43.5128328494146 -73.2500714436228 43.3108539907423 -73.2760052890117 42.9402941192892 -73.2795831999318 42.8371033274803 -73.2961697572314 42.8035493647592 -73.2692753169001 42.7474814329983 -73.2580598287651 42.7460586400617 </gml:posList>
    </gml:LinearRing>
    </gml:exterior>
    </gml:Polygon>
    -----------------------------------------
    <gml:MultiSurface srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
    <gml:surfaceMember>
    <gml:Polygon>
    <gml:exterior>
    <gml:LinearRing>
    <gml:posList srsDimension="2">-71.7901942031213 41.6013068793251 -71.8027434308056 41.415829054006 -71.8459956537022 41.403854541649 -71.8368696812943 41.3419614666217 -71.8477722040922 41.3253484832966 -71.866678442895 41.3227696452717 -71.7222643227053 41.327264312184 -71.4898880400564 41.3920853196253 -71.427318519639 41.4866893796324 -71.4192468515382 41.6522122329241 -71.3690125475301 41.7032911019032 -71.3935805976545 41.7611558353254 -71.3673874451962 41.7413502009834 -71.2840016520154 41.6795489704365 -71.2289761591777 41.7076939683675 -71.2666285816006 41.7497430522049 -71.3193277902704 41.7721958646079 -71.33979862314 41.784425562696 -71.3454831662469 41.8131613833438 -71.3345427095385 41.8579036075386 -71.3424931202155 41.875782891498 -71.3330859502879 41.8960311596525 -71.3839531547034 41.8884397544728 -71.3824052822434 41.9792630768654 -71.3786442228911 42.0137133195164 -71.4974303691298 42.0092535031424 -71.7978316087618 42.0042748046853 -71.7882488621949 41.721603395324 -71.7926052182918 41.6417579304639 -71.7901942031213 41.6013068793251 </gml:posList>
    </gml:LinearRing>
    </gml:exterior>
    </gml:Polygon>
    </gml:surfaceMember>
    <gml:surfaceMember>
    <gml:Polygon>
    <gml:exterior>
    <gml:LinearRing>
    <gml:posList srsDimension="2">-71.1988086806703 41.6785003452844 -71.1999371652607 41.4633184834308 -71.1171327154704 41.4930619563069 -71.1412126344661 41.6552730544526 -71.1988086806703 41.6785003452844 </gml:posList>
    </gml:LinearRing>
    </gml:exterior>
    </gml:Polygon>
    </gml:surfaceMember>
    <gml:surfaceMember>
    <gml:Polygon>
    <gml:exterior>
    <gml:LinearRing>
    <gml:posList srsDimension="2">-71.2691694549114 41.6212683171835 -71.3495250332551 41.445857741455 -71.288007152861 41.4836193369167 -71.2386732340455 41.4748497781273 -71.2194468005559 41.6356423127122 -71.2691694549114 41.6212683171835 </gml:posList>
    </gml:LinearRing>
    </gml:exterior>
    </gml:Polygon>
    </gml:surfaceMember>
    </gml:MultiSurface>
    */
    void GeometryToString::getPolygonGML(FileGDBAPI::MultiPartShapeBuffer *&polygonGeometry,string srid,string dimension, string &xml){
    int numPts;
    polygonGeometry->GetNumPoints(numPts);
    int numParts;
    polygonGeometry->GetNumParts(numParts);
    int* parts;
    polygonGeometry->GetParts(parts);
    Point* points;
    polygonGeometry->GetPoints(points);
    string gmlSub("");
    if(numParts==1){
    xml= "<gml:Polygon srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> \
    <gml:exterior> \
    <gml:LinearRing> \
    <gml:posList srsDimension=\""+dimension+"\">";
    for (int i = 0; i < numPts; i++)
    {
    char buffer[32];
    sprintf(buffer, "%1.14g", points[i].x);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[i].y);
    gmlSub.append(buffer).append(" ");
    }  
    xml.append(gmlSub);
    xml.append("</gml:posList></gml:LinearRing>\
      </gml:exterior>\
      </gml:Polygon>");
    return;
    }
    if(numParts>1){
    xml="<gml:MultiSurface srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\">";
    for(int i=0;i<numParts;i++){
    gmlSub.append("<gml:surfaceMember>\
     <gml:Polygon>\
     <gml:exterior>\
     <gml:LinearRing>\
     <gml:posList srsDimension=\"").append(dimension).append("\">");
    int gt=0;
    if( i==(numParts-1)){
    gt=numPts;
    }else{
    gt=parts[i+1];
    }
    for (int j= parts[i]; j < gt; j++){
    char buffer[32];
    sprintf(buffer, "%1.14g", points[j].x);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[j].y);
    gmlSub.append(buffer).append(" ");
    }
    gmlSub.append("</gml:posList>\
     </gml:LinearRing>\
     </gml:exterior>\
     </gml:Polygon>\
     </gml:surfaceMember>");
    }
    xml.append(gmlSub);
    xml.append("</gml:MultiSurface>");
    return;
    }
    }
    /**
    <gml:MultiPoint srsName="SDO:2230" xmlns:gml="http://www.opengis.net/gml">
    <gml:pointMember>
    <gml:Point>
    <gml:posList srsDimension="3">6301153.87493073 1913012.75794829 435.0 </gml:posList>
    </gml:Point>
    </gml:pointMember>
    <gml:pointMember>
    <gml:Point>
    <gml:posList srsDimension="3">6301172.62522131 1913331.50796697 424.0 </gml:posList>
    </gml:Point>
    </gml:pointMember>
    </gml:MultiPoint>
    */
    void GeometryToString::getMultipointGML(FileGDBAPI::MultiPointShapeBuffer *&multipointGeometry,string srid,string dimension, string &xml){
    int numPts;
    multipointGeometry->GetNumPoints(numPts);
    wcout << "Multipoint test:" << endl;
    wcout << "Points: " << numPts << endl;
    Point* points;
    multipointGeometry->GetPoints(points);
    double* zArray;
    multipointGeometry->GetZs(zArray);
    xml= "<gml:MultiPoint srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> ";
    string gmlSub("");
    for (int i = 0; i < numPts; i++)
    {
    gmlSub.append("<gml:pointMember><gml:Point><gml:posList srsDimension=\""+dimension+"\">");
    char buffer[32];
    sprintf(buffer, "%1.14g", points[i].x);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[i].y);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", zArray[i]);
    gmlSub.append(buffer).append(" ");
    gmlSub.append("</gml:posList></gml:Point></gml:pointMember>");
    }
    xml.append(gmlSub);
    xml.append("</gml:MultiPoint>");
    }
    /**
    <gml:Curve srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
    <gml:segments>
    <gml:LineStringSegment>
    <gml:posList srsDimension="2">-91.3082592401631 40.0073363232732 -91.3055891069314 39.995346341049 -91.3139124547158 39.9690362798168 -91.3254189367963 39.9469572142013 -91.3246098997585 39.9350861975012 -91.32260281264 39.9251371873939 -91.3238158572038 39.896847138931 -91.3220157795743 39.8891571322064 -91.3241598689896 39.8853761196319 -91.3383584637069 39.873997056967 -91.3394875098243 39.8690760451917 -91.3354593387828 39.8630950480564 -91.3031399738825 39.8280070993682 -91.3022619338156 39.8090860744066 -91.2985697775187 39.7987370721841 -91.3005688605598 39.7949870596141 -91.3073361425165 39.7886050259611 -91.3117993281738 39.783596002295 -91.3119823326406 39.7676969773468 -91.3108232836762 39.7648359772821 -91.3049330369361 39.7602849923819 -91.2990957929273 39.7579610108158 -91.1947826970924 39.7164273102698 </gml:posList>
    </gml:LineStringSegment>
    </gml:segments>
    </gml:Curve>
    <gml:MultiCurve srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
    <gml:curveMember>
    <gml:Curve>
    <gml:segments>
    <gml:LineStringSegment>
    <gml:posList srsDimension="2"> sssss</gml:posList>
    </gml:LineStringSegment>
    </gml:segments>
    </gml:Curve>
    </gml:curveMember>
    <gml:curveMember>
    <gml:Curve>
    <gml:segments>
    <gml:LineStringSegment>
    <gml:posList srsDimension="2">sssss </gml:posList>
    </gml:LineStringSegment>
    </gml:segments>
    </gml:Curve>
    </gml:curveMember>
    </gml:MultiCurve>
    */
    void GeometryToString::getLineGML(MultiPartShapeBuffer *&lineGeometry,string srid,string dimension, string &xml)
    {
    int numPts,numParts;
    lineGeometry->GetNumPoints(numPts);
    lineGeometry->GetNumParts(numParts);
    int* parts;
    lineGeometry->GetParts(parts);
    Point* points;
    lineGeometry->GetPoints(points);
    string gmlSub("");
    if(numParts==1){
    xml= "<gml:Curve srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> \
     <gml:segments> \
     <gml:LineStringSegment> \
     <gml:posList srsDimension=\""+dimension+"\">";
    for (int i = 0; i < numPts; i++)
    {
    char buffer[32];
    sprintf(buffer, "%1.14g", points[i].x);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[i].y);
    gmlSub.append(buffer).append(" ");
    }  
    xml.append(gmlSub);
    xml.append("</gml:posList> \
      </gml:LineStringSegment>\
      </gml:segments> \
      </gml:Curve>");
    return;
    }
    if(numParts>1){
    xml="<gml:MultiCurve srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\">";
    for(int i=0;i<numParts;i++){
    gmlSub.append("<gml:curveMember>\
     <gml:Curve>\
     <gml:segments>\
     <gml:LineStringSegment>\
     <gml:posList srsDimension=\"").append(dimension).append("\">");
    int gt=0;
    if( i==(numParts-1)){
    gt=numPts;
    }else{
    gt=parts[i+1];
    }
    for (int j= parts[i]; j < gt; j++){
    char buffer[32];
    sprintf(buffer, "%1.14g", points[j].x);
    gmlSub.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[j].y);
    gmlSub.append(buffer).append(" ");
    }
    gmlSub.append("</gml:posList>\
     </gml:LineStringSegment>\
     </gml:segments>\
     </gml:Curve>\
     </gml:curveMember>");
    }
    xml.append(gmlSub);
    xml.append("</gml:MultiCurve>");
    return;
    }
    }
    /*
    <gml:Point srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
    <gml:posList srsDimension="2">-88.0261499418109 44.4722440557492 </gml:posList>
    </gml:Point>
    */
    void GeometryToString::getPointGML( PointShapeBuffer *&pbuffer,string srid,string dimension, string &xml)
    {
    xml= "<gml:Point srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"><gml:posList srsDimension=\""+dimension+"\">";
    Point* points;
    pbuffer->GetPoint(points);
    char buffer[32];
    sprintf(buffer, "%1.14g", points[0].x);
    xml.append(buffer).append(" ");
    sprintf(buffer, "%1.14g", points[0].y);
    xml.append(buffer).append(" ");
    xml.append("</gml:posList></gml:Point>");
    }
    posted @ 2014-01-02 10:19 brock 閱讀(336) | 評論 (0)編輯 收藏

    寫給自己看看
    java --HelloJNI ---
    import java.io.UnsupportedEncodingException;
    public class HelloJNI {
    static {
         System.loadLibrary("HelloJNI"); // hello.dll (Windows) or libhello.so (Unixes)
      
      }
      // A native method that receives nothing and returns void
      private native void sayHello();
      
      private native double sayOK(String dd);
      
      private native void getFileGdb(String path);
      
      private native String getFileGdbStr(String path);
      
      private native GeodbEntity getGdbTable(GeodbEntity geo);
     
      /**
    * @param args
    * @throws UnsupportedEncodingException
    */
    /**  
    * @param args
    * @throws UnsupportedEncodingException
    */
    public static void main(String[] args) throws UnsupportedEncodingException {
    //   System.out.println( System.getProperty("java.library.path"));
      HelloJNI hello =  new HelloJNI();
    //   hello.sayHello();  // invoke the native method
      
    //   System.out.println(hello.sayOK("Apple"));
    //   
      //hello.getFileGdb("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb");
      //GeodbEntity dd= hello.getGdbTable("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb","dd");
      GeodbEntity dd= new GeodbEntity();
      dd.setTable("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb 阿切爾");
      
      hello.getGdbTable(dd);
     
     System.out.println("java"+dd.getSrid());
     for(int i=0;i<dd.getFieldValues().size();i++){
     System.out.println(dd.getFieldValues().get(i));
     
     }
     // System.out.println(hello.getFileGdbStr("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb"));
      
      }
    }
    -----GeodbEntity ----
    import java.util.List;
    import java.util.ArrayList;
    public class GeodbEntity {
    //輸入
    private String table;
    private String eodbPath;
    //輸出
    /**列字段##隔開*/
    private String Fields;
    /**數據表##隔開*/
    private ArrayList<String> FieldValues=new ArrayList<String>();
    /**空間參考標識符*/
    private String srid;
    /**維度*/
    private String dimension;
    public String getTable() {
    return table;
    }
    public void setTable(String table) {
    this.table = table;
    }
    public String getEodbPath() {
    return eodbPath;
    }
    public void setEodbPath(String eodbPath) {
    this.eodbPath = eodbPath;
    }
    public String getSrid() {
    return srid;
    }
    public void setSrid(String srid) {
    this.srid = srid;
    }
    public String getDimension() {
    return dimension;
    }
    public void setDimension(String dimension) {
    this.dimension = dimension;
    }
    public String getFields() {
    return Fields;
    }
    public void setFields(String fields) {
    Fields = fields;
    }
    public ArrayList<String> getFieldValues() {
    return FieldValues;
    }
    public void setFieldValues(ArrayList<String> fieldValues) {
    FieldValues = fieldValues;
    }
    public String toString() {
            return Fields;
        }
    }
    --c++
    hellojni.h
    #define _Included_HelloJNI
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     HelloJNI
     * Method:    sayHello
     * Signature: ()V
     */
    JNIEXPORT void JNICALL Java_HelloJNI_sayHello
      (JNIEnv *, jobject);
    /*
     * Class:     HelloJNI
     * Method:    sayOK
     * Signature: (Ljava/lang/String;)D
     */
    JNIEXPORT jdouble JNICALL Java_HelloJNI_sayOK
      (JNIEnv *, jobject, jstring);
    /*
     * Class:     HelloJNI
     * Method:    getFileGdb
     * Signature: (Ljava/lang/String;)V
     */
    JNIEXPORT void JNICALL Java_HelloJNI_getFileGdb
      (JNIEnv *, jobject, jstring);
    /*
     * Class:     HelloJNI
     * Method:    getFileGdbStr
     * Signature: (Ljava/lang/String;)Ljava/lang/String;
     */
    JNIEXPORT jstring JNICALL Java_HelloJNI_getFileGdbStr
      (JNIEnv *, jobject, jstring);
    /*
     * Class:     HelloJNI
     * Method:    getGdbTable
     * Signature: (LGeodbEntity;)LGeodbEntity;
     */
    JNIEXPORT jobject JNICALL Java_HelloJNI_getGdbTable
      (JNIEnv *, jobject, jobject);
    #ifdef __cplusplus
    }
    #endif
    #endif
    ----------hello c++------

    #include <jni.h>
    #include <stdio.h>
    #include <iostream>
    #include <string.h>
    #include "HelloJNI.h"
    #include <fstream>
    #include <time.h>
    #include <FileGDBAPI.h>
    using namespace std;
    using namespace FileGDBAPI;
    using namespace std;
     
    JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
    printf("Hello World!\n");
    return;
    }
    JNIEXPORT jdouble JNICALL Java_HelloJNI_sayOK
    (JNIEnv* env, jobject obj, jstring name){
    const char* pname=env->GetStringUTFChars(name,NULL);
    if(strcmp(pname,"Apple")==0){
    env->ReleaseStringUTFChars(name,pname);
    cout<<"After release:"<<pname<<endl;
    return 1.2;
    }
    else{
    env->ReleaseStringUTFChars(name,pname);
    cout<<"After release:"<<pname<<endl;
    return 2.1;
    }
    }
    JNIEXPORT jstring JNICALL Java_HelloJNI_getFileGdbStr
    (JNIEnv *env, jobject thisObj, jstring path){
    /* fgdbError hr;
    wstring errorText;
    Geodatabase geodatabase;
    std::wstring value;
    const jchar* raw = env->GetStringChars(path, NULL);
    if (raw != NULL) {
    jsize len = env->GetStringLength(path);
    value.assign(raw, raw + len);
    env->ReleaseStringChars(path, raw);
    }
    if ((hr = OpenGeodatabase(value, geodatabase)) != S_OK)
    {
    wcout << "An error occurred while opening the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return (env)->NewStringUTF("7");
    }
    Row     attrQueryRow;
    EnumRows attrQueryRows;
    wstring sqlStatement(L"SELECT * FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
    if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
    {
    wcout << "An error occurred while performing the attribute query." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return (env)->NewStringUTF("7");
    }
    FieldInfo fieldInfo;
    attrQueryRows.GetFieldInformation(fieldInfo);
    int       fieldCount;
    FieldType fieldType;
    wstring   fieldName;
    // Iterate through the returned rows printing out all field values.
    short     shortField;
    int32     longField;
    float     floatField;
    double    doubleField;
    string    stringField;
    wstring   wstringField;
    tm        dateTimeField;
    char      datetime[80];
    Guid      globalIDField;
    Guid      guidField;
    wstring   strGuid;
    wstring   strGlobalID;
    bool      isNull;
    byte * shapeBufferBytes ;
    ShapeBuffer geometry;
    ByteArray  bss;
    while (attrQueryRows.Next(attrQueryRow) == S_OK)
    {
    fieldInfo.GetFieldCount(fieldCount);
    for (long fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++)
    {
    fieldInfo.GetFieldType(fieldNumber, fieldType);
    fieldInfo.GetFieldName(fieldNumber, fieldName);
    attrQueryRow.IsNull(fieldName, isNull);
    if (!isNull)
    {
    switch (fieldType)
    {
    case fieldTypeSmallInteger:
    attrQueryRow.GetShort(fieldName, shortField);
    wcout <<  shortField << endl;
    break;
    case fieldTypeInteger:
    attrQueryRow.GetInteger(fieldName, longField);
    wcout << longField << '\t';
    break;
    case fieldTypeSingle:
    attrQueryRow.GetFloat(fieldName, floatField);
    wcout << floatField << '\t';
    break;
    case fieldTypeDouble:
    attrQueryRow.GetDouble(fieldName, doubleField);
    wcout << doubleField << '\t';
    break;
    case fieldTypeString:
    attrQueryRow.GetString(fieldName, wstringField);
    wcout << wstringField << '\t';
    break;
    case fieldTypeDate:
    attrQueryRow.GetDate(fieldName, dateTimeField);
    strftime(datetime,80,"%a %b %d %I:%M:%S%p %Y", &dateTimeField);
    wcout << datetime << '\t';
    break;
    case fieldTypeOID:
    attrQueryRow.GetOID(longField);
    wcout << longField << '\t';
    break;
    case fieldTypeGeometry:{
    attrQueryRow.GetGeometry(geometry);
    // attrQueryRow.GetBinary(fieldName, bss);
    double x, y;
    shapeBufferBytes = geometry.shapeBuffer;
    wcout << "d::x::"<< x<<"y:"<<y<< '\t';;
    wcout <<shapeBufferBytes<< "Geometry" << '\t';}
    break;
    case fieldTypeBlob:
    wcout << "Blob" << '\t';
    break;
    case fieldTypeGUID:
    attrQueryRow.GetGUID(fieldName, guidField);
    guidField.ToString(strGuid);
    wcout << strGuid << '\t';
    break;
    case fieldTypeGlobalID:
    attrQueryRow.GetGlobalID(globalIDField);
    globalIDField.ToString(strGlobalID);
    wcout << strGlobalID << '\t';
    break;
    default:
    break;
    }
    }
    else
    {
    wcout << "null" << '\t';
    }
    }
    wcout << endl;
    }
    attrQueryRows.Close(); // Close the EnumRows
    */
    const char * pat="zhy好棒呀 第一個東東出來了";
    //定義java String類 strClass  
    jclass strClass = (env)->FindClass("Ljava/lang/String;");  
    //獲取String(byte[],String)的構造器,用于將本地byte[]數組轉換為一個新String  
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");  
    //建立byte數組  
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));  
    //將char* 轉換為byte數組  
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);  
    // 設置String, 保存語言類型,用于byte數組轉換至String時的參數  
    jstring encoding = (env)->NewStringUTF("GB2312");   
    //將byte數組轉換為java String,并輸出  
    return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);  
    //return path;
    }
    JNIEXPORT void JNICALL Java_HelloJNI_getFileGdb(JNIEnv *env, jobject thisObj, jstring path) {
    fgdbError hr;
    wstring errorText;
    Geodatabase geodatabase;
    // const wchar_t * szStr =(wchar_t * )env->GetStringChars(path, NULL);
    std::wstring value;
    const jchar* raw = env->GetStringChars(path, NULL);
    if (raw != NULL) {
    jsize len = env->GetStringLength(path);
    value.assign(raw, raw + len);
    env->ReleaseStringChars(path, raw);
    }
    if ((hr = OpenGeodatabase(value, geodatabase)) != S_OK)
    {
    wcout << "An error occurred while opening the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return;
    }
    wstring sqlStatement(L"SELECT CITY_NAME, POP1990 FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
    EnumRows attrQueryRows;
    if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
    {
    wcout << "An error occurred while performing the attribute query." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return ;
    }
    // Iterate through the returned rows.
    Row     attrQueryRow;
    int32   cityPop;
    wstring cityName;
    while (attrQueryRows.Next(attrQueryRow) == S_OK)
    {
    attrQueryRow.GetInteger(L"POP1990", cityPop);
    attrQueryRow.GetString(L"CITY_NAME", cityName);
    wcout << cityName << '\t' << cityPop << endl;
    }
    // SELECT * - Return all fields.
    sqlStatement.assign(L"SELECT * FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
    if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
    {
    wcout << "An error occurred while performing the attribute query." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return;
    }
    // Get the field type and name from the row enumerator.
    FieldInfo fieldInfo;
    attrQueryRows.GetFieldInformation(fieldInfo);
    int       fieldCount;
    FieldType fieldType;
    wstring   fieldName;
    // Iterate through the returned rows printing out all field values.
    short     shortField;
    int32     longField;
    float     floatField;
    double    doubleField;
    string    stringField;
    wstring   wstringField;
    tm        dateTimeField;
    char      datetime[80];
    Guid      globalIDField;
    Guid      guidField;
    wstring   strGuid;
    wstring   strGlobalID;
    bool      isNull;
    byte * shapeBufferBytes ;
    ShapeBuffer geometry;
    while (attrQueryRows.Next(attrQueryRow) == S_OK)
    {
    fieldInfo.GetFieldCount(fieldCount);
    for (long fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++)
    {
    fieldInfo.GetFieldType(fieldNumber, fieldType);
    fieldInfo.GetFieldName(fieldNumber, fieldName);
    attrQueryRow.IsNull(fieldName, isNull);
    if (!isNull)
    {
    switch (fieldType)
    {
    case fieldTypeSmallInteger:
    attrQueryRow.GetShort(fieldName, shortField);
    wcout <<  shortField << endl;
    break;
    case fieldTypeInteger:
    attrQueryRow.GetInteger(fieldName, longField);
    wcout << longField << '\t';
    break;
    case fieldTypeSingle:
    attrQueryRow.GetFloat(fieldName, floatField);
    wcout << floatField << '\t';
    break;
    case fieldTypeDouble:
    attrQueryRow.GetDouble(fieldName, doubleField);
    wcout << doubleField << '\t';
    break;
    case fieldTypeString:
    attrQueryRow.GetString(fieldName, wstringField);
    wcout << wstringField << '\t';
    break;
    case fieldTypeDate:
    attrQueryRow.GetDate(fieldName, dateTimeField);
    strftime(datetime,80,"%a %b %d %I:%M:%S%p %Y", &dateTimeField);
    wcout << datetime << '\t';
    break;
    case fieldTypeOID:
    attrQueryRow.GetOID(longField);
    wcout << longField << '\t';
    break;
    case fieldTypeGeometry:{
    attrQueryRow.GetGeometry(geometry);
    // attrQueryRow.GetBinary(fieldName, bss);
    double x, y;
    shapeBufferBytes = geometry.shapeBuffer;
    memcpy(&x, geometry.shapeBuffer + 4, sizeof(x));
    memcpy(&y, geometry.shapeBuffer + 12, sizeof(y));
    //std::string *str3 = new std::string((char *)shapeBufferBytes);
    wcout << "d::x::"<< x<<"y:"<<y<< '\t';;
    wcout <<shapeBufferBytes<< "Geometry" << '\t';}
      break;
    case fieldTypeBlob:
    wcout << "Blob" << '\t';
    break;
    case fieldTypeGUID:
    attrQueryRow.GetGUID(fieldName, guidField);
    guidField.ToString(strGuid);
    wcout << strGuid << '\t';
    break;
    case fieldTypeGlobalID:
    attrQueryRow.GetGlobalID(globalIDField);
    globalIDField.ToString(strGlobalID);
    wcout << strGlobalID << '\t';
    break;
    default:
    break;
    }
    }
    else
    {
    wcout << "null" << '\t';
    }
    }
    wcout << endl;
    }
    attrQueryRows.Close(); // Close the EnumRows
    // Close the geodatabase
    if ((hr = CloseGeodatabase(geodatabase)) != S_OK)
    {
    wcout << "An error occurred while closing the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return ;
    }
    printf("Hello World  geodatebase!\n");
    return;
    }
    std::string jstring2str(JNIEnv* env, jstring jstr)  
    {     
        char*   rtn   =   NULL;     
        jclass   clsstring   =   env->FindClass("java/lang/String");     
        jstring   strencode   =   env->NewStringUTF("GB2312");     
        jmethodID   mid   =   env->GetMethodID(clsstring,   "getBytes",   "(Ljava/lang/String;)[B");     
        jbyteArray   barr=   (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);     
        jsize   alen   =   env->GetArrayLength(barr);     
        jbyte*   ba   =   env->GetByteArrayElements(barr,JNI_FALSE);     
        if(alen   >   0)     
        {     
            rtn   =   (char*)malloc(alen+1);           
            memcpy(rtn,ba,alen);     
            rtn[alen]=0;     
        }     
        env->ReleaseByteArrayElements(barr,ba,0);     
        std::string stemp(rtn);  
        free(rtn);  
        return   stemp;     
    }  
    jstring str2jstring(JNIEnv* env,const char* pat)  
    {  
        //定義java String類 strClass  
        jclass strClass = (env)->FindClass("Ljava/lang/String;");  
        //獲取String(byte[],String)的構造器,用于將本地byte[]數組轉換為一個新String  
        jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");  
        //建立byte數組  
        jbyteArray bytes = (env)->NewByteArray(strlen(pat));  
        //將char* 轉換為byte數組  
        (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);  
        // 設置String, 保存語言類型,用于byte數組轉換至String時的參數  
        jstring encoding = (env)->NewStringUTF("GB2312");   
        //將byte數組轉換為java String,并輸出  
        return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);  
    }  
    JNIEXPORT jobject JNICALL Java_HelloJNI_getGdbTable(JNIEnv *env, jobject obj,jobject _GeodbEntity){
    const char * dd="4096";
    //jclass userClass = env->FindClass("GeodbEntity");  
    jclass userClass=env->GetObjectClass(_GeodbEntity); 
    //jmethodID userMethod = env->GetMethodID(userClass,"<init>","()V"); 
    //jobject userObject = env->NewObject(userClass,userMethod);  
    //jmethodID construction_id = env->GetMethodID(userClass, "<init>", "()V"); 
    //得到構造方法的ID
        //jobject userObject = env->NewObject(userClass, construction_id); 
    //jobject   userObject = env->AllocObject(userClass);     
    //
    //jmethodID setName_method=env->GetMethodID(userClass,"setSrid","(Ljava/lang/String;)V");
    //env->CallVoidMethod(userObject,setName_method,dd);
       //jclass objectClass = (env)->FindClass("GeodbEntity
         jmethodID methodId=env->GetMethodID(userClass,"getTable","()Ljava/lang/String;");
     //調用customer對象的特定方法getName
           jstring js_name=(jstring)env->CallObjectMethod(_GeodbEntity,methodId,NULL);
       //jfieldID table = (env)->GetFieldID(userClass,"table","Ljava/lang/String;");
    //jchar dd=(env)->GetCharField(userClass,table);
       //std::string value;
    //const jchar* raw = env->GetStringChars(js_name, NULL);
    //if (raw != NULL) {
    //jsize len = env->GetStringLength(js_name);
    //value.assign(raw, raw + len);
    //env->ReleaseStringChars(js_name, raw);
    //}
    cout<<jstring2str(env,js_name)<<endl;
       jfieldID str = (env)->GetFieldID(userClass,"srid","Ljava/lang/String;");
      (env)->SetObjectField(_GeodbEntity,str,(env)->NewStringUTF(dd));
       //獲取arraylist 類
       jclass cls_ArrayList = env->FindClass("java/util/ArrayList");
    //獲得arraylist id
            jmethodID construct = env->GetMethodID(cls_ArrayList,"<init>","()V");  
    //創建arraylist
            jobject obj_ArrayList = env->NewObject(cls_ArrayList,construct); 
    //獲取 arraylist 的add 方法
            jmethodID arrayList_add = env->GetMethodID(cls_ArrayList,"add","(Ljava/lang/Object;)Z");  
    for(int i=0;i<10;i++){
    jobject alistadd = (env)->NewStringUTF("my name is D:"+i); 
    //通過 add 方法 添加數據到 arraylist中
    env->CallObjectMethod(obj_ArrayList,arrayList_add,alistadd);  
    }
    jfieldID str1 = (env)->GetFieldID(userClass,"FieldValues","Ljava/util/ArrayList;");
      (env)->SetObjectField(_GeodbEntity,str1,obj_ArrayList);
    return _GeodbEntity;
    }



    posted @ 2013-12-30 14:18 brock 閱讀(227) | 評論 (0)編輯 收藏

    -環境的搭建,下載與安裝LIBXML2和ICONV

              Libxml2是一個C語言的XML程序庫,可以簡單方便的提供對XML文檔的各種操作,并且支持XPATH查詢,以及部分的支持XSLT轉換等功能。Libxml2的下載地址是http://xmlsoft.org/downloads.html,完全版的庫是開源的,并且帶有例子程序和說明文檔。完全版的文件名為:libxml2-2.7.8.tar.gz。

              Libxml2中默認的內碼是UTF-8,所有使用libxml2進行處理的xml文件,必須首先顯式或者默認的轉換為UTF-8編碼才能被處理。
    要在xml中使用中文,就必須能夠在UTF-8和GB2312內碼(較常用的一種簡體中文編碼)之間進行轉換。Libxml2提供了默認的內碼轉換機制,并且在libxml2的Tutorial中有一個例子,事實證明這個例子并不適合用來轉換中文。所以需要我們顯式的使用ICONV來進行內碼轉換,libxml2本身也是ICONV使用進行轉換的。ICONV是一個專門用來進行編碼轉換的庫,基本上支持目前所有常用的編碼。它是glibc庫的一個部分,常常被用于UNIX系統中。當然,在windows下面使用也沒有任何問題。

    其下載地址是http://gnuwin32.sourceforge.net/packages/libiconv.htm,文件名為libiconv-1.9.2-1-lib.zip。

              將libiconv-1.9.2-1-lib.zip解壓,將其中的iconv.h放入C:\opt\include目錄中,將其中的libiconv.lib放入C:\opt\lib中,并改名為iconv.lib.(沒有opt目錄就新建一個)。

              解壓libxml2-2.7.8.tar.gz文件到C盤根目錄,在c:\libxml2-2.7.8\libxml2-2.7.8\win32目錄中存放了多個Windows平臺編譯器的Makefile文件,我們使用vs2008,所以待會會用Makefile.msvc文件。

    1.進入Visual Studio 2008 Command Prompt;

    2.cd c:\libxml2-2.7.8\libxml2-2.7.8\win32

    3.輸入cscript configure.js compiler=msvc prefix=c:\opt  include=c:\opt\include lib=c:\opt\lib debug=yes,回車執行。

    4.最后使用nmake命令進行編譯,輸入nmake /f Makefile.msvc并回車。

    此時會出現一下錯誤提示,

    Makefile.msvc(465) : fatal error U1020: end-of-file found before next directive
    Stop.

    網上找了下原因,原來是Makefile.msvc中存在錯誤。

    +!if "$(WITH_ICU)" == "1"
    +LIBS = $(LIBS) icu.lib
    +!endif

    將以上三行前面的+號都刪掉,重新執行nmake即可。

    在當前win32目錄中生成了一個bin.msvc目錄,其中就有開發需要的libxml2.lib和libxml2.dll文件。

    posted @ 2013-12-25 14:49 brock 閱讀(230) | 評論 (0)編輯 收藏

    Visual Studio Ultimate 2012Visual Studio Ultimate 2012 靜態激活密鑰,有興趣的可以試一下。

    RBCXF-CVBGR-382MK-DFHJ4-C69G8
    posted @ 2013-12-17 11:07 brock 閱讀(177) | 評論 (0)編輯 收藏

    1、創建索引   
    -------------------------------------------------------------------------------------------
    GeohashPrefixTree grid = new GeohashPrefixTree(ctx, 12);//< 1 meter == 11 maxLevels
            this.strategy = new RecursivePrefixTreeStrategy(grid, "shape");
            ((RecursivePrefixTreeStrategy) this.strategy).setDistErrPct(LUCENE_4464_distErrPct);//1% radius (small!)

     String wktstr = clobtoString(map.get("wkt"));//圖形信息
                    String objectid = map.get("objectid").toString();//對象id
                    String name = map.get("name").toString();//對象名稱
                    Shape shape = wktGeoRect(wktstr);
                    Document doc = new Document();
                    doc.add(new StringField("objectidtable", objectid + tableName, Field.Store.YES));
                    doc.add(new StringField("objectid", objectid, Field.Store.YES));
                    doc.add(new StringField("tableName", tableName, Field.Store.YES));
                    doc.add(new StringField("metadataid", mid.toString(), Field.Store.YES));
                    doc.add(new TextField ("title", name, Field.Store.YES));
                    if (shape != null) {
                        for (Field f : strategy.createIndexableFields(shape)) {
                            doc.add(f);
                        }
                        doc.add(new StoredField(strategy.getFieldName(), ctx.toString(shape)));
                    }
      indexWriter.addDocument(doc);
    ---------------------------------------------------------------
        public Shape wktGeoRect(String wktStr) {
            JtsGeometry jtsGeom = null;
            try {
                if (StringUtils.trim(wktStr.substring(0, wktStr.indexOf("("))).equalsIgnoreCase("POINT")) {
                    wktStr = wktStr.substring(wktStr.indexOf("(") + 1, wktStr.lastIndexOf(")"));
                    String[] point = wktStr.split(" ");
                    return ctx.makePoint(Double.parseDouble(point[0]), Double.parseDouble(point[1]));
                } else {
                    jtsGeom = (JtsGeometry) ctx.readShape(wktStr);
                }
            } catch (Exception e) {
            }
            return jtsGeom;
        }
    2、查詢空間索引

       @Test
        public void testshape() throws Exception {
                    JtsSpatialContext ctx = JtsSpatialContext.GEO;
            Directory directory = new SimpleFSDirectory(new File("D:/platform/spatiallucence"));
            IndexReader[] indexReaders1 = new IndexReader[]{IndexReader.open(directory)};
            MultiReader multiReader = new MultiReader(indexReaders1);
            indexSearcher = new IndexSearcher(multiReader);
            indexSearcher.setSimilarity(new NoScoreSimilarity());
            GeohashPrefixTree grid = new GeohashPrefixTree(ctx, 12);//< 1 meter == 11 maxLevels
            strategy = new RecursivePrefixTreeStrategy(grid, "shape");
            ((RecursivePrefixTreeStrategy) strategy).setDistErrPct(0.025);//1% radius (small!)
            //POINT (121.591953019118 28.7566972164043)
            //Shape shape = ctx.readShape("POINT (121.454715099823 28.860595871703)");
            Shape shape = ctx.readShape("POLYGON(" +
                    "(121.10836126349 28.84450508816,\n" +
                    "121.12569906256 28.84450508816,\n" +
                    "121.12569906256 28.856950537989,\n" +
                    "121.10836126349 28.856950537989,\n" +
                    "121.10836126349 28.84450508816))");
            shape = ctx.makeRectangle(121.10836126349d ,121.12569906256d, 28.84450508816d ,28.856950537989d);
            SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, shape);
            args.setDistErrPct(0.025);
            Query query = strategy.makeQuery(args);
            TopDocs results = indexSearcher.search(query, 1000);
            int numTotalHits = results.totalHits;
            System.out.println("共 " + numTotalHits + " 完全匹配的文檔");
            ScoreDoc[] hits = results.scoreDocs;
            for (int i = 0; i < hits.length; i++) {
                Document document = indexSearcher.doc(hits[i].doc);
                System.out.println("Id: " + document);
            }
        }

    posted @ 2013-11-29 16:15 brock 閱讀(700) | 評論 (0)編輯 收藏

    ext grid 刪除最后一行數據后還是顯示

    grid刪除最后一行數據后,store reload ,因為數據庫中已經沒有數據了,所以返回null .

    但是ext不認這個東西,所以在service中進行判斷。如果數據為null ,則返回

    "{total:0,gridData:[]}" ;

    重新編譯,運行后,刪除最后一行數據,就會看不到了。

    posted @ 2013-10-24 10:40 brock 閱讀(256) | 評論 (0)編輯 收藏


    一.問題的提出

    /usr/local/webserver/mysql/bin/mysql -u root -h 172.29.141.112  -p -S /tmp/mysql.sock
    Enter password: 
    ERROR 2003 (HY000): Can't connect to MySQL server on '172.29.141.112' (113)

    二.問題的分析

     

    出現上述問題,可能有以下幾種可能

     

    1. my.cnf 配置文件中 skip-networking 被配置

    skip-networking 這個參數,導致所有TCP/IP端口沒有被監聽,也就是說出了本機,其他客戶端都無法用網絡連接到本mysql服務器

    所以需要把這個參數注釋掉。

     

    2.my.cnf配置文件中 bindaddress 的參數配置

    bindaddress,有的是bind-address  ,這個參數是指定哪些ip地址被配置,使得mysql服務器只回應哪些ip地址的請求,所以需要把這個參數注釋掉。

     

    3.防火墻的原因

    通過 /etc/init.d/iptables  stop  關閉防火墻

    我的問題,就是因為這個原因引起的。關閉mysql 服務器的防火墻就可以使用了。

     

    三.問題的解決

    1.  如果是上述第一個原因,那么 找到 my.cnf  ,注釋掉 skip-networking 這個參數

    sed -i  's%skip-networking%#skip-networking%g'  my.cnf

     

    2. 如果是上述第二個原因,那么  找到 my.cnf  ,注釋掉 bind-address  這個參數

    sed -i  's%bind-address%#bind-address%g'    my.cnf

    sed -i  's%bindaddress%#bindaddress%g'      my.cnf

     

    最好修改完查看一下,這個參數。

     

    3.如果是上述第三個原因,那么 把防火墻關閉,或者進行相應配置

     

    /etc/init.d/iptables stop

     

    四.參考

    http://hi.baidu.com/vbkan/blog/item/cd5035030cefee793812bb56.html

    http://dev.firnow.com/course/7_databases/mysql/myxl/20090820/169010.html

    http://www.dnbcw.com/biancheng/sql/lojz182597.html

    posted @ 2013-10-08 10:34 brock 閱讀(219) | 評論 (0)編輯 收藏

      private static double getCpuRateForLinux(){
            InputStream is = null;
            InputStreamReader isr = null;
            BufferedReader brStat = null;
            StringTokenizer tokenStat = null;
            try{
                System.out.println("Get usage rate of CUP , linux version: "+linuxVersion);
                Process process = Runtime.getRuntime().exec("top -b -n 1");
                is = process.getInputStream();
                isr = new InputStreamReader(is);
                brStat = new BufferedReader(isr);
                if(linuxVersion.equals("2.4")){
                    brStat.readLine();
                    brStat.readLine();
                    brStat.readLine();
                    brStat.readLine();
                    tokenStat = new StringTokenizer(brStat.readLine());
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    String user = tokenStat.nextToken();
                    tokenStat.nextToken();
                    String system = tokenStat.nextToken();
                    tokenStat.nextToken();
                    String nice = tokenStat.nextToken();
                    System.out.println(user+" , "+system+" , "+nice);
                    user = user.substring(0,user.indexOf("%"));
                    system = system.substring(0,system.indexOf("%"));
                    nice = nice.substring(0,nice.indexOf("%"));
                    float userUsage = new Float(user).floatValue();
                    float systemUsage = new Float(system).floatValue();
                    float niceUsage = new Float(nice).floatValue();
                    return (userUsage+systemUsage+niceUsage)/100;
                }else{
                    brStat.readLine();
                    brStat.readLine();
                    tokenStat = new StringTokenizer(brStat.readLine());
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    tokenStat.nextToken();
                    String cpuUsage = tokenStat.nextToken();
                    System.out.println("CPU idle : "+cpuUsage);
                    Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));
                    return (1-usage.floatValue()/100);
                }
            } catch(IOException ioe){
                System.out.println(ioe.getMessage());
                freeResource(is, isr, brStat);
                return 1;
            } finally{
                freeResource(is, isr, brStat);
            }
        }
        private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
            try{
                if(is!=null)
                    is.close();
                if(isr!=null)
                    isr.close();
                if(br!=null)
                    br.close();
            }catch(IOException ioe){
                System.out.println(ioe.getMessage());
            }
        }
        /**
         * 獲得CPU使用率.   
         * @return 返回cpu使用率
         * @author GuoHuang
         */
        private double getCpuRatioForWindows() {
            try {
                String procCmd = System.getenv("windir")
                        + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
                        + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
                // 取進程信息    
                long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
                Thread.sleep(CPUTIME);
                long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
                if (c0 != null && c1 != null) {
                    long idletime = c1[0] - c0[0];
                    long busytime = c1[1] - c0[1];
                    return Double.valueOf(
                            PERCENT * (busytime) / (busytime + idletime))
                            .doubleValue();
                } else {
                    return 0.0;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return 0.0;
            }
        }
        /**
         * 讀取CPU信息.
         * @param proc
         * @return
         * @author GuoHuang
         */
        private long[] readCpu(final Process proc) {
            long[] retn = new long[2];
            try {
                proc.getOutputStream().close();
                InputStreamReader ir = new InputStreamReader(proc.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                String line = input.readLine();
                if (line == null || line.length() < FAULTLENGTH) {
                    return null;
                }
                int capidx = line.indexOf("Caption");
                int cmdidx = line.indexOf("CommandLine");
                int rocidx = line.indexOf("ReadOperationCount");
                int umtidx = line.indexOf("UserModeTime");
                int kmtidx = line.indexOf("KernelModeTime");
                int wocidx = line.indexOf("WriteOperationCount");
                long idletime = 0;
                long kneltime = 0;
                long usertime = 0;
                while ((line = input.readLine()) != null) {
                    if (line.length() < wocidx) {
                        continue;
                    }
                    // 字段出現順序:Caption,CommandLine,KernelModeTime,ReadOperationCount,    
                    // ThreadCount,UserModeTime,WriteOperation    
                    String caption = Bytes.substring(line, capidx, cmdidx - 1)
                            .trim();
                    String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
                    if (cmd.indexOf("wmic.exe") >= 0) {
                        continue;
                    }
                    // log.info("line="+line);    
                    if (caption.equals("System Idle Process")
                            || caption.equals("System")) {
                        idletime += Long.valueOf(
                                Bytes.substring(line, kmtidx, rocidx - 1).trim())
                                .longValue();
                        idletime += Long.valueOf(
                                Bytes.substring(line, umtidx, wocidx - 1).trim())
                                .longValue();
                        continue;
                    }
                    kneltime += Long.valueOf(
                            Bytes.substring(line, kmtidx, rocidx - 1).trim())
                            .longValue();
                    usertime += Long.valueOf(
                            Bytes.substring(line, umtidx, wocidx - 1).trim())
                            .longValue();
                }
                retn[0] = idletime;
                retn[1] = kneltime + usertime;
                return retn;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    proc.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    上面方法不行,下面的可以
      String result = "";
            try {
                File file = File.createTempFile("tmp", ".vbs");
                file.deleteOnExit();
                FileWriter fw = new java.io.FileWriter(file);
                String vbs ="Set objProc = GetObject(\"winmgmts:\\\\.\\root\\cimv2:win32_processor='cpu0'\")\n" +
                        "WScript.Echo  \"CPU Load Percentage: \"& chr(13) & chr(10) & Round(objProc.LoadPercentage,2) & \"%\"";
                fw.write(vbs);
                fw.close();
                Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = input.readLine()) != null) {
                    result += line;
                }
                input.close();
                file.delete();
            } catch (Exception e) {
                e.fillInStackTrace();
            }
            if (result.trim().length() < 1 || result == null) {
            }else{
                System.out.println(result.trim());
            }




    posted @ 2013-08-19 10:40 brock 閱讀(720) | 評論 (0)編輯 收藏

    #encoding=UTF-8
    # Configuration files must begin with a line specifying the encoding
    #  of the the file.
    #********************************************************************
    # Wrapper License Properties (Ignored by Community Edition)
    #********************************************************************
    # Professional and Standard Editions of the Wrapper require a valid
    #  License Key to start.  Licenses can be purchased or a trial license
    #  requested on the following pages:
    # http://wrapper.tanukisoftware.com/purchase
    # http://wrapper.tanukisoftware.com/trial
    # Include file problems can be debugged by removing the first '#'
    #  from the following line:
    ##include.debug
    # The Wrapper will look for either of the following optional files for a
    #  valid License Key.  License Key properties can optionally be included
    #  directly in this configuration file.
    #include ../conf/wrapper-license.conf
    #include ../conf/wrapper-license-%WRAPPER_HOST_NAME%.conf
    # The following property will output information about which License Key(s)
    #  are being found, and can aid in resolving any licensing problems.
    #wrapper.license.debug=TRUE
    #********************************************************************
    # Wrapper Localization
    #********************************************************************
    # Specify the locale which the Wrapper should use.  By default the system
    #  locale is used.
    #wrapper.lang=en_US # en_US or ja_JP
    # Specify the location of the Wrapper's language resources.  If these are
    #  missing, the Wrapper will default to the en_US locale.
    wrapper.lang.folder=../lang
    #********************************************************************
    # Wrapper Java Properties
    #********************************************************************
    # Java Application
    #  Locate the java binary on the system PATH:
    wrapper.java.command=java
    #  Specify a specific java binary:
    #set.JAVA_HOME=/java/path
    set.LIB=D:/MonitorApp/lib
    #wrapper.java.command=%JAVA_HOME%/bin/java
    # Tell the Wrapper to log the full generated Java command line.
    #wrapper.java.command.loglevel=INFO
    # Java Main class.  This class must implement the WrapperListener interface
    #  or guarantee that the WrapperManager class is initialized.  Helper
    #  classes are provided to do this for you.  See the Integration section
    #  of the documentation for details.
    wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
    # Java Classpath (include wrapper.jar)  Add class path elements as
    #  needed starting from 1
    echo %LIB%
    wrapper.java.classpath.1=%LIB%/wrapper.jar
    wrapper.java.classpath.2=%LIB%/commons-beanutils-1.8.3.jar
    wrapper.java.classpath.3=%LIB%/commons-codec-1.4.jar
    wrapper.java.classpath.4=%LIB%/commons-collections-3.1.jar
    wrapper.java.classpath.5=%LIB%/commons-collections-3.2.1.jar
    wrapper.java.classpath.6=%LIB%/commons-dbcp-1.3.jar
    wrapper.java.classpath.7=%LIB%/commons-dbcp-1.4.jar
    wrapper.java.classpath.8=%LIB%/commons-fileupload-1.2.1.jar
    wrapper.java.classpath.9=%LIB%/commons-httpclient-3.0.1.jar
    wrapper.java.classpath.10=%LIB%/commons-io-1.4.jar
    wrapper.java.classpath.11=%LIB%/commons-io-2.0.1.jar
    wrapper.java.classpath.12=%LIB%/commons-jexl-1.1.jar
    wrapper.java.classpath.13=%LIB%/commons-lang-2.5.jar
    wrapper.java.classpath.14=%LIB%/commons-logging-1.1.1.jar
    wrapper.java.classpath.15=%LIB%/commons-logging-api-1.1.jar
    wrapper.java.classpath.16=%LIB%/commons-management-1.0.jar
    wrapper.java.classpath.17=%LIB%/commons-pool-1.5.4.jar
    wrapper.java.classpath.18=%LIB%/jedis-2.0.0.jar
    wrapper.java.classpath.19=%LIB%/log4j-1.2.14.jar
    wrapper.java.classpath.20=%LIB%/quartz-all-1.6.3.jar
    wrapper.java.classpath.21=%LIB%/spring-aop-3.0.2.RELEASE.jar
    wrapper.java.classpath.22=%LIB%/spring-asm-3.0.2.RELEASE.jar
    wrapper.java.classpath.23=%LIB%/spring-beans-3.0.2.RELEASE.jar
    wrapper.java.classpath.24=%LIB%/spring-binding-2.0.8.RELEASE.jar
    wrapper.java.classpath.25=%LIB%/spring-context-3.0.2.RELEASE.jar
    wrapper.java.classpath.26=%LIB%/spring-context-support-3.0.2.RELEASE.jar
    wrapper.java.classpath.27=%LIB%/spring-core-3.0.2.RELEASE.jar
    wrapper.java.classpath.28=%LIB%/spring-expression-3.0.2.RELEASE.jar
    wrapper.java.classpath.29=%LIB%/springside-3.3.2.jar
    wrapper.java.classpath.30=%LIB%/spring-test-3.0.2.RELEASE.jar
    wrapper.java.classpath.31=%LIB%/spring-tx-3.0.2.RELEASE.jar
    wrapper.java.classpath.32=%LIB%/slf4j-api-1.5.8.jar
    wrapper.java.classpath.33=%LIB%/slf4j-log4j12-1.5.8.jar
    wrapper.java.classpath.34=%LIB%/monitor.jar
    wrapper.java.classpath.35=%LIB%   #可以讀到這里的文件 xml pro 等       
    # Java Library Path (location of Wrapper.DLL or libwrapper.so)
    wrapper.java.library.path.1=../bin
    # Java Bits.  On applicable platforms, tells the JVM to run in 32 or 64-bit mode.
    wrapper.java.additional.auto_bits=TRUE
    # Java Additional Parameters
    wrapper.java.additional.1=-Dlog4j.configuration=file:%LIB%/log4j.xml
    wrapper.java.additional.2=-Dorg.tanukisoftware.wrapper.WrapperManager.mbean=TRUE
    # Initial Java Heap Size (in MB)
    wrapper.java.initmemory=128
    # Maximum Java Heap Size (in MB)
    wrapper.java.maxmemory=512
    # Application parameters.  Add parameters as needed starting from 1
    wrapper.app.parameter.1=com.zjasm.tomcat.TomcatStat
    #********************************************************************
    # Wrapper Logging Properties
    #********************************************************************
    # Enables Debug output from the Wrapper.
    #wrapper.debug=TRUE
    # Format of output for the console.  (See docs for formats)
    wrapper.console.format=PM
    # Log Level for console output.  (See docs for log levels)
    wrapper.console.loglevel=INFO
    # Log file to use for wrapper output logging.
    wrapper.logfile=../logs/wrapper.log
    # Format of output for the log file.  (See docs for formats)
    wrapper.logfile.format=LPTM
    # Log Level for log file output.  (See docs for log levels)
    wrapper.logfile.loglevel=INFO
    # Maximum size that the log file will be allowed to grow to before
    #  the log is rolled. Size is specified in bytes.  The default value
    #  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
    #  'm' (mb) suffix.  For example: 10m = 10 megabytes.
    wrapper.logfile.maxsize=0
    # Maximum number of rolled log files which will be allowed before old
    #  files are deleted.  The default value of 0 implies no limit.
    wrapper.logfile.maxfiles=0
    # Log Level for sys/event log output.  (See docs for log levels)
    wrapper.syslog.loglevel=NONE
    #********************************************************************
    # Wrapper General Properties
    #********************************************************************
    # Allow for the use of non-contiguous numbered properties
    wrapper.ignore_sequence_gaps=TRUE
    # Do not start if the pid file already exists.
    wrapper.pidfile.strict=TRUE
    # Title to use when running as a console
    wrapper.console.title=Test Wrapper Sample Application
    #********************************************************************
    # Wrapper JVM Checks
    #********************************************************************
    # Detect DeadLocked Threads in the JVM. (Requires Standard Edition)
    wrapper.check.deadlock=TRUE
    wrapper.check.deadlock.interval=10
    wrapper.check.deadlock.action=RESTART
    wrapper.check.deadlock.output=FULL
    # Out Of Memory detection.
    # (Ignore output from dumping the configuration to the console.  This is only needed by the TestWrapper sample application.)
    wrapper.filter.trigger.999=wrapper.filter.trigger.*java.lang.OutOfMemoryError
    wrapper.filter.allow_wildcards.999=TRUE
    wrapper.filter.action.999=NONE
    #  Ignore -verbose:class output to avoid false positives.
    wrapper.filter.trigger.1000=[Loaded java.lang.OutOfMemoryError
    wrapper.filter.action.1000=NONE
    # (Simple match)
    wrapper.filter.trigger.1001=java.lang.OutOfMemoryError
    # (Only match text in stack traces if -XX:+PrintClassHistogram is being used.)
    #wrapper.filter.trigger.1001=Exception in thread "*" java.lang.OutOfMemoryError
    #wrapper.filter.allow_wildcards.1001=TRUE
    wrapper.filter.action.1001=RESTART
    wrapper.filter.message.1001=The JVM has run out of memory.
    #********************************************************************
    # Wrapper Email Notifications. (Requires Professional Edition)
    #********************************************************************
    # Common Event Email settings.
    #wrapper.event.default.email.debug=TRUE
    #wrapper.event.default.email.smtp.host=<SMTP_Host>
    #wrapper.event.default.email.smtp.port=25
    #wrapper.event.default.email.subject=[%WRAPPER_HOSTNAME%:%WRAPPER_NAME%:%WRAPPER_EVENT_NAME%] Event Notification
    #wrapper.event.default.email.sender=<Sender email>
    #wrapper.event.default.email.recipient=<Recipient email>
    # Configure the log attached to event emails.
    #wrapper.event.default.email.attach_log=TRUE
    #wrapper.event.default.email.maillog.lines=50
    #wrapper.event.default.email.maillog.format=LPTM
    #wrapper.event.default.email.maillog.loglevel=INFO
    # Enable specific event emails.
    #wrapper.event.wrapper_start.email=TRUE
    #wrapper.event.jvm_prelaunch.email=TRUE
    #wrapper.event.jvm_start.email=TRUE
    #wrapper.event.jvm_started.email=TRUE
    #wrapper.event.jvm_deadlock.email=TRUE
    #wrapper.event.jvm_stop.email=TRUE
    #wrapper.event.jvm_stopped.email=TRUE
    #wrapper.event.jvm_restart.email=TRUE
    #wrapper.event.jvm_failed_invocation.email=TRUE
    #wrapper.event.jvm_max_failed_invocations.email=TRUE
    #wrapper.event.jvm_kill.email=TRUE
    #wrapper.event.jvm_killed.email=TRUE
    #wrapper.event.jvm_unexpected_exit.email=TRUE
    #wrapper.event.wrapper_stop.email=TRUE
    # Specify custom mail content
    wrapper.event.jvm_restart.email.body=The JVM was restarted.\n\nPlease check on its status.\n
    #********************************************************************
    # Wrapper Windows NT/2000/XP Service Properties
    #********************************************************************
    # WARNING - Do not modify any of these properties when an application
    #  using this configuration file has been installed as a service.
    #  Please uninstall the service before modifying this section.  The
    #  service can then be reinstalled.
    # Name of the service
    wrapper.name=testwrapper
    # Display name of the service
    wrapper.displayname=Test Wrapper Sample Application
    # Description of the service
    wrapper.description=Test Wrapper Sample Application Description
    # Service dependencies.  Add dependencies as needed starting from 1
    wrapper.ntservice.dependency.1=
    # Mode in which the service is installed.  AUTO_START, DELAY_START or DEMAND_START
    wrapper.ntservice.starttype=AUTO_START
    # Allow the service to interact with the desktop.
    wrapper.ntservice.interactive=false
    posted @ 2013-08-09 14:20 brock 閱讀(274) | 評論 (0)編輯 收藏

    步驟1、配置/etc/sysconfig/network-scripts/ifcfg-eth0 里的文件。it動力的CentOS下的ifcfg-eth0的配置詳情:

    [root@localhost ~]# vim /etc/sysconfig/network-scripts/ifcfg-eth0

    DEVICE="eth0"
    HWADDR="00:0C:29:FD:FF:2A"
    NM_CONTROLLED="yes"
    ONBOOT="yes"
    IPADDR=192.168.1.31
    NETMASK=255.255.255.0
    GATEWAY=192.168.1.1
    BOOTPROTO=static

    前面三行是系統睚帶的,后面就是手動添加的。
    這樣設置扣,記得重啟網卡:
    [root@localhost ~]# /etc/init.d/network stop
    [root@localhost ~]# /etc/init.d/network start

    行了,現在就可以PING得通網關了,如果還得上網,不必須設置DNS。設置DNS就詳見步驟2

    步驟2、修改dns
    [root@localhost ~]# vi /etc/resolv.conf 
    在里面添加二個dns:
    nameserver 202.96.134.133
    nameserver 8.8.8.8

    ok,大攻告成,即可上網了?。。?!

    posted @ 2013-07-31 18:42 brock 閱讀(227) | 評論 (0)編輯 收藏

     The VMware vSphere Web Services SDK includes all the components necessary to work with the VMware vSphere API, including WSDL files, sample code, and libraries. The vSphere Web Services SDK facilitates development of client applications that target the VMware vSphere API. With the vSphere Web Services SDK, developers can create client applications to manage, monitor, and maintain VMware vSphere components, as deployed on VMware®VMware vSphere®ESX®, ESXi™, and VMware®vCenter™ Server systems.

    這是官方對vSphere Web Services SDK的介紹,簡單來說就是提供了管理vcenter,ESXi的程序接口,目前支持JAVA和.NET平臺,下面以windows 7平臺為例,介紹JAVA開發環境的部署過程

    一、開發環境準備

    1、安裝JAVA開發環境 J2SE 1.6 b22

    http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html#jdk-6u22-oth-JPR

    安裝到c:\java下,不要安裝到C:\program files下,目錄中有空格,執行腳本的時候會報錯

     

    2、安裝SOAP工具JAX-WS2.1

    http://jax-ws.java.net/2.1.1/index.html

    雙擊安裝即可

     

    3、下載vSphere Web Services SDK 5.1

    http://communities.vmware.com/community/vmtn/developer/downloads

    解壓到c:\devprojects下

     

    二、開發環境配置

    1、設置系統變量

    JAVA_HOME=C:\java\jdk1.6.0_22

    JAVAHOME=C:\java\jdk1.6.0_22

    SDKHOME=C:\devprojects

    VMKEYSTORE=C:\VMware-Certs\vmware.keystore(稍后介紹安裝過程)

    WEBHOME=C:\devprojects\vsphere-ws\java\Axis\lib\wbem.jar

    WS_SDK_HOME=C:\devprojects\SDK\vsphere-ws

    CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;C:\devprojects\SDK\vsphere-ws\java\JAXWS\lib\samples.jar;C:\devprojects\SDK\vsphere-ws\java\JAXWS\lib\vim25.jar(這個變量很重要)

     

    2、服務器認證

    2.1、將ESX Server或Vcenter的證書導入本機,ESXi的證書在/etc/vmware/ssl/rui.crt;Vcenter的證書在C:/Documents and Settings/All Users/Application Data/VMware/VMware VitualCenter/SSL/rui.crt

    2.2、證書拷貝到本機的C:/VMware-Certs目錄下,打開windows7的命令行界面,切換到C:/VMware-Certs目錄下,使用jdk的keytool工具導入證書:

    keytool -import -file <certificate-filename> -alias <server-name> -keystore vmware.keystore

    其中certificate-filename為rui.crt,service-name可以為服務器的機器名或IP地址,運行成功后會在C:/VMware-Certs目錄下生成vmware.keystore文件。

     

    3、重新編譯JAX-WS

    如果你的安裝的版本不是JDK 1.6 b22或者SOAP不是用 JAX-WS2.1,就需要重新編譯

    打開CMD,切換到C:\devprojects\SDK\vsphere-ws\java\JAXWS\

    運行build.bat

    運行成功會出現會出現

    Generating stubs from wsdl
     
    Compiling stubs.
    ...
    Done
     
    三、運行簡單的客戶端腳本以驗證安裝成功
     
    打開CMD,切換到C:\devprojects\SDK\vsphere-ws\java\JAXWS\
     
    run.bat com.vmware.general.SimpleClient --urlhttps://yourFQDNservername/sdk --username  username --password password,如下輸出表示配置SDK成功
     
     
     
    四、錯誤調試
    1、如果出現找不到類的錯誤,ClassNotFoundException:........,可以這樣
     
    打開CMD,切換到C:\devprojects\SDK\vsphere-ws\java\JAXWS\
     
    java -Djavax.net.ssl.trustStore=%VMKEYSTORE% com.vmware.general.SimpleClient--url https://example.com/sdk --username pubs --password ***
     
    2、如果提示JAVA虛擬機的內存不夠,可以這樣
     
    java -Djavax.net.ssl.trustStore=%VMKEYSTORE% -Xms 512M -XMx1024M com.vmware.general.SimpleClient--url https://example.com/sdk --username pubs --password ***
    posted @ 2013-07-31 18:41 brock 閱讀(890) | 評論 (0)編輯 收藏

    BIND-DLZ實驗:http://bind-dlz.sourceforge.net/
    實驗環境:RHEL4,BIND-9.5.0-P2.tar.gz(9.4.0以上版本都已含DLZ補丁),Mysql-5.0.56.tar.gz
    1、安裝mysql(先安裝gcc等相關軟件包)
       #tar zxvf mysql-5.0.56.tar.gz 
       #cd mysql-5.0.56
       #./configure --prefix=/usr/local/mysql --localstatedir=/usr/loal/mysql/data --   libexecdir=/usr/local/mysql/lib --disable-shared
       #make
       #make install
       #cd /usr/local/mysql/
       #groupadd -g 1003 mysql
       #useradd -g 1003 mysql
       #chown -R mysql .
       #chgrp -R mysql .
       #chown -R mysql lib
       #./bin/mysql_install_db --user=mysql //以mysql的用戶身份安裝
       #chown -R root .
       #./bin/mysqld_safe --user=mysql & //在后臺啟動mysql

    # cd /root/mysql-5.0.56
    # cp support-files/my-medium.cnf /etc/my.cnf
    # cp support-files/mysql.server /etc/rc.d/init.d/mysqld
    # chmod 700 !$
    # chkconfig --add mysqld
    # chkconfig --list mysqld
      mysqld 1:off 2:on 3:on 4:on 5:on 6:off
    # service mysqld start[restart/reload/stop]
    # vi /etc/my.cnf
     add this:(
    防止mysql服務器無查詢后8小時自動重連)
    wait_timeout = 86400

    interactive_timeout = 86400

       #/usr/local/mysql/bin/mysqladmin -uroot password 'aptech'
       #./bin/mysql -uroot -paptech
       #echo "PATH=$PATH:/usr/local/mysql/bin" >> /etc/profile
       #. !$
      
    2、安裝bind
       #tar zxvf bind-9.5.0-P2.tar.gz 
       #cd bind-9.5.0-P2
       #./configure --prefix=/usr/local/bind9 --with-dlz-mysql=/usr/local/mysql --enable-threads=no
       //--with-dlz-mysql=/usr/local/mysql 要求bind安裝中支持DLZ
       //--enable-threads=no 關閉多線程 
       //--disable-openssl-version-check 禁止openssl版本的檢查
       #make
       #make install

    3、創建database,table
       create database mydata;
       use mydata;
       create table other_dns_records(
       zone varchar(255),
       host varchar(255),
       type varchar(255),
       data varchar(255),
       ttl int(11),
       mx_priority varchar(255), 
       refresh int(11),
       retry int(11),
       expire int(11),
       minimum int(11),
       serial bigint(11),
       resp_person varchar(255), 
       primary_ns varchar(255));
     
       create table cnc_dns_records(
       host varchar(255),
       type varchar(255),
       data varchar(255),
       ttl int(11),
       mx_priority varchar(255), 
       refresh int(11),
       retry int(11),
       expire int(11),
       minimum int(11),
       serial bigint(11),
       resp_person varchar(255), 
       primary_ns varchar(255));
      
       insert other_dns_records(zone,host,type,data,ttl,retry)
       values('aaa.com','www','A','192.168.199.2','86400','13');
       insert cnc_dns_records(zone,host,type,data,ttl,retry)
       values('bbb.com','www','A','192.55.199.199','86400','13');
    4、編輯/usr/local/bind9/etc/named.conf
       #cd /usr/local/bind9/etc
       #../sbin/rndc-confgen -a
       #../sbin/rndc-confgen > named.conf
       #vi !$   //vi named.conf
       #less named.conf
     # Use with the following in named.conf, adjusting the allow list as needed:
     key "rndc-key" {
            algorithm hmac-md5;
            secret "c4aUV+N7GbOF773V+/LnAA==";
     };
     
     controls {
            inet 127.0.0.1 port 953
                    allow { 127.0.0.1; } keys { "rndc-key"; };
     };
    # End of named.conf
    options {
    directory "/usr/local/bind9/etc/";
    pid-file "/usr/local/bind9/var/run/named.pid";
    allow-query { any; };
    recursion no;
    version "gaint-d1";
    };
    include "/usr/local/bind9/etc/cnc.cl";
    include "/usr/local/bind9/etc/other.cl";
    view "cnc-user" {
    match-clients { cnc; };
    dlz "Mysql zone" {
    database "mysql
    {host=localhost dbname=mydata ssl=false port=3306 user=root pass=aptech}
    {select zone from cnc_dns_records where zone = '%zone%'}
    {select ttl, type, mx_priority, case when lower(type)='txt' then concat('/"', data, 
    '/"')
    when lower(type) = 'soa' then concat_ws('
    ', data, resp_person, serial, refresh, retry, expire, minimum) else data end as mydata from
    cnc_dns_records where zone = '%zone%' and host = '%record%'}";
    };
    };
    view "other-user" {
    match-clients { other; };
    dlz "Mysql zone" {
    database "mysql
    {host=localhost dbname=mydata ssl=false port=3306 user=root pass=aptech}
    {select zone from other_dns_records where zone='%zone%'}
    {select ttl, type, mx_priority, case when lower(type) = 'txt' then concat('/"', data, 
    '/"')
    when lower(type)='soa' then concat_ws('
    ', data, resp_person, serial, refresh, retry, expire, minimum) else data end as mydata from
    other_dns_records where zone = '%zone%' and host = '%record%'}";
    };
    };
    [root@dlz etc]# less cnc.cl 
    acl "cnc"{
    192.168.9.0/24;
    };
    [root@dlz etc]# less other.cl 
    acl "other" {
    127.0.0.0/18;
    };
     
    5、啟動&測試
    [root@dlz ~]# /usr/local/bind9/sbin/named -gc  /usr/local/bind9/etc/named.conf
    06-Mar-2009 22:23:02.569 starting BIND 9.5.0-P2 -gc /usr/local/bind9/etc/named.conf
    06-Mar-2009 22:23:02.579 loading configuration from '/usr/local/bind9/etc/named.conf'
    06-Mar-2009 22:23:02.583 listening on IPv4 interface lo, 127.0.0.1#53
    06-Mar-2009 22:23:02.586 listening on IPv4 interface eth0, 192.168.1.5#53
    06-Mar-2009 22:23:02.588 Loading 'Mysql zone' using driver mysql
    06-Mar-2009 22:23:02.604 default max-cache-size (33554432) applies: view cnc-user
    06-Mar-2009 22:23:02.609 Loading 'Mysql zone' using driver mysql
    06-Mar-2009 22:23:02.612 default max-cache-size (33554432) applies: view other-user
    06-Mar-2009 22:23:02.616 default max-cache-size (33554432) applies: view _bind
    06-Mar-2009 22:23:02.621 command channel listening on 127.0.0.1#953
    06-Mar-2009 22:23:02.621 ignoring config file logging statement due to -g option
    06-Mar-2009 22:23:02.623 running
    posted @ 2013-07-31 18:40 brock 閱讀(345) | 評論 (0)編輯 收藏

         摘要: Spring的事務管理難點剖析(7):數據連接泄漏底層連接資源的訪問問題    對于應用開發者來說,數據連接泄漏無疑是一個可怕的夢魘。只要你開發的應用存在數據連接泄漏的問題,應用程序最終都將因數據連接資源的耗盡而崩潰,甚至還可能引起數據庫的崩潰。數據連接泄漏像一個黑洞那樣讓開發者避之唯恐不及。    Spring DAO對所有支持的數據訪...  閱讀全文
    posted @ 2013-05-29 09:53 brock 閱讀(1019) | 評論 (0)編輯 收藏

    癥狀:系統運行了一段時間報錯:java.sql.SQLException: ORA-01000: 超出打開游標的最大數

    step 1:
        查看數據庫當前的游標數配置slqplus:show parameter open_cursors;

    step 2:
        查看游標使用情況:
    select o.sid, osuser, machine, count(*) num_curs
    from v$open_cursor o, v$session s
    where user_name = 'user' and o.sid=s.sid
    group by o.sid, osuser, machine
    order by  num_curs desc;
    此處的user_name='user'中,user代表占用數據庫資源的數據庫用戶名.

    step 3:
        查看游標執行的sql情況:

    select o.sid q.sql_text
    from v$open_cursor o, v$sql q
    where q.hash_value=o.hash_value and o.sid = 123;

    step 4:
        根據游標占用情況分析訪問數據庫的程序在資源釋放上是否正常,如果程序釋放資源沒有問題,則加大游標數。
        alter system set open_cursors=2000 scope=both;
        
        補充:在java代碼中,執行conn.createStatement()和conn.prepareStatement()的時候,實際上都是相當與在數據庫中打開了一個cursor。尤其是,如果你的createStatement和prepareStatement是在一個循環里面的話,就會非常容易出現這個問題。因為游標一直在不停的打開,而且沒有關閉。
         一般來說,我們在寫Java代碼的時候,createStatement和prepareStatement都應該要放在循環外面,而且使用了這些Statment后,及時關閉。最好是在執行了一次executeQuery、executeUpdate等之后,如果不需要使用結果集(ResultSet)的數據,就馬上將Statment關閉,調用close()方法。

    posted @ 2013-05-29 09:53 brock 閱讀(194) | 評論 (0)編輯 收藏

    主站蜘蛛池模板: 亚洲色大成网站www尤物| 亚洲人成影院午夜网站| 亚洲一区免费观看| 亚洲国产成人精品无码区在线网站| 亚洲国产品综合人成综合网站| 涩涩色中文综合亚洲| 免费人成再在线观看网站| 中国一级特黄的片子免费 | 国产2021精品视频免费播放| 中文字幕无码免费久久99| 国产精品成人免费综合| 亚洲综合无码精品一区二区三区| 亚洲色图.com| 亚洲a∨无码精品色午夜| baoyu122.永久免费视频| 999国内精品永久免费视频| 国产免费变态视频网址网站| 亚洲精品无码MV在线观看| 亚洲国产精品xo在线观看| 另类小说亚洲色图| 久久久久久影院久久久久免费精品国产小说 | 亚洲欧美一区二区三区日产| 成人国产网站v片免费观看| 久久成人a毛片免费观看网站| 毛片免费在线观看网址| 4338×亚洲全国最大色成网站| 亚洲一区二区三区高清| 国产亚洲精品美女2020久久| 无码国产精品一区二区免费vr| 免费无码又爽又刺激高潮的视频| 亚洲日韩精品A∨片无码| 激情综合亚洲色婷婷五月| 黄色短视频免费看| 国产美女在线精品免费观看| 国产AⅤ无码专区亚洲AV| 国产精品亚洲片夜色在线| 成人免费乱码大片A毛片| 成年人免费观看视频网站| 国产亚洲一区二区三区在线观看| 亚洲成a∨人片在无码2023| 未满十八18禁止免费无码网站 |