Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions egiby/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,44 @@
<artifactId>jcommander</artifactId>
<version>1.48</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.fizteh.fivt.students.egiby.miniorm;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
* Created by egiby on 18.12.15.
*/

@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String name() default "";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
package ru.fizteh.fivt.students.egiby.miniorm;

import org.h2.jdbcx.JdbcConnectionPool;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
* Created by egiby on 17.12.15.
*/
public class DatabaseService<T> implements Closeable {
private Class<T> workingClass;

private String connectionName;
private String username;
private String password;

private String tableName;
private Field[] fields;
private int primaryKeyId = -1;

private JdbcConnectionPool databasePool;

private void parseProperties(String properties) {
Properties settings = new Properties();

try (InputStream input = this.getClass().getResourceAsStream(properties)) {
settings.load(input);
} catch (IOException e) {
e.printStackTrace();
}

connectionName = settings.getProperty("connection_name");
username = settings.getProperty("username");
password = settings.getProperty("password");
}

private void init() throws IllegalArgumentException {
parseProperties("/h2.properties");
if (!workingClass.isAnnotationPresent(Table.class)) {
throw new IllegalArgumentException("table class without @Table annotation");
}

tableName = workingClass.getName();
if (tableName.equals("")) {
tableName = NamesHelper.convert(workingClass.getSimpleName());
}

if (!NamesHelper.isGood(tableName)) {
throw new IllegalArgumentException("bad table name");
}

List<Field> allFields = new ArrayList<>();
Set<Field> set = new HashSet<>();

for (Field f: workingClass.getDeclaredFields()) {
if (f.isAnnotationPresent(Column.class)) {
if (!NamesHelper.isGood(f.getName())) {
throw new IllegalArgumentException("bad column name");
}

allFields.add(f);
set.add(f);

if (f.isAnnotationPresent(PrimaryKey.class)) {
if (primaryKeyId != -1) {
throw new IllegalArgumentException("not single @PrimaryKey");
}

primaryKeyId = allFields.size() - 1;
}
} else if (f.isAnnotationPresent(PrimaryKey.class)) {
throw new IllegalArgumentException("@PrimaryKey, but not @Column");
}
}

if (set.size() != allFields.size()) {
throw new IllegalArgumentException("There are two columns with one name");
}

fields = new Field[allFields.size()];
allFields.toArray(fields);

databasePool = JdbcConnectionPool.create(connectionName, username, password);
}

DatabaseService(Class<T> className) {
workingClass = className;
init();
}

private void executeSimpleRequest(String request) throws SQLException {
try (Connection connection = databasePool.getConnection()) {
connection.createStatement().execute(request);
}
}

public void createTable() throws SQLException {
StringBuilder request = new StringBuilder();
request.append("CREATE TABLE IF NOT EXISTS ");
request.append(tableName + "(");
for (int i = 0; i < fields.length; ++i) {
request.append(fields[i].getName() + " " + NamesHelper.getSQLTypeName(fields[i].getType()));
if (i == primaryKeyId) {
request.append(" PRIMARY KEY ");
}

if (i != fields.length - 1) {
request.append(", ");
}
}

request.append(")");
executeSimpleRequest(request.toString());
}

public void dropTable() throws SQLException {
String request = "DROP TABLE IF EXISTS " + tableName;
executeSimpleRequest(request.toString());
}

public void delete(T record) throws IllegalArgumentException, SQLException, IllegalAccessException {
if (primaryKeyId == -1) {
throw new IllegalArgumentException("There is no primary key in the table");
}

StringBuilder request = new StringBuilder();

request.append("DELETE FROM " + tableName + " ").append("WHERE ").
append(fields[primaryKeyId].getName()).append(" = ?");

try (Connection connection = databasePool.getConnection()) {
PreparedStatement statement
= connection.prepareStatement(request.toString());
statement.setObject(1, fields[primaryKeyId].get(record));
statement.execute();
}
}

public void insert(T record) throws SQLException, IllegalAccessException {
StringBuilder request = new StringBuilder();

request.append("INSERT INTO " + tableName + " VALUES(");
for (int i = 0; i < fields.length; ++i) {
request.append("?");
if (i != fields.length - 1) {
request.append(", ");
}
}
request.append(")");

try (Connection connection = databasePool.getConnection()) {
PreparedStatement statement
= connection.prepareStatement(request.toString());
for (int i = 0; i < fields.length; ++i) {
statement.setObject(i + 1, fields[i].get(record));
}

statement.execute();
}
}

public void update(T record) throws IllegalArgumentException, SQLException, IllegalAccessException {
if (primaryKeyId == -1) {
throw new IllegalArgumentException("There is no primary key in the table");
}

StringBuilder request = new StringBuilder();

request.append("UPDATE TABLE " + tableName).append(" SET ");
for (int i = 0; i < fields.length; ++i) {
if (i == primaryKeyId) {
continue;
}

request.append(fields[i].getName() + " = ?");
if (i != fields.length - 1) {
request.append(", ");
}
}

request.append(" WHERE ").append(fields[primaryKeyId].getName() + " = ?");

try (Connection connection = databasePool.getConnection()) {
PreparedStatement statement
= connection.prepareStatement(request.toString());
int current = 1;
for (int i = 0; i < fields.length; ++i) {
if (i != primaryKeyId) {
statement.setObject(current++, fields[i].get(record));
}
}

statement.setObject(current, fields[primaryKeyId].get(record));
statement.execute();
}
}

/*<K> T queryById(K key) {

}

List<T> queryForAll() {

}*/

@Override
public void close() {

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package ru.fizteh.fivt.students.egiby.miniorm;

import com.google.common.base.CaseFormat;
import com.google.common.primitives.Booleans;

import java.math.BigDecimal;
import java.sql.Array;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* Created by egiby on 18.12.15.
*/
public class NamesHelper {
private static final String REGEX = "[A-Za-z0-9_-]*";

public static Boolean isGood(String name) {
return name.matches(REGEX);
}

public static String convert(String name) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
}

private static Map<Class, String> toSQL = new HashMap<Class, String>();

private static void createMap() {
toSQL.put(Integer.class, "INTEGER");
toSQL.put(Booleans.class, "BOOLEAN");
toSQL.put(Byte.class, "TINYINT");
toSQL.put(Short.class, "SMALLINT");
toSQL.put(Long.class, "BIGINT");
toSQL.put(BigDecimal.class, "DECIMAL");
toSQL.put(Double.class, "DOUBLE");
toSQL.put(Float.class, "REAL");
toSQL.put(Time.class, "TIME");
toSQL.put(Date.class, "DATE");
toSQL.put(Timestamp.class, "DATETIME");
toSQL.put(Character.class, "CHAR");
toSQL.put(String.class, "VARCHAR"); // not very good, but what can I do?
toSQL.put(UUID.class, "UUID");
toSQL.put(Array.class, "ARRAY");
}

public static String getSQLTypeName(Class type) {
if (toSQL.isEmpty()) {
createMap();
}

if (toSQL.containsKey(type)) {
return toSQL.get(type);
} else {
return "OTHER";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.fizteh.fivt.students.egiby.miniorm;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
* Created by egiby on 18.12.15.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface PrimaryKey {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.fizteh.fivt.students.egiby.miniorm;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
* Created by egiby on 18.12.15.
*/

@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String name() default "";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.fizteh.fivt.students.egiby.moduletests;

import com.beust.jcommander.JCommander;
import ru.fizteh.fivt.students.egiby.moduletests.library.JCommanderParams;
import ru.fizteh.fivt.students.egiby.moduletests.library.TwitterPrinter;
import twitter4j.TwitterException;

/**
* Created by egiby on 24.09.15.
*/

public class TwitterStream {
public static void main(String[] args) {
JCommanderParams jcp = new JCommanderParams();
JCommander jcm = new JCommander(jcp, args);
if (jcp.isHelp()) {
TwitterPrinter.printHelp(jcm);
System.exit(0);
}
if (jcp.isStream()) {
if (jcp.getNumberTweets() != null) {
TwitterPrinter.printHelp(jcm);
System.exit(0);
}
TwitterPrinter.getStream(jcp, System.out);
} else {
try {
TwitterPrinter.printAllTweets(jcp, System.out);
} catch (TwitterException te) {
te.printStackTrace();
}
}
}
}
Loading