diff --git a/.gitignore b/.gitignore index 1e056e9..d6e5a5d 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,5 @@ workbench.xmi *.swp .settings .checkstyle + +twitter4j.properties \ No newline at end of file diff --git a/projects/egdeliya/pom.xml b/projects/egdeliya/pom.xml new file mode 100644 index 0000000..ad202b7 --- /dev/null +++ b/projects/egdeliya/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + ru.mipt.diht.students + parent + 1.0-SNAPSHOT + + ru.mipt.diht.students + egdeliya + 1.0-SNAPSHOT + egdeliya + http://maven.apache.org + + UTF-8 + + + + org.twitter4j + twitter4j-core + 4.0.4 + + + org.twitter4j + twitter4j-stream + 4.0.4 + + + com.beust + jcommander + 1.48 + + + com.h2database + h2 + 1.4.190 + + + diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Column.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Column.java new file mode 100644 index 0000000..144fdf0 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Column.java @@ -0,0 +1,14 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +/** + * Created by Эгделия on 19.12.2015. + */ +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Column { + //аннотации для столца, чтобы программа узнавала + //что это поле - столбец + String name() default ""; +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/DatabaseService.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/DatabaseService.java new file mode 100644 index 0000000..5968431 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/DatabaseService.java @@ -0,0 +1,318 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +//import java.io.Closeable; + +//import java.util.ArrayList; +import org.h2.jdbcx.JdbcConnectionPool; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.Field; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Эгделия on 19.12.2015. + */ +public class DatabaseService implements Closeable { + + private Class tableClass; + private String tableName; + private Field[] fields; + private Table tableAnnotation; + private List columnsNames = new ArrayList<>(); + + //столбец, который является primary key + private int primaryKeyPosition; + private String primaryKeyColumnsName = ""; + + //соединенеи с сервером + private JdbcConnectionPool connection; + + private void setTableAnnotations() { + + //нам нужны аннотации, чтобы распознать, + //где какие поля у класса + tableAnnotation = tableClass.getAnnotation(Table.class); + if (tableAnnotation == null) { + System.err.println("There is no @Table annotation"); + } + + } + + private void setTableName() { + tableName = tableAnnotation.name(); + if (tableName.equals("")) { + tableName = "DefaultTableName"; + } + } + + private void setFields() { + + //массив полей + fields = tableClass.getDeclaredFields(); + boolean thereIsPrimaryKye = false; + int fieldsCounter = 0; + for (Field column: fields) { + if (!column.isAnnotationPresent(Column.class)) { + System.err.println("There is incorrect @Column annotation"); + } + + //узнаем имя поля через аннотацию + String currentColumnName = column.getAnnotation(Column.class).name(); + if (currentColumnName.equals("")) { + currentColumnName = "DefaultColumnName"; + } + + //поле с аннотацией primary key + if (column.isAnnotationPresent(PrimaryKey.class)) { + if (!thereIsPrimaryKye) { + thereIsPrimaryKye = true; + primaryKeyPosition = fieldsCounter; + primaryKeyColumnsName = currentColumnName; + } else { + System.err.println("There is too many primary keys"); + } + } + + ++fieldsCounter; + columnsNames.add(currentColumnName); + } + } + + public final void createTable() { + + //конструируем запрос + String query = "CREATE TABLE IF NOT EXISTS " + tableName; + query += "("; + for (int i = 0; i < fields.length; i++) { + query += columnsNames.get(i) + " "; + query += new TypeConverter(fields[i].getType()).toSqlType(); + if (fields[i].isAnnotationPresent(PrimaryKey.class)) { + query += " PRIMARY KEY"; + } + if (i != fields.length - 1) { + query += ", "; + } + } + query += ")"; + + //отправляем запрос на сервер + try { + Connection connect = connection.getConnection(); + connect.createStatement().execute(query); + } catch (SQLException sql) { + System.err.println(sql.getMessage()); + System.out.println("SQLException in createTable"); + } + + } + + public final void insert(T element) { + //конструируем запрос + String insertQuery = "INSERT INTO " + tableName + " VALUES"; + insertQuery += "("; + + for (int i = 0; i < fields.length; ++i) { + insertQuery += "?"; + if (i != fields.length - 1) { + insertQuery += ", "; + } + } + insertQuery += ")"; + + //System.out.println(insertQuery); + + //подстановка нужных значений для вопросов + + try { + Connection connect = connection.getConnection(); + PreparedStatement statement = connect.prepareStatement(insertQuery); + + //нужно так делать, потому что мы не знаем тип SQL + //Prepare приводит наш запрос к нужному виду + for (int i = 0; i < fields.length; i++) { + Field currentField = fields[i]; + + //значение этого поля при подстановке + Object elementObject = currentField.get(element); + + statement.setObject(i + 1, elementObject); + } + //посылаем запрос на сервер + statement.execute(); + } catch (SQLException sql) { + System.err.println(sql.getMessage()); + System.out.println("SQLException in insert"); + } catch (IllegalAccessException access) { + System.err.println(access.getMessage()); + System.out.println("IllegalAccessException in insert"); + } + } + + public final void dropTable() { + + //составляем запрос и отправляем + try { + Connection connect = connection.getConnection(); + connect.createStatement().execute("DROP TABLE IF EXISTS " + tableName); + } catch (SQLException exc) { + System.err.println(exc.getMessage()); + System.out.println("SQLException in dropTable"); + } + + } + + public final void delete(T element) { + String deleteQuery = "DELETE FROM " + tableName + " WHERE " + + primaryKeyColumnsName + " = ?"; + + System.out.println(deleteQuery); + //подставляем под вопросики всё что нужно + try { + Connection connect = connection.getConnection(); + PreparedStatement statement = connect.prepareStatement(deleteQuery); + + //подставляем на место первого вопросика + statement.setObject(1, fields[primaryKeyPosition].get(element)); + + //отправляем запрос + statement.execute(); + + } catch (SQLException s) { + System.err.println(s.getMessage()); + System.out.println("SQLException in delete"); + } catch (IllegalAccessException i) { + System.err.println(i.getMessage()); + System.out.println("IllegalAccessException in delete"); + } + } + + public final void updated(T element) { + + //должны обновить каждое поле нашей строки + for (int i = 0; i < columnsNames.size(); i++) { + if (i == primaryKeyPosition) { + continue; + } + + String currentColumn = columnsNames.get(i); + //sql запрос + String updateQuery = "UPDATE " + tableName + "SET " + currentColumn + + " = ? WHERE " + primaryKeyColumnsName + " = ?"; + + try { + Connection connect = connection.getConnection(); + PreparedStatement statement = connect.prepareStatement(updateQuery); + + //подготовка запросов на отправление (замена вопросиков) + statement.setObject(1, fields[i].get(element)); + statement.setObject(2, fields[primaryKeyPosition].get(element)); + + // Отправление на исполнение. + statement.execute(); + } catch (SQLException s) { + System.err.println(s.getMessage()); + System.out.println("SQLException in updated"); + } catch (IllegalAccessException illegal) { + System.err.println(illegal.getMessage()); + System.out.println("IllegalAccessException in update"); + } + + } + } + + //запрос SELECT * + //должен вернуть список всех полей + public final List queryForAll() { + String query = "SELECT * FROM " + tableName; + List tableStrings = new ArrayList<>(); + try { + Connection connect = connection.getConnection(); + + ResultSet result = connect.createStatement().executeQuery(query); + + + while (result.next()) { + T newTableString = tableClass.newInstance(); + + for (int i = 0; i < fields.length; i++) { + String currentColumn = columnsNames.get(i); + + Object currentObject = result.getObject(currentColumn); + fields[i].set(newTableString, currentObject); + } + tableStrings.add(newTableString); + } + return tableStrings; + } catch (SQLException sql) { + System.err.println(sql.getMessage()); + System.out.println("SQLException in SELECT FROM *"); + } catch (InstantiationException ins) { + System.err.println(ins.getMessage()); + System.out.println("InstantiationException in SELECT FROM *"); + } catch (IllegalAccessException illeg) { + System.err.println(illeg.getMessage()); + System.out.println("IllegalAccessException in SELECT FROM *"); + } + return tableStrings; + } + + //два шабона, + //потому что уникальные ключи могут быть разными типами + public final T queryById(K primaryKey) throws SQLException, IllegalAccessException, InstantiationException { + String query = "SELECT * FROM " + tableName + " WHERE " + primaryKeyColumnsName + + " = " + primaryKey; + + //должен выдать единственную строку + T tableString = tableClass.newInstance(); + + Connection connect = connection.getConnection(); + + //ответ базы данных возвращается в виде ResultSet + ResultSet result = connect.createStatement().executeQuery(query); + + if (result.next()) { + for (int i = 0; i < fields.length; i++) { + String currentColumn = columnsNames.get(i); + + //по иени колонки возвращает значение поля + //в текущей строке + Object currentObject = result.getObject(currentColumn); + fields[i].set(tableString, currentObject); + } + } + + return tableString; + } + + public DatabaseService(Class newClass) { + tableClass = newClass; + + setTableAnnotations(); + setTableName(); + setFields(); + + //подключение + try { + Class.forName("org.h2.Driver"); + } catch (ClassNotFoundException ex) { + System.out.println(ex.getMessage()); + } + + connection = JdbcConnectionPool.create("jdbc:h2:~/test", "test", "test"); + } + + @SuppressWarnings("checkstyle:designforextension") + @Override + public void close() throws IOException { + if (connection != null) { + connection.dispose(); + } + } + +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/PrimaryKey.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/PrimaryKey.java new file mode 100644 index 0000000..207a07d --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/PrimaryKey.java @@ -0,0 +1,11 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Created by Эгделия on 19.12.2015. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface PrimaryKey { +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Star.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Star.java new file mode 100644 index 0000000..25a4591 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Star.java @@ -0,0 +1,104 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +import java.sql.SQLException; +import java.util.List; + +/** + * Created by Эгделия on 19.12.2015. + */ + +//таблица будет сожержать инфу о звёздах +//чтобы можно было делать переменные не private +@SuppressWarnings("checkstyle:visibilitymodifier") +@Table(name = "STARS") +public class Star { + @PrimaryKey + @Column(name = "ID") + Integer id; + + @Column(name = "Name") + String starName; + + @Column(name = "Radius") + Integer radius; + + Star(Integer ourId, String n, Integer r) { + starName = n; + radius = r; + id = ourId; + } + + Star() { + starName = ""; + radius = 0; + id = 0; + } + + public final String toString() { + String result = starName + " " + radius + " " + id; + return result; + } + + @SuppressWarnings("checkstyle:magicnumber") + public static void main(String[] args) { + DatabaseService dataBase = new DatabaseService<>(Star.class); + try { + + dataBase.createTable(); + + Star sun = new Star(0, "Sun", 60000); + + //insert + System.out.println("\ninsert test"); + dataBase.insert(sun); + dataBase.insert(new Star(1, "Alpha", 63000)); + dataBase.insert(new Star(2, "Betta", 28000)); + dataBase.insert(new Star(3, "Gamma", 15000)); + dataBase.insert(new Star(4, "Delta", 57900)); + dataBase.insert(new Star(5, "Omega", 1000)); + + //SELECT * + System.out.println("\nSelect all test"); + List table; + table = dataBase.queryForAll(); + + for (int i = 0; i < table.size(); i++) { + System.out.println(table.get(i).toString()); + } + + //queryById + System.out.println("\nqueryById test"); + try { + Star myStar; + myStar = dataBase.queryById(2); + System.out.println(myStar); + } catch (IllegalAccessException illegal) { + System.out.println("IllegalAccessException in queryById"); + System.err.println(illegal.getMessage()); + } catch (SQLException sql) { + System.err.println(sql.getMessage()); + System.out.println("SQLException in queryById"); + } catch (InstantiationException instal) { + System.err.println(instal.getMessage()); + System.out.println("InstantiationException in queryById"); + } + + System.out.println("\ndelete test"); + //delete + dataBase.delete(sun); + + //SELECT * + List tableAfterDelete; + tableAfterDelete = dataBase.queryForAll(); + + for (int i = 0; i < tableAfterDelete.size(); i++) { + System.out.println(tableAfterDelete.get(i)); + } + + } finally { + dataBase.dropTable(); + } + } +} + + diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Table.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Table.java new file mode 100644 index 0000000..45c3c49 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/Table.java @@ -0,0 +1,12 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +/** + * Created by Эгделия on 19.12.2015. + */ +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Table { + String name() default ""; +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/TypeConverter.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/TypeConverter.java new file mode 100644 index 0000000..53bdf7f --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/MiniORM/TypeConverter.java @@ -0,0 +1,22 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +/** + * Created by Эгделия on 19.12.2015. + */ + +//todo +public class TypeConverter { + + private String sqlType; + + TypeConverter(Class sqlClass) { + if (sqlClass == Integer.class) { + sqlType = "INTEGER"; + } else if (sqlClass == String.class) { + sqlType = "VARCHAR(255)"; + } + } + public final String toSqlType() { + return sqlType; + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Reverser/Reverser.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Reverser/Reverser.java new file mode 100644 index 0000000..492961a --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Reverser/Reverser.java @@ -0,0 +1,16 @@ +package ru.mipt.diht.students.egdeliya.Reverser; + +/** + * Created by Эгделия on 15.12.2015. + */ +public class Reverser { + public static void main(String[] args) { + for (int i = args.length - 1; i >= 0; i--) { + String[] str = args[i].split("\\D+"); + for (int j = str.length - 1; j >= 0; j--) { + System.out.print(str[j] + " "); + } + } + System.out.println(); + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueue.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueue.java new file mode 100644 index 0000000..f3cbe2a --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueue.java @@ -0,0 +1,102 @@ +package ru.mipt.diht.students.egdeliya.Thread; + +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Created by Эгделия on 17.12.2015. + */ +public class BlockingQueue { + private int maxQueueSize; + private Queue queue; + private Lock offerLock = new ReentrantLock(); + private Lock queueLock = new ReentrantLock(); + private Lock takeLock = new ReentrantLock(); + + private Object takeWait = new Object(); + private Object offerWait = new Object(); + + //конструктор + public BlockingQueue(int size) { + maxQueueSize = size; + queue = new ArrayDeque(); + } + + //добавление элементов + public final void offer(List elements) { + offerLock.lock(); + try { + int offeredElementsNumber = 0; + while (offeredElementsNumber != elements.size()) { + synchronized (takeWait) { + //пока не можем добавить элементы + while (queue.size() == maxQueueSize) { + try { + //ждём, пока кто-нибудь вытащит элемент + takeWait.wait(); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } + //можем вставить элемент + try { + //вставляем атомарно, т.е блокируем очередь + queueLock.lock(); + while (offeredElementsNumber < elements.size() && queue.size() < maxQueueSize) { + queue.add(elements.get(offeredElementsNumber)); + ++offeredElementsNumber; + } + } finally { + queueLock.unlock(); + } + } + } + } finally { + //будим всех, кто хочет добавить элементы + synchronized (offerWait) { + offerWait.notifyAll(); + } + offerLock.unlock(); + } + } + + //возвращает numberOfElements первых элементов из очереди + public final List take(int numberOfElements) { + takeLock.lock(); + try { + List answer = new ArrayList<>(); + while (answer.size() != numberOfElements) { + synchronized (offerWait) { + + //пока количество элементов в очереди меньше, + // чем numberOfElements + while (queue.size() < numberOfElements - answer.size()) { + try { + offerWait.wait(); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } + //можем удалить элемент + try { + queueLock.lock(); + while (answer.size() < numberOfElements + && + queue.size() >= numberOfElements - answer.size()) { + answer.add(queue.poll()); + } + } finally { + queueLock.unlock(); + } + } + } + return answer; + } finally { + synchronized (takeWait) { + takeWait.notifyAll(); + } + takeLock.unlock(); + } + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueueRunner.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueueRunner.java new file mode 100644 index 0000000..51d0372 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/BlockingQueueRunner.java @@ -0,0 +1,23 @@ +package ru.mipt.diht.students.egdeliya.Thread; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Эгделия on 17.12.2015. + */ +@SuppressWarnings("checkstyle:magicnumber") +public class BlockingQueueRunner { + public static void main(String[] args) { + int maxQueueSize = Integer.parseInt(args[0]); + BlockingQueue queue = new BlockingQueue(maxQueueSize); + List list = new ArrayList<>(4); + + list.add("Hello everyone! I just do it!"); + list.add("But I have to do some more..."); + list.add("Help me, please!"); + list.add("Oh, my God..."); + + queue.offer(list); + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Call.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Call.java new file mode 100644 index 0000000..183d741 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Call.java @@ -0,0 +1,50 @@ +package ru.mipt.diht.students.egdeliya.Thread; + +import java.util.Random; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Created by Эгделия on 17.12.2015. + */ +@SuppressWarnings("checkstyle:magicnumber") +public class Call { + private Thread[] threads; + private int numberOfThreads; + private Random randomAnswer = new Random(); + private int threadAnswer; + private final int percentage = 10; + private boolean allThreadsReplyYes = false; + private Lock lock = new ReentrantLock(); + + public final void threadsCall(String arg) { + numberOfThreads = Integer.parseInt(arg); + threads = new Thread[numberOfThreads]; + for (int i = 0; i < numberOfThreads; ++i) { + threads[i] = new Thread(new Reply()); + } + + while (!allThreadsReplyYes) { + System.out.println("Are you ready?"); + allThreadsReplyYes = true; + for (int i = 0; i < numberOfThreads; ++i) { + threads[i].run(); + } + } + } + + public class Reply implements Runnable { + + public final void run() { + lock.lock(); + threadAnswer = randomAnswer.nextInt(percentage); + if (threadAnswer == 1) { + System.out.println("No"); + allThreadsReplyYes = false; + } else { + System.out.println("Yes"); + } + lock.unlock(); + } + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/CallRunner.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/CallRunner.java new file mode 100644 index 0000000..e2e5afa --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/CallRunner.java @@ -0,0 +1,11 @@ +package ru.mipt.diht.students.egdeliya.Thread; + +/** + * Created by Эгделия on 17.12.2015. + */ +public class CallRunner { + public static void main(String[] args) { + Call call = new Call(); + call.threadsCall(args[0]); + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Counter.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Counter.java new file mode 100644 index 0000000..e67fb33 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/Thread/Counter.java @@ -0,0 +1,53 @@ +package ru.mipt.diht.students.egdeliya.Thread; + +/** + * Created by Эгделия on 15.12.2015. + */ +public class Counter { + private static Object object = new Object(); + private static int numberOfThreads; + private static int currentThreadId; + private static Thread[] threads; + + public static void main(String[] args) { + numberOfThreads = Integer.parseInt(args[0]); + threadsCounter(); + } + + public static void threadsCounter() { + threads = new Thread[numberOfThreads]; + currentThreadId = 0; + for (int i = 0; i < numberOfThreads; i++) { + threads[i] = new Thread(new PrintName(i, (i + 1) % numberOfThreads)); + threads[i].start(); + } + } + + public static class PrintName implements Runnable { + private int myThreadId, nextThreadId; + + public PrintName(int id1, int id2) { + myThreadId = id1; + nextThreadId = id2; + } + + @Override + public final synchronized void run() { + while (true) { + synchronized (object) { + while (myThreadId != currentThreadId) { + try { + object.wait(); + } catch (InterruptedException e) { + System.err.println("Thread " + myThreadId + " interrupted"); + } + } + System.out.println("Thread-" + myThreadId); + currentThreadId = nextThreadId; + object.notifyAll(); + } + } + } + } +} + diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/JCommanderParser.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/JCommanderParser.java new file mode 100644 index 0000000..9688a94 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/JCommanderParser.java @@ -0,0 +1,58 @@ +package ru.mipt.diht.students.egdeliya.TwitterStream; + +import com.beust.jcommander.Parameter; + +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("checkstyle:designforextension") +public class JCommanderParser { + //список параметров + @Parameter + private List parameters = new ArrayList<>(); + + @Parameter(names = {"--query", "-q"}, description = "Ключевые слова") + private String query = ""; + + @Parameter(names = {"--place", "-p"}, arity = 1, description = "Твиты по заданному региону") + //место поиска по умолчанию + private String place = ""; + + @Parameter(names = {"--stream", "-s"}, description = "Печать твитов") + private boolean stream = false; + + @Parameter(names = "--hideRetweets", description = "Не показывать ретвиты") + private boolean hideRetweets = false; + + @Parameter( + names = {"--limit", "-l"}, + description = "Ограничение числа выведенных твитов") + private Integer limit = Integer.MAX_VALUE; + + @Parameter(names = {"--help", "-h"}, description = "Справка") + private boolean help = false; + + public String getLocation() { + return place; + } + + public boolean isStream() { + return stream; + } + + public boolean isHideRetweets() { + return hideRetweets; + } + + public Integer getLimit() { + return limit; + } + + public boolean isHelp() { + return help; + } + + public String getUsersQuery() { + return query; + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamRunner.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamRunner.java new file mode 100644 index 0000000..bb77fd8 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamRunner.java @@ -0,0 +1,11 @@ +package ru.mipt.diht.students.egdeliya.TwitterStream; + +/** + * Created by Эгделия on 18.12.2015. + */ +public class TwitterStreamRunner { + public static void main(String[] args) { + TwitterStreamer tweet = new TwitterStreamer(args); + tweet.twitterStreamRun(); + } +} diff --git a/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamer.java b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamer.java new file mode 100644 index 0000000..abceaa4 --- /dev/null +++ b/projects/egdeliya/src/main/java/ru/mipt/diht/students/egdeliya/TwitterStream/TwitterStreamer.java @@ -0,0 +1,182 @@ +package ru.mipt.diht.students.egdeliya.TwitterStream; + +import com.beust.jcommander.JCommander; +import twitter4j.*; + +import java.util.List; +import java.util.Scanner; +import java.util.Vector; + +@SuppressWarnings("checkstyle:magicnumber") +public class TwitterStreamer { + private Twitter twitter; + private String usersQuery; + private JCommanderParser jCommander = new JCommanderParser(); + private String[] arguments; + + private static final int RADIUS = 50; + + public TwitterStreamer(String[] args) { + arguments = args; + + //парсим входую строку + new JCommander(jCommander, arguments); + } + + public final void help() { + //пользователь запрашивает справку + if (jCommander.isHelp()) { + JCommander jCommand = new JCommander(jCommander, arguments); + jCommand.usage(); + } + } + + public final void query() throws TwitterException, InterruptedException { + twitter = TwitterFactory.getSingleton(); + Query twitterQuery = new Query(usersQuery); + + //если установлено место + if (!jCommander.getLocation().equals("")) { + twitterQuery = place(twitterQuery); + } + + //если указан параметр stream + if (jCommander.isStream()) { + streamRunner(twitterQuery); + } else { + + //если установлен лимит + if (jCommander.getLimit() < Integer.MAX_VALUE) { + twitterQuery.setCount(jCommander.getLimit()); + } + + try { + QueryResult result = twitter.search(twitterQuery); + + //если по запросу не найдены твиты + if (result.getTweets().size() == 0) { + System.out.println("There is no tweets for " + usersQuery); + } + + for (Status status : result.getTweets()) { + printTweet(status); + } + } catch (TwitterException t) { + System.err.println(t.getMessage()); + } + } + } + + public final void streamRunner(Query twitterQuery) throws InterruptedException, TwitterException { + + TwitterStream streamer = new TwitterStreamFactory().getInstance(); + StatusAdapter listener = new StatusAdapter() { + @Override + public void onStatus(Status status) { + printTweet(status); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } + } + @Override + public void onException(Exception ex) { + System.err.println(ex.getMessage()); + } + }; + + streamer.addListener(listener); + + //фильтруем запросы + FilterQuery filterQuery = new FilterQuery(); + filterQuery.track(twitterQuery.getQuery()); + streamer.filter(filterQuery); + + Scanner scanner = new Scanner(System.in); + while (scanner.hasNextLine()) { + Thread.sleep(1000); + } + } + + public final void printTweet(Status status) { + + //если параметр stream не установлен + if (!jCommander.isStream()) { + System.out.println(status.getCreatedAt()); + } + + //красит ник в синий цвет + System.out.println("@" + "\033[34m@" + status.getUser().getName() + + "\033[0m: " + " : " + status.getText()); + + //если не нужно прятать ретвиты + if (!jCommander.isHideRetweets() && !jCommander.isStream()) { + try { + List statusList = twitter.getRetweets(status.getId()); + for (Status node : statusList) { + System.out.println("@" + " \033[34m@" + node.getUser().getName() + "\033[0m: " + " : " + + node.getText()); + } + } catch (TwitterException t) { + System.err.println(t.getMessage()); + } + } + } + + public final Query place(Query twitterQuery) throws TwitterException { + + Vector locations = new Vector<>(); + + //устанавливаем магический ip + GeoQuery geoQuery = new GeoQuery("0.0.0.0"); + geoQuery.setQuery(jCommander.getLocation()); + + //получаем информацию о местах + //в эпсилон окрестности нашего места + ResponseList responseList; + responseList = twitter.searchPlaces(geoQuery); + + for (Place geoPlace : responseList) { + + for (int i = 0; i < geoPlace.getBoundingBoxCoordinates().length; i++) { + for (int j = 0; + j < geoPlace.getBoundingBoxCoordinates()[i].length; j++) { + locations.add(geoPlace.getBoundingBoxCoordinates()[i][j]); + //System.out.println(geoPlace.getBoundingBoxCoordinates()[i][j]); + } + } + } + + //вычисляем центр + double x = 0; + double y = 0; + for (GeoLocation location : locations) { + x += location.getLatitude(); + y += location.getLongitude(); + } + x /= locations.size(); + y /= locations.size(); + + GeoLocation ourLocation = new GeoLocation(x, y); + twitterQuery.setGeoCode(ourLocation, RADIUS, Query.Unit.km); + + return twitterQuery; + } + + public final void twitterStreamRun() { + + //проверяем, что есть параметр help + help(); + usersQuery = jCommander.getUsersQuery(); + + try { + query(); + } catch (TwitterException t) { + System.err.println(t.getMessage()); + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } + } + +} diff --git a/projects/egdeliya/src/test/java/ru/mipt/diht/students/AppTest.java b/projects/egdeliya/src/test/java/ru/mipt/diht/students/AppTest.java new file mode 100644 index 0000000..4bb8dd4 --- /dev/null +++ b/projects/egdeliya/src/test/java/ru/mipt/diht/students/AppTest.java @@ -0,0 +1,38 @@ +package ru.mipt.diht.students; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/projects/egdeliya/src/test/java/ru/mipt/diht/students/egdeliya/MiniORM/DataBaseServiceTest.java b/projects/egdeliya/src/test/java/ru/mipt/diht/students/egdeliya/MiniORM/DataBaseServiceTest.java new file mode 100644 index 0000000..2b92235 --- /dev/null +++ b/projects/egdeliya/src/test/java/ru/mipt/diht/students/egdeliya/MiniORM/DataBaseServiceTest.java @@ -0,0 +1,43 @@ +package ru.mipt.diht.students.egdeliya.MiniORM; + +import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Created by Эгделия on 19.12.2015. + */ + +// +public class DataBaseServiceTest extends TestCase { + DatabaseService dataBase; + + @Before + public void initializer() { + dataBase = new DatabaseService<>(Star.class); + + dataBase.createTable(); + } + + @Test + public void testInsert() { +/* + dataBase.insert(new Star("Sun", 60000, "Red")); + dataBase.insert(new Star("Alpha", 63000, "Blue")); + dataBase.insert(new Star("Betta", 28000, "Yellow")); + dataBase.insert(new Star("Gamma", 15000, "Red")); + dataBase.insert(new Star("Delta", 57900, "Blue")); + dataBase.insert(new Star("Omega", 1000, "Orange")); + */ + } + + @After + public void cleaner() { + dataBase.dropTable(); + } + + + + +} diff --git a/projects/pom.xml b/projects/pom.xml index 5d14966..99e7448 100644 --- a/projects/pom.xml +++ b/projects/pom.xml @@ -1,5 +1,5 @@ - + + 4.0.0 ru.mipt.diht.students @@ -30,7 +30,8 @@ dkhurtin ale3otik Pitovsky - + egdeliya + @@ -133,4 +134,4 @@ - + \ No newline at end of file