Rising Sun

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  148 随笔 :: 0 文章 :: 22 评论 :: 0 Trackbacks

#

头文件
#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 阅读(312) | 评论 (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 阅读(210) | 评论 (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 阅读(215) | 评论 (0)编辑 收藏

Visual Studio Ultimate 2012Visual Studio Ultimate 2012 静态激活密钥,有兴趣的可以试一下。

RBCXF-CVBGR-382MK-DFHJ4-C69G8
posted @ 2013-12-17 11:07 brock 阅读(170) | 评论 (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 阅读(685) | 评论 (0)编辑 收藏

ext grid 删除最后一行数据后还是显示

grid删除最后一行数据后,store reload ,因为数据库中已经没有数据了,所以返回null .

但是ext不认这个东西,所以在service中进行判断。如果数据为null ,则返回

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

重新编译,运行后,删除最后一行数据,就会看不到了。

posted @ 2013-10-24 10:40 brock 阅读(241) | 评论 (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 阅读(205) | 评论 (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 阅读(707) | 评论 (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 阅读(259) | 评论 (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 阅读(213) | 评论 (0)编辑 收藏

仅列出标题
共15页: 上一页 1 2 3 4 5 6 7 8 9 下一页 Last