tourapi.TourAPI.java Source code

Java tutorial

Introduction

Here is the source code for tourapi.TourAPI.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tourapi;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author kimmyongjoon
 */

public class TourAPI extends Application {
    private Document doc;
    private URL url;
    private HttpURLConnection connection;
    private Document doc1;
    private Document doc2;
    private final Button saveButton = new Button();
    private final Text keyworld = new Text();
    private final TextField customAPIUrl2 = new TextField();
    private final Pane custompane = new Pane();
    private final Scene customScene = new Scene(custompane, 1000, 100);
    private final Stage customStage = new Stage();
    private final Label customlabel = new Label();
    private final TextField customAPIUrl1 = new TextField();
    private final ImageView clickedResultimageView = new ImageView();
    private final Pane rootPane = new Pane();
    private final ClickedResultPane clickedResultPane = new ClickedResultPane();
    private final Text clickedResultTitle = new Text();
    private final TabPane tabPane = new TabPane();
    private final SearchResultPane searchResultPane = new SearchResultPane();
    private final TextField searchTextField = new TextField();
    private final Button searchButton = new Button();
    private final Button clearButton = new Button();
    private final Button customButton = new Button();
    private final itemButton z = new itemButton();
    private final itemButton z1 = new itemButton();
    private final itemButton z2 = new itemButton();
    private final Text introduction = new Text();
    private final Text zipcodeText = new Text();
    private final Text telephone = new Text();
    private final Text TeleNameText = new Text();
    private final Text address = new Text();
    private final Text summary = new Text();
    private final String customwebsiteURL = "api.visitkorea.or.kr";
    private final String detailedsearchURL1 = "/openapi/service/rest/KorService/detailCommon?ServiceKey=rmQkQPyjWG0PYeTPAecwBJSQ4fxBotjv7F0OZcz4dcw3wCPtuo%2FplyHblzoZg6LynLDEPCJRB8klwH264SUf4w%3D%3D&contentTypeId=";
    private final String detailedsearchURL4 = "/openapi/service/rest/KorService/detailIntro?ServiceKey=rmQkQPyjWG0PYeTPAecwBJSQ4fxBotjv7F0OZcz4dcw3wCPtuo%2FplyHblzoZg6LynLDEPCJRB8klwH264SUf4w%3D%3D&contentTypeId=";
    private final String detailedsearchURL2 = "&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&defaultYN=Y&firstImageYN=Y&areacodeYN=Y&catcodeYN=Y&addrinfoYN=Y&mapinfoYN=Y&overviewYN=Y&transGuideYN=Y";
    private final String detailedsearchURL3 = "&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&introYN=Y";
    private final String serverIp = "104.199.161.180";
    private final String data_n3_PATH = "./data.n3";
    private final String eyeURL = "104.199.189.198:8000";
    private final String backEndURL = "104.199.161.180:8080";
    private final String frontEndURL = "104.155.224.198:8080";
    private final String localhosteyeURI = "/?data=http://" + frontEndURL + "/data.n3&query=http://" + frontEndURL
            + "/query.n3";
    private Element item = null;
    private String URLSTRING = null;
    private String APIURL1 = null;
    private String APIURL2 = null;
    private String customAPIURLHeader = "/openapi/service/rest/KorService/searchKeyword?ServiceKey=rmQkQPyjWG0PYeTPAecwBJSQ4fxBotjv7F0OZcz4dcw3wCPtuo%2FplyHblzoZg6LynLDEPCJRB8klwH264SUf4w%3D%3D&keyword=";
    private TextField customAPIURLHeaderTextField = new TextField();
    private TextField customprotocolText = new TextField();
    private String customprotocol = "http";

    private MongoClient getMongoClient() {
        MongoClient mongoClient = null;
        mongoClient = new MongoClient("104.199.189.198", 81);
        return mongoClient;
    };

    private void MLUpdate(String from, String to) {
        // ?
        //fromt->to 
        MongoClient mongoClient = getMongoClient();
        String result = null;
        try {
            DB db = mongoClient.getDB("my_database");
            DBCollection coll = db.getCollection("ML_Result");
            WriteConcern w = new WriteConcern(1, 0);
            mongoClient.setWriteConcern(w);

            DBObject doc = new BasicDBObject();
            // string?  select
            BasicDBObject query = new BasicDBObject();
            query.put("from", from);
            query.put("to", to);

            DBCursor cursor = coll.find(query);

            if (cursor.hasNext())// ?? 
            {
                DBObject mapObj = cursor.next();
                int num = ((Number) mapObj.get("num")).intValue();
                num++;
                BasicDBObject newDocument = new BasicDBObject();
                newDocument.append("$set", new BasicDBObject().append("num", num));
                BasicDBObject searchQuery = new BasicDBObject().append("from", from).append("to", to);
                coll.update(searchQuery, newDocument);
                cursor.close();
            } else {// ??  ? -> ?? insert
                doc.put("from", from);
                doc.put("to", to);
                doc.put("num", 1);
                coll.insert(doc);
                cursor.close();
            }
            System.out.println(coll.getCount());
            // close resources
            mongoClient.close();
        } catch (Exception e) {
            System.err.println("error evoke");
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    private String convertTitleToId(String title, String url, int num) {
        String result = null;
        try {

            // To connect to mongodb server
            MongoClient mongoClient = getMongoClient();
            DB db = mongoClient.getDB("my_database");
            DBCollection coll = db.getCollection("TB_titleID");
            System.out.println("? ");

            WriteConcern w = new WriteConcern(1, 0);
            mongoClient.setWriteConcern(w);
            // Now connect to your databases

            DBObject doc = new BasicDBObject();
            BasicDBObject query = new BasicDBObject("title", title);

            DBCursor cursor = coll.find(query);

            if (cursor.hasNext())// ?? 
            {
                result = cursor.next().get("ID").toString();
                cursor.close();
            } else {// ??  ? -> ?? insert
                int autoIncre = (int) coll.getCount();
                doc.put("ID", autoIncre);
                doc.put("title", title);
                System.out.println("URL : " + url);
                doc.put("url", url);
                doc.put("num", num);
                coll.insert(doc);
                cursor.close();
                result = autoIncre + "";
            }
            // close resources
            mongoClient.close();
        } catch (Exception e) {
            System.err.println("convertTitleToId error");
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return result;
    }

    private void TCP_File_Client() throws IOException {
        String url = "http://" + frontEndURL + "/upload";
        String charset = "UTF-8";
        String param = "value";
        File textFile = new File(data_n3_PATH);
        File binaryFile = new File(data_n3_PATH);
        String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
        String CRLF = "\r\n"; // Line separator required by multipart/form-data.

        URLConnection connection = new URL(url).openConnection();
        HttpURLConnection http = (HttpURLConnection) connection;
        http.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);) {
            // Send normal param.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF).append(param).append(CRLF).flush();

            // Send text file.
            writer.append("--" + boundary).append(CRLF);
            writer.append(
                    "Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"")
                    .append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
            writer.append(CRLF).flush();
            Files.copy(textFile.toPath(), output);
            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

            // Send binary file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                    + "\"").append(CRLF);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                    .append(CRLF);
            writer.append("Content-Transfer-Encoding: binary").append(CRLF);
            writer.append(CRLF).flush();
            Files.copy(binaryFile.toPath(), output);
            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

            // End of multipart/form-data.
            writer.append("--" + boundary + "--").append(CRLF).flush();
            writer.close();
        }

        File uploadFile1 = new File(data_n3_PATH);
        String requestURL = "http://" + frontEndURL + "/upload";
        try {
            MultipartUtility multipart = new MultipartUtility(requestURL, charset);

            multipart.addHeaderField("User-Agent", "CodeJava");
            multipart.addHeaderField("Test-Header", "Header-Value");

            multipart.addFormField("description", "Cool Pictures");
            multipart.addFormField("keywords", "Java,upload,Spring");

            multipart.addFilePart("fileUpload", uploadFile1);

            List<String> response = multipart.finish();

            System.out.println("SERVER REPLIED:");

            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            System.err.println("IOException");
            System.err.println(ex);
        }
    }

    private void redrawClickedResultPane(itemButton myButton) {
        try {

            zipcodeText.setVisible(true);
            TeleNameText.setVisible(true);
            telephone.setVisible(true);
            address.setVisible(true);
            summary.setVisible(true);
            clickedResultimageView.setVisible(true);

            Element myitem = myButton.getElement();
            clickedResultTitle.setText(((Element) myitem.getElementsByTagName("title").item(0)).getTextContent());
            url = new URL("http", customwebsiteURL, detailedsearchURL1
                    + ((Element) myitem.getElementsByTagName("contenttypeid").item(0)).getTextContent()
                    + "&contentId=" + ((Element) myitem.getElementsByTagName("contentid").item(0)).getTextContent()
                    + detailedsearchURL2);
            try {
                try {
                    doc1 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connectToURL(url));
                    if (doc1.hasChildNodes()) {
                        Node root1 = doc1.getDocumentElement();
                        Element body1 = (Element) root1.getChildNodes().item(1);
                        Element item1 = (Element) ((Element) body1.getChildNodes().item(0)).getChildNodes().item(0);
                        String zipcode = "?";
                        if (item1.getElementsByTagName("zipcode").item(0) != null) {
                            zipcode = item1.getElementsByTagName("zipcode").item(0).getTextContent();
                        }
                        String TeleName = " ?";
                        if (item1.getElementsByTagName("telname").item(0) != null) {
                            TeleName = item1.getElementsByTagName("telname").item(0).getTextContent();
                        }
                        String TelePhone = item1.getElementsByTagName("tel").item(0).getTextContent();
                        String Adress = item1.getElementsByTagName("addr1").item(0).getTextContent();
                        Element imageElement = (Element) item1.getElementsByTagName("firstimage").item(0);
                        String clickedimage;
                        if (imageElement == null) {
                            clickedimage = "https://upload.wikimedia.org/wikipedia/b/thumb/a/ac/No_image_available.svg/600px-No_image_available.svg.png";

                        } else {
                            clickedimage = item1.getElementsByTagName("firstimage").item(0).getTextContent();
                        }
                        String Summary = item1.getElementsByTagName("overview").item(0).getTextContent();
                        zipcodeText.setText("-  : " + zipcode);
                        TeleNameText.setText("-  : " + TeleName);
                        telephone.setText("-  : " + TelePhone);
                        address.setText("-  : " + Adress);
                        summary.setText(" : " + Summary);
                        Image image = new Image(clickedimage);
                        clickedResultimageView.setImage(image);
                        if (image.getHeight() > image.getWidth()) {
                            clickedResultimageView.setFitWidth(100);
                        } else {
                            clickedResultimageView.setFitHeight(100);
                        }
                        clickedResultimageView.setPreserveRatio(true);
                        clickedResultimageView.setSmooth(true);
                        clickedResultimageView.setCache(true);
                    }
                } catch (SAXException | IOException ex) {
                    System.err.println("SAXException | IOException");
                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (ParserConfigurationException ex) {
                System.err.println("ParserConfigurationException");
                Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (MalformedURLException ex) {
            System.err.println("MalformedURLException");
            Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // 
    public void introDraw(itemButton myButton) {
        clickedResultPane.introductioninformation.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                try {
                    zipcodeText.setVisible(false);
                    TeleNameText.setVisible(false);
                    telephone.setVisible(false);
                    address.setVisible(false);
                    summary.setVisible(false);
                    clickedResultimageView.setVisible(false);
                    Element myitem = myButton.getElement();
                    clickedResultTitle
                            .setText(((Element) myitem.getElementsByTagName("title").item(0)).getTextContent());
                    url = new URL("http", customwebsiteURL,
                            detailedsearchURL4
                                    + ((Element) myitem.getElementsByTagName("contenttypeid").item(0))
                                            .getTextContent()
                                    + "&contentId="
                                    + ((Element) myitem.getElementsByTagName("contentid").item(0)).getTextContent()
                                    + detailedsearchURL3);
                    try {
                        try {
                            doc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                    .parse(connectToURL(url));
                            if (doc2.hasChildNodes()) {
                                Node root = doc2.getDocumentElement();
                                Element body = (Element) root.getChildNodes().item(1);
                                Element items = (Element) body.getChildNodes().item(0);
                                if (items.hasChildNodes() != false) {
                                    item = (Element) items.getChildNodes().item(0);
                                    introduction.setText(item.getTextContent());
                                }
                            }
                        } catch (SAXException | IOException ex) {
                            System.err.println("SAXException  | IOException");
                            Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (ParserConfigurationException ex) {
                        System.err.println("ParserConfigurationException");
                        Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } catch (MalformedURLException ex) {
                    System.err.println("MalformedURLException");
                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    @Override
    public void start(Stage primaryStage) {
        customAPIURLHeaderTextField.setText(customAPIURLHeader);
        customAPIURLHeaderTextField.setMaxWidth(220);

        customAPIURLHeaderTextField.setMinWidth(220);
        customprotocolText.setText(customprotocol);
        custompane.getChildren().add(customAPIURLHeaderTextField);
        customAPIURLHeaderTextField.setLayoutX(205);
        customAPIURLHeaderTextField.setLayoutY(25);
        custompane.getChildren().add(customprotocolText);
        customprotocolText.setLayoutX(25);
        customprotocolText.setLayoutY(25);
        customprotocolText.setMaxWidth(50);
        APIURL1 = customwebsiteURL;
        APIURL2 = "&areaCode=&sigunguCode=&cat1=&cat2=&cat3=&listYN=Y&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&arrange=A&numOfRows=12&pageNo=1";
        custompane.getChildren().add(saveButton);
        saveButton.setText("save");
        saveButton.setLayoutX(450);
        saveButton.setLayoutY(65);
        saveButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                APIURL1 = customAPIUrl1.getText();
                APIURL2 = customAPIUrl2.getText();
            }
        });

        custompane.getChildren().add(keyworld);
        custompane.getChildren().add(customAPIUrl2);
        custompane.getChildren().add(customAPIUrl1);
        custompane.getChildren().add(customlabel);
        searchResultPane.initConfig();
        searchResultPane.getChildren().add(z);
        searchResultPane.getChildren().add(z1);
        searchResultPane.getChildren().add(z2);
        tabPane.setLayoutX(10);
        tabPane.setLayoutY(50);
        clickedResultPane.getChildren().add(clickedResultimageView);
        rootPane.getChildren().add(searchResultPane);
        rootPane.getChildren().add(tabPane);
        searchTextField.setLayoutX(10);
        searchTextField.setLayoutY(10);
        rootPane.getChildren().add(searchTextField);
        rootPane.getChildren().add(clickedResultPane);
        clickedResultTitle.setText("result");
        clickedResultTitle.setVisible(false);
        clickedResultPane.getChildren().add(address);
        clickedResultPane.getChildren().add(clickedResultTitle);
        clickedResultPane.getChildren().add(introduction);
        clickedResultPane.getChildren().add(zipcodeText);
        clickedResultPane.getChildren().add(summary);
        summary.setLayoutX(10);
        summary.setLayoutY(270);
        introduction.setLayoutY(110);
        zipcodeText.setLayoutX(170);
        zipcodeText.setLayoutY(110);
        clickedResultimageView.setLayoutY(100);
        clickedResultPane.getChildren().add(TeleNameText);
        TeleNameText.setLayoutX(170);
        TeleNameText.setLayoutY(150);
        clickedResultPane.getChildren().add(telephone);
        telephone.setLayoutX(170);
        telephone.setLayoutY(190);
        address.setLayoutX(170);
        address.setLayoutY(230);
        searchButton.setText("search");
        searchButton.setLayoutX(200);
        searchButton.setLayoutY(10);

        //eye  data.n3 ? 
        File data_n3 = new File("./data.n3");
        try {
            FileWriter data_n3_writer = new FileWriter(data_n3, false);
            String initial_data_n3_content = "@prefix log: <http://www.w3.org/2000/10/swap/log#>.\n"
                    + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n"
                    + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.\n"
                    + "@prefix : <http://www.agfa.com/w3c/euler/socrates#>.\n";
            data_n3_writer.write(initial_data_n3_content);
            String initial_inference = "{?A a ?B. ?B a ?C} => {?A a ?C}.\n"
                    + "{?A rdfs:subClassOf ?B. ?S a ?A} => {?S rdfs:subClassOf ?B}.\n"
                    + "{?A rdfs:subClassOf ?B. ?A a ?S} => {?S rdfs:subClassOf ?B}.\n";
            data_n3_writer.write(initial_inference);
            data_n3_writer.flush();
            data_n3_writer.close();
        } catch (IOException ex) {
            System.out.println("data_n3_writer_error");
            Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
        }
        //?  data.n3? ?? ?
        //

        searchButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                /////eye? ?  ??
                try {
                    FileWriter data_n3_writer = new FileWriter(data_n3, true);
                    if (searchResultPane.getsearchText().equals("")) {

                    } else {
                        String one_arrow = ":" + searchResultPane.getsearchText() + " a :"
                                + searchTextField.getText() + ".\n";
                        data_n3_writer.write(one_arrow);
                        data_n3_writer.flush();
                        data_n3_writer.close();
                        TCP_File_Client();
                    }
                } catch (IOException ex) {
                    System.out.println("eye_one_arrow_error");
                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                }
                /////   a->b?  ?? ??

                Tab tab = new Tab(searchTextField.getText());
                tab.setOnSelectionChanged(new EventHandler<Event>() {
                    @Override
                    public void handle(Event t) {
                        if (tab.isSelected()) {
                            searchResultPane.setsearchText(tab.getText());
                            try {
                                String encodeResult = tab.getText();
                                System.out.println("URLencode is : " + encodeResult);
                                try {
                                    encodeResult = URLEncoder.encode(tab.getText(), "utf-8");
                                } catch (UnsupportedEncodingException ex) {
                                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                URLSTRING = "http://" + APIURL1 + customAPIURLHeaderTextField.getText()
                                        + encodeResult + APIURL2;
                                System.out.println(URLSTRING);
                                url = new URL(customprotocol, customwebsiteURL,
                                        "/openapi/service/rest/KorService/searchKeyword?ServiceKey=rmQkQPyjWG0PYeTPAecwBJSQ4fxBotjv7F0OZcz4dcw3wCPtuo%2FplyHblzoZg6LynLDEPCJRB8klwH264SUf4w%3D%3D&keyword="
                                                + encodeResult
                                                + "&areaCode=&sigunguCode=&cat1=&cat2=&cat3=&listYN=Y&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&arrange=A&numOfRows=12&pageNo=1");
                            } catch (MalformedURLException ex) {
                                Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            try {
                                try {
                                    //url = new URL(dictionaryapiProtocal, dictionaryapiHost, dictionaryapiPath + searchedWord + dictionaryapiKeys);
                                    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                            .parse(connectToURL(url));
                                    if (doc.hasChildNodes()) {
                                        System.out.println("I have Child");
                                        Node root = doc.getDocumentElement();
                                        Element body = (Element) root.getChildNodes().item(1);
                                        Element items = (Element) body.getChildNodes().item(0);
                                        System.out.println("my Body is : " + body.getTextContent());
                                        System.out.println("my items is : " + items.getTextContent());
                                        if (items.hasChildNodes() != false) {
                                            item = (Element) items.getChildNodes().item(0);
                                            System.out.println("my item is : " + item.getTextContent());
                                            Element title = (Element) item.getElementsByTagName("title").item(0);
                                            System.out.println("my title is : " + title.getTextContent());
                                            Element imageURL = (Element) item.getElementsByTagName("firstimage")
                                                    .item(0);
                                            searchResultPane.setiv1(imageURL);
                                            z.buttonConfig(0, 150, title.getTextContent());
                                        }
                                        z.setmyURL(URLSTRING, 0);
                                        z.setElement(item);

                                        z.setOnAction(new EventHandler<ActionEvent>() {
                                            @Override
                                            public void handle(ActionEvent event) {
                                                try {
                                                    FileWriter data_n3_writer = new FileWriter(data_n3, true);
                                                    System.out.println("URLSTRING : " + URLSTRING);
                                                    String one_arrow = ":"
                                                            + eyerefactoring(searchResultPane.getsearchText())
                                                            + " rdfs:subClassOf :"
                                                            + convertTitleToId(z.getText(), URLSTRING, 0) + ".\n";
                                                    data_n3_writer.write(one_arrow);
                                                    data_n3_writer.flush();
                                                    data_n3_writer.close();
                                                    System.out.println("eye_serch_arrow_success");
                                                    TCP_File_Client();
                                                } catch (IOException ex) {
                                                    System.out.println("eye_serch_arrow_error");
                                                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE,
                                                            null, ex);
                                                }
                                                redrawClickedResultPane(z);
                                                introDraw(z);

                                                clickedResultPane.setButtonConfig();
                                                clickedResultTitle.setVisible(true);
                                            }
                                        });
                                        if (items.hasChildNodes() != false
                                                && (Element) items.getChildNodes().item(1) != null) {
                                            item = (Element) items.getChildNodes().item(1);
                                            System.out.println("my item is : " + item.getTextContent());
                                            Element title = (Element) item.getElementsByTagName("title").item(0);
                                            System.out.println("my title is : " + title.getTextContent());
                                            Element imageURL = (Element) item.getElementsByTagName("firstimage")
                                                    .item(0);
                                            searchResultPane.setiv2(imageURL);
                                            z1.buttonConfig(200, 150, title.getTextContent());
                                        }
                                        z1.setmyURL(URLSTRING, 1);
                                        z1.setElement(item);
                                        z1.setOnAction(new EventHandler<ActionEvent>() {
                                            @Override
                                            public void handle(ActionEvent event) {
                                                try {
                                                    FileWriter data_n3_writer = new FileWriter(data_n3, true);
                                                    String one_arrow = ":"
                                                            + eyerefactoring(searchResultPane.getsearchText())
                                                            + " rdfs:subClassOf :"
                                                            + convertTitleToId(z1.getText(), URLSTRING, 1) + ".\n";
                                                    data_n3_writer.write(one_arrow);
                                                    data_n3_writer.flush();
                                                    data_n3_writer.close();
                                                    System.out.println("eye_serch_arrow_success");
                                                    TCP_File_Client();
                                                } catch (IOException ex) {
                                                    System.out.println("eye_serch_arrow_error");
                                                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE,
                                                            null, ex);
                                                }
                                                redrawClickedResultPane(z1);
                                                introDraw(z1);
                                                clickedResultPane.setButtonConfig();
                                                clickedResultTitle.setVisible(true);
                                            }
                                        });
                                        tour_Information iv3tour = findwithDB(searchResultPane.getsearchText());
                                        System.out.println(iv3tour.myURL);
                                        if (iv3tour.myURL != null) {
                                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                                    .parse(connectToURL(new URL(iv3tour.myURL)));
                                            if (doc.hasChildNodes()) {
                                                root = doc.getDocumentElement();
                                                body = (Element) root.getChildNodes().item(1);
                                                items = (Element) body.getChildNodes().item(0);
                                                System.out.println("my Body is : " + body.getTextContent());
                                                System.out.println("my items is : " + items.getTextContent());
                                                if (items.hasChildNodes() != false) {
                                                    item = (Element) items.getChildNodes().item(iv3tour.myLocation);
                                                    System.out.println("my item is : " + item.getTextContent());
                                                    Element title = (Element) item.getElementsByTagName("title")
                                                            .item(0);
                                                    System.out.println("my title is : " + title.getTextContent());
                                                    Element imageURL = (Element) item
                                                            .getElementsByTagName("firstimage").item(0);
                                                    searchResultPane.setiv3(imageURL);
                                                    z2.buttonConfig(0, 300, title.getTextContent());
                                                }
                                                z2.setmyURL(URLSTRING, 0);
                                                z2.setElement(item);
                                                z2.setOnAction(new EventHandler<ActionEvent>() {
                                                    @Override
                                                    public void handle(ActionEvent event) {
                                                        try {
                                                            FileWriter data_n3_writer = new FileWriter(data_n3,
                                                                    true);
                                                            String one_arrow = ":"
                                                                    + eyerefactoring(
                                                                            searchResultPane.getsearchText())
                                                                    + " rdfs:subClassOf :"
                                                                    + convertTitleToId(z.getText(), URLSTRING, 0)
                                                                    + ".\n";
                                                            data_n3_writer.write(one_arrow);
                                                            data_n3_writer.flush();
                                                            data_n3_writer.close();
                                                            System.out.println("eye_serch_arrow_success");
                                                            TCP_File_Client();
                                                        } catch (IOException ex) {
                                                            System.out.println("eye_serch_arrow_error");
                                                            Logger.getLogger(TourAPI.class.getName())
                                                                    .log(Level.SEVERE, null, ex);
                                                        }
                                                        redrawClickedResultPane(z2);
                                                        introDraw(z2);
                                                        clickedResultPane.setButtonConfig();
                                                        clickedResultTitle.setVisible(true);
                                                    }
                                                });
                                            }
                                        }
                                    }
                                } catch (SAXException ex) {
                                    System.err.println("SAX Error");
                                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (IOException ex) {
                                    System.err.println("3 ? URL?  ");
                                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            } catch (ParserConfigurationException ex) {
                                System.err.println("Parser");
                                Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            doc.normalize();
                        }
                    }
                });
                tabPane.getTabs().add(tab);
            }
        });

        rootPane.getChildren().add(searchButton);

        customButton.setText("custom");
        customButton.setLayoutX(325);
        customButton.setLayoutY(10);
        customButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                customAPIUrl1.setText(APIURL1);
                customAPIUrl1.setMaxWidth(130);
                customAPIUrl1.setMinWidth(130);
                customAPIUrl1.setLayoutX(75);
                customAPIUrl1.setLayoutY(25);
                keyworld.setText("KEYWORD");
                keyworld.setLayoutX(440);
                keyworld.setLayoutY(40);
                customAPIUrl2.setText(APIURL2);
                customAPIUrl2.setMinWidth(400);
                customAPIUrl2.setMaxWidth(400);
                customAPIUrl2.setLayoutX(525);
                customAPIUrl2.setLayoutY(25);
                customStage.setScene(customScene);
                customStage.setTitle("Custom");
                customStage.show();
            }
        });

        clearButton.setText("clear");
        clearButton.setLayoutX(267);
        clearButton.setLayoutY(10);
        clearButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                tabPane.getTabs().clear();
                clickedResultPane.clearAll();
                searchResultPane.clearAll();
            }
        });
        rootPane.getChildren().add(clearButton);
        rootPane.getChildren().add(customButton);

        Scene scene = new Scene(rootPane, 1000, 500);

        primaryStage.setTitle("TourAPI");
        primaryStage.setScene(scene);
        primaryStage.show();

        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            public void handle(WindowEvent we) {

                try {
                    url = new URL("http://" + eyeURL + "/?data=http://" + frontEndURL + "/data.n3&query=http://"
                            + frontEndURL + "/query.n3");// url? eyeserver ?  ?   db 
                } catch (MalformedURLException ex) {
                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                }

                try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
                    String from = null;
                    String to = null;
                    for (String line; (line = reader.readLine()) != null;) {
                        if (line.length() == 0) {
                            continue;
                        } else if (line.charAt(0) == 'P') {
                            //PREFIX
                            continue;
                        } else if (line.charAt(0) == ':') {
                            String[] fromtoken = line.split("rdfs:subClassOf")[0].split(":")[1].split(" ");
                            from = fromtoken[0];
                            to = line.split(" rdfs:subClassOf <http://www.agfa.com/w3c/euler/socrates#")[1]
                                    .split(">.")[0];
                            System.out.println("from : " + from + " to : " + to);
                            MLUpdate(from, to);
                            //continue;
                        }
                        System.out.println(line);
                    }
                } catch (IOException ex) {
                    System.err.println("IOException");
                    Logger.getLogger(TourAPI.class.getName()).log(Level.SEVERE, null, ex);
                }
                // ???  -> ?  data.n3 query.n3?  eyeserver 
                //1. ?  : eye?  url? ?  .
                //2.  ? ? ?  ??  eye ?     
                //3. ? ?? get    
                //    ? ?
                //   ? ?? 
                //System.out.println("Stage is closing");
            }
        });
    }

