Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RatmirEspo/30268011023986a1d226c3c65f59abc5 to your computer and use it in GitHub Desktop.
Save RatmirEspo/30268011023986a1d226c3c65f59abc5 to your computer and use it in GitHub Desktop.
Create
<component name="ArtifactManager">
<artifact type="jar" build-on-make="true" name="Segure Data Base Desktop:jar">
<output-path>$PROJECT_DIR$/out/artifacts/Segure_Data_Base_Desktop_jar</output-path>
<root id="archive" name="Segure Data Base Desktop.jar">
<element id="module-output" name="Segure Data Base Desktop" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/pax-jdbc-sqlite-0.9.0.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/org.osgi.core-4.3.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/org.osgi.enterprise-4.2.0.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/sqlite-jdbc-3.8.10.1.jar" path-in-jar="/" />
</root>
</artifact>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value />
</option>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default (1)" />
</component>
</project>
<html>Simple <b>Java</b> application that includes a class with <code>main()</code> method</html>
<component name="ProjectDictionaryState">
<dictionary name="RATMIR">
<words>
<w>jdbc</w>
<w>sequre</w>
<w>sergejudovitskij</w>
</words>
</dictionary>
</component>
<component name="libraryTable">
<library name="org.ops4j.pax.jdbc:pax-jdbc-sqlite:0.9.0" type="repository">
<properties maven-id="org.ops4j.pax.jdbc:pax-jdbc-sqlite:0.9.0" />
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/pax-jdbc-sqlite-0.9.0.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/org.osgi.core-4.3.1.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/org.osgi.enterprise-4.2.0.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/sqlite-jdbc-3.8.10.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$PROJECT_DIR$/lib/pax-jdbc-sqlite-0.9.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$PROJECT_DIR$/lib/pax-jdbc-sqlite-0.9.0-sources.jar!/" />
</SOURCES>
</library>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClientPropertiesManager">
<properties class="javax.swing.AbstractButton">
<property name="hideActionText" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JComponent">
<property name="html.disable" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JEditorPane">
<property name="JEditorPane.w3cLengthUnits" class="java.lang.Boolean" />
<property name="JEditorPane.honorDisplayProperties" class="java.lang.Boolean" />
<property name="charset" class="java.lang.String" />
</properties>
<properties class="javax.swing.JList">
<property name="List.isFileList" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JPasswordField">
<property name="JPasswordField.cutCopyAllowed" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JSlider">
<property name="Slider.paintThumbArrowShape" class="java.lang.Boolean" />
<property name="JSlider.isFilled" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JTable">
<property name="Table.isFileList" class="java.lang.Boolean" />
<property name="JTable.autoStartsEdit" class="java.lang.Boolean" />
<property name="terminateEditOnFocusLost" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JToolBar">
<property name="JToolBar.isRollover" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JTree">
<property name="JTree.lineStyle" class="java.lang.String" />
</properties>
<properties class="javax.swing.text.JTextComponent">
<property name="caretAspectRatio" class="java.lang.Double" />
<property name="caretWidth" class="java.lang.Integer" />
</properties>
</component>
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectKey">
<option name="state" value="project://e2804f05-5315-4fc6-a121-c522a6c26470" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Segure Data Base Desktop.iml" filepath="$PROJECT_DIR$/Segure Data Base Desktop.iml" />
</modules>
</component>
</project>
<template>
<input-field default="com.company">IJ_BASE_PACKAGE</input-field>
</template>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/out/production/Segure Data Base Desktop" />
<output-test url="file://$MODULE_DIR$/out/test/Segure Data Base Desktop" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="org.ops4j.pax.jdbc:pax-jdbc-sqlite:0.9.0" level="project" />
</component>
</module>
Manifest-Version: 1.0
Main-Class: ru.ratmir.sequredb.Main
package ru.ratmir.sequredb.controllers;
import ru.ratmir.sequredb.data.DataHelper;
import ru.ratmir.sequredb.data.ProjectModel;
import java.util.ArrayList;
/**
* Created RATMIR on 03.01.17.
* Copyright © Ratmir
*/
/**
* Controller class for main tool bar
*/
public final class MainToolBar {
/**
* Button 'New Project'
* Method create new project
* @param filePatch new project file patch
* @param projectModel project model (all info and settings)
* @return if project created - true, else - false
*/
public static boolean createNewProject(String filePatch,
String projectName,
ProjectModel projectModel){
return false;
}
/**
* Button 'Add new Data Base file'
* Method added file to project and show all table list
* @param filePatch file patch
* @return table list
*/
public static ArrayList<String> addFileToProject(String filePatch){
DataHelper dataHelper = new DataHelper();//
//запросы в методах доступа к базе данных,
//не должны иметь жестко закодированных имён таблиц, полей и т.п.
return new ArrayList<>();
}
}
package ru.ratmir.sequredb.data;
import ru.ratmir.sequredb.services.Constant;
import java.sql.*;
import java.util.ArrayList;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
/**
* Data Base Helper class
*/
public class DataHelper {
private Connection conn = null;
private Statement stat;
private ResultSet resSet;
private PreparedStatement pStat;
// --------Подключение к базе данных--------
/**
* Method connection to data base
*
* @param dbName data base name
* @throws ClassNotFoundException --
* @throws SQLException --
*/
public void Conn(String dbName) throws ClassNotFoundException, SQLException {
Class.forName(Constant.DRIVER_JDBC_NAME);
conn = DriverManager.getConnection(Constant.DRIVER_CONNECTION + dbName);
stat = conn.createStatement();
System.out.println("База подключена!");
}
/**
* The method encrypts the data in the specified row of the selected column
* @param dbName Data base name (It may not need)
* @param tableName Table name
* @param columnName Column name
* @param rowId currentRowId
* @param rowData Encrypted data
*/
public void updateTableRowEncryptedData(String dbName,
String tableName,
String columnName,
String rowData,
int rowId){
}
/**
* This method return count row in the specified table
* @param dbName data base name
* @param tableName table name
* @return count row in the specified table
* @throws SQLException --
* @throws ClassNotFoundException --
*/
public int getCountRowsInTable(String dbName, String tableName) throws SQLException, ClassNotFoundException {
Conn(dbName);
int result;
resSet = stat.executeQuery("SELECT seq FROM sqlite_sequence WHERE name = '" + tableName +"';");
result = resSet.getInt("seq");
CloseDB();
return result;
}
/**
* Test method, push to data base temp data
*
* @param dbName data base name
* @throws SQLException --
* @throws ClassNotFoundException --
*/
public void newDataEncrypted(String dbName)
throws SQLException, ClassNotFoundException {
Conn(dbName);
for (int i = 0; i < 2601; i++) {
stat.execute("INSERT INTO first_table (wordAr) VALUES ('VALUE " + i + "');");
}
CloseDB();
}
/**
* Check exist table from data base
*
* @param tableName table name
* @param dbName data base name
* @return true if exist, else false
* @throws SQLException --
* @throws ClassNotFoundException --
*/
public boolean isExistCurrentTable(String tableName, String dbName)
throws SQLException, ClassNotFoundException {
Conn(dbName);
boolean result = false;
resSet = stat.executeQuery("SELECT count(*) AS 'ID' " +
"FROM sqlite_master WHERE type='table' AND name='" + tableName + "';");
while (resSet.next()) {
int isExist = resSet.getInt("ID");
if (isExist == 1) {
result = true;
} else {
result = false;
}
}
CloseDB();
return result;
}
//--------- Получить имена всех таблиц ----
/**
* Read all tables name
*
* @param dbName data base name
* @return array list table names
* @throws SQLException --
* @throws ClassNotFoundException --
*/
public ArrayList<String> getAllTableName(String dbName)
throws SQLException, ClassNotFoundException {
ArrayList<String> result = new ArrayList<>();
try {
Conn(dbName);
resSet = stat.executeQuery("SELECT name AS 'TB_NAME' FROM sqlite_master;");
while (resSet.next()) {
String SentAr = resSet.getString("TB_NAME");
result.add(SentAr);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
CloseDB();
}
return result;
}
//получить имена столбцов в таблице--------
/**
* Read all column names
*
* @param tableName table name
* @param dbName data base name
* @return array list column names
* @throws SQLException --
* @throws ClassNotFoundException --
*/
public ArrayList<String> getColumnName(String tableName, String dbName)
throws SQLException, ClassNotFoundException {
ArrayList<String> columns = new ArrayList<>();
try {
Conn(dbName);
resSet = stat.executeQuery("pragma table_info(" + tableName + ");");
while (resSet.next()) {
String columnName = resSet.getString("name");
columns.add(columnName);
System.out.println(columnName + "\n");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDB();
}
return columns;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// -------- Вывод данных из таблицы--------
/**
* Test method read data base
*
* @throws ClassNotFoundException --
* @throws SQLException --
*/
public void ReadDB(String dataBaseName) throws ClassNotFoundException, SQLException {
Conn(dataBaseName);
resSet = stat.executeQuery("SELECT first_table._id AS 'F_ID',\n" +
" wordAr AS 'WordAr',\n" +
" second_table._id AS 'S_ID', second_table.first_id AS 'S_F_ID',\n" +
" second_table.SentAr AS 'SentAr' FROM first_table, second_table\n" +
" WHERE first_table._id = second_table.first_id;");
while (resSet.next()) {
int id = resSet.getInt("F_ID");
String wordAr = resSet.getString("WordAr");
int second_table_id = resSet.getInt("S_ID");
int first_id = resSet.getInt("S_F_ID");
String SentAr = resSet.getString("SentAr");
System.out.println("first_table._id = " + id);
System.out.println("WordAr = " + wordAr);
System.out.println("second_table._id = " + second_table_id);
System.out.println("first_id = " + first_id);
System.out.println("SentAr = " + SentAr);
System.out.println();
}
System.out.println("Данные выведены");
CloseDB();
}
/**
* Test method
* @param dataBaseName data base name
* @return list String
* @throws ClassNotFoundException --
* @throws SQLException --
*/
public ArrayList<String> ReadDBToList(String dataBaseName) throws ClassNotFoundException, SQLException {
ArrayList<String> result = new ArrayList<>();
Conn(dataBaseName);
resSet = stat.executeQuery("SELECT first_table._id AS 'F_ID',\n" +
" wordAr AS 'WordAr',\n" +
" second_table._id AS 'S_ID', second_table.first_id AS 'S_F_ID',\n" +
" second_table.SentAr AS 'SentAr' FROM first_table, second_table\n" +
" WHERE first_table._id = second_table.first_id;");
while (resSet.next()) {
int id = resSet.getInt("F_ID");
String wordAr = resSet.getString("WordAr");
int second_table_id = resSet.getInt("S_ID");
int first_id = resSet.getInt("S_F_ID");
String SentAr = resSet.getString("SentAr");
result.add("first_table._id = " + id);
result.add("WordAr = " + wordAr);
result.add("second_table._id = " + second_table_id);
result.add("first_id = " + first_id);
result.add("SentAr = " + SentAr);
result.add("\n=======================================\n");
}
System.out.println("Данные выведены");
return result;
/*CloseDB();*/
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* Close Data Base method
*
* @return if closed - true, else false
* @throws ClassNotFoundException --
* @throws SQLException --
*/
public boolean CloseDB() throws ClassNotFoundException, SQLException {
try {
if (conn != null) conn.close();
//if (stat != null) stat.close();
if (resSet != null) resSet.close();
} catch (SQLException e) {
System.out.println("-----------" + e.getMessage());
return false;
}
System.out.println("Соединение закрыто удачно");
return true;
}
}
package ru.ratmir.sequredb.data;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created RATMIR on 05.01.17.
* Copyright © Ratmir
*/
public class DataModel {
/**
* List have information about table where encrypted column
* HashMap Key - Table name, Value - List column name
*/
private ArrayList<HashMap<String,ArrayList<String>>> encData;
/**
* Необходимо реализовать последовательное добавление таблицы, а в неё столбцов
*/
public ArrayList<HashMap<String, ArrayList<String>>> getEncData() {
return encData;
}
public void setEncData(ArrayList<HashMap<String, ArrayList<String>>> encData) {
this.encData = encData;
}
}
package ru.ratmir.sequredb.data;
import ru.ratmir.sequredb.services.Constant;
import ru.ratmir.sequredb.services.EncryptKey;
import java.io.File;
import java.io.Serializable;
import java.util.UUID;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*
* ***************************************************************
* *
* This class encapsulates all project settings and project data *
* pattern Singleton *
* *
* ***************************************************************
*
*/
public class ProjectModel implements Serializable {
private static ProjectModel instance = new ProjectModel();
private int id;
private File mProjectFilePatch;
private String mProjectFileName;
private String mProjectFolder;
private File mDataBasePatch;
private String mDataBaseName;
private String mEncDataBaseFileName;
private String mTempDataBaseName;
private File mTempDataBaseFilePatch;
private EncryptKey mProjectKey;
private String mOperationId;
private ProjectModel() {
this.mOperationId = UUID.randomUUID().toString();
this.mProjectKey = new EncryptKey();
}
/**
* getInstance method
* @return this object
*/
public static ProjectModel getInstance(){
if(instance == null){
instance = new ProjectModel();
}
return instance;
}
//Getters and setters field
public EncryptKey getProjectKey() {
return mProjectKey;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setProjectFilePatch(File projectFilePatch) {
if (projectFilePatch != null) {
this.mProjectFilePatch = projectFilePatch;
//replace string
this.mProjectFileName = ((mProjectFilePatch.getName() +
Constant.FILE_EXTENSION_PROJECT).toLowerCase().replace(" ", ""));
this.mProjectFolder = mProjectFilePatch.getAbsolutePath();
}
else {
throw new NullPointerException("File not selected !!!");
}
}
public String getProjectFolder() {
return mProjectFolder;
}
public File getProjectFilePatch() {
return mProjectFilePatch;
}
public String getProjectFileName() {
return mProjectFileName;
}
public void setDataBasePatch(File dataBasePatch) {
this.mDataBasePatch = dataBasePatch;
this.mDataBaseName = mDataBasePatch.getName();
this.mEncDataBaseFileName = mDataBaseName + Constant.FILE_EXTENSION;
this.mTempDataBaseName = mDataBasePatch.getName() +
Constant.DATA_BASE_TEMPORARY_EXTENDED;
}
public String getTempDataBaseName() {
return mTempDataBaseName;
}
public void setTempDataBaseFilePatch(File tempDataBaseFilePatch) {
mTempDataBaseFilePatch = tempDataBaseFilePatch;
}
public File getTempDataBaseFilePatch() {
return mTempDataBaseFilePatch;
}
public File getDataBasePatch() {
return mDataBasePatch;
}
public String getDataBaseName() {
return mDataBaseName;
}
public String getOperationId() {
return mOperationId;
}
public String getEncDataBaseFileName() {
return mEncDataBaseFileName;
}
}
package ru.ratmir.sequredb.exeption;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
/**
* Class exception, for validation special crypt key
*/
public class KeyIsNotValidly extends Exception {
public KeyIsNotValidly(String message) {
super(message);
}
public KeyIsNotValidly() {
super("The key is not validly");
}
}
package ru.ratmir.sequredb.exeption;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
public class NotAValidKeyFile extends Exception {
public NotAValidKeyFile() {
super("Not a valid key file");
}
public NotAValidKeyFile(String message) {
super(message);
}
}
package ru.ratmir.sequredb.exeption;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
/**
* Class exception, for validation project file
*/
public class NotAValidProjectFile extends Exception {
public NotAValidProjectFile(String message) {
super(message);
}
public NotAValidProjectFile() {
super("Not a valid project file");
}
}
package ru.ratmir.sequredb;
import ru.ratmir.sequredb.views.MainView;
import javax.swing.*;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
SwingUtilities.invokeLater(() -> {
try {
new MainView();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
});
}
}
package ru.ratmir.sequredb.services;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
/**
* Project constants
*/
public class Constant {
/*****************************************************************
******************** Data base constants ************************
/****************************************************************/
//public final static String DATA_BASE_NAME = "encryptedData.db";
public final static String DRIVER_JDBC_NAME = "org.sqlite.JDBC";
public final static String DRIVER_CONNECTION = "jdbc:sqlite:";
public final static String DATA_BASE_KEY_PATTERN = "_id";
public final static String DATA_BASE_TEMPORARY_EXTENDED = ".tmp";
/***************************************************************/
/***************** Project file constant ***********************/
/***************************************************************/
public final static String FILE_EXTENSION = ".enc";
public final static String FILE_EXTENSION_PROJECT = ".sdb";
/***************************************************************/
}
package ru.ratmir.sequredb.services;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Random;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
public class EncryptDecryptFile {
/**
* Method encrypt file and save encrypted file from disk
*
* @param inputFile input file patch
* @param outputFile output file patch
* @param key special key
* @throws IOException --
* @throws NoSuchAlgorithmException --
* @throws InvalidKeySpecException --
* @throws NoSuchPaddingException --
* @throws InvalidAlgorithmParameterException --
* @throws InvalidKeyException --
* @throws BadPaddingException --
* @throws IllegalBlockSizeException --
*/
public static void encryptData(String inputFile, String outputFile, EncryptKey key)
throws IOException,
NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidAlgorithmParameterException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
FileInputStream inFile = new FileInputStream(inputFile);
FileOutputStream outFile = new FileOutputStream(outputFile);
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
//PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
outFile.write(salt);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outFile.write(output);
System.out.println("#");
}
byte[] output = cipher.doFinal();
if (output != null)
outFile.write(output);
inFile.close();
outFile.flush();
outFile.close();
}
/**
* Method read encrypted file and decrypt, after save decrypted file
* to the disc
*
* @param inputFile input
* @param outputFile output
* @param key key
* @throws NoSuchAlgorithmException --
* @throws InvalidKeySpecException --
* @throws IOException --
* @throws NoSuchPaddingException --
* @throws InvalidAlgorithmParameterException --
* @throws InvalidKeyException --
* @throws BadPaddingException --
* @throws IllegalBlockSizeException --
*/
public static void decryptData(String inputFile, String outputFile, EncryptKey key)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
IOException,
NoSuchPaddingException,
InvalidAlgorithmParameterException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
FileInputStream fis = new FileInputStream(inputFile);
byte[] salt = new byte[8];
fis.read(salt);
//PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] in = new byte[64];
int read;
while ((read = fis.read(in)) != -1) {
byte[] output = cipher.update(in, 0, read);
if (output != null)
fos.write(output);
System.out.println("#");
}
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
fos.close();
}
}
package ru.ratmir.sequredb.services;
import javax.crypto.SecretKey;
import java.io.Serializable;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
public class EncryptKey implements SecretKey, Serializable {
// Поле для хранения информации о зашифрованых полях базы
/*private DataModel mDataModel;
public DataModel getDataModel() {
return mDataModel;
}
public void setDataModel(DataModel dataModel) {
mDataModel = dataModel;
}*/
//private String uuid;
public EncryptKey() {}
//private byte[] key = uuid.getBytes(); // ключ
private byte[] key = new byte[]{1, 2, 3, 4, 5, 6, 7, 8}; // ключ
// не должен иметь длину более 8 байт, для безопасного шифрования его
// необходимо изменить
@Override
public String getAlgorithm() {
return "DES";
}
@Override
public String getFormat() {
return "RAW";
}
@Override
public byte[] getEncoded() {
return key;
}
@Override
public String toString() {
return String.format("Key - Format: %s, Algorithm: %s", getFormat(), getAlgorithm());
}
}
package ru.ratmir.sequredb.services;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Created RATMIR on 03.01.17.
* Copyright © Ratmir
*/
public class SequreStrings {
/**
* Method String encrypt
* @param securedTextText source
* @param secret Key
* @return array byte
* @throws Exception --
*/
public static byte[] encryptString(String securedTextText, SecretKey secret) throws Exception {
Cipher cipher;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
return cipher.doFinal(securedTextText.getBytes("UTF-8"));
}
/**
* Method decrypt String
* @param cipherText encrypted source
* @param secret Key
* @return decrypted text
* @throws Exception --
*/
public static String decryptString(byte[] cipherText, SecretKey secret) throws Exception {
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
return new String(cipher.doFinal(cipherText), "UTF-8");
}
/**
* Key generator
* @param password user password
* @return SecretKey
* @throws Exception --
*/
public static SecretKey generateKey(String password) throws Exception {
return new SecretKeySpec(password.getBytes(), "AES");
}
}
package ru.ratmir.sequredb.services;
import ru.ratmir.sequredb.data.ProjectModel;
import java.io.*;
import java.nio.file.Files;
/**
* Created RATMIR on 03.01.17.
* Copyright © Ratmir
*/
public final class Writer {
/**
* Write Object to file
* @param key Object EncryptKey
*/
public static void writeKey(EncryptKey key, String filePatch){
try (FileOutputStream fo = new FileOutputStream(filePatch);
ObjectOutputStream serial = new ObjectOutputStream(fo)){
serial.writeObject(key);
serial.flush();
} catch (Exception ex) {
//System.out.println("Ошибка при сериализации объекта");
ex.printStackTrace();
}
}
/**
* Read Object from file
* @param filePatch File patch
* @return Object Encrypt key
*/
public static EncryptKey readKey(String filePatch){
EncryptKey key = null;
try
(FileInputStream fi = new FileInputStream(filePatch);
ObjectInputStream des = new ObjectInputStream(fi)){
key = (EncryptKey) des.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return key;
}
/**
* Write project to file
* @param project project model class
* @param filePatch file patch
*/
public static void writeProjet(ProjectModel project, String filePatch){
try (FileOutputStream fo = new FileOutputStream(filePatch);
ObjectOutputStream serial = new ObjectOutputStream(fo)){
serial.writeObject(project);
serial.flush();
} catch (Exception ex) {
//System.out.println("Ошибка при сериализации объекта");
ex.printStackTrace();
}
}
/**
* Read project model from file
* @param filePatch project file patch
* @return ProjectModel class object
*/
public static ProjectModel readProjectModel(String filePatch){
ProjectModel model = null;
try
(FileInputStream fi = new FileInputStream(filePatch);
ObjectInputStream des = new ObjectInputStream(fi)){
model = (ProjectModel) des.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return model;
}
// простой и удобный метод копирования файла в Java 7
/**
* This method for copy file (Java 7)
* @param source source file
* @param dest dest file
* @throws IOException --
*/
public static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
/**
* This Method for copy file (using stream and try with resource)
* @param source source file
* @param dest dest file
* @throws IOException --
*/
public static void copyFileUsingStream(File source, File dest) throws IOException {
try(InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}
}
}
package ru.ratmir.sequredb.services;
/**
* Created RATMIR on 02.01.17.
* Copyright © Ratmir
*/
public class XorEncrypt {
public static byte[] encrypt(String text, String keyWord)
{
byte[] arr = text.getBytes();
byte[] keyarr = keyWord.getBytes();
byte[] result = new byte[arr.length];
for(int i = 0; i< arr.length; i++)
{
result[i] = (byte) (arr[i] ^ keyarr[i % keyarr.length]);
}
return result;
}
public static String decrypt(byte[] text, String keyWord)
{
byte[] result = new byte[text.length];
byte[] keyarr = keyWord.getBytes();
for(int i = 0; i < text.length;i++)
{
result[i] = (byte) (text[i] ^ keyarr[i% keyarr.length]);
}
return new String(result);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="ru.ratmir.sequredb.views.ColumnsList">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="10" bottom="10" right="10"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<scrollpane id="4f485">
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="5ef6e" class="javax.swing.JList" binding="mList">
<constraints/>
<properties/>
</component>
</children>
</scrollpane>
<component id="b9039" class="javax.swing.JButton" binding="mBtEncrypt">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<enabled value="false"/>
<text value="Encrypt selected"/>
</properties>
</component>
<component id="bb9b7" class="javax.swing.JButton" binding="mBtCansel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Cansel"/>
</properties>
</component>
</children>
</grid>
</form>
package ru.ratmir.sequredb.views;
import ru.ratmir.sequredb.data.DataHelper;
import ru.ratmir.sequredb.data.ProjectModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created RATMIR on 05.01.17.
* Copyright © Ratmir
*/
public class ColumnsList extends JFrame {
private JFrame mFrame;
private JFrame mMainFrame;
private JPanel mainPanel;
private JList mList;
private JButton mBtEncrypt;
private JButton mBtCansel;
private int mainState;
private Dimension mainSize;
private String dataTableName;
private String dataBaseName;
private DataHelper mDataHelper;
private ArrayList<String> column;
private EncryptProgressDialog dialog;
public ColumnsList(JFrame mainFrame,
int state, Dimension size,
String tableName,
String dbName, ProjectModel projectModel) throws HeadlessException {
this.mMainFrame = mainFrame;
this.mainState = state;
this.mainSize = size;
this.dataTableName = tableName;
this.dataBaseName = dbName;
mDataHelper = new DataHelper();
column = new ArrayList<>();
JFrame.setDefaultLookAndFeelDecorated(true);
mFrame = new JFrame("Show Column name");
mFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mFrame.setSize(600, 400);
mFrame.setVisible(true);
mFrame.setResizable(false);
mFrame.setLocationRelativeTo(null);
mFrame.setContentPane(mainPanel);
mList.setModel(new DefaultListModel());
mList.setCellRenderer(new CheckboxListCellRenderer());
DefaultListModel listModel = new DefaultListModel();
try {
ArrayList<String> fields = mDataHelper.getColumnName(dataTableName, dataBaseName);
for (String field : fields) {
//Added new item data
listModel.addElement(new CheckableItem(field));
}
mList.setModel(listModel);
} catch (SQLException | ClassNotFoundException e1) {
e1.printStackTrace();
}
mList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mBtCansel.addActionListener(e -> {
mainFrame.setExtendedState(state);
mainFrame.setSize(mainSize);
mainFrame.setLocationRelativeTo(null);
mFrame.setVisible(false);
mFrame.dispose();
});
mBtEncrypt.addActionListener(e -> {
if (dialog == null) // в первый раз
try {
dialog = new EncryptProgressDialog(ColumnsList.this,
column, projectModel, dataTableName);
//Записать в HashMap имя таблицы и выбранные столбцы
//Этот HashMap необходим для дальнейшего поиска и розшифровки в
//андроид приложении.
//Сохранять список нужно в объекте ключа и добавлять в файл проэкта
} catch (SQLException | ClassNotFoundException e1) {
e1.printStackTrace();
}
// !!!! Нужно сохранить результат выделенных полей из этой базы
//
dialog.setVisible(true); // отобразить диалог
mainFrame.setExtendedState(state);
mainFrame.setSize(mainSize);
mainFrame.setLocationRelativeTo(null);
mFrame.setVisible(false);
mFrame.dispose();
});
mList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int index = mList.locationToIndex(e.getPoint());
CheckableItem item = (CheckableItem) mList.getModel().getElementAt(index);
mList.setSelectedIndex(index);
item.setSelected(!item.isSelected());
Rectangle rect = mList.getCellBounds(index, index);
mList.repaint(rect);
if (item.isSelected) {
column.add(item.toString());
} else {
column.remove(item.toString());
}
if (!mBtEncrypt.isEnabled()) {
mBtEncrypt.setEnabled(true);
}
}
});
}
public class CheckableItem {
private String str;
private boolean isSelected;
public CheckableItem(String str) {
this.str = str;
isSelected = false;
}
public void setSelected(boolean b) {
isSelected = b;
}
public boolean isSelected() {
return isSelected;
}
public String toString() {
return str;
}
}
public class CheckboxListCellRenderer extends JCheckBox implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
setComponentOrientation(list.getComponentOrientation());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setSelected(((CheckableItem) value).isSelected());
setEnabled(list.isEnabled());
setText(value == null ? "" : value.toString());
return this;
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="ru.ratmir.sequredb.views.EncryptProgressDialog">
<grid id="cbd77" binding="contentPane" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="10" bottom="10" right="10"/>
<constraints>
<xy x="48" y="54" width="436" height="297"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="2247a" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="8b619" class="javax.swing.JProgressBar" binding="mProgressEncrypt">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="68dd3" class="javax.swing.JLabel" binding="mLbTitle">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Label"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
</form>
package ru.ratmir.sequredb.views;
import ru.ratmir.sequredb.data.DataHelper;
import ru.ratmir.sequredb.data.ProjectModel;
import ru.ratmir.sequredb.services.Constant;
import javax.swing.*;
import java.sql.SQLException;
import java.util.ArrayList;
public class EncryptProgressDialog extends JDialog {
private JDialog mJDialog; // для передачи себя в управление фоновому потоку
private JPanel contentPane;
private JProgressBar mProgressEncrypt;
private JLabel mLbTitle;
private BoundedRangeModel model;
private DataHelper mDataHelper; // Класс для работы с базой
private ProjectModel mProjectModel; // Хранит ссылку на модель проэкта
private String tableName;
private ArrayList<String>mColumn;
EncryptProgressDialog(JFrame owner, ArrayList<String> column,
ProjectModel projectModel, String tableName)
throws SQLException, ClassNotFoundException {
super(owner, "Encrypt progress dialog", true);
setContentPane(contentPane);
setSize(260, 160);
setResizable(false);
setLocationRelativeTo(null);
mJDialog = this;
this.mProjectModel = projectModel;// получаем ссылку на модель проэкта
this.tableName = tableName;// Имя таблицы
this.mColumn = column; // выделенные столбцы
mDataHelper = new DataHelper();// экземпляр базы данных
//Выполняем шифровку базы в фоновом потоке
new ThreadProcess().start();
}
class ThreadProcess extends Thread {
public void run() {
// Тут будем работать с базой !!!
//
// -Заполнить модель
// -Зашифровать
// -Обновить базу
String dbPatch = mProjectModel.getDataBasePatch().getAbsolutePath();// dbName
// Get table and encrypt rows
for (String t: mColumn) {
if(t.contains(Constant.DATA_BASE_KEY_PATTERN))
continue;// If this column is PRIMARY or FOREIGN KEY this
// field DO NOT ENCRYPT !!!!
int count = 0;
try {
count = mDataHelper.getCountRowsInTable(dbPatch, tableName);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
mLbTitle.setText("Encrypt column: \"" + t +"\"");// добавить имя столбца в базу
model = new DefaultBoundedRangeModel(0, 0, 0, count);
mProgressEncrypt.setStringPainted(true);
mProgressEncrypt.setModel(model);
// Проверка завершения процесса
while ( model.getValue() < model.getMaximum() ) {
try {
// Увеличение текущего значение
model.setValue(model.getValue() + 1);
// Временная задержка
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Получаем значение из базы, шифруем и обновляем запись по id
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
model.setValue(0);
}
mJDialog.setVisible(false);
mJDialog.dispose();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="ru.ratmir.sequredb.views.MainView">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="10" bottom="10" right="10"/>
<constraints>
<xy x="20" y="20" width="500" height="492"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<scrollpane id="94744">
<constraints>
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="d042b" class="javax.swing.JTable" binding="mTableMain">
<constraints/>
<properties/>
</component>
</children>
</scrollpane>
<component id="c0e18" class="javax.swing.JLabel" binding="mLbTitle">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Data base table list"/>
</properties>
</component>
<grid id="9f914" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<scrollpane id="860c">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="39e5c" class="javax.swing.JTextArea" binding="mTxtLog">
<constraints/>
<properties>
<editable value="false"/>
<rows value="10"/>
</properties>
<clientProperties>
<caretWidth class="java.lang.Integer" value="0"/>
</clientProperties>
</component>
</children>
</scrollpane>
</children>
</grid>
</children>
</grid>
</form>
package ru.ratmir.sequredb.views;
import ru.ratmir.sequredb.data.DataHelper;
import ru.ratmir.sequredb.data.ProjectModel;
import ru.ratmir.sequredb.services.Constant;
import ru.ratmir.sequredb.services.Writer;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created RATMIR on 04.01.17.
* Copyright © Ratmir
*/
public class MainView extends JFrame{
private JFrame frame;
private JPanel mainPanel;
private JLabel mLbTitle;
private JTable mTableMain;
private JTextArea mTxtLog;
private ProjectModel projectModel;//project class
DataHelper mDataHelper;
String dbPatch = "/Users/sergejudovitskij/Documents/2/DataBaseWork/TestData.sqlite";
public MainView() throws SQLException, ClassNotFoundException {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Encrypt Decrypt Data Base");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Создание строки главного меню
JMenuBar menuBar = new JMenuBar();
// Добавление в главное меню выпадающих пунктов меню
menuBar.add(createFileMenu());
menuBar.add(createEditMenu());
menuBar.add(createViewMenu());
// Подключаем меню к интерфейсу приложения
frame.setJMenuBar(menuBar);
frame.setSize(600, 400);
frame.setVisible(true);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setContentPane(mainPanel);
mDataHelper = new DataHelper();
}
//--------------------------------------------------------
/**
* Функция создания меню "Файл"
*
* @return tasting
*/
private JMenu createFileMenu() {
// Создание выпадающего меню
JMenu file = new JMenu("File");
//Новый проэкт
JMenuItem newData = new JMenuItem("New project");
//Добавить базу данных
JMenuItem openDataBase = new JMenuItem("Add data base");
openDataBase.setEnabled(false);
// Пункт меню "Открыть" с изображением
JMenuItem open = new JMenuItem("Open project");
open.setEnabled(false);
//Пункт меню закрыть
JMenuItem close = new JMenuItem("Close project");
close.setEnabled(false);
//Пункт сохранить проект
JMenuItem save = new JMenuItem("Save project");
save.setEnabled(false);
// Пункт меню из команды с выходом из программы
JMenuItem exit = new JMenuItem(new ExitAction());
// Добавление к пункту меню изображения
//exit.setIcon(new ImageIcon("images/exit.png"));
// Добавим в меню пункты
file.add(newData);
file.add(openDataBase);
file.add(open);
file.add(save);
file.add(close);
file.addSeparator();
file.add(exit);
/**
* Open project
*/
open.addActionListener(e -> {
});
/**
* Close project
*/
close.addActionListener(e -> {
//Save project file (with settings)
});
/**
* New project
*/
newData.addActionListener(e -> {
//Create new project
projectModel = ProjectModel.getInstance();//Create project file
projectModel.setProjectFilePatch(createNewProjectDialog());
mLbTitle.setText("Project Name: ("
+ projectModel.getProjectFilePatch().getName() + ")");
mTxtLog.append(String.format("File patch: %s\nFile Name: %s",
projectModel.getProjectFilePatch().getParent(),
projectModel.getProjectFileName()));
openDataBase.setEnabled(true);
newData.setEnabled(false);
///Create directory for project
new File(projectModel.getProjectFilePatch().getAbsolutePath()).mkdir();
//copy database in project folder, append '.temp'
});
/**
* Open data base
*/
openDataBase.addActionListener(e -> {
mTableMain.setModel(new DefaultTableModel());
openDataBaseFile(openDataBase, save, close, open);
/*mTxtLog.append("New Data Patch: " + projectModel.getDataBasePatch() + "\n");
mTxtLog.append("Data Base tmp: " + projectModel.getTempDataBaseName() + "\n");
mTxtLog.append("Tmp db file patch: " + projectModel.getTempDataBaseFilePatch() + "\n");
*/
mLbTitle.setText(projectModel.getDataBasePatch().getAbsolutePath());
createEditMenu().setEnabled(true);
readDataBaseTablesName(projectModel.getDataBasePatch().getAbsolutePath());
mTxtLog.setText("");
mTxtLog.append("Project Patch " + projectModel.getProjectFilePatch().getAbsolutePath() + "\n");
mTxtLog.append("Project Name " + projectModel.getProjectFileName() + "\n");
mTxtLog.append("Project ENC DB NAME " + projectModel.getEncDataBaseFileName() + "\n");
mTxtLog.append("Project DB NAME " + projectModel.getDataBaseName() + "\n");
mTxtLog.append("Project OP ID " + projectModel.getOperationId() + "\n");
mTxtLog.append("Project DB PATCH " + projectModel.getDataBasePatch().getAbsolutePath() + "\n");
mTxtLog.append("Project PR KEY " + projectModel.getProjectKey().toString() + "\n");
mTxtLog.append( "SAVE IN: " + projectModel.getProjectFilePatch().getAbsolutePath()
+ "/" + projectModel.getProjectFileName() + "\n");
mTxtLog.append("PR DIR: " + projectModel.getProjectFolder() + "\n");
mTxtLog.append("New Data Patch: " + projectModel.getDataBasePatch() + "\n");
mTxtLog.append("Data Base tmp: " + projectModel.getTempDataBaseName() + "\n");
mTxtLog.append("Tmp db file patch: " + projectModel.getTempDataBaseFilePatch() + "\n");
openDataBase.setEnabled(false);
mTableMain.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.invokeLater(() -> {
String t = (String) mTableMain.getValueAt(mTableMain.getSelectedRow(), 0);
// Окно подтверждения c 4-мя параметрами
int result = JOptionPane.showConfirmDialog(
MainView.this,
"Show this (" + t + ") tables field ?",
null,
JOptionPane.YES_NO_OPTION);
// Окна подтверждения c 2-мя параметрами
if (result == JOptionPane.YES_OPTION) {
//TO DO Show new view with table field
Dimension s = frame.getSize();
int stat = getState();
SwingUtilities.invokeLater(() -> {
new ColumnsList(frame, stat, s, t.trim(),
projectModel.getDataBasePatch().getAbsolutePath(), projectModel);
});
frame.setExtendedState(JFrame.ICONIFIED);
} else if (result == JOptionPane.NO_OPTION) {
/*JOptionPane.showConfirmDialog(MainView.this,
"Вы отказались?");*/
}
/*JOptionPane.showConfirmDialog(MainView.this,
"Open view this: " + t + " table field ?");*/
});
}
}
});
});
/**
* Save project to file
*/
save.addActionListener(e -> {
//mkdirs();
File f = new File(projectModel.getProjectFilePatch().getAbsolutePath());
f.mkdir();
Writer.writeProjet(projectModel,
projectModel.getProjectFilePatch().getAbsolutePath() + "/" +
projectModel.getProjectFileName());
});
return file;
}
//--------------------------------------------------------
// создадим забавное меню
/**
* Функция создания меню
*
* @return tasting
*/
private JMenu createViewMenu() {
// создадим выпадающее меню
JMenu viewMenu = new JMenu("View");
JMenuItem clearLog = new JMenuItem("Clear log");
// меню-флажки
JCheckBoxMenuItem line = new JCheckBoxMenuItem("Line");
JCheckBoxMenuItem grid = new JCheckBoxMenuItem("Grid");
JCheckBoxMenuItem navig = new JCheckBoxMenuItem("Nav");
// меню-переключатели
JRadioButtonMenuItem one = new JRadioButtonMenuItem("One Pages");
JRadioButtonMenuItem two = new JRadioButtonMenuItem("Two Pages");
// организуем переключатели в логическую группу
ButtonGroup bg = new ButtonGroup();
bg.add(one);
bg.add(two);
// добавим все в меню
viewMenu.add(clearLog);
viewMenu.addSeparator();
viewMenu.add(line);
viewMenu.add(grid);
viewMenu.add(navig);
// разделитель можно создать и явно
viewMenu.add(new JSeparator());
viewMenu.add(one);
viewMenu.add(two);
clearLog.addActionListener(e -> System.out.println(""));
return viewMenu;
}
/**
* Menu Edit
* @return menu Edit
*/
private JMenu createEditMenu() {
JMenu createMenu = new JMenu("Edit");
//createMenu.setEnabled(false);
//Новый проэкт
JMenuItem encryptData = new JMenuItem("EncryptData");
// Добавим в меню пункты
createMenu.add(encryptData);
encryptData.addActionListener(e->{
JOptionPane.showMessageDialog(this,
"<html>" +
"<h2 style='color: red;'>Encrypt Data base</h2>" +
"<i>Data base be encrypted.</i>" +
"<h2 style='color: #ff0000;'>" +
"Data base be saved like - \"dbName.sqlite.tmp\"</h2>" +
"</html>",
"Test Message",
JOptionPane.WARNING_MESSAGE);
//After thad save data base with name, show progress dialog encrypt data base
});
return createMenu;
}
//--------------------------------------------------------
/**
* Вложенный класс завершения работы приложения
*/
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
ExitAction() {
putValue(NAME, "Exit");
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
//-
private File createNewProjectDialog() {
//TO DO: most return only file
JFileChooser dialog = new JFileChooser();
dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter =
new FileNameExtensionFilter("Encrypt data project file",
Constant.FILE_EXTENSION_PROJECT);
dialog.setFileFilter(filter);
//!!!!!!!!!this is for debug
dialog.setCurrentDirectory(new File("/Users/sergejudovitskij/Desktop"));
//dialog.setApproveButtonText("Select");//выбрать название для кнопки согласия
dialog.setDialogTitle("Select project patch");// выбрать название
dialog.setDialogType(JFileChooser.SAVE_DIALOG);// выбрать тип диалога Open или Save
dialog.showSaveDialog(this);
if (dialog.getSelectedFile() != null) {
return new File(dialog.getSelectedFile().getAbsolutePath());
}else return null;
}
private void openDataBaseFile(JMenuItem openData,
JMenuItem save,
JMenuItem close,
JMenuItem open) {
JFileChooser fileOpen = new JFileChooser();
FileNameExtensionFilter filter =
new FileNameExtensionFilter("SQLite data base files",
"sqlite", "db");
fileOpen.setFileFilter(filter);
int ret = fileOpen.showDialog(null, "Open File");
if (ret == JFileChooser.APPROVE_OPTION) {
projectModel.setDataBasePatch(fileOpen.getSelectedFile());
//Copy data base file in project folder
//Create temp file from data base
File fSource = projectModel.getDataBasePatch();
File fDest = new File(projectModel.getProjectFilePatch().getAbsolutePath()
+ "/" + projectModel.getDataBaseName() + Constant.DATA_BASE_TEMPORARY_EXTENDED);
File fDataBase = new File(projectModel.getProjectFilePatch().getAbsolutePath()
+ "/" + projectModel.getDataBaseName() );
try {
Writer.copyFileUsingStream(fSource, fDest);
Writer.copyFileUsingStream(fSource, fDataBase);
projectModel.setDataBasePatch(new File(projectModel.getProjectFilePatch().getAbsolutePath()
+ "/" + projectModel.getDataBaseName()));
projectModel.setTempDataBaseFilePatch(new File(projectModel.getProjectFilePatch().getAbsolutePath()
+ "/" + projectModel.getDataBaseName() + Constant.DATA_BASE_TEMPORARY_EXTENDED));
} catch (IOException e1) {
e1.printStackTrace();
}
//Create temporary data base file in project dir
//Mast replace file patch in project file
openData.setEnabled(false);
save.setEnabled(true);
close.setEnabled(true);
open.setEnabled(false);
}
}
private void readDataBaseTablesName(String dbName) {
ArrayList<String> dbTableName = new ArrayList<>();
try {
dbTableName = mDataHelper.getAllTableName(dbName);
} catch (SQLException | ClassNotFoundException e1) {
e1.printStackTrace();
}
DefaultTableModel tModel = new DefaultTableModel();
tModel.setColumnIdentifiers(new String[]{"Table Names"});
try {
for (String t : dbTableName) {
tModel.addRow(new Object[]{t});
}
} catch (Exception e1) {
e1.printStackTrace();
}
mTableMain.setModel(tModel);
}
//test
private void chosFolder(){
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("choosertitle");
chooser.setCurrentDirectory(new File("/Users/sergejudovitskij/Desktop"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String c = chooser.getCurrentDirectory().toString();
// аналогично можно поймать и файл
mTxtLog.append(String.format("Dir: %s\n",c));
} else {
System.out.println("No Selection ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment