OSDN Git Service

first commit
authorhayashi <hayashi.yuu@gmail.com>
Fri, 19 Oct 2012 14:28:55 +0000 (23:28 +0900)
committerhayashi <hayashi.yuu@gmail.com>
Fri, 19 Oct 2012 14:28:55 +0000 (23:28 +0900)
build.xml [new file with mode: 0644]
classes/database.properties [new file with mode: 0644]
src/ConvBusstop.bat [new file with mode: 0644]
src/database.properties [new file with mode: 0644]
src/expBusstop.bat [new file with mode: 0644]
src/osm/jp/ConvBusstop.java [new file with mode: 0644]
src/osm/jp/DbBusstop.java [new file with mode: 0644]
src/osm/jp/api/HttpGET.java [new file with mode: 0644]

diff --git a/build.xml b/build.xml
new file mode 100644 (file)
index 0000000..50181f8
--- /dev/null
+++ b/build.xml
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE configuration>
+<project name="ConvBusstop" default="all" basedir=".">
+       <!--
+       ソース以外にビルドに必要なライブラリ
+       ./lib/hayashi_0223.jar
+       ./lib/hsqldb_2_2_8.jar
+       ./lib/jar-in-jar-loader.zip
+       -->
+    <property name="src" value="${basedir}/src" />
+    <property name="classes" value="${basedir}/classes" />
+       <property name="appname" value="ConvBusstop"></property>
+       <property name="version" value=""></property>
+       <property name="dblib" value="hsqldb.jar"></property>
+       <property name="hayashilib" value="hayashi.jar"></property>
+       <property name="dest" value="${basedir}/dest"></property>
+
+
+       <!--
+       [STEP 1] クリーンナップ
+ -->
+       <target name="clean" description="前回作成したclassファイルを削除する">
+               <delete>
+                       <fileset dir="${classes}" includes="**/*.class" />
+                       <fileset dir="${src}" includes="**/*.class" />
+               </delete>
+       </target>
+
+
+       <!--
+       [STEP 2] コンパイル
+        -->
+       <target name="compile_src" depends="clean" description="コンパイル src">
+           <javac      optimize="off" debug="on" verbose="false" srcdir="${src}" destdir="${classes}" encoding="UTF-8" >
+                       <include name="**" />
+               <exclude name="**/*.smap" />
+
+               <classpath>
+                               <pathelement path="${src}"/>
+                               <fileset dir="${basedir}/..">
+                                       <include name="${hayashilib}"/>
+                                       <include name="${dblib}"/>
+                               </fileset>
+                       </classpath>
+               </javac>
+       </target>
+
+       <!--
+       [STEP 3] リンク
+        -->
+    <target name="create_run_jar" depends="compile_src" description="'${appname}.jar'を作成する">
+               <tstamp>
+                       <format property="ts" pattern="yyyy/MM/dd-HH:mm:ss-z"/>
+               </tstamp>
+        <jar destfile="${dest}/${appname}.jar">
+                       <fileset dir="${src}" includes="**/*.png" />
+                       <fileset dir="${src}" includes="**/*.gif" />
+                       <fileset dir="${src}" includes="**/*.jpg" />
+                       <fileset dir="${src}" includes="database.properties" />
+
+                       <manifest>
+                               <attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/>
+                               <attribute name="Rsrc-Main-Class" value="osm.jp.ConvBusstop"/>
+                               <attribute name="Class-Path" value="."/>
+                               <attribute name="Rsrc-Class-Path" value="./ ../ ${hayashilib} ${dblib}"/>
+                               <attribute name="Implementation-Title"   value="${appname}"/>
+                               <attribute name="Implementation-Version" value="${appname}"/>
+                               <attribute name="Implementation-Vendor"  value="hayashi"/>
+                               <attribute name="Build-Id" value="${ts} (${user.name} [${os.name} ${os.version} ${os.arch}])"/>
+                       </manifest>
+                       <zipfileset src="../jar-in-jar-loader.zip"/>
+                       <zipfileset dir="classes"/>
+                       <zipfileset dir="${src}"/>
+            <zipfileset dir="${basedir}/.." includes="${hayashilib}"/>
+            <zipfileset dir="${basedir}/.." includes="${dblib}"/>
+        </jar>
+    </target>
+
+       <!--
+       [STEP 4] デプロイ
+        -->
+    <target name="deploy" depends="create_run_jar" description="'${appname}.jar'を作成する">
+               <copy preservelastmodified="true" todir="${deploy}">
+                       <fileset file="${src}/ConvBusstop.bat"/>
+                       <fileset file="${src}/expBusstop.bat"/>
+               </copy>
+    </target>
+
+       <target name="all" depends="create_run_jar"></target>
+</project>
+
diff --git a/classes/database.properties b/classes/database.properties
new file mode 100644 (file)
index 0000000..b8aa951
--- /dev/null
@@ -0,0 +1,4 @@
+db_driver=org.hsqldb.jdbcDriver
+db_url=jdbc:hsqldb:file:./database/db
+db_user=sa
+db_passwd=
diff --git a/src/ConvBusstop.bat b/src/ConvBusstop.bat
new file mode 100644 (file)
index 0000000..478f259
--- /dev/null
@@ -0,0 +1,3 @@
+java -jar ConvBusstop.jar
+
+pause
\ No newline at end of file
diff --git a/src/database.properties b/src/database.properties
new file mode 100644 (file)
index 0000000..b8aa951
--- /dev/null
@@ -0,0 +1,4 @@
+db_driver=org.hsqldb.jdbcDriver
+db_url=jdbc:hsqldb:file:./database/db
+db_user=sa
+db_passwd=
diff --git a/src/expBusstop.bat b/src/expBusstop.bat
new file mode 100644 (file)
index 0000000..895a323
--- /dev/null
@@ -0,0 +1,3 @@
+java -jar ReadKIBAN.jar DbBusstop
+
+pause
\ No newline at end of file
diff --git a/src/osm/jp/ConvBusstop.java b/src/osm/jp/ConvBusstop.java
new file mode 100644 (file)
index 0000000..632cb6c
--- /dev/null
@@ -0,0 +1,642 @@
+package osm.jp;
+import osm.jp.api.HttpGET;
+import javax.xml.parsers.*;
+import javax.xml.transform.TransformerException;
+
+import org.w3c.dom.*;
+import org.xml.sax.*;
+
+import java.io.*;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+
+import jp.co.areaweb.tools.database.*;
+
+public class ConvBusstop {
+
+       String filter = "";
+       String urlStr = "";
+
+       public static final boolean DB_INIT = false;
+
+       // 近くのバス停を探す範囲(バス停を中心としたNEER×2m四方の領域
+       static final int NEER = 75;
+
+       /**
+        * メイン
+        *
+        * @throws IOException
+        * @throws SQLException
+        * @throws ClassNotFoundException
+        * @throws FileNotFoundException
+        * @throws TransformerException
+        * @throws SAXException
+        * @throws ParserConfigurationException */
+       public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, SQLException, IOException, ParserConfigurationException, SAXException, TransformerException
+       {
+               int index = 0;
+               boolean updateDb = true;
+               if (args.length > index) {
+                       if (args[index].equals("-exp")) {
+                               updateDb = false;
+                               index++;
+                       }
+               }
+
+               /**
+                * アプリケーション [ConvBusstop]
+                * > java -jar ReadKIBAN.jar <オプション>
+                *      オプション: -exp 実行する直前にデータベースを初期化する(省略可能)
+                */
+               Connection con = DatabaseTool.openDb("database");
+               try {
+                       /**
+                        * バス停データ変換のメイン処理
+                        */
+                       int fcounter = 0;
+                       if (args.length > index) {
+                               File iFile = new File(args[index]);
+                               fcounter++;
+
+                               ConvBusstop.initDb(con);
+                               inputFile(con, iFile);
+                               String iStr = iFile.getName();
+                               outputDb(con, iStr.substring(0, iStr.length() - 4));
+                       }
+                       else {
+                               if (updateDb) {
+                                       File dbdir = new File("database");
+                                       if (dbdir.isDirectory()) {
+                                               dbdir.delete();
+                                       }
+                                       dbdir.mkdir();
+                               }
+
+                               File dir = new File(".");
+                               File[] files = dir.listFiles();
+
+                               for (File iFile : files) {
+                                       ConvBusstop.initDb(con);
+                                       if (checkFile(iFile)) {
+                                               fcounter++;
+                                               inputFile(con, iFile);
+                                       }
+                               }
+                               // ローカルデータベース内の情報を出力する
+                               for (File iFile : files) {
+                                       if (checkFile(iFile)) {
+                                               String iStr = iFile.getName();
+                                               outputDb(con, iStr.substring(0, iStr.length() - 4));
+                                       }
+                               }
+                       }
+                       System.out.println("["+ fcounter +"]つのファイルをインポートしました。");
+               }
+               finally {
+                       DatabaseTool.closeDb(con);
+               }
+       }
+
+       static String[] shiftArgs(String[] args) {
+               String[] values = new String[args.length - 1];
+               for (int i=1; i < args.length; i++) {
+                       values[i - 1] = new String(args[i]);
+               }
+               return values;
+       }
+
+       /**
+        * ソースファイルを読み取ってローカルベータベースへ記録する
+        * @param con
+        * @param iFile
+        * @throws FileNotFoundException
+        * @throws ClassNotFoundException
+        * @throws SQLException
+        * @throws IOException
+        */
+       public static void inputFile (Connection con, File iFile) throws FileNotFoundException, ClassNotFoundException, SQLException, IOException {
+               int iCounter = 0;
+               String timeStampStr = null;
+
+               String iStr = iFile.getName();
+               File dir = new File(iStr.substring(0, iStr.length() - 4));
+               dir.mkdir();
+
+               DocumentBuilderFactory factory;
+               DocumentBuilder        builder;
+               Node root;
+
+               iCounter = 0;
+               try {
+                       factory = DocumentBuilderFactory.newInstance();
+                       builder = factory.newDocumentBuilder();
+                       factory.setIgnoringElementContentWhitespace(true);
+                       factory.setIgnoringComments(true);
+                       factory.setValidating(true);
+                       root    = builder.parse(iStr);
+
+                       iCounter += showNodes(con, root, iStr.substring(0, iStr.length() - 4), timeStampStr);
+               } catch (ParserConfigurationException e0) {
+                       System.out.println(e0.getMessage());
+               } catch (SAXException e1){
+                       System.out.println(e1.getMessage());
+               } catch (IOException e2) {
+                       System.out.println(e2.getMessage());
+               } catch (SQLException e2) {
+                       System.out.println(e2.getMessage());
+               }
+               System.out.println("バス停数["+ iCounter +"]");
+       }
+
+       public static void initDb(Connection con) {
+
+               try {
+                       if (DB_INIT) {
+                               DbBusstop.drop(con);    // 'table.BUS_STOP'を削除する
+                       }
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_stop] is not created.");
+               }
+
+               try {
+                       if (DB_INIT) {
+                               String createSt = "DROP TABLE bus_course;";
+                               PreparedStatement ps = con.prepareStatement(createSt);
+                               ps.executeUpdate();
+                               ps.close();
+                       }
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_course] is not created.");
+               }
+
+               try {
+                       if (DB_INIT) {
+                               String createSt = "DROP TABLE bus_ref;";
+                               PreparedStatement ps = con.prepareStatement(createSt);
+                               ps.executeUpdate();
+                               ps.close();
+                       }
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_ref] is not created.");
+               }
+
+               // 'table.BUS_STOP'を新規に作る
+               try {
+                       DbBusstop.create(con);
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_stop] is already created.");
+               }
+
+               try {
+                       String createSt = "CREATE TABLE bus_course (code int, type int, corp VARCHAR(128) NOT NULL, course VARCHAR(512), ifile VARCHAR(128), CONSTRAINT bus_course_pk PRIMARY KEY(code));";
+                       PreparedStatement ps = con.prepareStatement(createSt);
+                       ps.executeUpdate();
+                       ps.close();
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_course] is already created.");
+               }
+
+               try {
+                       String createSt = "CREATE TABLE bus_ref (idref VARCHAR(12), code INT);";
+                       PreparedStatement ps = con.prepareStatement(createSt);
+                       ps.executeUpdate();
+                       ps.close();
+               }
+               catch (SQLException e) {
+                       System.out.println("table [bus_ref] is already created.");
+               }
+       }
+
+
+       /**
+        * ローカルデータベース内の情報を出力する
+        * @param con
+        * @param iCode
+        * @throws IOException
+        * @throws SQLException
+        */
+       public static void outputDb(Connection con, String iCode) throws IOException, SQLException {
+               SimpleDateFormat timeStampFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+               String timeStampStr = timeStampFmt.format(new Date(Calendar.getInstance().getTimeInMillis()));
+               File dir = new File(iCode);
+               dir.mkdir();
+
+               BufferedWriter ow = null;
+               BufferedWriter gw = null;
+
+               File htmlFile = new File(iCode  +".html");
+               BufferedWriter hw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
+               hw.write("<!DOCTYPE html>");
+               hw.newLine();
+               hw.write("<html><head><meta charset=\"utf-8\" /></head>");
+               hw.newLine();
+               hw.write("<body><table border='1'>");
+               hw.newLine();
+               hw.write("<tr>");
+               hw.write("<td>type</td>");
+               hw.write("<td>corp</td>");
+               hw.write("<td>course</td>");
+               hw.write("<td>GPX</td>");
+               hw.write("<td>SAMPLE</td>");
+               hw.write("<td>バス停数</td>");
+               hw.write("<td>未入力</td>");
+               hw.write("<td>既存</td>");
+               hw.write("</tr>");
+               hw.newLine();
+
+               PreparedStatement ps7 = con.prepareStatement("SELECT code,type,corp,course,ifile FROM bus_course WHERE ifile=? ORDER BY corp,course");
+               PreparedStatement ps9 = con.prepareStatement("SELECT idref FROM bus_ref WHERE code=?");
+               PreparedStatement ps8 = con.prepareStatement("SELECT name,lat,lon,fixed FROM bus_stop WHERE idref=?");
+               ps7.setString(1, iCode);
+               ResultSet rset7 = ps7.executeQuery();
+               while (rset7.next()) {
+                       int code = rset7.getInt(1);
+                       int type = rset7.getInt(2);
+                       String corp = rset7.getString(3);
+                       String course = rset7.getString(4);
+
+                       File osmFile = new File(dir, iCode + String.format("_%1$08d", code) +".osm");
+                       File gpxFile = new File(dir, iCode + String.format("_%1$08d", code) +".gpx");
+                       File osmSample = new File(dir, iCode + String.format("_s%1$08d", code) +".osm");
+
+                       System.out.println("course = "+ course);
+                       int stopCount = 0;
+                       int fixedCount = 0;
+                       int unfixedCount = 0;
+
+                       // index file header
+                       hw.write("<tr>");
+                       hw.write("<td>"+ type +"</td>");
+                       hw.write("<td>"+ corp +"</td>");
+                       hw.write("<td><a href='"+ dir.getName() +"/"+ osmFile.getName() +"'>"+ course +"</a></td>");
+                       hw.write("<td><a href='"+ dir.getName() +"/"+ gpxFile.getName() +"'>"+ gpxFile.getName() +"</a></td>");
+                       hw.write("<td><a href='"+ dir.getName() +"/"+ osmSample.getName() +"'>"+ osmSample.getName() +"</a></td>");
+                       hw.newLine();
+
+                       // OSM file header
+                       ow = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(osmFile), "UTF-8"));
+                       ow.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+                       ow.newLine();
+                       ow.write("<osm version=\"0.5\" generator=\"ReadKIBAN\">");
+                       ow.newLine();
+
+                       // GPX file header
+                       gw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(gpxFile), "UTF-8"));
+                       gw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+                       gw.newLine();
+                       gw.write("<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" version=\"1.1\" creator=\"osmtracker-android\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd \">");
+                       gw.newLine();
+
+                       double maxLat = 0.0;
+                       double minLat = 180.0;
+                       double maxLon = 0.0;
+                       double minLon = 180.0;
+
+                       ps9.setInt(1, code);
+                       ResultSet rset9 = ps9.executeQuery();
+                       while (rset9.next()) {
+                               String idref = rset9.getString(1);
+
+                               ps8.setString(1, idref);
+                               ResultSet rset8 = ps8.executeQuery();
+                               if (rset8.next()) {
+                                       stopCount++;
+                                       String name = rset8.getString(1);
+                                       Double lat = rset8.getDouble(2);
+                                       Double lon = rset8.getDouble(3);
+                                       int fixed = rset8.getInt(4);
+
+                                       if (lat > maxLat) {
+                                               maxLat = lat;
+                                       }
+                                       if (lon > maxLon) {
+                                               maxLon = lon;
+                                       }
+                                       if (lat < minLat) {
+                                               minLat = lat;
+                                       }
+                                       if (lon < minLon) {
+                                               minLon = lon;
+                                       }
+
+                                       System.out.println("\tway point = "+ idref);
+                                       fixedCount += fixed;
+                                       if (fixed == 0) {
+                                               unfixedCount++;
+
+                                               // OSM node
+                                               int nodeid = Integer.parseInt(idref.substring(1)) * -1;
+                                               String osm_node = nodeBusstop(nodeid, name, lat, lon, timeStampStr);
+                                               ow.write(osm_node);
+                                               ow.newLine();
+
+                                               // TEXT node
+                                               File txtFile = new File(dir, iCode + idref +".txt");
+                                               BufferedWriter gw2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFile), "UTF-8"));
+                                               gw2.write(osm_node);
+                                               gw2.newLine();
+                                               gw2.close();
+
+                                               // GPX waypoint
+                                               gw.write("<wpt lat=\""+ lat +"\" lon=\""+ lon +"\">\n");
+                                               gw.write(" <time>"+ timeStampStr +"Z</time>\n");
+                                               gw.write(" <name><![CDATA["+ name +"]]></name>\n");
+                                               gw.write(" <link href=\""+ txtFile.getName() +"\"><text>"+ idref +"</text></link>\n");
+                                               gw.write("</wpt>\n");
+                                               gw.newLine();
+                                       }
+                               }
+                               rset8.close();
+                       }
+                       rset9.close();
+
+                       // INDEX file
+                       hw.write("<td>"+ stopCount +"</td>");
+                       hw.write("<td>"+ unfixedCount +"</td>");
+                       hw.write("<td>"+ fixedCount +"</td>");
+                       hw.write("</tr>");
+                       hw.newLine();
+
+                       // OSM file header
+                       BufferedWriter ow2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(osmSample), "UTF-8"));
+                       ow2.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+                       ow2.newLine();
+                       ow2.write("<osm version=\"0.5\" generator=\"ReadKIBAN\">");
+                       ow2.newLine();
+
+                       ow2.write(nodeBusstop(code, "SAMPLE", ((maxLat+minLat)/2), ((maxLon+minLon)/2), timeStampStr));
+                       ow2.newLine();
+                       ow2.write("</osm>");
+                       ow2.newLine();
+                       ow2.close();
+
+                       // OSM file footer
+                       ow.write("</osm>");
+                       ow.newLine();
+                       ow.close();
+
+                       // GPX file footer
+                       gw.write("</gpx>");
+                       gw.newLine();
+                       gw.close();
+               }
+               rset7.close();
+
+               // index file footer
+               hw.write("</table></body></html>");
+               hw.newLine();
+               hw.close();
+       }
+
+       public static String nodeBusstop(int code, String name, Double lat, Double lon, String timeStampStr) {
+               String osm_node = ("<node id=\"-"+ code +"\" timestamp=\""+ timeStampStr +"Z\" lat=\""+ lat +"\" lon=\""+ lon +"\">\n");
+               osm_node += "<tag k=\"name\" v=\""+ name +"\"/>\n";
+               osm_node += "<tag k=\"highway\" v=\"bus_stop\"/>\n";
+               osm_node += "<tag k=\"bus\" v=\"yes\"/>\n";
+               osm_node += "<tag k=\"fixme\" v=\"このバス停を正しい位置に移動させて欲しい\"/>\n";
+               osm_node += ("<tag k=\"source\" v=\"KSJ2\"/>\n");
+               osm_node += ("<tag k=\"source_ref\" v=\"http://nlftp.mlit.go.jp/ksj/gml/datalist/KsjTmplt-P11.html\"/>\n");
+               osm_node += ("<tag k=\"created_by\" v=\"National-Land-Numerical-Information_MLIT_Japan\"/>\n");
+               osm_node += ("<tag k=\"note\" v=\"National-Land Numerical Information (Bus stop) 2012, MLIT Japan\"/>\n");
+               osm_node += ("<tag k=\"note:ja\" v=\"国土数値情報(バス停留所)平成24年 国土交通省\"/>\n");
+               osm_node += ("<tag k=\"public_transport\" v=\"stop_position\"/>\n");
+               osm_node += ("</node>\n");
+               return osm_node;
+       }
+
+       /**
+        *
+        * @param con
+        * @param node
+        * @param iFileName             // ソースファイル名(拡張子を含まない)
+        * @param timeStampStr
+        * @return
+        * @throws IOException
+        * @throws SQLException
+        */
+       public static int showNodes(Connection con, Node node, String iFileName, String timeStampStr) throws IOException, SQLException {
+               int iCounter = 0;
+               NamedNodeMap nodeMap = node.getAttributes();
+               if ( null != nodeMap ) {
+                       for ( int j=0; j < nodeMap.getLength(); j++ ) {
+                               if (nodeMap.item(j).getNodeName().equals("timeStamp")) {
+                                       timeStampStr = nodeMap.item(j).getNodeValue();
+                               }
+                       }
+               }
+
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i<nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       if (node2.getNodeName().equals("jps:GM_Point")) {
+                               showGmPoint(con, node2);
+                       }
+                       else if (node2.getNodeName().equals("ksj:ED01")) {
+                               iCounter++;
+                               showED01(con, node2, iFileName);
+                       }
+                       else {
+                               iCounter += showNodes(con, node2, iFileName, timeStampStr);
+                       }
+               }
+               return iCounter;
+       }
+
+       /**
+        *
+        * @param con
+        * @param node
+        * @param iFileName             // ソースファイル名(拡張子を含まない)
+        * @throws IOException
+        * @throws SQLException
+        */
+       public static void showED01(Connection con, Node node, String iFileName) throws IOException, SQLException {
+               String idrefStr = "";
+               String nameStr = "";
+               PreparedStatement ps1 = con.prepareStatement("SELECT idref FROM bus_stop WHERE idref=?");
+               PreparedStatement ps2 = con.prepareStatement("INSERT INTO bus_stop (idref,name,ifile) VALUES (?,?,?)");
+               PreparedStatement ps3 = con.prepareStatement("SELECT code FROM bus_course WHERE course=? AND corp=? AND ifile=?");
+               PreparedStatement ps4 = con.prepareStatement("INSERT INTO bus_course (code,type,corp,course,ifile) VALUES (?,?,?,?,?)");
+               PreparedStatement ps5 = con.prepareStatement("INSERT INTO bus_ref (idref,code) VALUES (?,?)");
+               PreparedStatement ps6 = con.prepareStatement("SELECT max(code) FROM bus_course WHERE ifile=?");
+
+               ArrayList<String[]> bris = new ArrayList<String[]>();
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i < nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       if (node2.getNodeName().equals("ksj:POS")) {
+                               NamedNodeMap nodeMap = node2.getAttributes();
+                               if (null != nodeMap) {
+                                       for ( int j=0; j < nodeMap.getLength(); j++ ) {
+                                               if (nodeMap.item(j).getNodeName().equals("idref")) {
+                                                       idrefStr = nodeMap.item(j).getNodeValue();
+                                                       System.out.println("found idref='"+ idrefStr +"'");
+                                                       break;
+                                               }
+                                       }
+                               }
+                       }
+                       else if (node2.getNodeName().equals("ksj:BSN")) {
+                               nameStr = node2.getTextContent();
+                       }
+                       else if (node2.getNodeName().equals("ksj:BRI")) {
+                               String[] rtn = anaComm(node2);
+                               if (rtn != null) {
+                                       bris.add(rtn);
+                               }
+                       }
+               }
+
+               // idref と nameStr をデータベースに格納する
+               boolean insert = false;
+               ps1.setString(1, idrefStr);
+               ResultSet rset = ps1.executeQuery();
+               if (!rset.next()) {
+                       insert = true;
+               }
+               rset.close();
+
+               if (insert) {
+                       ps2.setString(1, idrefStr);
+                       ps2.setString(2, nameStr);
+                       ps2.setString(3, iFileName);
+                       ps2.executeUpdate();
+               }
+
+               for (String[] rtn : bris) {
+                       int code = 0;
+                       ps3.setString(1, rtn[1]);
+                       ps3.setString(2, rtn[2]);
+                       ps3.setString(3, iFileName);
+                       rset = ps3.executeQuery();
+                       if (rset.next()) {
+                               code = rset.getInt(1);
+                       }
+                       rset.close();
+
+                       if (code == 0) {
+                               ps6.setString(1, iFileName);
+                               ResultSet rset6 = ps6.executeQuery();
+                               if (rset6.next()) {
+                                       code = rset6.getInt(1);
+                               }
+                               rset6.close();
+                               code++;
+
+                               System.out.println("code="+code);
+                               ps4.setInt(1, code);
+                               ps4.setInt(2, Integer.parseInt(rtn[0]));
+                               ps4.setString(3, rtn[2]);
+                               ps4.setString(4, rtn[1]);
+                               ps4.setString(5, iFileName);
+                               ps4.executeUpdate();
+                       }
+
+                       ps5.setString(1, idrefStr);
+                       ps5.setInt(2, code);
+                       ps5.executeUpdate();
+               }
+
+               ps1.close();
+               ps2.close();
+               ps3.close();
+               ps4.close();
+               ps5.close();
+       }
+
+       public static String[] anaComm(Node briNode) {
+               String[] rtn = new String[3];
+               rtn[0] = "";    // corp type
+               rtn[1] = "";    // course name
+               rtn[2] = "";    // corp name
+
+               NodeList nodes = briNode.getChildNodes();
+               for (int i=0; i < nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       if (node2.getNodeName().equals("ksj:BSC")) {
+                               rtn[0] = node2.getTextContent();
+                       }
+                       else if (node2.getNodeName().equals("ksj:BLN")) {
+                               rtn[1] = node2.getTextContent();
+                       }
+                       else if (node2.getNodeName().equals("ksj:BOC")) {
+                               rtn[2] = node2.getTextContent();
+                       }
+               }
+               return rtn;
+       }
+
+       public static void showGmPoint(Connection con, Node node) throws IOException, SQLException {
+               String positionStr = "";
+               String latStr = "";
+               String lonStr = "";
+               String idStr = "";
+
+               NamedNodeMap nodeMap = node.getAttributes();
+               if ( null != nodeMap ) {
+                       for ( int j=0; j<nodeMap.getLength(); j++ ) {
+                               if (nodeMap.item(j).getNodeName().equals("id")) {
+                                       idStr = nodeMap.item(j).getNodeValue();
+                               }
+                       }
+               }
+
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i < nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       if (node2.getNodeName().equals("jps:GM_Point.position")) {
+                               NodeList nodes3 = node2.getChildNodes();
+                               for (int j=0; j < nodes3.getLength(); j++) {
+                                       Node node3 = nodes3.item(j);
+                                       if (node3.getNodeName().equals("jps:DirectPosition")) {
+                                               NodeList nodes4 = node3.getChildNodes();
+                                               for (int k=0; k < nodes4.getLength(); k++) {
+                                                       Node node4 = nodes4.item(k);
+                                                       if (node4.getNodeName().equals("DirectPosition.coordinate")) {
+                                                               positionStr = node4.getTextContent();
+                                                               String[] str4Ary = positionStr.split(" ");
+                                                               latStr = str4Ary[0];
+                                                               lonStr = str4Ary[1];
+                                                               break;
+                                                       }
+                                               }
+                                               break;
+                                       }
+                               }
+
+                               PreparedStatement ps6 = con.prepareStatement("UPDATE bus_stop SET lat=?,lon=?,fixed=? WHERE idref=?");
+                               double lat = Double.parseDouble(latStr);
+                               double lon = Double.parseDouble(lonStr);
+                               ps6.setDouble(1, lat);
+                               ps6.setDouble(2, lon);
+                               ps6.setInt(3, HttpGET.getMap(lat, lon, NEER));
+                               ps6.setString(4, idStr);
+                               ps6.executeUpdate();
+                       }
+               }
+       }
+
+       static boolean checkFile(File f) {
+               String name = f.getName();
+               if (!name.startsWith("P11-")) {
+                       return false;
+               }
+               if (!name.toUpperCase().endsWith(".XML")) {
+                       return false;
+               }
+               return true;
+       }
+
+
+}
\ No newline at end of file
diff --git a/src/osm/jp/DbBusstop.java b/src/osm/jp/DbBusstop.java
new file mode 100644 (file)
index 0000000..b6982a6
--- /dev/null
@@ -0,0 +1,86 @@
+package osm.jp;
+
+import java.io.*;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import jp.co.areaweb.tools.database.*;
+
+public class DbBusstop {
+       File inputFile;
+       String filter = "";
+       int iCounter = 0;
+       String urlStr = "";
+       Connection con;
+       String timeStampStr = null;
+       File dir = null;
+
+       /** メイン
+        * @throws IOException
+        * @throws SQLException
+        * @throws ClassNotFoundException
+        * @throws FileNotFoundException */
+       public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException, SQLException 
+       {
+               Connection con = null;
+               try {
+                       con = DatabaseTool.openDb("database");
+                       DbBusstop.export(con);
+               }
+               finally {
+                       if (con != null) {
+                               DatabaseTool.closeDb(con);
+                       }
+               }
+       }
+
+       /**
+        * 'table.BUS_STOP'を新規に作る
+        * @param con
+        * @throws SQLException
+        */
+       public static void create(Connection con) throws SQLException {
+               String createSt = "CREATE TABLE bus_stop (idref VARCHAR(12) NOT NULL, name VARCHAR(128), lat DOUBLE, lon DOUBLE, fixed INT, ifile VARCHAR(128), CONSTRAINT bus_stop_pk PRIMARY KEY(idref));";
+               PreparedStatement ps = con.prepareStatement(createSt);
+               ps.executeUpdate();
+               ps.close();
+       }
+
+       /**
+        * 'table.BUS_STOP'を削除する
+        * @param con
+        * @throws SQLException
+        */
+       public static void drop(Connection con) throws SQLException {
+               String createSt = "DROP TABLE bus_stop;";
+               PreparedStatement ps = con.prepareStatement(createSt);
+               ps.executeUpdate();
+               ps.close();
+       }
+       
+       /**
+        * 'table.BUS_STOP'の内容をCSV形式にして標準出力に出力する
+        * @param con
+        */
+       public static void export(Connection con) {
+               try {
+                       System.out.println("TABLE: BUS_STOP");
+                       System.out.println("\"name\",\"lat\",\"lon\",\"fixed\",\"ifile\"");
+                       PreparedStatement ps8 = con.prepareStatement("SELECT name,lat,lon,fixed,ifile FROM bus_stop");
+                       ResultSet rset8 = ps8.executeQuery();
+                       while (rset8.next()) {
+                               String name = rset8.getString(1);
+                               Double lat = rset8.getDouble(2);
+                               Double lon = rset8.getDouble(3);
+                               int fixed = rset8.getInt(4);
+                               String ifile = rset8.getString(5);
+                               System.out.println("\""+ name +"\","+ lat +","+ lon +","+ fixed +",\""+ ifile +"\"");
+                       }
+                       rset8.close();
+               }
+               catch (SQLException e) {
+                       e.printStackTrace();
+               }
+       }
+}
\ No newline at end of file
diff --git a/src/osm/jp/api/HttpGET.java b/src/osm/jp/api/HttpGET.java
new file mode 100644 (file)
index 0000000..dd625f9
--- /dev/null
@@ -0,0 +1,287 @@
+package osm.jp.api;
+
+import java.net.*;
+import java.io.*;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+/**
+ * Java HTTP クライアントサンプル - HttpURLConnection 版 -
+ *
+ * @author 68user http://X68000.q-e-d.net/~68user/
+ */
+public class HttpGET {
+       //public static String host = "http://api06.dev.openstreetmap.org";
+       public static String host = "http://api.openstreetmap.org";
+       
+       public static void main(String[] args) throws MalformedURLException, ProtocolException, IOException {
+        getCapabilities();
+        
+        /*
+               <node id="-4131" timestamp="2011-01-21T16:47:41Z" lat="35.4350644157973" lon="139.423684433498">
+                       <tag k="name" v="あやせ荘"/>
+               </node>
+               <node id="-4152" timestamp="2011-01-21T16:47:41Z" lat="35.4341675801122" lon="139.418362759267">
+                       <tag k="name" v="武者奇橋"/>
+               </node>
+               <node id="-4155" timestamp="2011-01-21T16:47:41Z" lat="35.4369651010672" lon="139.426400070915">
+                       <tag k="name" v="綾瀬市役所"/>
+               </node>
+         */
+
+        double minlon = 139.4197591d;
+               double maxlon = 139.4279939d;
+               double minlat = 35.4320438d;
+               double maxlat = 35.4375923d;
+               HttpGET.getMap(minlon, minlat, maxlon, maxlat);
+        
+               HttpGET.getMap(35.4350644157973d, 139.423684433498d, 50);       // あやせ荘
+               HttpGET.getMap(35.4341675801122d, 139.418362759267d, 50);       // 武者奇橋
+               HttpGET.getMap(35.4369651010672d, 139.426400070915d, 50);       // 綾瀬市役所
+    }
+       
+       public static void getCapabilities() throws MalformedURLException, ProtocolException, IOException {
+               System.out.println(host + "/api/capabilities");
+        URL url = new URL(host + "/api/capabilities");
+
+        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
+        urlconn.setRequestMethod("GET");
+        urlconn.setInstanceFollowRedirects(false);
+        urlconn.setRequestProperty("Accept-Language", "ja;q=0.7,en;q=0.3");
+        urlconn.connect();
+
+        System.out.println("レスポンスコード[" + urlconn.getResponseCode() + "] " +
+                           "レスポンスメッセージ[" + urlconn.getResponseMessage() + "]");
+        System.out.println("\n---- ボディ ----");
+
+        BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
+
+        while (true){
+            String line = reader.readLine();
+            if ( line == null ){
+                break;
+            }
+            System.out.println(line);
+        }
+
+        reader.close();
+        urlconn.disconnect();
+       }
+       
+
+       public static final double BIG_Y = (6378137.0d + 6356752.314d) / 2d;    // 地球の平均半径(m)
+       public static final double LAT1 = Math.PI * 2d * BIG_Y / 360d;                  // 緯度1度の距離(m)
+       public static int getMap(double lat, double lon, int m) throws MalformedURLException, ProtocolException, IOException {
+               double dLat = m / LAT1;                                         // 距離を表す緯度(差分)
+               double minlat = lat - dLat;             // 底辺(緯度)
+               double maxlat = lat + dLat;             // 上辺(緯度)
+               
+               double y = Math.cos(lat / 180.0d * Math.PI) * BIG_Y;    // 緯線上の地球の半径
+               double lon1 = (y * 2.0d * Math.PI) / 360;                       // 経度1度の距離(m)
+               double dLon = m / lon1;                                         // 距離を表す経度(差分)
+               double minlon = lon - dLon;             // 左辺
+               double maxlon = lon + dLon;             // 右辺
+
+               System.out.println("緯線上の地球の半径= "+ y);
+               System.out.println("緯度1秒の長さ(m)= "+ LAT1 / 3600);
+               System.out.println("経度1秒の長さ(m)= "+ lon1 / 3600);
+
+               return getMap(minlon, minlat, maxlon, maxlat);
+       }
+       
+       public static int getMap(RectArea center) throws MalformedURLException, ProtocolException, IOException {
+               return getMap(center.minlon, center.minlat, center.maxlon, center.maxlat);
+       }
+       
+       public static int getMap(double minlon, double minlat, double maxlon, double maxlat) throws MalformedURLException, ProtocolException, IOException {
+               String param = host + "/api/0.6/map" + "?bbox="+ Double.toString(minlon) +","+ Double.toString(minlat) +","+ Double.toString(maxlon) +","+ Double.toString(maxlat);
+
+               System.out.println(param);
+        URL url = new URL(param);
+
+        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
+        urlconn.setRequestMethod("GET");
+        urlconn.setInstanceFollowRedirects(false);
+        urlconn.setRequestProperty("Accept-Language", "ja;q=0.7,en;q=0.3");
+        urlconn.connect();
+
+        System.out.println("レスポンスコード[" + urlconn.getResponseCode() + "] " +
+                           "レスポンスメッセージ[" + urlconn.getResponseMessage() + "]");
+        System.out.println("\n---- ボディ ----");
+
+        //------------------------------------------
+        DocumentBuilderFactory factory;
+               DocumentBuilder        builder;
+               Node root;
+
+               try {
+                       factory = DocumentBuilderFactory.newInstance();
+                       builder = factory.newDocumentBuilder();
+                       factory.setIgnoringElementContentWhitespace(true);
+                       factory.setIgnoringComments(true);
+                       factory.setValidating(true);
+                       root    = builder.parse(urlconn.getInputStream());
+
+                       counter = 0;
+                       checkNodes(root);
+               } catch (ParserConfigurationException e0) {
+                       System.out.println(e0.getMessage());
+               } catch (SAXException e1){
+                       System.out.println(e1.getMessage());
+               } catch (IOException e2) {
+                       System.out.println(e2.getMessage());
+               }
+
+               System.out.println("バス停数["+ counter +"]");
+        urlconn.disconnect();
+        
+        return counter;
+       }
+       
+       public void sendCMD(String api) throws MalformedURLException, ProtocolException, IOException {
+               System.out.println(host + api);
+        URL url = new URL(host + api);
+
+        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
+        urlconn.setRequestMethod("GET");
+        urlconn.setInstanceFollowRedirects(false);
+        urlconn.setRequestProperty("Accept-Language", "ja;q=0.7,en;q=0.3");
+        urlconn.connect();
+
+        System.out.println("レスポンスコード[" + urlconn.getResponseCode() + "] " +
+                           "レスポンスメッセージ[" + urlconn.getResponseMessage() + "]");
+        System.out.println("\n---- ボディ ----");
+
+        BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
+
+        while (true){
+            String line = reader.readLine();
+            if ( line == null ){
+                break;
+            }
+            System.out.println(line);
+        }
+
+        reader.close();
+        urlconn.disconnect();
+    }
+       
+       public static int counter;
+       public static void checkNodes(Node node) {
+               if (isBusstop(node)) {
+                       counter++;
+                       showNode(node);
+               }
+               
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i<nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       checkNodes(node2);
+               }
+       }
+       
+       /**
+        * [バス停]か?
+        * @param node
+        * @throws IOException
+        * @throws SQLException
+        */
+       public static boolean isBusstop(Node node) {
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i < nodes.getLength(); i++) {
+                       Node node2 = nodes.item(i);
+                       if (isBusstopTag(node2)) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * [bus_stop]タグか?
+        * @param node
+        * @return
+        */
+       private static boolean isBusstopTag(Node node) {
+               if (node.getNodeName().equals("tag")) {
+                       boolean highway = false;
+                       boolean bus_stop = false;
+                       NamedNodeMap nodeMap = node.getAttributes();
+                       if ( null != nodeMap ) {
+                               for (int j=0; j < nodeMap.getLength(); j++ ) {
+                                       String key = nodeMap.item(j).getNodeName();
+                                       String value = nodeMap.item(j).getNodeValue();
+                                       if (key.equals("k") && value.equals("highway")){
+                                               highway = true;
+                                       }
+                                       if (key.equals("v") && value.equals("bus_stop")){
+                                               bus_stop = true;
+                                       }
+                               }
+                               if (highway && bus_stop) {
+                                       return true;
+                               }
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * 指定されたノードを再帰的に表示する。
+        * 
+        * @param node
+        * @throws IOException
+        * @throws SQLException
+        */
+       public static void showNode(Node node) {
+               System.out.print("<"+ node.getNodeName());
+               NamedNodeMap nodeMap = node.getAttributes();
+               if ( null != nodeMap ) {
+                       for ( int j=0; j < nodeMap.getLength(); j++ ) {
+                               System.out.print(" "+ nodeMap.item(j).getNodeName() +"=\""+ nodeMap.item(j).getNodeValue() +"\"");
+                       }
+               }
+
+               System.out.print(">"+ node.getNodeValue());
+               
+               NodeList nodes = node.getChildNodes();
+               for (int i=0; i<nodes.getLength(); i++) {
+                       showNode(nodes.item(i));
+               }
+               System.out.println("</"+ node.getNodeName() +">");
+       }
+       
+       class RectArea {
+        public double minlon;
+        public double maxlon;
+        public double minlat;
+        public double maxlat;
+
+        /**
+         * 矩形領域を中心点と中心点からの距離(メートル)でセットする
+         * 
+         * @param lat  // 中心点の緯度
+         * @param lon  // 中心点の経度
+         * @param m            // 距離 領域の一辺の長さの半分
+         */
+               public RectArea(double lat, double lon, int m) {
+                       double BIG_Y = (40000000.0d / 2.0d / Math.PI);          // 地球の半径
+                       double LAT1 = (10000000.0d / 90.0d);            // 緯度1度の距離(m)
+                       double dLat = m / LAT1;                                         // 距離を表す緯度(差分)
+                       minlat = lat - dLat;            // 底辺(緯度)
+                       maxlat = lat + dLat;            // 上辺(緯度)
+                       double y = Math.sin((90.0d - lat) / 180.0d) * BIG_Y;    // 緯線上の地球の半径
+                       double lon1 = y * 2.0d * Math.PI;                       // 経度1度の距離(m)
+                       double dLon = m / lon1;                                         // 距離を表す経度(差分)
+                       minlon = lon - dLon;            // 左辺
+                       maxlon = lon + dLon;            // 右辺
+               }
+       }
+}