Skip to content

Instantly share code, notes, and snippets.

@Med116
Last active August 21, 2019 02:42
Show Gist options
  • Save Med116/fdfb95d5ff3e02448999c5ccab257cb2 to your computer and use it in GitHub Desktop.
Save Med116/fdfb95d5ff3e02448999c5ccab257cb2 to your computer and use it in GitHub Desktop.
java jx git gui code Main
package sample;
public class DBColumn implements DBItem {
private String columnName;
private String columnTypeName;
private int columnType;
private boolean primaryKey;
private boolean checked = false;
public DBColumn(String name){
columnName = name;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getColumnTypeName() {
return columnTypeName;
}
public void setColumnTypeName(String columnTypeName) {
this.columnTypeName = columnTypeName;
}
public int getColumnType() {
return columnType;
}
public void setColumnType(int columnType) {
this.columnType = columnType;
}
public boolean isPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(boolean primaryKey) {
this.primaryKey = primaryKey;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
@Override
public String getItemName() {
return getColumnName();
}
@Override
public String toString(){
return getItemName();
}
}
package sample;
import java.util.ArrayList;
import java.util.List;
public class DBDataBase implements DBItem{
private String name;
private List<DBSchema> schemas;
public DBDataBase(String name){
this.name = name;
schemas = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DBSchema> getSchemas() {
return schemas;
}
public void setSchemas(List<DBSchema> schemas) {
this.schemas = schemas;
}
@Override
public String toString(){
return getItemName();
}
@Override
public String getItemName() {
return name;
}
}
package sample;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.css.CssMetaData;
import javafx.css.Styleable;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.stream.Collectors;
public class DBItemTreeCell extends TreeCell<DBItem> {
private ColumnsSelected colSelCallBack;
interface ColumnsSelected{
void columnsSelectedCallback(DBQuery queryToExec);
}
public DBItemTreeCell() {
}
public DBItemTreeCell(ColumnsSelected selCb) {
colSelCallBack = selCb;
}
@Override
public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
return super.getControlCssMetaData();
}
@Override
protected void updateItem(DBItem item, boolean empty) {
super.updateItem(item, empty);
if(item != null) {
setText(item.getItemName());
} else {
setText("-");
}
if(item instanceof DBColumn){
setStyle("-fx-font-size:1.0em;");
HBox node = new HBox();
CheckBox checkBox = new CheckBox();
node.getChildren().add(checkBox);
updateSelected(false);
checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(newValue == true){
System.out.println("Checked item true");
getTreeView().getSelectionModel().select(getTreeItem());
((DBColumn) item).setChecked(true);
//updateSelected(true);
}else{
System.out.println("Checked item false");
//getTreeView().getSelectionModel().
//updateSelected(false);
}
}
});
setGraphic(node);
}
else if (item instanceof DBDataBase){
setStyle("-fx-font-size:1.4em;-fx-font-weight:bold");
setGraphicImageView("/home/med/Pictures/db.png");
}else{
setGraphic(null);
}
// logic to create table context menu
if(item instanceof DBTable){
Node menuIcon = setTableNode(getText());
setText("");
System.out.println("Setting context menu for table");
getStyleClass().add("db_column");
setStyle("-fx-font-size:1.1em;-fx-font-weight:bold");
ContextMenu menu = new ContextMenu();
MenuItem menuItem = new MenuItem("SELECT");
MenuItem menuItemDrop = new MenuItem("DROP TABLE");
//Label label = new Label("T:");
//setGraphic(label);
setContextMenu(menu);
menu.getItems().addAll(menuItem,menuItemDrop);
menuIcon.setOnMouseClicked( c -> {
menu.show(menuIcon, Side.BOTTOM, c.getX(), c.getY());
});
menuItem.setOnAction(e ->{
// get children that are selected
List<DBColumn> selectedCols = getTreeItem().getChildren().stream().map(treeItem -> {
return (DBColumn)treeItem.getValue();
}).filter(dbCol -> dbCol.isChecked())
.collect(Collectors.toList());
if( selectedCols.size() > 0 && colSelCallBack != null){
DBQuery query = new DBQuery(DBQuery.QueryType.SELECT);
query.setColumns(selectedCols.stream().map(DBColumn::getColumnName).collect(Collectors.toList()));
colSelCallBack.columnsSelectedCallback(query);
}
});
menuItemDrop.setOnAction(e -> {
Postgres postgres = new Postgres();
postgres.dropTable(((DBTable) item).getName(),"foo");
});
}else if (item instanceof DBSchema){
setContextMenu(null);
setStyle("-fx-font-size:1.2em;-fx-font-weight:bold;-fx-font-style:italic;-fx-text-fill:red;-fx-letter-spacing:1.2em;");
}else if (item instanceof DBDataBase){
setContextMenu(null);
setStyle("-fx-font-size:1.3em;-fx-font-weight:bold");
}
else{
setContextMenu(null);
setStyle("-fx-font-size:1.0em");
}
}
private void setGraphicImageView(String path){
File dbFile = new File(path);
Image image = null;
try {
image = new Image(new FileInputStream(dbFile));
ImageView node = new ImageView(image);
node.setFitHeight(32);
node.setFitWidth(32);
setGraphic(node);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private Node setTableNode(String tableName){
HBox tableView = new HBox();
File tableImageFile = new File("/home/med/Pictures/db-table.png");
File menuFile = new File( "/home/med/Downloads/menu.png");
Image image = null;
Image menuImage = null;
try {
image = new Image(new FileInputStream(tableImageFile));
ImageView tblImg = new ImageView(image);
tblImg.setFitHeight(32);
tblImg.setFitWidth(32);
menuImage = new Image(new FileInputStream(menuFile));
ImageView menuImg = new ImageView(menuImage);
menuImg.setFitHeight(48);
menuImg.setFitWidth(48);
tableView.getChildren().addAll(tblImg, new Label(tableName), menuImg);
setGraphic(tableView);
return menuImg;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
public void updateSelected(boolean selected) {
super.updateSelected(selected);
}
}
package sample;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DBQuery {
enum QueryType{ UPDATE,SELECT, DELETE }
private String tableName;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public QueryType getQueryType() {
return queryType;
}
public void setQueryType(QueryType queryType) {
this.queryType = queryType;
}
private List<String> columns = new ArrayList<>();
private QueryType queryType;
private DBQuery(){};
public DBQuery(QueryType qt){
queryType = qt;
};
public String buildQuery(){
return queryType.name() + " " + ((columns == null || columns.size() == 0) ? " * " : columns.stream().collect(Collectors.joining(","))) + " + WHERE 1;";
}
}
package sample;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.util.Callback;
import java.util.List;
import java.util.stream.Collectors;
public class FilesToAddList extends ListView<FileListItem> {
private List<FileListItem> filesToAdd;
public FilesToAddList(List<FileListItem> filesToAdd){
super();
this.filesToAdd = filesToAdd;
setMinWidth(500);
setMinHeight(250);
init();
}
private void init(){
getItems().addAll(filesToAdd);
setCellFactory(CheckBoxListCell.forListView(new Callback<FileListItem, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(FileListItem item) {
return item.onProperty();
}
}));
}
public List<FileListItem> getCheckedFiles(){
return this.filesToAdd.stream()
.filter(FileListItem::isOn)
.collect(Collectors.toList());
}
public void clear() {
this.filesToAdd.clear();
}
}
package sample;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.CheckBox;
public class FileListItem {
public FileListItem(String name) {
setName(name);
setOn(false);
}
public String getFileName() {
return fileName;
}
@Override
public String toString() {
return getName();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public GitRepo getRepo() {
return repo;
}
public void setRepo(GitRepo repo) {
this.repo = repo;
}
public String getName() {
return nameProperty().get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.nameProperty().set(name);
}
public boolean isOn() {
return onProperty().get();
}
public BooleanProperty onProperty() {
return on;
}
public void setOn(boolean on) {
this.onProperty().set(on);
}
String fileName;
GitRepo repo;
private final StringProperty name = new SimpleStringProperty();
private final BooleanProperty on = new SimpleBooleanProperty();
}
import java.io.File;
/**
* Created by markdavis on 8/3/19.
*/
public class GitRepo {
public String name;
String localPath;
public String remote;
public String workingBranch;
public String status;
public GitRepo(String path){
localPath = path;
this.name = new File(path).getName();
}
}
private String convertJqplToSql(Query jpqlQuery){
Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)jpqlQuery).getDatabaseQuery();
DatabaseRecord recordWithValues= new DatabaseRecord();
recordWithValues.add(new DatabaseField("ratName"), "ROO");
String sqlStringWithArgs =
databaseQuery.getTranslatedSQLString(session, recordWithValues);
//databaseQuery.bindAllParameters();
//databaseQuery.dontBindAllParameters();
databaseQuery.prepareCall(session, new DatabaseRecord());
String sql =databaseQuery.getSQLString();
System.out.println("sql: " + sqlStringWithArgs);
return sql;
}
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static javafx.application.Application.launch;
public class Main extends Application {
TilePane tilePane;
File filterImageFile = new File("/home/med/Downloads/filter.png");
List<GitRepo> gitRepos = new ArrayList<>();
FilesToAddList filesToAddList = null;
Pattern COMMIT_PREFIX_PATTERN = Pattern.compile("(?<COMMITPREFIX>[A-Z]{1,5}-[0-9]{1,4})");
boolean hideMaster;
public Stream<String> runCommand(GitRepo repo, String command) {
Stream.Builder<String> sb = Stream.builder();
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(repo.localPath));
try{
Process proc = pb.command("/bin/bash", "-c", command).start();
System.out.println("Running cmd: " + command);
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
return reader.lines();
}catch(IOException e){
System.err.println("NO OUTPUT FROM CMD: " + command);
return null;
}
}
public void checkoutBranch(GitRepo repo, String branch){
runCommand(repo, "git checkout " + branch).forEach(System.out::println);
}
public ObservableList<String> getBranches(GitRepo repo){
List<String> branches = runCommand(repo ,"git branch -a").collect(Collectors.toList());
ObservableList<String> options =
FXCollections.observableArrayList(
branches
);
return options;
}
public String gitStatus(GitRepo repo){
String status = runCommand(repo, "git status").collect(Collectors.joining("\n"));
return status;
}
/**
* Sets the working branch anf returns it from
* the list if branch options from git output
* @return
*/
public String determineWorkingBranch(GitRepo repo, ObservableList<String> branchOptions){
String workingB = branchOptions.stream()
.map(String::trim)
//.peek(branch -> {workingBranch = branch;})
.filter(br -> br.startsWith("*"))
.findFirst().get();
if(workingB != null){
repo.workingBranch = workingB;
//tilePane.getChildren().get(listIndex);
//repo.workingBranchText.setText("Working Branch: " + repo.workingBranch);
return workingB;
}
return null;
}
public void drawRepos(){
if(tilePane == null){
tilePane = new TilePane();
tilePane.setPadding(new Insets(5, 5, 5, 5));
tilePane.setVgap(5);
tilePane.setHgap(5);
tilePane.setPrefColumns(1);
tilePane.setStyle("-fx-background-color: #ccc;-fx-text-color:white");
}else{
if(tilePane.getChildren().size() > 0){
System.out.println("Removing chilren");
Platform.runLater(() -> {
System.out.println("child count: " + tilePane.getChildren().size());
tilePane.getChildren().clear();
});
}
}
for(GitRepo repo : gitRepos){
TextArea sysOutText = new TextArea();
Label headerLabel = new Label(repo.name);
headerLabel.setStyle("-fx-font-size: 1.2em;-fx-start-margin: 1.2em;-fx-fill-width: 100%;-fx-background-color:#ddd");
headerLabel.setPrefWidth(100);
HBox vBox = new HBox(headerLabel);
Label workingBranchText = new Label();
vBox.getChildren().addAll(workingBranchText);
ObservableList<String> branchOptions = getBranches(repo);
final ComboBox comboBox = new ComboBox(branchOptions);
comboBox.setPrefWidth(100);
String workingB = determineWorkingBranch(repo, branchOptions);
workingBranchText.setText(workingB);
System.out.println("WORKING BRANCH: " + workingB);
workingBranchText.setStyle("-fx-font-family: courier");
workingBranchText.setAlignment(Pos.BASELINE_CENTER);
workingBranchText.setPrefWidth(200);
comboBox.getSelectionModel().select(workingB);
HBox filterBox = new HBox();
try{
Image filterImage = new Image(new FileInputStream(filterImageFile));
ImageView filterImageView = new ImageView(filterImage);
TextField filterText = new TextField();
filterText.setPrefWidth(100);
filterBox.getChildren().addAll(filterImageView, filterText);
filterText.textProperty().addListener((obs, old, newText) -> {
if(branchOptions != null){
List<String> filteredBranches = new ArrayList<>();
filteredBranches = branchOptions.stream().filter( branch -> {
return branch.contains(newText);
}).collect(Collectors.toList());
if(filteredBranches.size() > 0){
ObservableList<String> filteredOptions =
FXCollections.observableArrayList(
filteredBranches
);
comboBox.setItems(filteredOptions);
}else{
comboBox.setItems(branchOptions);
}
}
});
}catch (FileNotFoundException e){
e.printStackTrace();
}
HBox branchSelectBox = new HBox();
Button checkoutBtn = new Button("Checkout ");
checkoutBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String branch = (String) comboBox.getSelectionModel().getSelectedItem();
System.out.println("Checking out branch : " + branch);
checkoutBranch(repo, branch);
ObservableList<String> branchOptions = getBranches(repo);
comboBox.setItems(branchOptions);
String wb = determineWorkingBranch(repo, branchOptions);
comboBox.getSelectionModel().select(wb);
workingBranchText.setText(wb);
}
});
branchSelectBox.getChildren().add(comboBox);
branchSelectBox.getChildren().add(checkoutBtn);
Button commitBtn = new Button("Commit");
int filesToAddCount = getFilesToAdd(repo).size();
if(filesToAddCount > 0){
commitBtn.setText("Commit ("+ filesToAddCount + ")");
}
branchSelectBox.getChildren().add(commitBtn);
sysOutText.setPrefColumnCount(200);
sysOutText.setPrefRowCount(3);
TextArea statusTextArea = new TextArea();
class CommitConfirm{
public String cmtMsg;
}
commitBtn.setOnAction((action) -> {
Dialog<CommitConfirm> commitDialog = new Dialog();
List<String> filesToAdd = getFilesToAdd(repo);
System.out.println("files to add");
sysOutText.setText(filesToAdd.toString());
DialogPane dialogPane = new DialogPane();
VBox dialogContents = new VBox();
dialogContents.setPrefSize(600,600);
dialogContents.setStyle("-fx-border-color:red");
//dialogContents.getChildren().add(new TextArea());
List<FileListItem> fileListItems = new ArrayList<>();
//VBox filesToAddView = new VBox();
dialogPane.getButtonTypes().add(ButtonType.CANCEL);
if(filesToAdd.size() > 0) {
dialogPane.getButtonTypes().add(ButtonType.OK);
dialogPane.setPrefWidth(700);
dialogPane.setPrefHeight(700);
//filesToAddView.setPrefWidth(800);
//filesToAddView.setOrientation(Orientation.VERTICAL);
//filesToAddView.setAlignment(Pos.TOP_LEFT);
for(String fileNameToAdd : filesToAdd){
//FlowPane fileToAddView = new FlowPane();
//fileToAddView.setPrefColumns(1);
//fileToAddView.setOrientation(Orientation.HORIZONTAL);
//filesToAddView.setFillWidth(true);
//Label fileText = new Label(fileNameToAdd);
FileListItem fileListItem = new FileListItem(fileNameToAdd);
// CheckBox fileCheck = new CheckBox();
//fileListItem.setCheckBox(fileCheck);
fileListItem.setFileName(fileNameToAdd);
fileListItem.setOn(false);
fileListItem.setRepo(repo);
// fileCheck.setId(fileNameToAdd);
fileListItems.add(fileListItem);
//fileToAddView.getChildren().addAll(fileText,fileCheck );
//filesToAddView.getChildren().add(fileToAddView);
}
filesToAddList = new FilesToAddList(fileListItems);
filesToAddList.setCellFactory(CheckBoxListCell.forListView(new Callback<FileListItem, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(FileListItem item) {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected) ->
item.setOn(isNowSelected));
return observable ;
}
}));
dialogContents.getChildren().add(filesToAddList);
dialogPane.getChildren().add(dialogContents);
System.out.println("FILES TO SHOW: " + fileListItems);
}else{
TextArea nothing = new TextArea();
nothing.setText(gitStatus(repo));
dialogPane.setContent(nothing);
}
commitDialog.setDialogPane(dialogPane);
TextArea commitMsg = new TextArea();
commitMsg.setText(getCommitPrefix(repo.workingBranch) + ": ");
commitMsg.setPrefColumnCount(500);
commitMsg.setPrefRowCount(8);
commitMsg.setMinWidth(200);
Label commitLabel = new Label("Commit Msg:");
commitLabel.setLabelFor(commitMsg);
commitLabel.setPrefSize(500,70);
commitLabel.setMinWidth(400);
commitMsg.setMinWidth(400);
commitMsg.setMinHeight(100);
dialogContents.getChildren().addAll(commitLabel, commitMsg);
commitDialog.setResultConverter((btn -> {
if(btn.getButtonData().isCancelButton()){
return null;
}
CommitConfirm cmtConf = new CommitConfirm();
cmtConf.cmtMsg = commitMsg.getText();
return cmtConf;
}));
commitDialog.setTitle("Select Files to Add; Enter your Commit;");
commitDialog.showAndWait().ifPresent( cmt -> {
String filesToCommit = filesToAddList.getCheckedFiles().stream()
.filter(ch-> ch.onProperty().get())
.map(ch -> {
return ch.toString();
}).collect(Collectors.joining(" "));
runCommand(repo, "git add " + filesToCommit).forEach(System.out::println);
System.out.println("Commit msg : " + cmt.cmtMsg);
String out = commit(repo, cmt.cmtMsg);
sysOutText.setText(out);
String status = gitStatus(repo);
statusTextArea.setText(status);
filesToAddList.clear();
});
});
vBox.getChildren().add(filterBox);
vBox.getChildren().add(branchSelectBox);
TitledPane statusPane = new TitledPane();
statusPane.setExpanded(false);
statusPane.setText("Git Status");
statusTextArea.setPrefRowCount(150);
statusTextArea.setPrefColumnCount(50);
String status = gitStatus(repo);
statusTextArea.setText(status);
statusPane.setContent(statusTextArea);
//vBox.getChildren().add(statusPane);
HBox leftRightBox = new HBox(vBox);
VBox outputPane = new VBox();
outputPane.getChildren().add(new Label("Sys Out:"));
outputPane.getChildren().add(sysOutText);
sysOutText.setStyle("-fx-font-family:courier;-fx-font-color:neon-green;-fx-background-color:black;");
leftRightBox.getChildren().add(outputPane);
vBox.setStyle("-fx-padding: 3px;-fx-border-color: " + getBorderColor(status));
Button statusBtn = new Button("Status");
statusBtn.setOnAction(a-> {
Alert statusAlert = new Alert(Alert.AlertType.INFORMATION, status);
statusAlert.setHeaderText("Status of '" + repo.name + "'");
statusAlert.setTitle("Status");
statusAlert.show();
});
repo.status = status;
vBox.getChildren().add(statusBtn);
if(hideMaster && workingB.endsWith("master")){
// vBox.setVisible(false);
System.out.println("HIDING");
}else
{
tilePane.getChildren().addAll(vBox);
}
}
}
public void start(Stage stage) {
// sample git repo paths
GitRepo gitUiRepo = new GitRepo("gitui");
GitRepo ratRepo = new GitRepo("ratrepo");
//GitRepo simpleGit = new GitRepo("/path/simplegit");
gitRepos.add(gitUiRepo);
gitRepos.add(ratRepo);
//gitRepos.add(simpleGit);
Button hideMasterBtn = new Button("Refresh");
hideMasterBtn.setOnAction(a -> {
/* if(hideMaster){
hideMaster = false;
}
else{
hideMaster = true;
}
*/
drawRepos();
});
drawRepos();
int listIndex = 0;
ScrollPane scrollPane = new ScrollPane(tilePane);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(scrollPane);
Label topLabel = new Label("GIT REPOSITORY MANAGER");
topLabel.setScaleX(2);
topLabel.setPrefWidth(500);
topLabel.setPrefHeight(25);
topLabel.setAlignment(Pos.CENTER);
topLabel.setStyle("-fx-background-color:black;-fx-color:yellow;");
borderPane.setTop(topLabel);
borderPane.getTop().autosize();
borderPane.setBottom(hideMasterBtn);
Scene scene = new Scene(borderPane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
public boolean nothingToCommit(String status){
status = status.toLowerCase();
if(status.contains("nothing to commit")){
return true;
}
else{
return false;
}
}
public String getBorderColor(String status){
if(nothingToCommit(status)){
return "green";
}
else{
return "red";
}
}
public List<String> getFilesToAdd(GitRepo repo){
List<String> filesToAdd = runCommand(repo, "git status")
.filter(line -> {
line = line.trim();
System.out.println(line);
if(line.isEmpty()){
return false;
}
File file = new File(repo.localPath + "/" + line.trim());
System.out.println("Checking file : " + repo.localPath + "/" + line.trim());
if(file.exists()){
System.out.println("File Exists: " + file.getAbsolutePath());
return true;
}
if(line.startsWith("modified:")){
return true;
}
if(line.startsWith("new file:")){
return true;
}
return false;
}).map(matchedLine -> {
matchedLine = matchedLine.trim();
System.out.println("matched line:" + matchedLine);
if(matchedLine.startsWith("modified:")){
System.out.println("Start w modified:");
return repo.localPath + "/" + matchedLine.replaceAll("modified:\\s+", "").trim();
}
if(matchedLine.startsWith("new file:")){
System.out.println("Start w new file:");
return repo.localPath + "/" + matchedLine.replaceAll("new file:\\s+", "").trim();
}
return repo.localPath + "/" + matchedLine;
})
.distinct()
.collect(Collectors.toList());
return filesToAdd;
}
public String getCommitPrefix(String workingBranch){
String cmtPre = "";
Matcher matcher = COMMIT_PREFIX_PATTERN.matcher(workingBranch);
if(matcher.find()){
cmtPre = matcher.group("COMMITPREFIX");
}
System.out.println("COMMIT PREFIX: " + cmtPre);
return cmtPre;
}
public String commit(GitRepo repo, String commitMsg){
String out = runCommand(repo, "git commit -m '" + getCommitPrefix(repo.workingBranch) + ": " + commitMsg + "' ").collect(Collectors.joining("\n"));
drawRepos();
return out;
}
}
package sample;
import javafx.collections.ListChangeListener;
import javafx.scene.control.*;
import javafx.util.Callback;
import java.sql.*;
import java.util.*;
public class Postgres {
private Map<String,Set<DBTable>> schemaTableMap = new HashMap<>();
class DataItem{
String col;
int dataType;
Object value;
}
class QueryResult{
List<String> columns;
List<List<DataItem>> data;
Map<String,Integer> colNameToIndex = new HashMap<>();
public QueryResult(){
data = new ArrayList<List<DataItem>>();
}
public void addRow(List<DataItem> dataItem){
data.add(dataItem);
}
}
public Postgres() {
}
public Map<String,Set<DBTable>> getSchemaTableMap() {
return schemaTableMap;
}
public void dropTable(String table, String dbName) {
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/" + dbName, "admin", "password")) {
if (conn != null) {
System.out.println("Connected to the database!");
conn.setAutoCommit(false);
Statement st = conn.createStatement();
String sql = "DROP TABLE " + table + ";";
System.out.println("SQL : " + sql);
int res = st.executeUpdate(sql);
System.out.println("DROP TABLE RES: " + res);
conn.commit();
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} catch (SQLException e) {
e.printStackTrace();
}
}
public QueryResult convertResultSet(ResultSet res) throws SQLException {
QueryResult qr = new QueryResult();
ResultSetMetaData md = res.getMetaData();
int colCount = md.getColumnCount();
List<String> colNames = new ArrayList<>();
for(int i = 1; i < colCount; i++){
String colName = md.getColumnName(i);
colNames.add(colName);
qr.colNameToIndex.put(colName, i);
int dataType = md.getColumnType(i);
}
qr.columns = colNames;
//List<List<DataItem>> data =
//data.a
while(res.next()){
List<DataItem> dataItemList = new ArrayList<>();
colNames.stream().forEach(col ->{
DataItem item = new DataItem();
item.col = col;
item.dataType = qr.colNameToIndex.get(col);
System.out.println("Col data type: " + item.dataType);
System.out.println("Converting col: " + col);
try{
switch(item.dataType){
case Types.BOOLEAN:
item.value = res.getBoolean(col);
break;
case Types.BIGINT:
case Types.INTEGER:
item.value = res.getInt(col);
break;
case Types.CHAR:
case Types.VARCHAR:
item.value = res.getString(col);
break;
case Types.DATE:
item.value = res.getDate(col);
break;
case Types.TIME:
item.value = res.getTime(col);
break;
case Types.TIMESTAMP:
item.value = res.getTimestamp(col);
break;
case Types.TIMESTAMP_WITH_TIMEZONE:
item.value = res.getTimestamp(col);
break;
default:
System.out.println("no type found for col val: " + col);
}
} catch (SQLException e){
e.printStackTrace();
}
dataItemList.add(item);
});
qr.addRow(dataItemList);
}
return qr;
}
public TreeView<DBItem> getSchemaCheckboxTreeView(String dbName){
DBDataBase db = getDBDatabase("foo");
TreeView<DBItem> dbSchemaTreeView = new TreeView<>();
TreeItem<DBItem> rootTreeItem = new TreeItem(db);
dbSchemaTreeView.setRoot(rootTreeItem);
// dbSchemaTreeView.setEditable(true);
dbSchemaTreeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
dbSchemaTreeView.setCellFactory(new Callback<TreeView<DBItem>, TreeCell<DBItem>>() {
@Override
public TreeCell<DBItem> call(TreeView<DBItem> param) {
return new DBItemTreeCell(new DBItemTreeCell.ColumnsSelected() {
@Override
public void columnsSelectedCallback(DBQuery queryToExec) {
// set
System.out.println("IN COLUMNS SELECTED CALLBACK: " + queryToExec.buildQuery());
}
});
}
});
//int sc = 0;
for(DBSchema schema : db.getSchemas()){
TreeItem<DBItem> schemaLeafItem = new TreeItem<>(schema);
rootTreeItem.getChildren().add(schemaLeafItem);
// dbSchemaTreeView.setCellFactory(new Callback<TreeView<DBItem>, TreeCell<DBItem>>() {
// @Override
// public TreeCell<DBItem> call(TreeView<DBItem> param) {
// //TreeItem<DBItem> i = param.getTreeItem(c);
// TreeCell<DBItem> cell = new TreeCell<>();
//
// int i = param.getRow(schemaLeafItem);
// TreeItem<DBItem> treeItem = param.getTreeItem(i);
//
// if(treeItem.getValue() != null && treeItem.getValue() instanceof DBColumn){
// CheckBoxTreeCell<DBItem> dbTreeCell = new CheckBoxTreeCell<DBItem>();
// dbTreeCell.setConverter(new StringConverter<TreeItem<DBItem>>() {
// @Override
// public String toString(TreeItem<DBItem> dbItem) {
// return dbItem.getValue().getItemName();
// }
//
// @Override
// public TreeItem<DBItem> fromString(String string) {
// return null;
// }
// });
// cell = dbTreeCell;
// }
//
//
//
//
// return cell;
// }
// });
for(DBTable table : schema.getTables()){
TreeItem<DBItem> tableLeafItem = new TreeItem<>(table);
schemaLeafItem.getChildren().add(tableLeafItem);
for(DBColumn col : table.getCols()){
TreeItem colLeafItem = new TreeItem<>(col);
tableLeafItem.getChildren().add(colLeafItem);
}
}
}
return dbSchemaTreeView;
}
public DBDataBase getDBDatabase(String dbName){
DBDataBase dbDatabase = new DBDataBase(dbName);
dbDatabase.setSchemas(new ArrayList<>());
TreeView<String> treeView = new TreeView<>();
treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
TreeItem<String> rootItem = new TreeItem<>(dbName);
rootItem.setExpanded(true);
treeView.setRoot(rootItem);
treeView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<TreeItem<String>>() {
@Override
public void onChanged(Change<? extends TreeItem<String>> c) {
List<TreeItem<String>> selected = treeView.getSelectionModel().getSelectedItems();
}
});
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/" + dbName, "admin", "password")) {
if (conn != null) {
System.out.println("Connected to the database!");
conn.setAutoCommit(false);
ResultSet schemaSet = conn.getMetaData().getSchemas();
ResultSetMetaData setMetaData = schemaSet.getMetaData();
int colCount = setMetaData.getColumnCount();
System.out.println("count = " + colCount);
while(schemaSet.next()){
//System.out.println("TABLE_CAT = " + schemaSet.getString("TABLE_CAT") );
for(int i = 1; i <= colCount; i++){
String schemaName = schemaSet.getString(i);
System.out.println("SCHEMA NAME: " + schemaName);
TreeItem<String> schemaTreeItem = new TreeItem<>(schemaName);
DBSchema dbSchema = new DBSchema(schemaName);
if(schemaName == null){
continue;
}else{
schemaTableMap.put(schemaName, new HashSet());
System.out.println("schema: " + schemaName);
dbDatabase.getSchemas().add(dbSchema);
}
ResultSet tablesRes = conn.getMetaData().getTables(dbName , schemaName, null, new String[]{"TABLE"});
while(tablesRes.next()){
String table = tablesRes.getString(3);
TreeItem<String> tableTreeItem = new TreeItem(table);
/*tableTreeItem.addEventHandler(new EventType<MouseEvent>(), (e) ->{
if(e.isSecondaryButtonDown()){
ContextMenu menu = new ContextMenu();
MenuItem item = new MenuItem("query");
menu.getItems().add(item);
item.setOnAction((ev)-> {
String sql = "SELECT ";
List<String> tableCols = tableTreeItem.getChildren().stream()
.map(ti -> ti.getValue()).collect(Collectors.toList());
List<TreeItem<String>> selected = treeView.getSelectionModel().getSelectedItems();
selected = selected.stream().filter(ti -> tableCols.contains(ti))
.collect(Collectors.toList());
if(selected.size() > 0){
sql += selected.stream().map(ti -> ti.getValue()).collect(Collectors.joining(","));
}else{
sql += " * ";
}
sql += " FROM " + tableTreeItem.getValue();
System.out.println("SQL TO RUN :" + sql);
menu.show(tableTreeItem.getGraphic(), e.getScreenX(), e.getScreenY());
});
}
});
*/
schemaTreeItem.getChildren().add(tableTreeItem);
DBTable dbTable = new DBTable();
dbTable.setName(table);
System.out.println("\tTABLE:" + table);
dbSchema.getTables().add(dbTable);
ResultSet colRes = conn.getMetaData().getColumns(dbName, schemaName, table, null );
dbTable.setCols(new ArrayList<>());
while(colRes.next()){
String col = colRes.getString(4);
System.out.println("\t\t" + col);
TreeItem<String> colTreeItem = new TreeItem<>(col);
tableTreeItem.getChildren().add(colTreeItem);
dbTable.getCols().add(new DBColumn(col));
}
schemaTableMap.get(schemaName).add(dbTable);
//DBSchema dbSchema = new DBSchema(schemaName);
}
if(schemaTreeItem.getChildren().size() > 0){
rootItem.getChildren().add(schemaTreeItem);
}
}
}
//Statement st = conn.createStatement();
//ResultSet res = st.executeQuery();
} else {
System.out.println("Failed to make connection!");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return dbDatabase;
}
public ResultSet runQuery(String sql) {
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/foo", "admin", "password")) {
if (conn != null) {
System.out.println("Connected to the database!");
conn.setAutoCommit(false);
Statement st = conn.createStatement();
ResultSet res = st.executeQuery(sql);
/*while(res.next()){
int emailCol = res.findColumn("email");
String email = res.getString(emailCol);
System.out.println("email: " + email);
}
*/
//res.close();
//st.close();
return res;
} else {
System.out.println("Failed to make connection!");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package sample;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Postgres {
class DataItem{
String col;
int dataType;
Object value;
}
class QueryResult{
List<String> columns;
List<List<DataItem>> data;
Map<String,Integer> colNameToIndex = new HashMap<>();
public QueryResult(){
data = new ArrayList<List<DataItem>>();
}
public void addRow(List<DataItem> dataItem){
data.add(dataItem);
}
}
public Postgres() {
}
public QueryResult convertResultSet(ResultSet res) throws SQLException {
QueryResult qr = new QueryResult();
ResultSetMetaData md = res.getMetaData();
int colCount = md.getColumnCount();
List<String> colNames = new ArrayList<>();
for(int i = 1; i < colCount; i++){
String colName = md.getColumnName(i);
colNames.add(colName);
qr.colNameToIndex.put(colName, i);
int dataType = md.getColumnType(i);
}
qr.columns = colNames;
//List<List<DataItem>> data =
//data.a
while(res.next()){
List<DataItem> dataItemList = new ArrayList<>();
colNames.stream().forEach(col ->{
DataItem item = new DataItem();
item.col = col;
item.dataType = qr.colNameToIndex.get(col);
System.out.println("Col data type: " + item.dataType);
System.out.println("Converting col: " + col);
try{
switch(item.dataType){
case Types.BOOLEAN:
item.value = res.getBoolean(col);
break;
case Types.BIGINT:
case Types.INTEGER:
item.value = res.getInt(col);
break;
case Types.CHAR:
case Types.VARCHAR:
item.value = res.getString(col);
break;
case Types.DATE:
item.value = res.getDate(col);
break;
case Types.TIME:
item.value = res.getTime(col);
break;
case Types.TIMESTAMP:
item.value = res.getTimestamp(col);
break;
case Types.TIMESTAMP_WITH_TIMEZONE:
item.value = res.getTimestamp(col);
break;
default:
System.out.println("no type found for col val: " + col);
}
} catch (SQLException e){
e.printStackTrace();
}
dataItemList.add(item);
});
qr.addRow(dataItemList);
}
return qr;
}
public ResultSet runQuery(String sql) {
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/db", "u", "pw")) {
if (conn != null) {
System.out.println("Connected to the database!");
conn.setAutoCommit(false);
Statement st = conn.createStatement();
ResultSet res = st.executeQuery(sql);
/*while(res.next()){
int emailCol = res.findColumn("email");
String email = res.getString(emailCol);
System.out.println("email: " + email);
}
*/
//res.close();
//st.close();
return res;
} else {
System.out.println("Failed to make connection!");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
TableView<Postgres.DataItem> tableView = new TableView<>();
Platform.runLater(() -> {
Postgres postgres = new Postgres();
try {
ResultSet res = postgres.runQuery("SELECT * FROM table;");
Postgres.QueryResult queryRes = postgres.convertResultSet(res);
queryRes.columns.stream().forEach(colName -> {
TableColumn<String, Postgres.DataItem> tableColumn = new TableColumn<>(colName);
tableColumn.setCellValueFactory(new PropertyValueFactory<>("value"));
});
List<List<Postgres.DataItem>> dataItemList = queryRes.data;
dataItemList.stream().forEach(dataItemRow -> {
dataItemRow.stream().forEach((di) -> {
tableView.getItems().add(di);
});
});
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
});
tab2.setContent(tableView);
package sample;
import java.util.ArrayList;
import java.util.List;
public class DBSchema implements DBItem {
private List<DBTable> tables;
private String name;
public DBSchema(){};
public DBSchema (String name){
this.name = name;
tables = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DBTable> getTables() {
return tables;
}
public void setTables(List<DBTable> tables) {
this.tables = tables;
}
@Override
public String toString(){
return getItemName();
}
@Override
public String getItemName() {
return name;
}
}
package sample;
import java.util.List;
public class DBTable implements DBItem {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DBColumn> getCols() {
return cols;
}
public void setCols(List<DBColumn> cols) {
this.cols = cols;
}
private String name;
private List<DBColumn> cols;
public DBTable(){
}
@Override
public String toString(){
return getItemName();
}
@Override
public String getItemName() {
return name;
}
}
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="animals" transaction-type="RESOURCE_LOCAL">
<jar-file>rat.jar</jar-file>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://127.0.0.1:5432/rat" />
<property name="javax.persistence.jdbc.user" value="rat" />
<property name="javax.persistence.jdbc.password" value="rat" />
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.level" value="FINE"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
</properties>
</persistence-unit>
</persistence>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment