remove MySql references

switch to DIYLC php-based service
This commit is contained in:
bancika
2016-10-21 12:35:35 +02:00
parent 8850616584
commit 0c75ab2b5a
12 changed files with 223 additions and 304 deletions
@@ -13,6 +13,7 @@
<classpathentry kind="lib" path="lib/org-openide-util-lookup.jar"/>
<classpathentry kind="lib" path="lib/app-framework.jar"/>
<classpathentry kind="lib" path="lib/swing-framework.jar"/>
<classpathentry kind="lib" path="lib/http-proxy.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/diylc-core"/>
<classpathentry kind="lib" path="lib/xstream-1.4.3.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk1.6.0_45"/>
@@ -45,15 +45,15 @@ public class OnlineManager implements IPlugIn {
@Override
protected Void doInBackground() throws Exception {
libraryPresenter.connectDb();
//libraryPresenter.connectDb();
return null;
}
@Override
protected void done() {
if (libraryPresenter.isLoggedIn()) {
}
// if (libraryPresenter.isLoggedIn()) {
//
// }
}
};
worker.execute();
@@ -1,28 +0,0 @@
package org.diylc.swing.plugins.online;
import org.apache.log4j.BasicConfigurator;
import org.diylc.swing.plugins.online.presenter.LibraryPresenter;
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
BasicConfigurator.configure();
LibraryPresenter pres = new LibraryPresenter();
// pres.createUser("bancika", "pwd", "bancika@gmail.com");
System.out.println(pres.fetchCategories());
pres.login("bancika", "pwd");
int id = pres.fetchMyProjectRows().get(0).getId();
// InputStream stream = pres.downloadProjectContent(id);
// byte[] buf = new byte[100];
// int len = stream.read(buf);
System.out.println(pres.downloadProjectContent(id));
// System.out.println(pres.hashPassword("bancikabancikabancikabancikabancika"));
pres.dispose();
}
}
@@ -1,12 +1,7 @@
package org.diylc.swing.plugins.online.model;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
public class ProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
@@ -16,18 +11,26 @@ public class ProjectEntity implements Serializable {
private String description;
private String owner;
private String category;
private String updated;
private String thumbnailUrl;
private String downloadUrl;
public ProjectEntity() {
super();
}
public ProjectEntity(int id, String name, String description, String owner, String category) {
public ProjectEntity(int id, String name, String description, String owner,
String category, String updated, String thumbnailUrl,
String downloadUrl) {
super();
this.id = id;
this.name = name;
this.description = description;
this.owner = owner;
this.category = category;
this.updated = updated;
this.thumbnailUrl = thumbnailUrl;
this.downloadUrl = downloadUrl;
}
public int getId() {
@@ -70,28 +73,59 @@ public class ProjectEntity implements Serializable {
this.category = category;
}
public Action getDownload() {
Action a = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, name);
}
};
a.putValue(AbstractAction.NAME, "Download");
return a;
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
// public Action getDownload() {
//
// Action a = new AbstractAction() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// JOptionPane.showMessageDialog(null, name);
// }
// };
// a.putValue(AbstractAction.NAME, "Download");
// return a;
// }
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result
+ ((category == null) ? 0 : category.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result
+ ((downloadUrl == null) ? 0 : downloadUrl.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result
+ ((thumbnailUrl == null) ? 0 : thumbnailUrl.hashCode());
result = prime * result + ((updated == null) ? 0 : updated.hashCode());
return result;
}
@@ -114,6 +148,11 @@ public class ProjectEntity implements Serializable {
return false;
} else if (!description.equals(other.description))
return false;
if (downloadUrl == null) {
if (other.downloadUrl != null)
return false;
} else if (!downloadUrl.equals(other.downloadUrl))
return false;
if (id != other.id)
return false;
if (name == null) {
@@ -126,11 +165,21 @@ public class ProjectEntity implements Serializable {
return false;
} else if (!owner.equals(other.owner))
return false;
if (thumbnailUrl == null) {
if (other.thumbnailUrl != null)
return false;
} else if (!thumbnailUrl.equals(other.thumbnailUrl))
return false;
if (updated == null) {
if (other.updated != null)
return false;
} else if (!updated.equals(other.updated))
return false;
return true;
}
@Override
public String toString() {
return name;
return name + " by " + owner + " updated on " + updated;
}
}
@@ -1,6 +1,6 @@
package org.diylc.swing.plugins.online.presenter;
public class AlreadyExistsException extends Exception {
public class DIYLCServiceException extends Exception {
private static final long serialVersionUID = 1L;
@@ -0,0 +1,137 @@
package org.diylc.swing.plugins.online.presenter;
import java.io.File;
import java.util.List;
import org.diylc.swing.plugins.online.model.ProjectEntity;
import com.diyfever.httpproxy.ParamName;
/***
* Interface of DIYLC PHP server located at www.diy-fever.com/diylc/api
*
* @author bancika
*
*/
public interface IServiceAPI {
public static final String URL_KEY = "serviceUrl";
/**
* Creates a user with the specified details.
*
* @param username
* @param password
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it
* failed.
*/
String createUser(@ParamName("username") String username,
@ParamName("password") String password,
@ParamName("email") String email,
@ParamName("website") String website, @ParamName("bio") String bio);
/***
* Updates user details using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it
* failed.
*/
String updateUser(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId,
@ParamName("email") String email,
@ParamName("website") String website, @ParamName("bio") String bio);
/***
* Tries to login with the provided credentials and machineId.
*
* @param username
* @param password
* @param machineId
* @return login token if the login was successful or string literal "Error"
* if it failed.
*/
String login(@ParamName("username") String username,
@ParamName("password") String password,
@ParamName("machineId") String machineId);
/***
* Tries to authenticate with the token that was previously created by
* calling login() function.
*
* @param username
* @param password
* @param machineId
* @return "Success" if the login is successful or error message if it
* failed.
*/
String loginWithToken(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId);
/***
* Searches for projects that meet the specified search criteria. Supports
* pagination.
*
* @param criteria
* @param category
* @param format
* @param page
* @param itemsPerPage
* @param sort
* @return string with error message if the error occurred or a list of
* {@link ProjectEntity} objects.
*/
Object search(@ParamName("criteria") String criteria,
@ParamName("category") String category,
@ParamName("format") String format,
@ParamName("page") Integer page,
@ParamName("itemsPerPage") Integer itemsPerPage,
@ParamName("sort") String sort);
/**
* Uploads a project using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param projectName
* @param category
* @param description
* @param diylcVersion
* @param keywords
* @param thumbnail
* @param project
* @return "Success" if the upload was successful or error message if it
* failed.
*/
String upload(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId,
@ParamName("projectName") String projectName,
@ParamName("category") String category,
@ParamName("description") String description,
@ParamName("diylcVersion") String diylcVersion,
@ParamName("keywords") String keywords,
@ParamName("thumbnail") File thumbnail,
@ParamName("thumbnail") File project);
/**
* @return a {@link List} of available categories.
*/
List<String> getCategories();
/**
* @return a {@link List} of available sortings.
*/
List<String> getAvailableSortings();
}
@@ -1,177 +1,23 @@
package org.diylc.swing.plugins.online.presenter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.diylc.swing.plugins.online.model.ProjectEntity;
import org.diylc.appframework.miscutils.ConfigurationManager;
import com.diyfever.httpproxy.PhpFlatProxy;
import com.diyfever.httpproxy.ProxyFactory;
public class LibraryPresenter {
private final static Logger LOG = Logger.getLogger(LibraryPresenter.class);
private static final String DB_HOST = "diy-fever.com";
private static final String DB_PORT = "3306";
private static final String DB_USER = "diylc-app";
private static final String DB_PASS = "zuf7RuS8";
private static final String CATEGORY_SQL = "SELECT * FROM diylc.category WHERE 1=1";
private static final String USER_SQL = "SELECT * FROM diylc.user WHERE name = \"%s\"";
private static final String CREATE_USER_SQL = "INSERT INTO diylc.user (name, password, email) VALUES (\"%s\", \"%s\", \"%s\")";
private static final String MY_PROJECTS_SQL = "SELECT project_id, name, category_id, description FROM diylc.project WHERE owner_user_id = %s";
private static final String PROJECT_SQL = "SELECT content FROM diylc.project WHERE project_id = %s";
private static final String UPLOAD_PROJECT_SQL = "INSERT INTO diylc.project (name, description, content, category_id, owner_user_id) VALUES (\"%s\", \"%s\", \"%s\", %s, %s)";
private static final String UPDATE_PROJECT_SQL = "UPDATE diylc.project SET name = \"%s\", description = \"%s\", content = \"%s\", category_id = %s WHERE project_id = %s";
private MySqlDBManager dbManager;
private MessageDigest messageDigest;
private Integer currentUserId;
private IServiceAPI service;
private String serviceUrl;
public LibraryPresenter() {
dbManager = new MySqlDBManager(DB_HOST, DB_PORT, DB_USER, DB_PASS);
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
LOG.error("Could not initialize MD5, algorithm not found.");
}
serviceUrl = ConfigurationManager.getInstance().readString(
IServiceAPI.URL_KEY, "http://www.diy-fever.com/diylc/api");
ProxyFactory factory = new ProxyFactory(new PhpFlatProxy());
service = factory.createProxy(IServiceAPI.class, serviceUrl);
}
public boolean connectDb() {
try {
dbManager.connectDB();
return true;
} catch (Exception e) {
LOG.error("Could not connect to the database: " + e.getMessage());
return false;
}
}
public void createUser(String userName, String password, String email) throws SQLException,
NotConnectedException, AlreadyExistsException {
LOG.info("Creating user: " + userName);
if (dbManager.isConnected()) {
ResultSet resultSet = dbManager.getResultSet(String.format(USER_SQL, userName));
if (resultSet.next()) {
throw new AlreadyExistsException();
}
dbManager.updateDB(String.format(CREATE_USER_SQL, userName, hashPassword(password),
email));
resultSet = dbManager.getResultSet(String.format(USER_SQL, userName));
if (resultSet.next()) {
LOG.info("Logged in as \"" + userName + "\"");
currentUserId = resultSet.getInt("user_id");
}
} else {
LOG.error("Not connected");
throw new NotConnectedException();
}
}
public boolean login(String userName, String password) throws SQLException,
NotConnectedException {
LOG.info("Logging in as: " + userName);
if (dbManager.isConnected()) {
ResultSet resultSet = dbManager.getResultSet(String.format(USER_SQL, userName));
if (resultSet.next()) {
String dbPassword = resultSet.getString("password");
String hashPassword = hashPassword(password);
if (dbPassword.equals(hashPassword)) {
LOG.info("Logged in as \"" + userName + "\"");
currentUserId = resultSet.getInt("user_id");
} else {
LOG.info("User name and password do not match.");
}
}
return false;
} else {
LOG.error("Not connected");
throw new NotConnectedException();
}
}
public Map<Integer, String> fetchCategories() throws SQLException, NotConnectedException {
LOG.info("Fetching categories");
if (dbManager.isConnected()) {
Map<Integer, String> categories = new HashMap<Integer, String>();
ResultSet resultSet = dbManager.getResultSet(CATEGORY_SQL);
while (resultSet.next()) {
categories.put(resultSet.getInt("category_id"), resultSet.getString("name"));
}
return categories;
} else {
LOG.error("Not connected");
throw new NotConnectedException();
}
}
public List<ProjectEntity> fetchMyProjectRows() throws NotLoggedInException,
NotConnectedException, SQLException {
if (dbManager.isConnected()) {
if (isLoggedIn()) {
Map<Integer, String> categories = fetchCategories();
List<ProjectEntity> projects = new ArrayList<ProjectEntity>();
ResultSet resultSet = dbManager.getResultSet(String.format(MY_PROJECTS_SQL,
currentUserId));
while (resultSet.next()) {
projects.add(new ProjectEntity(resultSet.getInt("project_id"), resultSet
.getString("name"), resultSet.getString("description"), "", categories
.get(resultSet.getInt("category_id"))));
}
return projects;
} else {
LOG.error("Not logged in");
throw new NotLoggedInException();
}
} else {
LOG.error("Not connected");
throw new NotConnectedException();
}
}
public String downloadProjectContent(int projectId) throws NotConnectedException,
NotExistsException, SQLException {
if (dbManager.isConnected()) {
ResultSet resultSet = dbManager.getResultSet(String.format(PROJECT_SQL, projectId));
if (resultSet.next()) {
return resultSet.getString("content");
}
throw new NotExistsException("Project with id = " + projectId + " does not exist.");
} else {
LOG.error("Not connected");
throw new NotConnectedException();
}
}
public List<ProjectEntity> fetchProjectRows(String searchCriteria) {
return null;
}
public boolean isLoggedIn() {
return currentUserId != null;
}
public String hashPassword(String password) {
messageDigest.reset();
byte[] bytes = messageDigest.digest(password.getBytes());
String md5 = "";
for (byte b : bytes) {
String str = Integer.toHexString(b);
if (str.length() == 1) {
str = "0" + str;
}
md5 += str.substring(str.length() - 2);
}
return md5;
}
public void dispose() {
dbManager.closeConnection();
}
}
@@ -1,86 +0,0 @@
package org.diylc.swing.plugins.online.presenter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
public class MySqlDBManager {
private final static Logger LOG = Logger.getLogger(MySqlDBManager.class);
protected Connection connection;
protected Statement statement;
protected ResultSet resultSet;
protected String url;
protected String user;
protected String pass;
protected boolean connected;
public MySqlDBManager(String url, String user, String pass) {
this.url = url;
this.user = user;
this.pass = pass;
this.connected = false;
}
public MySqlDBManager(String host, String port, String userName, String password) {
this(String.format("jdbc:mysql://%s%s", host, port.trim().equals("") ? "" : (":" + port)),
userName, password);
}
public void connectDB() throws Exception {
if (!connected) {
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
DriverManager.registerDriver(driver);
String finalUrl = String.format("%s?user=%s&password=%s", url, user, pass);
LOG.info("Trying to connect to: " + url);
connection = DriverManager.getConnection(finalUrl);
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connected = true;
}
}
public boolean isConnected() {
return connected;
}
public void closeConnection() {
LOG.info("Closing connection.");
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
connected = false;
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getResultSet(String query) throws SQLException {
LOG.info("Executing query: " + query);
resultSet = statement.executeQuery(query);
return resultSet;
}
public Connection getConnection() {
return connection;
}
public int updateDB(String query) throws SQLException {
LOG.info("Executing query: " + query);
statement.execute(query);
return statement.getUpdateCount();
}
}
@@ -22,8 +22,8 @@ public class TableTest {
BasicConfigurator.configure();
List<ProjectEntity> projects = new ArrayList<ProjectEntity>();
projects.add(new ProjectEntity(1, "first", "some text", "bane", "none"));
projects.add(new ProjectEntity(2, "second", "anoter text", "bisera", "none"));
projects.add(new ProjectEntity(1, "first", "some text", "bane", "none", "", "", ""));
projects.add(new ProjectEntity(2, "second", "anoter text", "bisera", "none", "", "", ""));
ObjectListTable<ProjectEntity> t = new ObjectListTable<ProjectEntity>(ProjectEntity.class,
new String[] { "getName", "getDescription", "getCategory", "getOwner",