/**
   * Adds a section of road with 2 lanes that travels in the directions east and west
   *
   * @param x the x coordinate where to add the road
   * @param y the y coordinate where to add the road
   * @param map the map to add the road to
   * @param mapGridGUIDecorator the GUI decorator associated with this map
   * @param mapGridPane the gridPane that would need to be updated with the new view
   * @param imgView the associated image to place in the x,y cell
   */
  private void addRoadEW(
      int x,
      int y,
      Map map,
      MapGridGUIDecorator mapGridGUIDecorator,
      GridPane mapGridPane,
      ImageView imgView) {
    Coordinate coord = new Coordinate(x, y);
    Road road = new Road(coord, coord);
    try {
      road.addLane(new Lane(coord, coord, MapDirection.EAST));
      road.addLane(new Lane(coord, coord, MapDirection.WEST));
      map.addRoad(road);
      StackPane sp = mapGridGUIDecorator.redrawCell(x, y, mapGridPane);

      sp.setOnMouseClicked(
          click -> {
            ComponentType currentFocused = MapMakerController.getCurrentFocused();
            if (currentFocused == ComponentType.INTERSECTION) {
              addIntersection(x, y, map, mapGridGUIDecorator, mapGridPane, intersectionImgView);
            } else if (currentFocused == ComponentType.ROADNS) {
              addRoadNS(x, y, map, mapGridGUIDecorator, mapGridPane, roadNSImgView);
            } else if (currentFocused == ComponentType.GRASS) {
              addGrass(x, y, map, mapGridGUIDecorator, mapGridPane, grassImgView);
            }
          });

      // put focus back on RoadEW
      MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
      MapMakerController.setCurrentFocused(ComponentType.ROADEW);
      imgView.requestFocus();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @FXML
  private void removeSubs() {
    try {

      MultiTransformation transformation = new MultiTransformation();
      if (isFileToConvert) {
        transformation.addTransformation(new TransformationConfig(file, percentageToRemove, true));
        //    multiTransformation.addFile(file);
      } else {
        transformation.addDirectory(file, percentageToRemove, true);
      }
      transformation.perform();
      alertInfo.showDialog(
          "Subtitles successfully modified !",
          "The subtitles file(s) has/have been replaced by the new one(s), but you  can still find the old one(s) in the 'oldSubs' directory ");
      // Map<File, TransformationResult> result = multiTransformation.getResults();
      for (DefaultTransformation t : transformation.getTransformations()) {
        HistoryHelper.save(new TransformationResultHistory(t.getResult()));
      }
    } catch (Exception ex) {
      logger.error(ex);
      alertError.showDialog(ex);
      ex.printStackTrace();
    }
    buttonRemoveSubs.setDisable(true);
  }
  private void initPane() {
    //		WebEngine engine = optionView.getEngine();
    try {
      Document document = Jsoup.connect(webView.getEngine().getLocation()).get();
      Element table =
          document.select("#normal_basket_" + document.select("[name=item_id]").val()).first();
      Element td = table.select("td").first();
      Elements spans = td.select("span");
      Elements selects = td.select("select");
      //			System.out.println(spans.size());
      cmb = new ArrayList<ComboBox>();
      for (int i = 0; i < spans.size(); i++) {

        ObservableList<ValuePair> obs = FXCollections.observableArrayList();
        Elements options = selects.get(i).select("option");
        for (int k = 0; k < options.size(); k++) {
          Element option = options.get(k);
          obs.add(new ValuePair("choice", option.text(), option.val()));
        }

        cmb.add(new ComboBox<ValuePair>(obs));
        optionArea.getChildren().addAll(new Text(spans.get(i).text()), cmb.get(i));
      }

    } catch (Exception e) {
      // TODO 自動生成された catch ブロック
      e.printStackTrace();
    }
  }
  public boolean checkPnr(String param) {

    // Local variables
    String query;
    ResultSet rs;
    PreparedStatement stmt;
    boolean result = false;

    try {
      // Set the SQL statement into the query variable
      query = "SELECT personnummer FROM Stamkund WHERE personnummer = ?";
      stmt = con.prepareStatement(query);
      stmt.setString(1, param);

      // Execute the SQL statement that is prepared in the variable stmt
      // and store the result in the variable rs.
      rs = stmt.executeQuery();

      // Sets result to true if personnummer exists
      result = rs.next();

      // Close the variable stmt and release all resources bound to it
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Data check error");
    }
    return result;
  }
Пример #5
0
  public boolean validLogin(String username, String password) {
    boolean validUser = false;
    try {

      dbStm =
          dbCon.prepareStatement(
              "SELECT * FROM userInfo WHERE username = "******"\"" + username + "\"" + ";");

      dbRs = dbStm.executeQuery();

      while (dbRs.next()) {
        String un = "";
        String pw = "";

        un = dbRs.getString("username");
        System.out.println(un + " " + username);
        pw = dbRs.getString("password");
        System.out.println(pw + " " + password);

        if (((username.equals(un) == true) && ((password.equals(pw) == true)))) {
          validUser = true;
          System.out.println("Valid User");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return validUser;
  }
Пример #6
0
 public void load() {
   Stage primaryStage = new Stage();
   try {
     start(primaryStage);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Override
  public void initialize(URL location, ResourceBundle resources) {
    // TODO 自動生成されたメソッド・スタブ
    addOption.setOnAction(
        event -> {
          for (int i = 0; i < cmb.size(); i++) {
            //				System.out.println(cmb.get(i).getValue());
            if (cmb.get(i).getValue() == null) {
              break;
            } else if (i == cmb.size() - 1) {
              addTask.setDisable(false);
            }
          }
        });

    addTask.setOnAction(
        event -> {
          try {
            String url = webView.getEngine().getLocation();
            System.out.println(url);
            Document document = Jsoup.connect(url).get();

            Elements input = document.select("input");

            Map params = new HashMap<String, String>();
            for (ComboBox cmbx : cmb) {
              ValuePair vp = (ValuePair) cmbx.getValue();
              params.put(vp.getName(), vp.getvalue());
            }
            //				System.out.println(input.select("[name=shop_bid]").first());
            //				System.out.println(input.select("[name=shop_bid]").first().val());
            params.put("shop_bid", input.select("[name=shop_bid]").first().val());
            params.put("item_id", input.select("[name=item_id]").first().val());
            params.put("__event", input.select("[name=__event]").first().val());
            params.put("units", "1");

            Map map = new HashMap<String, Long>();

            //				System.out.println(document.select("#stime").size());
            if (document.select("#stime").size() != 0) {
              System.out.println(document.select("#stime"));
              map.put("stime", Long.parseLong((input.select("#stime").first().val())));
              map.put("etime", Long.parseLong((input.select("#etime").first().val())));
            } else {
              map = null;
            }

            BuyTask task = new BuyTask(url, params, map);
            task.call();
            this.getScene().getWindow().hide();
          } catch (Exception e) {
            // TODO 自動生成された catch ブロック
            e.printStackTrace();
          }
        });
  }
 @FXML
 void adminLoginAction(ActionEvent event) {
   if (adminUserID.getText().equals(validUserID)
       && adminPassword.getText().equals(validPassword)) {
     try {
       main.AdminEdit();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  public void saveStamboom(Event evt) {
    // todo opgave 3
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Sla Stamboom op");
    File f = fileChooser.showSaveDialog(new Stage());
    try {

      this.serialize(f);
    } catch (Exception exc) {
      exc.fillInStackTrace();
    }
  }
  // This method saves any changes to the database and closes the connection.
  // Messages are only printed to the console.
  public void closeProgram() {

    try {
      System.out.println("Programmet avslutas...");
      con.commit();
      System.out.println("Skriver ändringar...");
      con.close();
      System.out.println("Stänger anslutningen...");
      window.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Could not properly close program");
    }
  }
Пример #11
0
  void generateBackupPaths() {
    ObservableList restorePaths = FXCollections.observableArrayList();
    restorePaths.clear();
    vBarBDirs.getChildren().clear();
    //        cbRestoreDirectory.getItems().clear();
    String[] backupArr = constants.getValue("s_dumpDir").split(";");
    for (final String dir : backupArr) {
      restorePaths.add(dir);
      HBox hbox = new HBox();
      Label lbl = new Label(dir);
      Button btn = new Button("Delete");
      btn.setOnAction(
          new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
              String nString = constants.getValue("s_dumpDir");
              nString = nString.replaceAll(";" + dir, "");
              nString = nString.replaceAll(dir, "");
              constants.addValue("s_dumpDir", nString);
              System.out.println(constants.getValue("s_dumpDir"));
              txtDir.setText(nString);
              generateBackupPaths();
            }
          });
      hbox.getChildren().add(lbl);
      hbox.getChildren().add(btn);
      vBarBDirs.getChildren().add(hbox);
    }

    try {

      cbRestoreDirectory.setItems(restorePaths);
      cbRestoreDirectory.setValue(restorePaths.get(0));
      generateRestore(restorePaths.get(0).toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
    cbRestoreDirectory
        .valueProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(ObservableValue ov, String t, String t1) {
                //                System.out.println(ov);
                //                System.out.println(t);
                //                System.out.println(t1);
                generateRestore(t1);
              }
            });
  }
Пример #12
0
  public boolean connectToDB() {
    boolean estCon = false;
    try {
      dbCon =
          DriverManager.getConnection(
              "jdbc:mysql://192.168.1.6:3306/ale", "Root", "oqu#$XQgHFzDj@1MGg1G8");
      estCon = true;
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Could not connect to db");
    }

    return estCon;
  }
Пример #13
0
  public void displayCourse(String courseName) {
    // File f = new File("C:\\Users\\Josh\\IdeaProjects\\ALE\\src\\com\\silverfox\\ale\\course\\"
    // + courseName + ".html");
    // f.toURI().toURL().toString()

    try {
      courseWebEngine.load(
          "http://localhost:63342/ALE/com/silverfox/ale/course/" + courseName + ".html");

      coursesPanel.setContent(courseView);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #14
0
  public void systemClose() {

    if (client.isConnected == true) {
      client.disconnect(messageArea, messageInputArea, superUser);
    }

    try {
      if (dbCon != null) {
        dbCon.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
  // insertStamkund takes six strings as input and calls randomNumber for an integer
  public int insertStamkund(
      String pnrParam,
      String fnameParam,
      String snameParam,
      String addrParam,
      String mailParam,
      String cellParam) {

    // Call randomNumber() and stores the value to cardParam.
    int cardParam = randomNumber(1000, 9999);

    // Set the SQL statement into the query variable
    String query =
        "INSERT INTO Stamkund (kortnummer,personnummer,förnamn,"
            + "efternamn,adress,epost,mobilnummer) VALUES (?,?,?,?,?,?,?)";

    try {
      // Create a statement associated to the connection and the query.
      // The new statement is placed in the variable stmt.
      PreparedStatement stmt = con.prepareStatement(query);

      // Provide the values for the ?'s in the SQL statement, from 1 to 7.
      stmt.setInt(1, cardParam);
      stmt.setString(2, pnrParam);
      stmt.setString(3, fnameParam);
      stmt.setString(4, snameParam);
      stmt.setString(5, addrParam);
      stmt.setString(6, mailParam);
      stmt.setString(7, cellParam);

      // Execute the SQL statement that is prepared in the variable stmt
      stmt.executeUpdate();

      // Close the variable stmt and release all resources bound to it
      stmt.close();

      // Commit the changes made to the database.
      con.commit();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error on Data Insert");
    }

    // Returns card number for user display
    return cardParam;
  }
  @Override
  public void initialize(URL location, ResourceBundle resources) {
    urlField.setOnAction(
        event -> {
          String text = urlField.getText();
          urlField.setText("tetetetetetetete");
          webView.getEngine().load(text);
        });

    webView
        .getEngine()
        .getLoadWorker()
        .stateProperty()
        .addListener(
            (ov, oldState, newState) -> {
              if (newState == State.SUCCEEDED) {
                String url = webView.getEngine().getLocation();
                urlField.setText(url);
                if (Pattern.compile("http://item.rakuten.co.jp/.*").matcher(url).find()) {
                  try {
                    Elements tmp;
                    Document document = Jsoup.connect(url).get();
                    tmp = document.select("input");
                    tmp = tmp.select("#etime");
                    if (tmp.size() != 0) {
                      if (!(Long.parseLong(tmp.first().val()) < new Date().getTime())) {
                        entryButton.setDisable(false);
                      }
                    } else {
                      entryButton.setDisable(false);
                    }
                  } catch (Exception e) {
                    // TODO 自動生成された catch ブロック
                    e.printStackTrace();
                  }
                }
              }
              ;
            });

    entryButton.setOnAction(
        event -> {
          urlField.setText("webView disable");
          sendEntryTaskController();
        });
  }
Пример #17
0
  private void connectToDB() {
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost/BoolaBoolaUniversity";
    String username = "******";
    String password = "******";

    // Connect to database
    try {
      Class.forName(driver);
      connection = DriverManager.getConnection(url, username, password);

      System.out.println("Connected to " + url);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #18
0
 @FXML
 private void onRegisterHyperlinkClick(ActionEvent event) {
   FXMLLoader loader = new FXMLLoader();
   Stage dialogStage = new Stage();
   Parent root = null;
   dialogStage.setTitle("Register for sQuire");
   dialogStage.initModality(Modality.WINDOW_MODAL);
   dialogStage.initOwner(registerHyperlink.getScene().getWindow());
   dialogStage.setResizable(false);
   try {
     root = loader.load(getClass().getResource("/fxml/RegisterDialog.fxml"));
     Scene scene = new Scene(root);
     dialogStage.setScene(scene);
     dialogStage.showAndWait();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @FXML
 private void Ok_click(ActionEvent event) {
   logger.entry();
   LogEntry log = new LogEntry("6.16", "Local Delete Object Instance service");
   try {
     ObjectInstanceHandle instanceHandle =
         rtiAmb
             .getObjectInstanceHandleFactory()
             .decode(
                 ByteBuffer.allocate(4)
                     .putInt(Integer.parseInt(ObjectInstanceDesignator.getText()))
                     .array(),
                 0);
     log.getSuppliedArguments()
         .add(
             new ClassValuePair(
                 "Object instance designator",
                 ObjectInstanceHandle.class,
                 instanceHandle.toString()));
     rtiAmb.localDeleteObjectInstance(instanceHandle);
     log.setDescription("Local Object instance deleted successfully");
     log.setLogType(LogEntryType.REQUEST);
   } catch (FederateNotExecutionMember
       | NotConnected
       | NumberFormatException
       | CouldNotDecode
       | RTIinternalError
       | OwnershipAcquisitionPending
       | FederateOwnsAttributes
       | ObjectInstanceNotKnown
       | SaveInProgress
       | RestoreInProgress ex) {
     log.setException(ex);
     log.setLogType(LogEntryType.ERROR);
     logger.log(Level.ERROR, ex.getMessage(), ex);
   } catch (Exception ex) {
     log.setException(ex);
     log.setLogType(LogEntryType.FATAL);
     logger.log(Level.FATAL, ex.getMessage(), ex);
   }
   logEntries.add(log);
   ((Stage) OkButton.getScene().getWindow()).close();
   logger.exit();
 }
Пример #20
0
 public boolean checkIntConnection(String url) {
   boolean status = false;
   Socket sock = new Socket();
   InetSocketAddress address = new InetSocketAddress(url, 80);
   try {
     sock.connect(address, 3000);
     if (sock.isConnected()) {
       status = true;
     }
   } catch (Exception e) {
     System.out.println(e.toString());
   } finally {
     try {
       sock.close();
     } catch (Exception e) {
       System.out.println(e.toString());
     }
   }
   return status;
 }
Пример #21
0
  public void save() {
    ObservableList<StudentRecord> records = DataSource.getAllMarks(new File(currentFileName));
    try {
      FileWriter writer = new FileWriter(new File(currentFileName));
      for (StudentRecord student : records) {
        writer.append(student.getID());
        writer.append(",");
        writer.append(String.valueOf(student.getAssign()));
        writer.append(",");
        writer.append(String.valueOf(student.getMidterm()));
        writer.append(',');
        writer.append(String.valueOf(student.getFinal()));
        writer.append(",");
        writer.append(student.getGrade());
        writer.append("\n");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  // Method for fetching all stores to drop down menu
  public void getStores() {

    // Local variables
    ResultSet rs;
    Statement stmt;
    String query = "SELECT namn FROM Butik ORDER BY namn ASC";

    try {

      stmt = con.createStatement();
      rs = stmt.executeQuery(query);

      while (rs.next()) {
        choiceBox2.getItems().add(rs.getString("namn"));
      }
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error fetching data");
    }
  }
  // Method for generating and returning a randomized card number in the range of 1000-9999.
  // The range can be edited in the insertStamkund method.
  public int randomNumber(int min, int max) {

    // Local variables
    String query;
    ResultSet rs;
    PreparedStatement stmt;
    int internalNumber;

    // A random number is generated in the selected range min-max (1000-9999)
    Random rand = new Random();
    internalNumber = rand.nextInt((max - min) + 1) + min;

    try {

      // Set the SQL statement into the query variable
      // We check if our generated number exists in the database.
      query = "SELECT kortnummer FROM Stamkund WHERE kortnummer = ?";
      stmt = con.prepareStatement(query);
      stmt.setInt(1, internalNumber);

      // Execute the SQL statement that is prepared in the variable stmt
      // and store the result in the variable rs.
      // If we receive a ResultSet, boolean result is set to 1, and the generated number exists.
      rs = stmt.executeQuery();
      boolean result = rs.next();

      // If result is true, we call ourselves for a new number
      if (result) {
        return randomNumber(min, max);
      }

      // Close the variable stmt and release all resources bound to it
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Data Insert error");
    }
    // If result is false, returns the unique card number
    return internalNumber;
  }
  // Method for establishing a DB connection
  public void connect() {

    // Relative path to Access database, project can be run from anywhere.
    File dbfile = new File("Icooköp_v8.accdb");
    String relativepath = dbfile.getAbsolutePath();

    // Local Access DB static variables
    String URL = "jdbc:ucanaccess://" + relativepath;
    String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
    try {
      // Register the driver with DriverManager
      Class.forName(driver);
      // Create a connection to the database
      con = DriverManager.getConnection(URL);
      // Set the auto commit of the connection to false.
      // An explicit commit will be required in order to accept
      // any changes done to the DB through this connection.
      con.setAutoCommit(false);
      // Some logging
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @FXML
  void searchTktButton(ActionEvent event) {
    // send a request to server for searching a ticket from database

    c.setDate(datePick.getValue());
    c.setAC(ACradioButton.isSelected());
    c.setNonAC(nonACradioButton.isSelected());
    if (allOptionsFilledUp()) {
      try {
        main.availableBusView();
      } catch (Exception e) {
        e.printStackTrace();
      }

      /*
      try {
          //String serverAddress="127.0.0.1";
          //int serverPort=55555;
          //NetworkUtil nc = new NetworkUtil(serverAddress,serverPort);

          //nc.write(c);

      } catch(Exception e) {
          System.out.println (e);
      }
      */

    } else {
      alert.setVisible(true);
      PauseTransition visiblePause =
          new PauseTransition(
              Duration.seconds(2)); // making the "alert" label visible for 2 seconds
      visiblePause.setOnFinished(Event -> alert.setVisible(false));
      visiblePause.play();
    }
  }
  // Method for presenting all available brands of a selected product.
  public void preparedStatement(String ptype) {

    data = FXCollections.observableArrayList();

    // Local variables, query statement saved to variable query.
    ResultSet rs;
    PreparedStatement stmt;
    String query =
        "SELECT DISTINCT Märke.namn FROM "
            + "Märke, Märkesprodukt, Produkt, Produktbeskrivning, Produktgrupp "
            + "WHERE Märke.[märke_id]=Märkesprodukt.[märke_id] "
            + "AND Märkesprodukt.[produkt_id]=Produkt.[produkt_id] "
            + "AND Produkt.[pbeskrivning_id]=Produktbeskrivning.[pbeskrivning_id] "
            + "AND Produktbeskrivning.[pgrupp_id]=Produktgrupp.[pgrupp_id] "
            + "AND Produktgrupp.[namn]= ?";

    try {

      // Create a statement associated to the connection con.
      // The new statement is placed in the variable stmt.
      // Provide the value for the first ? in the SQL statement.
      // Execute query and save ResultSet to variable rs.
      stmt = con.prepareStatement(query);
      stmt.setString(1, ptype);
      rs = stmt.executeQuery();

      // Clearing tables of old data
      tableview.getItems().clear();
      tableview.getColumns().clear();

      // Table columns added dynamically using ResultSet metadata.
      for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {

        // We are using non property style for making dynamic table
        final int j = i;
        TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
        col.setCellValueFactory(
            new Callback<
                TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
              public ObservableValue<String> call(
                  TableColumn.CellDataFeatures<ObservableList, String> param) {
                return new SimpleStringProperty(param.getValue().get(j).toString());
              }
            });

        tableview.getColumns().addAll(col);
        System.out.println("Column [" + i + "] ");
      }

      // Data added to ObservableList
      while (rs.next()) {

        // Iterate Row
        ObservableList<String> row = FXCollections.observableArrayList();
        for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {

          // Iterate Column
          row.add(rs.getString(i));
        }
        // Console printout
        System.out.println("Row [1] added " + row);
        data.add(row);
      }

      // Data added to TableView
      tableview.setItems(data);

      // Close the variable stmt and release all resources bound to it
      // Any ResultSet associated to the Statement will be automatically closed too.
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error on Building Data");
    }
  }
  // Method for checking store stock and printing it to TableView
  public void storeStock(String store) {

    data = FXCollections.observableArrayList();

    // Local variables
    ResultSet rs;
    PreparedStatement stmt;
    // Store query string to variable
    String query =
        "SELECT Förpackning.[streckkod], LagerfördVara.[antalIButik], LagerfördVara.[maxantal] FROM Förpackning, LagerfördVara, Butik WHERE Förpackning.[streckkod]=LagerfördVara.[streckkod] AND LagerfördVara.[butik_id]=Butik.[butik_id] AND Butik.[namn]=?";

    try {

      // The new statement is placed in the variable stmt.
      // Provide the value for the first ? in the SQL statement.
      // Execute query and save ResultSet to variable rs.
      stmt = con.prepareStatement(query);
      stmt.setString(1, store);
      rs = stmt.executeQuery();

      // Clearing tables of old data
      tableview.getItems().clear();
      tableview.getColumns().clear();

      // Table columns added dynamically using ResultSet metadata.
      for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {

        // We are using non property style for making dynamic table
        final int j = i;
        TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
        col.setCellValueFactory(
            new Callback<
                TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
              public ObservableValue<String> call(
                  TableColumn.CellDataFeatures<ObservableList, String> param) {
                return new SimpleStringProperty(param.getValue().get(j).toString());
              }
            });

        tableview.getColumns().addAll(col);
        System.out.println("Column [" + i + "] ");
      }

      // Data added to ObservableList
      while (rs.next()) {

        // Iterate Row
        ObservableList<String> row = FXCollections.observableArrayList();
        for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {

          // Iterate Column
          row.add(rs.getString(i));
        }
        // Console printout
        System.out.println("Row [1] added " + row);
        data.add(row);
      }

      // Data added to TableView
      tableview.setItems(data);

      // Close the variable stmt and release all resources bound to it
      // Any ResultSet associated to the Statement will be automatically closed too.
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error on building Data");
    }
  }
  // Method for displaying all available product types
  public void createStatement() {

    data = FXCollections.observableArrayList();

    // Local variables
    ResultSet rs;
    Statement stmt;
    String query = "SELECT namn FROM Produktgrupp ORDER BY namn ASC";

    try {

      stmt = con.createStatement();
      rs = stmt.executeQuery(query);

      // Clearing tables of old data
      tableview.getItems().clear();
      tableview.getColumns().clear();

      // Table columns added dynamically using ResultSet metadata.
      for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {

        // We are using non property style for making dynamic table
        final int j = i;
        TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
        col.setCellValueFactory(
            new Callback<
                TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
              public ObservableValue<String> call(
                  TableColumn.CellDataFeatures<ObservableList, String> param) {
                return new SimpleStringProperty(param.getValue().get(j).toString());
              }
            });

        tableview.getColumns().addAll(col);
        System.out.println("Column [" + i + "] ");
      }

      // Data added to ObservableList
      while (rs.next()) {

        // Iterate Row
        ObservableList<String> row = FXCollections.observableArrayList();
        for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {

          // Iterate Column
          row.add(rs.getString(i));
        }

        data.add(row);
      }

      // Data added to TableView
      tableview.setItems(data);

      // Close the variable stmt and release all resources bound to it
      // Any ResultSet associated to the Statement will be automatically closed too.
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error on Building Data");
    }
  }
  /**
   * Draws the MapMaker screen and displays it to the user
   *
   * @param primaryStage the stage to show it in
   * @throws Exception
   */
  public void drawScreen(Stage primaryStage) throws Exception {
    // Create the base BorderPane for the whole window
    BorderPane borderPane = new BorderPane();
    borderPane.setStyle("-fx-background-color: papayawhip");

    // Add some instructions to the user
    String text =
        "Instructions:\n"
            + "1. Click on the map component that you would like to place in the map\n"
            + "2. Click on the place in the map where you want to place the component\n"
            + "3. Repeat until you built the map you want!\n"
            + "4. Hit the 'Save' button when you are done";
    Label instructions = new Label(text);
    instructions.setFont(Font.font("Arial", FontWeight.BOLD, 12));
    instructions.setPadding(new Insets(5, 5, 5, 5));
    borderPane.setTop(instructions);

    // Create the blank Map
    Pane mapPane = new Pane();
    Map map = new Map(width, height);
    MapGridGUIDecorator mapGridGUIDecorator = new MapGridGUIDecorator(map.getGrid());
    ResizeFactor rf = ResizeFactor.getSuggestedResizeFactor(width, height);
    mapGridGUIDecorator.setResizeFactor(rf);
    GridPane mapGridPane = mapGridGUIDecorator.drawComponents();
    mapGridPane.setPadding(new Insets(0, 0, 5, 5));
    mapPane.getChildren().add(mapGridPane);
    borderPane.setCenter(mapPane);
    MapMakerController.setCurrentFocused(ComponentType.NOTHING);

    VBox sideComponents = new VBox();

    /* Add "Components" label */
    Label componentsLabel = new Label("Components");
    componentsLabel.setFont(Font.font("Arial", FontWeight.EXTRA_BOLD, 14));
    componentsLabel.setPadding(new Insets(15, 5, 0, 20));
    sideComponents.getChildren().add(componentsLabel);

    /* Add Intersection square image */
    VBox intersectionPane = new VBox();
    Label intersectionLabel = new Label("Intersection");
    intersectionLabel.setPadding(new Insets(5, 5, 0, 30));
    intersectionLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image intersectionImg = new Image("IntersectionX.png", 60, 60, true, false);
    intersectionImgView = new ImageView(intersectionImg);
    StackPane intersectionStackPane = new StackPane(intersectionImgView);
    intersectionStackPane.setPadding(new Insets(0, 10, 10, 10));
    intersectionPane.getChildren().add(intersectionLabel);
    intersectionPane.getChildren().add(intersectionStackPane);
    sideComponents.getChildren().add(intersectionPane);

    /* Add RoadNS square image */
    VBox roadNSPane = new VBox();
    Label roadNSLabel = new Label("Road (North-South)");
    roadNSLabel.setPadding(new Insets(5, 5, 0, 15));
    roadNSLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image roadNSImg = new Image("RoadBackgroundNS.png", 60, 60, true, false);
    roadNSImgView = new ImageView(roadNSImg);
    StackPane roadNSStackPane = new StackPane(roadNSImgView);
    roadNSStackPane.setPadding(new Insets(0, 10, 10, 10));
    roadNSPane.getChildren().add(roadNSLabel);
    roadNSPane.getChildren().add(roadNSStackPane);
    sideComponents.getChildren().add(roadNSPane);

    /* Add RoadEW square image */
    VBox roadEWPane = new VBox();
    Label roadEWLabel = new Label("Road (East-West)");
    roadEWLabel.setPadding(new Insets(5, 5, 0, 15));
    roadEWLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image roadEWImg = new Image("RoadBackgroundEW.png", 60, 60, true, false);
    roadEWImgView = new ImageView(roadEWImg);
    StackPane roadEWStackPane = new StackPane(roadEWImgView);
    roadEWStackPane.setPadding(new Insets(0, 10, 10, 10));
    roadEWPane.getChildren().add(roadEWLabel);
    roadEWPane.getChildren().add(roadEWStackPane);
    sideComponents.getChildren().add(roadEWPane);

    /* Add Grass square image to empty out cells */
    VBox grassPane = new VBox();
    Label grassLabel = new Label("Grass (clear square)");
    grassLabel.setPadding(new Insets(5, 5, 0, 15));
    grassLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image grassImg = new Image("Grass.png", 60, 60, true, false);
    grassImgView = new ImageView(grassImg);
    StackPane grassStackPane = new StackPane(grassImgView);
    grassStackPane.setPadding(new Insets(0, 10, 10, 10));
    grassPane.getChildren().add(grassLabel);
    grassPane.getChildren().add(grassStackPane);
    sideComponents.getChildren().add(grassPane);

    /* Add Save, Reset buttons */
    VBox buttonsPane = new VBox();
    buttonsPane.setPadding(new Insets(0, 0, 0, 10));
    Label toolsLabel = new Label("Tools");
    toolsLabel.setFont(Font.font("Arial", FontWeight.EXTRA_BOLD, 14));
    toolsLabel.setPadding(new Insets(15, 5, 5, 35));
    buttonsPane.getChildren().add(toolsLabel);
    Insets padding = new Insets(0, 0, 5, 0);
    Button saveButton = new Button("Save Map");
    StackPane saveButtonPane = new StackPane(saveButton);
    saveButtonPane.setPadding(padding);
    saveButton.setStyle("-fx-base:Gold");
    saveButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    buttonsPane.getChildren().add(saveButtonPane);
    Button resetButton = new Button("Reset Map");
    resetButton.setStyle("-fx-base:Gold");
    resetButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    StackPane resetButtonPane = new StackPane(resetButton);
    resetButtonPane.setPadding(padding);
    buttonsPane.getChildren().add(resetButtonPane);
    Button backButton = new Button("Go Back");
    backButton.setStyle("-fx-base:Gold");
    backButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    StackPane backButtonPane = new StackPane(backButton);
    backButtonPane.setPadding(padding);
    buttonsPane.getChildren().add(backButtonPane);

    sideComponents.getChildren().add(buttonsPane);

    Ticker.start();

    /* Add click processing for Map grid squares */
    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        Node current = getNodeFromIndex(i, j, mapGridPane);
        final int x = j;
        final int y = i;
        current.setOnMouseClicked(
            (MouseEvent click) -> {
              MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
              MapMakerController.setCurrentFocused(ComponentType.MAP_SQUARE);
              current.requestFocus();
            });
        current
            .focusedProperty()
            .addListener(
                (ObservableValue<? extends Boolean> observable,
                    Boolean oldValue,
                    Boolean newValue) -> {
                  ComponentType previous = MapMakerController.getPreviousFocused();
                  if (previous == ComponentType.INTERSECTION) {
                    addIntersection(
                        x, y, map, mapGridGUIDecorator, mapGridPane, intersectionImgView);
                  } else if (previous == ComponentType.ROADNS) {
                    addRoadNS(x, y, map, mapGridGUIDecorator, mapGridPane, roadNSImgView);
                  } else if (previous == ComponentType.ROADEW) {
                    addRoadEW(x, y, map, mapGridGUIDecorator, mapGridPane, roadEWImgView);
                  } else if (previous == ComponentType.GRASS) {
                    addGrass(x, y, map, mapGridGUIDecorator, mapGridPane, grassImgView);
                  }
                });
      }
    }

    /* Add intersection icon click processing */
    DropShadow ds = new DropShadow(15, Color.BLUE);
    intersectionImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.INTERSECTION);
          intersectionImgView.requestFocus();
        });
    intersectionImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) intersectionImgView.setEffect(ds);
              else intersectionImgView.setEffect(null);
            });

    /* Add roadNS icon click processing */
    roadNSImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.ROADNS);
          roadNSImgView.requestFocus();
        });
    roadNSImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) roadNSImgView.setEffect(ds);
              else roadNSImgView.setEffect(null);
            });

    /* Add roadEW icon click processing */
    roadEWImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.ROADEW);
          roadEWImgView.requestFocus();
        });
    roadEWImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) roadEWImgView.setEffect(ds);
              else roadEWImgView.setEffect(null);
            });

    /* Add grass icon click processing */
    grassImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.GRASS);
          grassImgView.requestFocus();
        });
    grassImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) grassImgView.setEffect(ds);
              else grassImgView.setEffect(null);
            });

    /* Add save button functionality */
    saveButton.setOnMouseClicked(
        click -> {
          TextInputDialog nameDialog = new TextInputDialog();
          nameDialog.setTitle("Save Map");
          nameDialog.setHeaderText(
              "Please provide a name for your map (no spaces or special characters).\nSaved maps go into the /maps directory of your working directory.");
          nameDialog.setContentText("File name");
          Button btOk = (Button) nameDialog.getDialogPane().lookupButton(ButtonType.OK);
          TextField textfield = nameDialog.getEditor();
          Platform.runLater(() -> textfield.requestFocus());
          btOk.setDisable(true);
          textfield
              .textProperty()
              .addListener(
                  ((observable, oldValue, newValue) -> {
                    btOk.setDisable(newValue.trim().isEmpty());
                  }));

          Optional<String> result = nameDialog.showAndWait();
          result.ifPresent(
              name -> {
                name = name.concat(".map");
                try {
                  Map finalMap = buildAndSaveMap(map);
                  finalMap.saveMap(name);
                  goBack(primaryStage);
                } catch (Exception e) {
                  e.printStackTrace();
                }
              });
        });

    resetButton.setOnMouseClicked(
        click -> {
          for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
              Component component = map.getAtLocation(new Coordinate(x, y));
              if (component instanceof Road || component instanceof Intersection) {
                addGrass(x, y, map, mapGridGUIDecorator, mapGridPane, grassImgView);
              }
            }
          }
        });

    backButton.setOnMouseClicked(
        click -> {
          try {
            goBack(primaryStage);
          } catch (Exception e) {
            e.printStackTrace();
          }
        });

    borderPane.setRight(sideComponents);
    Scene scene = new Scene(borderPane);
    primaryStage.setScene(scene);
    primaryStage.centerOnScreen();
    primaryStage.setResizable(false);
  }
  @FXML
  private void OK_click(ActionEvent event) {
    logger.entry();
    FederateHandle federateHandle;
    LogEntry log = new LogEntry("4.9", "Join Federation Execution service");
    try {
      if (!FederateName.getText().isEmpty()) {
        log.getSuppliedArguments()
            .add(new ClassValuePair("Federate Name", String.class, FederateName.getText()));
      }
      log.getSuppliedArguments()
          .add(new ClassValuePair("Federate Type", String.class, FederateType.getText()));
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Federation Execution Name", String.class, FederationExecutionName.getText()));
      List<URL> foms = new ArrayList<>();
      int i = 1;
      for (File file : FomModuleDesignators.getFiles()) {
        foms.add(file.toURI().toURL());
        log.getSuppliedArguments()
            .add(
                new ClassValuePair(
                    "FOM Module Deisgnator " + i++, URL.class, file.toURI().toURL().toString()));
      }
      if (FederateName.getText().isEmpty() && FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(), FederationExecutionName.getText());
      } else if (FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(), FederateType.getText(), FederationExecutionName.getText());
      } else if (FederateName.getText().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      } else {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(),
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      }
      log.getReturnedArguments()
          .add(
              new ClassValuePair(
                  "Federate Handle", FederateHandle.class, federateHandle.toString()));
      log.setDescription("Federate joined federation execution successfully");
      log.setLogType(LogEntryType.REQUEST);
      logicalTimeFactory = rtiAmb.getTimeFactory();
      currentLogicalTime = logicalTimeFactory.makeInitial();

      // subscribe to HLAcurrentFDD to retrieve FDD
      ObjectClassHandle FederationHandle =
          rtiAmb.getObjectClassHandle("HLAobjectRoot.HLAmanager.HLAfederation");
      currentFDDHandle = rtiAmb.getAttributeHandle(FederationHandle, "HLAcurrentFDD");
      AttributeHandleSet set = rtiAmb.getAttributeHandleSetFactory().create();
      set.add(currentFDDHandle);
      rtiAmb.subscribeObjectClassAttributes(FederationHandle, set);
      rtiAmb.requestAttributeValueUpdate(FederationHandle, set, null);
      // In case of HLA_EVOKED we require this line to receive the FDD
      rtiAmb.evokeMultipleCallbacks(
          .05,
          1); // evoke one callback will not be enough because the reflect attribute is the second
              // one
    } catch (CouldNotCreateLogicalTimeFactory
        | CallNotAllowedFromWithinCallback
        | CouldNotOpenFDD
        | ErrorReadingFDD
        | InconsistentFDD
        | FederateNameAlreadyInUse
        | FederateAlreadyExecutionMember
        | FederationExecutionDoesNotExist
        | SaveInProgress
        | RestoreInProgress
        | NotConnected
        | RTIinternalError ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) FederationExecutionName.getScene().getWindow()).close();
    logger.exit();
  }