    private InputStream connectToURL(URL url) {
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/xml");
            System.out.println("c : " + url);
            return connection.getInputStream();

        } catch (IOException ex) {
            System.out.println("IOException ex");
        }
        return null;
    }

    private String eyerefactoring(String input) {
        int length = input.length();
        String tempInput;
        String newInput;
        tempInput = input;
        newInput = tempInput;
        for (int i = 0; i < length; i++) {
            if ("(".equals(tempInput.substring(i, i + 1)) || ")".equals(tempInput.substring(i, i + 1))
                    || " ".equals(tempInput.substring(i, i + 1))) {
                String s1 = tempInput.substring(0, i);
                String s2 = tempInput.substring(i + 1);
                ;
                newInput = s1 + s2;
                tempInput = newInput;
                length--;
                i--;
            }
        }
        return newInput;
    }

    /**
     * @param args the command line arguments
     */

    private tour_Information findwithDB(String from) {

        tour_Information returntour = new tour_Information();
        String to = null;

        try {
            MongoClient mongoClient = getMongoClient();
            DB db = mongoClient.getDB("my_database");
            DBCollection coll = db.getCollection("ML_Result");
            WriteConcern w = new WriteConcern(1, 0);
            mongoClient.setWriteConcern(w);

            // string?  select
            BasicDBObject query = new BasicDBObject();
            query.put("from", from);

            DBCursor cursor = coll.find(query);
            cursor.sort(new BasicDBObject("num", -1));

            int num = -1;
            System.out.println("from 0: " + from);
            if (cursor.hasNext())// ??  
            {
                DBObject mapObj = cursor.next();
                String temp = mapObj.get("to").toString();
                num = Integer.parseInt(temp);
                //num = ((Number) mapObj.get("to")).intValue();
                cursor.close();

            } else {
                //System.out.println("from2 : "+from);
                returntour.myURL = null;
            }
            System.out.println(coll.getCount());
            // close resources
            if (num != -1) {
                db = mongoClient.getDB("my_database");
                coll = db.getCollection("TB_titleID");
                w = new WriteConcern(1, 0);// ? ,   2000 // ? 2 ??  ? ?
                mongoClient.setWriteConcern(w);

                // string?  select
                query = new BasicDBObject();
                //
                query.put("ID", num);
                //query.put("to",to);
                cursor = coll.find(query);
                if (cursor.hasNext())// ?? 
                {
                    System.out.println("num : " + num);
                    DBObject mapObj = cursor.next();
                    returntour.myURL = mapObj.get("url").toString();
                    returntour.myLocation = Integer.parseInt(mapObj.get("num").toString());
                    cursor.close();
                } else {
                    returntour.myURL = null;
                    returntour.myLocation = 0;
                }
            }
            mongoClient.close();
        } catch (Exception e) {
            System.err.println("findwithDB Exception");
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return returntour;
    }

    public static void main(String[] args) {
        launch(args);
    }
}